@gala-chain/launchpad-sdk 5.0.4-beta.7 → 5.1.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 (1806) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/EXAMPLES.md +99 -0
  3. package/README.md +354 -49
  4. package/README.md.bak +3174 -0
  5. package/dist/LaunchpadSDK.d.ts +10744 -0
  6. package/dist/LaunchpadSDK.d.ts.map +1 -0
  7. package/dist/ai-docs.json +5433 -1237
  8. package/dist/api/LaunchpadAPI.d.ts +930 -0
  9. package/dist/api/LaunchpadAPI.d.ts.map +1 -0
  10. package/dist/api/dto/BondingCurveDTOs.d.ts +145 -0
  11. package/dist/api/dto/BondingCurveDTOs.d.ts.map +1 -0
  12. package/dist/api/dto/BurnTokensDto.d.ts +89 -0
  13. package/dist/api/dto/BurnTokensDto.d.ts.map +1 -0
  14. package/dist/api/dto/LockTokenDto.d.ts +97 -0
  15. package/dist/api/dto/LockTokenDto.d.ts.map +1 -0
  16. package/dist/api/dto/TransferTokenDto.d.ts +76 -0
  17. package/dist/api/dto/TransferTokenDto.d.ts.map +1 -0
  18. package/dist/api/dto/UnlockTokenDto.d.ts +86 -0
  19. package/dist/api/dto/UnlockTokenDto.d.ts.map +1 -0
  20. package/dist/auth/JwtAuth.d.ts +183 -0
  21. package/dist/auth/JwtAuth.d.ts.map +1 -0
  22. package/dist/auth/SessionAuthService.d.ts +151 -0
  23. package/dist/auth/SessionAuthService.d.ts.map +1 -0
  24. package/dist/auth/SignatureAuth.d.ts +181 -0
  25. package/dist/auth/SignatureAuth.d.ts.map +1 -0
  26. package/dist/auth/storage.d.ts +66 -0
  27. package/dist/auth/storage.d.ts.map +1 -0
  28. package/dist/auth/types.d.ts +50 -0
  29. package/dist/auth/types.d.ts.map +1 -0
  30. package/dist/bridge/BridgeService.d.ts +484 -0
  31. package/dist/bridge/BridgeService.d.ts.map +1 -0
  32. package/dist/bridge/GalaConnectClient.d.ts +170 -0
  33. package/dist/bridge/GalaConnectClient.d.ts.map +1 -0
  34. package/dist/bridge/constants/index.d.ts +7 -0
  35. package/dist/bridge/constants/index.d.ts.map +1 -0
  36. package/dist/bridge/constants/tokens.d.ts +212 -0
  37. package/dist/bridge/constants/tokens.d.ts.map +1 -0
  38. package/dist/bridge/index.d.ts +24 -0
  39. package/dist/bridge/index.d.ts.map +1 -0
  40. package/dist/bridge/strategies/BridgeStrategy.d.ts +160 -0
  41. package/dist/bridge/strategies/BridgeStrategy.d.ts.map +1 -0
  42. package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts +200 -0
  43. package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -0
  44. package/dist/bridge/strategies/SolanaBridgeStrategy.d.ts +258 -0
  45. package/dist/bridge/strategies/SolanaBridgeStrategy.d.ts.map +1 -0
  46. package/dist/bridge/types/bridge.dto.d.ts +772 -0
  47. package/dist/bridge/types/bridge.dto.d.ts.map +1 -0
  48. package/dist/bridge/types/bridgeable-token.dto.d.ts +205 -0
  49. package/dist/bridge/types/bridgeable-token.dto.d.ts.map +1 -0
  50. package/dist/bridge/types/eip712.d.ts +66 -0
  51. package/dist/bridge/types/eip712.d.ts.map +1 -0
  52. package/dist/bridge/types/index.d.ts +8 -0
  53. package/dist/bridge/types/index.d.ts.map +1 -0
  54. package/dist/bridge/utils/RateLimiter.d.ts +34 -0
  55. package/dist/bridge/utils/RateLimiter.d.ts.map +1 -0
  56. package/dist/bridge/utils/address-formatter.d.ts +25 -0
  57. package/dist/bridge/utils/address-formatter.d.ts.map +1 -0
  58. package/dist/bridge/utils/addressValidation.d.ts +200 -0
  59. package/dist/bridge/utils/addressValidation.d.ts.map +1 -0
  60. package/dist/bridge/utils/balanceHelpers.d.ts +215 -0
  61. package/dist/bridge/utils/balanceHelpers.d.ts.map +1 -0
  62. package/dist/bridge/utils/bridgeErrors.d.ts +98 -0
  63. package/dist/bridge/utils/bridgeErrors.d.ts.map +1 -0
  64. package/dist/bridge/utils/bridgeOutHelpers.d.ts +68 -0
  65. package/dist/bridge/utils/bridgeOutHelpers.d.ts.map +1 -0
  66. package/dist/bridge/utils/bridgePayload.d.ts +98 -0
  67. package/dist/bridge/utils/bridgePayload.d.ts.map +1 -0
  68. package/dist/bridge/utils/bridgeStatusParser.d.ts +75 -0
  69. package/dist/bridge/utils/bridgeStatusParser.d.ts.map +1 -0
  70. package/dist/bridge/utils/eip712Helpers.d.ts +66 -0
  71. package/dist/bridge/utils/eip712Helpers.d.ts.map +1 -0
  72. package/dist/bridge/utils/index.d.ts +19 -0
  73. package/dist/bridge/utils/index.d.ts.map +1 -0
  74. package/dist/bridge/utils/retry.d.ts +112 -0
  75. package/dist/bridge/utils/retry.d.ts.map +1 -0
  76. package/dist/bridge/utils/strategyDelegation.d.ts +69 -0
  77. package/dist/bridge/utils/strategyDelegation.d.ts.map +1 -0
  78. package/dist/bridge/utils/tokenIdUtils.d.ts +86 -0
  79. package/dist/bridge/utils/tokenIdUtils.d.ts.map +1 -0
  80. package/dist/bridge/utils/tokenMath.d.ts +39 -0
  81. package/dist/bridge/utils/tokenMath.d.ts.map +1 -0
  82. package/dist/bridge/utils/tokenMetadataResolver.d.ts +97 -0
  83. package/dist/bridge/utils/tokenMetadataResolver.d.ts.map +1 -0
  84. package/dist/config/environments.d.ts +51 -0
  85. package/dist/config/environments.d.ts.map +1 -0
  86. package/dist/constants/bondingCurve.d.ts +102 -0
  87. package/dist/constants/bondingCurve.d.ts.map +1 -0
  88. package/dist/constants/config.d.ts +30 -0
  89. package/dist/constants/config.d.ts.map +1 -0
  90. package/dist/constants/decimals.d.ts +63 -0
  91. package/dist/constants/decimals.d.ts.map +1 -0
  92. package/dist/constants/endpoints.d.ts +820 -0
  93. package/dist/constants/endpoints.d.ts.map +1 -0
  94. package/dist/constants/enums.d.ts +65 -0
  95. package/dist/constants/enums.d.ts.map +1 -0
  96. package/dist/constants/error-messages.d.ts +61 -0
  97. package/dist/constants/error-messages.d.ts.map +1 -0
  98. package/dist/constants/events.d.ts +53 -0
  99. package/dist/constants/events.d.ts.map +1 -0
  100. package/dist/constants/jwt.d.ts +41 -0
  101. package/dist/constants/jwt.d.ts.map +1 -0
  102. package/dist/constants/nft-fees.d.ts +30 -0
  103. package/dist/constants/nft-fees.d.ts.map +1 -0
  104. package/dist/constants/pagination.d.ts +66 -0
  105. package/dist/constants/pagination.d.ts.map +1 -0
  106. package/dist/constants/query-fields.d.ts +51 -0
  107. package/dist/constants/query-fields.d.ts.map +1 -0
  108. package/dist/constants/sdk-defaults.d.ts +37 -0
  109. package/dist/constants/sdk-defaults.d.ts.map +1 -0
  110. package/dist/constants/version.d.ts +6 -0
  111. package/dist/constants/version.d.ts.map +1 -0
  112. package/dist/constants/version.generated.d.ts +7 -0
  113. package/dist/constants/version.generated.d.ts.map +1 -0
  114. package/dist/examples/admin/api-key-advanced.d.ts +43 -0
  115. package/dist/examples/admin/api-key-advanced.d.ts.map +1 -0
  116. package/dist/examples/admin/moderator-invite-complete.d.ts +41 -0
  117. package/dist/examples/admin/moderator-invite-complete.d.ts.map +1 -0
  118. package/dist/examples/admin/overseer-management-advanced.d.ts +38 -0
  119. package/dist/examples/admin/overseer-management-advanced.d.ts.map +1 -0
  120. package/dist/examples/admin/overseer-page-stats.d.ts +26 -0
  121. package/dist/examples/admin/overseer-page-stats.d.ts.map +1 -0
  122. package/dist/examples/admin/token-ban-complete.d.ts +44 -0
  123. package/dist/examples/admin/token-ban-complete.d.ts.map +1 -0
  124. package/dist/examples/ai-moderation/ai-moderation-demo.d.ts +32 -0
  125. package/dist/examples/ai-moderation/ai-moderation-demo.d.ts.map +1 -0
  126. package/dist/examples/ai-moderation/flag-ai-verdicts-demo.d.ts +30 -0
  127. package/dist/examples/ai-moderation/flag-ai-verdicts-demo.d.ts.map +1 -0
  128. package/dist/examples/analytics/index.d.ts +23 -0
  129. package/dist/examples/analytics/index.d.ts.map +1 -0
  130. package/dist/examples/analytics/market-analysis-tools.d.ts +28 -0
  131. package/dist/examples/analytics/market-analysis-tools.d.ts.map +1 -0
  132. package/dist/examples/analytics/portfolio-performance-tracking.d.ts +25 -0
  133. package/dist/examples/analytics/portfolio-performance-tracking.d.ts.map +1 -0
  134. package/dist/examples/analytics/trading-analytics-advanced.d.ts +27 -0
  135. package/dist/examples/analytics/trading-analytics-advanced.d.ts.map +1 -0
  136. package/dist/examples/api-keys/advanced-configuration.d.ts +19 -0
  137. package/dist/examples/api-keys/advanced-configuration.d.ts.map +1 -0
  138. package/dist/examples/api-keys/complete-lifecycle.d.ts +18 -0
  139. package/dist/examples/api-keys/complete-lifecycle.d.ts.map +1 -0
  140. package/dist/examples/api-keys/crud.d.ts +22 -0
  141. package/dist/examples/api-keys/crud.d.ts.map +1 -0
  142. package/dist/examples/api-keys/token-delegation.d.ts +24 -0
  143. package/dist/examples/api-keys/token-delegation.d.ts.map +1 -0
  144. package/dist/examples/api-keys/user-api-key-auth.d.ts +24 -0
  145. package/dist/examples/api-keys/user-api-key-auth.d.ts.map +1 -0
  146. package/dist/examples/auth/auth-permissions-checking.d.ts +32 -0
  147. package/dist/examples/auth/auth-permissions-checking.d.ts.map +1 -0
  148. package/dist/examples/auth/auth-token-management.d.ts +32 -0
  149. package/dist/examples/auth/auth-token-management.d.ts.map +1 -0
  150. package/dist/examples/auth/auth-validation-workflows.d.ts +32 -0
  151. package/dist/examples/auth/auth-validation-workflows.d.ts.map +1 -0
  152. package/dist/examples/bans/ban-management.d.ts +24 -0
  153. package/dist/examples/bans/ban-management.d.ts.map +1 -0
  154. package/dist/examples/bans/demo-global-user-bans.d.ts +27 -0
  155. package/dist/examples/bans/demo-global-user-bans.d.ts.map +1 -0
  156. package/dist/examples/bonding/token-graduation-workflow.d.ts +21 -0
  157. package/dist/examples/bonding/token-graduation-workflow.d.ts.map +1 -0
  158. package/dist/examples/bonding-curve/basic-trading.d.ts +20 -0
  159. package/dist/examples/bonding-curve/basic-trading.d.ts.map +1 -0
  160. package/dist/examples/bonding-curve/graduation-workflow.d.ts +18 -0
  161. package/dist/examples/bonding-curve/graduation-workflow.d.ts.map +1 -0
  162. package/dist/examples/bonding-curve/pagination-variants.d.ts +17 -0
  163. package/dist/examples/bonding-curve/pagination-variants.d.ts.map +1 -0
  164. package/dist/examples/bonding-curve/pool-analysis.d.ts +18 -0
  165. package/dist/examples/bonding-curve/pool-analysis.d.ts.map +1 -0
  166. package/dist/examples/bonding-curve/pool-creator-filtering.d.ts +17 -0
  167. package/dist/examples/bonding-curve/pool-creator-filtering.d.ts.map +1 -0
  168. package/dist/examples/bonding-curve/pool-discovery.d.ts +19 -0
  169. package/dist/examples/bonding-curve/pool-discovery.d.ts.map +1 -0
  170. package/dist/examples/bonding-curve/price-impact.d.ts +18 -0
  171. package/dist/examples/bonding-curve/price-impact.d.ts.map +1 -0
  172. package/dist/examples/bonding-curve/token-launch.d.ts +18 -0
  173. package/dist/examples/bonding-curve/token-launch.d.ts.map +1 -0
  174. package/dist/examples/bonding-curve/user-holder-context.d.ts +18 -0
  175. package/dist/examples/bonding-curve/user-holder-context.d.ts.map +1 -0
  176. package/dist/examples/bonding-curve/volume-trading.d.ts +18 -0
  177. package/dist/examples/bonding-curve/volume-trading.d.ts.map +1 -0
  178. package/dist/examples/bridge/bridge-ethereum-specific.d.ts +18 -0
  179. package/dist/examples/bridge/bridge-ethereum-specific.d.ts.map +1 -0
  180. package/dist/examples/bridge/bridge-generic-operations.d.ts +18 -0
  181. package/dist/examples/bridge/bridge-generic-operations.d.ts.map +1 -0
  182. package/dist/examples/bridge/bridge-multi-chain-routing.d.ts +31 -0
  183. package/dist/examples/bridge/bridge-multi-chain-routing.d.ts.map +1 -0
  184. package/dist/examples/bridge/bridge-network-methods.d.ts +31 -0
  185. package/dist/examples/bridge/bridge-network-methods.d.ts.map +1 -0
  186. package/dist/examples/bridge/bridge-network-tokens.d.ts +18 -0
  187. package/dist/examples/bridge/bridge-network-tokens.d.ts.map +1 -0
  188. package/dist/examples/bridge/bridge-network-validation.d.ts +33 -0
  189. package/dist/examples/bridge/bridge-network-validation.d.ts.map +1 -0
  190. package/dist/examples/bridge/bridge-operations.d.ts +27 -0
  191. package/dist/examples/bridge/bridge-operations.d.ts.map +1 -0
  192. package/dist/examples/bridge/bridge-solana-specific.d.ts +18 -0
  193. package/dist/examples/bridge/bridge-solana-specific.d.ts.map +1 -0
  194. package/dist/examples/bridge/bridge-status-monitoring.d.ts +30 -0
  195. package/dist/examples/bridge/bridge-status-monitoring.d.ts.map +1 -0
  196. package/dist/examples/bridge/bridge-wrapped-token-operations.d.ts +30 -0
  197. package/dist/examples/bridge/bridge-wrapped-token-operations.d.ts.map +1 -0
  198. package/dist/examples/bridge/bridgeable-tokens.d.ts +27 -0
  199. package/dist/examples/bridge/bridgeable-tokens.d.ts.map +1 -0
  200. package/dist/examples/bridge/check-balances.d.ts +13 -0
  201. package/dist/examples/bridge/check-balances.d.ts.map +1 -0
  202. package/dist/examples/bridge/ethereum-in.d.ts +17 -0
  203. package/dist/examples/bridge/ethereum-in.d.ts.map +1 -0
  204. package/dist/examples/bridge/ethereum-out.d.ts +17 -0
  205. package/dist/examples/bridge/ethereum-out.d.ts.map +1 -0
  206. package/dist/examples/bridge/ethereum-roundtrip.d.ts +20 -0
  207. package/dist/examples/bridge/ethereum-roundtrip.d.ts.map +1 -0
  208. package/dist/examples/bridge/external-balances.d.ts +29 -0
  209. package/dist/examples/bridge/external-balances.d.ts.map +1 -0
  210. package/dist/examples/bridge/fee-estimation.d.ts +14 -0
  211. package/dist/examples/bridge/fee-estimation.d.ts.map +1 -0
  212. package/dist/examples/bridge/solana-in.d.ts +18 -0
  213. package/dist/examples/bridge/solana-in.d.ts.map +1 -0
  214. package/dist/examples/bridge/solana-out.d.ts +18 -0
  215. package/dist/examples/bridge/solana-out.d.ts.map +1 -0
  216. package/dist/examples/bridge/solana-roundtrip.d.ts +21 -0
  217. package/dist/examples/bridge/solana-roundtrip.d.ts.map +1 -0
  218. package/dist/examples/bridge/status-tracking.d.ts +16 -0
  219. package/dist/examples/bridge/status-tracking.d.ts.map +1 -0
  220. package/dist/examples/bridge/supported-tokens.d.ts +14 -0
  221. package/dist/examples/bridge/supported-tokens.d.ts.map +1 -0
  222. package/dist/examples/bridge/test-debug-unwrap.d.ts +13 -0
  223. package/dist/examples/bridge/test-debug-unwrap.d.ts.map +1 -0
  224. package/dist/examples/bridge/test-unwrap-execution.d.ts +13 -0
  225. package/dist/examples/bridge/test-unwrap-execution.d.ts.map +1 -0
  226. package/dist/examples/bridge/test-wrap-debug.d.ts +13 -0
  227. package/dist/examples/bridge/test-wrap-debug.d.ts.map +1 -0
  228. package/dist/examples/bridge/test-wrap-execution.d.ts +13 -0
  229. package/dist/examples/bridge/test-wrap-execution.d.ts.map +1 -0
  230. package/dist/examples/bridge/test-wrap-roundtrip.d.ts +13 -0
  231. package/dist/examples/bridge/test-wrap-roundtrip.d.ts.map +1 -0
  232. package/dist/examples/bridge/transaction-status.d.ts +26 -0
  233. package/dist/examples/bridge/transaction-status.d.ts.map +1 -0
  234. package/dist/examples/bridge/wallet-balances.d.ts +24 -0
  235. package/dist/examples/bridge/wallet-balances.d.ts.map +1 -0
  236. package/dist/examples/bridge/wrap-discovery.d.ts +16 -0
  237. package/dist/examples/bridge/wrap-discovery.d.ts.map +1 -0
  238. package/dist/examples/bridge/wrap-fee-estimation.d.ts +16 -0
  239. package/dist/examples/bridge/wrap-fee-estimation.d.ts.map +1 -0
  240. package/dist/examples/bridge/wrap-unwrap.d.ts +18 -0
  241. package/dist/examples/bridge/wrap-unwrap.d.ts.map +1 -0
  242. package/dist/examples/bridge/wrap-utilities.d.ts +21 -0
  243. package/dist/examples/bridge/wrap-utilities.d.ts.map +1 -0
  244. package/dist/examples/calculations/calculation-methods-comprehensive.d.ts +24 -0
  245. package/dist/examples/calculations/calculation-methods-comprehensive.d.ts.map +1 -0
  246. package/dist/examples/calculations/external-calculations-demo.d.ts +23 -0
  247. package/dist/examples/calculations/external-calculations-demo.d.ts.map +1 -0
  248. package/dist/examples/calculations/local-calculations-demo.d.ts +24 -0
  249. package/dist/examples/calculations/local-calculations-demo.d.ts.map +1 -0
  250. package/dist/examples/calculations/pool-calculation-context.d.ts +19 -0
  251. package/dist/examples/calculations/pool-calculation-context.d.ts.map +1 -0
  252. package/dist/examples/chat/basic-chat.d.ts +17 -0
  253. package/dist/examples/chat/basic-chat.d.ts.map +1 -0
  254. package/dist/examples/chat/chat-admin-controls.d.ts +41 -0
  255. package/dist/examples/chat/chat-admin-controls.d.ts.map +1 -0
  256. package/dist/examples/chat/chat-demo.d.ts +25 -0
  257. package/dist/examples/chat/chat-demo.d.ts.map +1 -0
  258. package/dist/examples/chat/chat-engagement-stats.d.ts +44 -0
  259. package/dist/examples/chat/chat-engagement-stats.d.ts.map +1 -0
  260. package/dist/examples/chat/chat-lifecycle.d.ts +26 -0
  261. package/dist/examples/chat/chat-lifecycle.d.ts.map +1 -0
  262. package/dist/examples/chat/chat-message-management.d.ts +18 -0
  263. package/dist/examples/chat/chat-message-management.d.ts.map +1 -0
  264. package/dist/examples/chat/chat-pinning-workflow.d.ts +37 -0
  265. package/dist/examples/chat/chat-pinning-workflow.d.ts.map +1 -0
  266. package/dist/examples/chat/demo-pin-messages.d.ts +17 -0
  267. package/dist/examples/chat/demo-pin-messages.d.ts.map +1 -0
  268. package/dist/examples/chat/multi-user-chat-test.d.ts +19 -0
  269. package/dist/examples/chat/multi-user-chat-test.d.ts.map +1 -0
  270. package/dist/examples/chat/quick-reaction-test.d.ts +4 -0
  271. package/dist/examples/chat/quick-reaction-test.d.ts.map +1 -0
  272. package/dist/examples/chat/typing-indicators.d.ts +23 -0
  273. package/dist/examples/chat/typing-indicators.d.ts.map +1 -0
  274. package/dist/examples/chat/websocket-chat.d.ts +21 -0
  275. package/dist/examples/chat/websocket-chat.d.ts.map +1 -0
  276. package/dist/examples/comments/basic-comments.d.ts +19 -0
  277. package/dist/examples/comments/basic-comments.d.ts.map +1 -0
  278. package/dist/examples/comments/comments-demo.d.ts +34 -0
  279. package/dist/examples/comments/comments-demo.d.ts.map +1 -0
  280. package/dist/examples/comments/comments-lifecycle.d.ts +24 -0
  281. package/dist/examples/comments/comments-lifecycle.d.ts.map +1 -0
  282. package/dist/examples/comments/comments-update-workflow.d.ts +35 -0
  283. package/dist/examples/comments/comments-update-workflow.d.ts.map +1 -0
  284. package/dist/examples/content/content-categorization.d.ts +51 -0
  285. package/dist/examples/content/content-categorization.d.ts.map +1 -0
  286. package/dist/examples/content/content-publishing-workflow.d.ts +45 -0
  287. package/dist/examples/content/content-publishing-workflow.d.ts.map +1 -0
  288. package/dist/examples/content/content-versioning.d.ts +52 -0
  289. package/dist/examples/content/content-versioning.d.ts.map +1 -0
  290. package/dist/examples/content-flags/comprehensive-flag-workflow.d.ts +40 -0
  291. package/dist/examples/content-flags/comprehensive-flag-workflow.d.ts.map +1 -0
  292. package/dist/examples/content-flags/flag-management.d.ts +28 -0
  293. package/dist/examples/content-flags/flag-management.d.ts.map +1 -0
  294. package/dist/examples/content-reactions/advanced-reactions.d.ts +24 -0
  295. package/dist/examples/content-reactions/advanced-reactions.d.ts.map +1 -0
  296. package/dist/examples/content-reactions/basic-reactions.d.ts +21 -0
  297. package/dist/examples/content-reactions/basic-reactions.d.ts.map +1 -0
  298. package/dist/examples/content-reactions/comprehensive-reactions-workflow.d.ts +41 -0
  299. package/dist/examples/content-reactions/comprehensive-reactions-workflow.d.ts.map +1 -0
  300. package/dist/examples/content-reactions/content-reactions-advanced.d.ts +40 -0
  301. package/dist/examples/content-reactions/content-reactions-advanced.d.ts.map +1 -0
  302. package/dist/examples/core/authenticated-operations.d.ts +14 -0
  303. package/dist/examples/core/authenticated-operations.d.ts.map +1 -0
  304. package/dist/examples/core/complete-sdk-demo.d.ts +22 -0
  305. package/dist/examples/core/complete-sdk-demo.d.ts.map +1 -0
  306. package/dist/examples/core/image-uploads.d.ts +28 -0
  307. package/dist/examples/core/image-uploads.d.ts.map +1 -0
  308. package/dist/examples/core/privatekey-override-pattern.d.ts +16 -0
  309. package/dist/examples/core/privatekey-override-pattern.d.ts.map +1 -0
  310. package/dist/examples/core/read-only-operations.d.ts +16 -0
  311. package/dist/examples/core/read-only-operations.d.ts.map +1 -0
  312. package/dist/examples/core/session-auth-demo.d.ts +15 -0
  313. package/dist/examples/core/session-auth-demo.d.ts.map +1 -0
  314. package/dist/examples/core/session-auth-lifecycle.d.ts +19 -0
  315. package/dist/examples/core/session-auth-lifecycle.d.ts.map +1 -0
  316. package/dist/examples/core/test-pagination-fix.d.ts +14 -0
  317. package/dist/examples/core/test-pagination-fix.d.ts.map +1 -0
  318. package/dist/examples/core/token-refresh-utilities.d.ts +18 -0
  319. package/dist/examples/core/token-refresh-utilities.d.ts.map +1 -0
  320. package/dist/examples/core/token-validation.d.ts +18 -0
  321. package/dist/examples/core/token-validation.d.ts.map +1 -0
  322. package/dist/examples/core/wallet-management.d.ts +23 -0
  323. package/dist/examples/core/wallet-management.d.ts.map +1 -0
  324. package/dist/examples/debug/check-recorded-bridge-tx.d.ts +8 -0
  325. package/dist/examples/debug/check-recorded-bridge-tx.d.ts.map +1 -0
  326. package/dist/examples/debug/debug-comment.d.ts +2 -0
  327. package/dist/examples/debug/debug-comment.d.ts.map +1 -0
  328. package/dist/examples/debug/test-volume-data-bounds-prod.d.ts +15 -0
  329. package/dist/examples/debug/test-volume-data-bounds-prod.d.ts.map +1 -0
  330. package/dist/examples/debug/test-volume-data-bounds.d.ts +14 -0
  331. package/dist/examples/debug/test-volume-data-bounds.d.ts.map +1 -0
  332. package/dist/examples/debug/websocket-event-discovery.d.ts +26 -0
  333. package/dist/examples/debug/websocket-event-discovery.d.ts.map +1 -0
  334. package/dist/examples/debug/websocket-monitor.d.ts +15 -0
  335. package/dist/examples/debug/websocket-monitor.d.ts.map +1 -0
  336. package/dist/examples/debug-single-trade.d.ts +6 -0
  337. package/dist/examples/debug-single-trade.d.ts.map +1 -0
  338. package/dist/examples/demo-librarian.d.ts +18 -0
  339. package/dist/examples/demo-librarian.d.ts.map +1 -0
  340. package/dist/examples/demo-runner.d.ts +22 -0
  341. package/dist/examples/demo-runner.d.ts.map +1 -0
  342. package/dist/examples/dex/demo-roundtrip-liquidity.d.ts +16 -0
  343. package/dist/examples/dex/demo-roundtrip-liquidity.d.ts.map +1 -0
  344. package/dist/examples/dex/dex-impermanent-loss-analysis.d.ts +28 -0
  345. package/dist/examples/dex/dex-impermanent-loss-analysis.d.ts.map +1 -0
  346. package/dist/examples/dex/dex-liquidity-management-advanced.d.ts +27 -0
  347. package/dist/examples/dex/dex-liquidity-management-advanced.d.ts.map +1 -0
  348. package/dist/examples/dex/dex-multi-hop-swaps.d.ts +32 -0
  349. package/dist/examples/dex/dex-multi-hop-swaps.d.ts.map +1 -0
  350. package/dist/examples/dex/dex-pool-pricing.d.ts +20 -0
  351. package/dist/examples/dex/dex-pool-pricing.d.ts.map +1 -0
  352. package/dist/examples/dex/dex-quote-calculations.d.ts +21 -0
  353. package/dist/examples/dex/dex-quote-calculations.d.ts.map +1 -0
  354. package/dist/examples/dex/dex-seasons-leaderboard.d.ts +22 -0
  355. package/dist/examples/dex/dex-seasons-leaderboard.d.ts.map +1 -0
  356. package/dist/examples/dex/dex-slippage-protection.d.ts +28 -0
  357. package/dist/examples/dex/dex-slippage-protection.d.ts.map +1 -0
  358. package/dist/examples/dex/dex-tokens-discovery.d.ts +20 -0
  359. package/dist/examples/dex/dex-tokens-discovery.d.ts.map +1 -0
  360. package/dist/examples/dex/dex-volume-analytics.d.ts +19 -0
  361. package/dist/examples/dex/dex-volume-analytics.d.ts.map +1 -0
  362. package/dist/examples/dex/leaderboard.d.ts +12 -0
  363. package/dist/examples/dex/leaderboard.d.ts.map +1 -0
  364. package/dist/examples/dex/pool-discovery.d.ts +25 -0
  365. package/dist/examples/dex/pool-discovery.d.ts.map +1 -0
  366. package/dist/examples/dex/pools-with-pricing.d.ts +28 -0
  367. package/dist/examples/dex/pools-with-pricing.d.ts.map +1 -0
  368. package/dist/examples/dex/quote-comparison.d.ts +16 -0
  369. package/dist/examples/dex/quote-comparison.d.ts.map +1 -0
  370. package/dist/examples/dex/swap-user-assets-comprehensive.d.ts +20 -0
  371. package/dist/examples/dex/swap-user-assets-comprehensive.d.ts.map +1 -0
  372. package/dist/examples/dex/swap-workflow.d.ts +20 -0
  373. package/dist/examples/dex/swap-workflow.d.ts.map +1 -0
  374. package/dist/examples/dex/token-discovery.d.ts +27 -0
  375. package/dist/examples/dex/token-discovery.d.ts.map +1 -0
  376. package/dist/examples/dex/volume-summary.d.ts +12 -0
  377. package/dist/examples/dex/volume-summary.d.ts.map +1 -0
  378. package/dist/examples/error-handling/error-recovery-patterns.d.ts +42 -0
  379. package/dist/examples/error-handling/error-recovery-patterns.d.ts.map +1 -0
  380. package/dist/examples/error-handling/timeout-management.d.ts +43 -0
  381. package/dist/examples/error-handling/timeout-management.d.ts.map +1 -0
  382. package/dist/examples/events/event-aggregation-analysis.d.ts +40 -0
  383. package/dist/examples/events/event-aggregation-analysis.d.ts.map +1 -0
  384. package/dist/examples/events/event-emission-patterns.d.ts +35 -0
  385. package/dist/examples/events/event-emission-patterns.d.ts.map +1 -0
  386. package/dist/examples/events/subscription-management-advanced.d.ts +38 -0
  387. package/dist/examples/events/subscription-management-advanced.d.ts.map +1 -0
  388. package/dist/examples/fees/complete-fee-test.d.ts +13 -0
  389. package/dist/examples/fees/complete-fee-test.d.ts.map +1 -0
  390. package/dist/examples/fees/demo-fee-generation-and-collection.d.ts +27 -0
  391. package/dist/examples/fees/demo-fee-generation-and-collection.d.ts.map +1 -0
  392. package/dist/examples/fees/demo-fees-high-volume.d.ts +13 -0
  393. package/dist/examples/fees/demo-fees-high-volume.d.ts.map +1 -0
  394. package/dist/examples/fees/demo-multi-wallet-fee-generation.d.ts +13 -0
  395. package/dist/examples/fees/demo-multi-wallet-fee-generation.d.ts.map +1 -0
  396. package/dist/examples/fees/trade-and-collect-fees.d.ts +13 -0
  397. package/dist/examples/fees/trade-and-collect-fees.d.ts.map +1 -0
  398. package/dist/examples/galachain/bundler-transactions.d.ts +28 -0
  399. package/dist/examples/galachain/bundler-transactions.d.ts.map +1 -0
  400. package/dist/examples/galachain/galachain-token-resolution.d.ts +28 -0
  401. package/dist/examples/galachain/galachain-token-resolution.d.ts.map +1 -0
  402. package/dist/examples/galachain/galachain-tokens.d.ts +28 -0
  403. package/dist/examples/galachain/galachain-tokens.d.ts.map +1 -0
  404. package/dist/examples/galachain/galachain-transfers.d.ts +25 -0
  405. package/dist/examples/galachain/galachain-transfers.d.ts.map +1 -0
  406. package/dist/examples/global-feed-demo.d.ts +17 -0
  407. package/dist/examples/global-feed-demo.d.ts.map +1 -0
  408. package/dist/examples/global-feed-filtering-demo.d.ts +20 -0
  409. package/dist/examples/global-feed-filtering-demo.d.ts.map +1 -0
  410. package/dist/examples/launchpad/demo-socials.d.ts +16 -0
  411. package/dist/examples/launchpad/demo-socials.d.ts.map +1 -0
  412. package/dist/examples/launchpad/fetch-token-stats.d.ts +18 -0
  413. package/dist/examples/launchpad/fetch-token-stats.d.ts.map +1 -0
  414. package/dist/examples/launchpad/update-token-config.d.ts +17 -0
  415. package/dist/examples/launchpad/update-token-config.d.ts.map +1 -0
  416. package/dist/examples/liquidity/apr-calculator.d.ts +18 -0
  417. package/dist/examples/liquidity/apr-calculator.d.ts.map +1 -0
  418. package/dist/examples/liquidity/demo-bundler-operations.d.ts +15 -0
  419. package/dist/examples/liquidity/demo-bundler-operations.d.ts.map +1 -0
  420. package/dist/examples/liquidity/demo-fetch-all-positions.d.ts +2 -0
  421. package/dist/examples/liquidity/demo-fetch-all-positions.d.ts.map +1 -0
  422. package/dist/examples/liquidity/demo-position-direct.d.ts +14 -0
  423. package/dist/examples/liquidity/demo-position-direct.d.ts.map +1 -0
  424. package/dist/examples/liquidity/demo-positions-with-chunked-pricing.d.ts +26 -0
  425. package/dist/examples/liquidity/demo-positions-with-chunked-pricing.d.ts.map +1 -0
  426. package/dist/examples/liquidity/demo-roundtrip-remove.d.ts +21 -0
  427. package/dist/examples/liquidity/demo-roundtrip-remove.d.ts.map +1 -0
  428. package/dist/examples/liquidity/detailed.d.ts +21 -0
  429. package/dist/examples/liquidity/detailed.d.ts.map +1 -0
  430. package/dist/examples/liquidity/errors.d.ts +18 -0
  431. package/dist/examples/liquidity/errors.d.ts.map +1 -0
  432. package/dist/examples/liquidity/fee-collection.d.ts +22 -0
  433. package/dist/examples/liquidity/fee-collection.d.ts.map +1 -0
  434. package/dist/examples/liquidity/liquidity-position-details.d.ts +21 -0
  435. package/dist/examples/liquidity/liquidity-position-details.d.ts.map +1 -0
  436. package/dist/examples/liquidity/liquidity-removal-estimation.d.ts +19 -0
  437. package/dist/examples/liquidity/liquidity-removal-estimation.d.ts.map +1 -0
  438. package/dist/examples/liquidity/multi-position.d.ts +22 -0
  439. package/dist/examples/liquidity/multi-position.d.ts.map +1 -0
  440. package/dist/examples/liquidity/positions-cli.d.ts +41 -0
  441. package/dist/examples/liquidity/positions-cli.d.ts.map +1 -0
  442. package/dist/examples/liquidity/ticks.d.ts +18 -0
  443. package/dist/examples/liquidity/ticks.d.ts.map +1 -0
  444. package/dist/examples/locks/burn-tokens.d.ts +25 -0
  445. package/dist/examples/locks/burn-tokens.d.ts.map +1 -0
  446. package/dist/examples/locks/lock-unlock-workflow.d.ts +20 -0
  447. package/dist/examples/locks/lock-unlock-workflow.d.ts.map +1 -0
  448. package/dist/examples/messages/messages-lifecycle.d.ts +37 -0
  449. package/dist/examples/messages/messages-lifecycle.d.ts.map +1 -0
  450. package/dist/examples/messages/messages-pinning.d.ts +37 -0
  451. package/dist/examples/messages/messages-pinning.d.ts.map +1 -0
  452. package/dist/examples/moderators/claim-invite.d.ts +28 -0
  453. package/dist/examples/moderators/claim-invite.d.ts.map +1 -0
  454. package/dist/examples/moderators/invite-management.d.ts +30 -0
  455. package/dist/examples/moderators/invite-management.d.ts.map +1 -0
  456. package/dist/examples/moderators/moderated-tokens-portfolio.d.ts +18 -0
  457. package/dist/examples/moderators/moderated-tokens-portfolio.d.ts.map +1 -0
  458. package/dist/examples/monitoring/demo-stream-events.d.ts +17 -0
  459. package/dist/examples/monitoring/demo-stream-events.d.ts.map +1 -0
  460. package/dist/examples/monitoring/demo-watch-pools.d.ts +18 -0
  461. package/dist/examples/monitoring/demo-watch-pools.d.ts.map +1 -0
  462. package/dist/examples/monitoring/demo-watch-tokens.d.ts +18 -0
  463. package/dist/examples/monitoring/demo-watch-tokens.d.ts.map +1 -0
  464. package/dist/examples/monitoring/fees-collection-e2e.d.ts +36 -0
  465. package/dist/examples/monitoring/fees-collection-e2e.d.ts.map +1 -0
  466. package/dist/examples/monitoring/fees-collection-guaranteed.d.ts +49 -0
  467. package/dist/examples/monitoring/fees-collection-guaranteed.d.ts.map +1 -0
  468. package/dist/examples/monitoring/liquidity-e2e-test.d.ts +15 -0
  469. package/dist/examples/monitoring/liquidity-e2e-test.d.ts.map +1 -0
  470. package/dist/examples/monitoring/liquidity-monitor.d.ts +17 -0
  471. package/dist/examples/monitoring/liquidity-monitor.d.ts.map +1 -0
  472. package/dist/examples/monitoring/pool-creation-integration.d.ts +27 -0
  473. package/dist/examples/monitoring/pool-creation-integration.d.ts.map +1 -0
  474. package/dist/examples/monitoring/pool-liquidity-tracker.d.ts +15 -0
  475. package/dist/examples/monitoring/pool-liquidity-tracker.d.ts.map +1 -0
  476. package/dist/examples/monitoring/subscribe-liquidity-added.d.ts +30 -0
  477. package/dist/examples/monitoring/subscribe-liquidity-added.d.ts.map +1 -0
  478. package/dist/examples/monitoring/subscribe-liquidity-removed.d.ts +30 -0
  479. package/dist/examples/monitoring/subscribe-liquidity-removed.d.ts.map +1 -0
  480. package/dist/examples/monitoring/subscribe-pool-creations.d.ts +29 -0
  481. package/dist/examples/monitoring/subscribe-pool-creations.d.ts.map +1 -0
  482. package/dist/examples/monitoring/subscribe-token-creations.d.ts +21 -0
  483. package/dist/examples/monitoring/subscribe-token-creations.d.ts.map +1 -0
  484. package/dist/examples/monitoring/token-creation-integration.d.ts +32 -0
  485. package/dist/examples/monitoring/token-creation-integration.d.ts.map +1 -0
  486. package/dist/examples/monitoring/websocket-event-handlers.d.ts +22 -0
  487. package/dist/examples/monitoring/websocket-event-handlers.d.ts.map +1 -0
  488. package/dist/examples/nft/demo-collection-management.d.ts +13 -0
  489. package/dist/examples/nft/demo-collection-management.d.ts.map +1 -0
  490. package/dist/examples/nft/demo-fee-calculations.d.ts +14 -0
  491. package/dist/examples/nft/demo-fee-calculations.d.ts.map +1 -0
  492. package/dist/examples/nft/demo-minting.d.ts +13 -0
  493. package/dist/examples/nft/demo-minting.d.ts.map +1 -0
  494. package/dist/examples/nft/demo-portfolio-query.d.ts +14 -0
  495. package/dist/examples/nft/demo-portfolio-query.d.ts.map +1 -0
  496. package/dist/examples/nft/nft-collection-lifecycle.d.ts +22 -0
  497. package/dist/examples/nft/nft-collection-lifecycle.d.ts.map +1 -0
  498. package/dist/examples/nft/nft-data-queries.d.ts +22 -0
  499. package/dist/examples/nft/nft-data-queries.d.ts.map +1 -0
  500. package/dist/examples/nft/nft-fee-estimation.d.ts +23 -0
  501. package/dist/examples/nft/nft-fee-estimation.d.ts.map +1 -0
  502. package/dist/examples/nft/nft-token-creation.d.ts +22 -0
  503. package/dist/examples/nft/nft-token-creation.d.ts.map +1 -0
  504. package/dist/examples/nft/nft-utilities.d.ts +23 -0
  505. package/dist/examples/nft/nft-utilities.d.ts.map +1 -0
  506. package/dist/examples/orchestrator-master.d.ts +22 -0
  507. package/dist/examples/orchestrator-master.d.ts.map +1 -0
  508. package/dist/examples/orchestrator-tasks.d.ts +38 -0
  509. package/dist/examples/orchestrator-tasks.d.ts.map +1 -0
  510. package/dist/examples/overseers/claim-invite.d.ts +31 -0
  511. package/dist/examples/overseers/claim-invite.d.ts.map +1 -0
  512. package/dist/examples/overseers/demo-list-users.d.ts +19 -0
  513. package/dist/examples/overseers/demo-list-users.d.ts.map +1 -0
  514. package/dist/examples/overseers/direct-promotion.d.ts +39 -0
  515. package/dist/examples/overseers/direct-promotion.d.ts.map +1 -0
  516. package/dist/examples/overseers/invite-management.d.ts +38 -0
  517. package/dist/examples/overseers/invite-management.d.ts.map +1 -0
  518. package/dist/examples/overseers/restricted-names-management.d.ts +27 -0
  519. package/dist/examples/overseers/restricted-names-management.d.ts.map +1 -0
  520. package/dist/examples/performance/caching-strategies-advanced.d.ts +28 -0
  521. package/dist/examples/performance/caching-strategies-advanced.d.ts.map +1 -0
  522. package/dist/examples/performance/performance-optimization-patterns.d.ts +28 -0
  523. package/dist/examples/performance/performance-optimization-patterns.d.ts.map +1 -0
  524. package/dist/examples/persistence/data-backup-recovery.d.ts +119 -0
  525. package/dist/examples/persistence/data-backup-recovery.d.ts.map +1 -0
  526. package/dist/examples/persistence/local-storage-patterns.d.ts +86 -0
  527. package/dist/examples/persistence/local-storage-patterns.d.ts.map +1 -0
  528. package/dist/examples/queries/advanced-sorting.d.ts +28 -0
  529. package/dist/examples/queries/advanced-sorting.d.ts.map +1 -0
  530. package/dist/examples/queries/complex-filtering.d.ts +27 -0
  531. package/dist/examples/queries/complex-filtering.d.ts.map +1 -0
  532. package/dist/examples/security/security-audit-trail.d.ts +42 -0
  533. package/dist/examples/security/security-audit-trail.d.ts.map +1 -0
  534. package/dist/examples/security/security-content-moderation-advanced.d.ts +42 -0
  535. package/dist/examples/security/security-content-moderation-advanced.d.ts.map +1 -0
  536. package/dist/examples/security/security-token-safety-checks.d.ts +41 -0
  537. package/dist/examples/security/security-token-safety-checks.d.ts.map +1 -0
  538. package/dist/examples/security/security-user-restrictions-advanced.d.ts +42 -0
  539. package/dist/examples/security/security-user-restrictions-advanced.d.ts.map +1 -0
  540. package/dist/examples/site-config-demo.d.ts +20 -0
  541. package/dist/examples/site-config-demo.d.ts.map +1 -0
  542. package/dist/examples/streaming/admin-controls.d.ts +30 -0
  543. package/dist/examples/streaming/admin-controls.d.ts.map +1 -0
  544. package/dist/examples/streaming/advanced-stream-demo.d.ts +28 -0
  545. package/dist/examples/streaming/advanced-stream-demo.d.ts.map +1 -0
  546. package/dist/examples/streaming/basic-stream.d.ts +17 -0
  547. package/dist/examples/streaming/basic-stream.d.ts.map +1 -0
  548. package/dist/examples/streaming/demo-countdown.d.ts +16 -0
  549. package/dist/examples/streaming/demo-countdown.d.ts.map +1 -0
  550. package/dist/examples/streaming/demo-get-stream-credentials.d.ts +29 -0
  551. package/dist/examples/streaming/demo-get-stream-credentials.d.ts.map +1 -0
  552. package/dist/examples/streaming/demo-platform-config.d.ts +20 -0
  553. package/dist/examples/streaming/demo-platform-config.d.ts.map +1 -0
  554. package/dist/examples/streaming/engagement-stats.d.ts +25 -0
  555. package/dist/examples/streaming/engagement-stats.d.ts.map +1 -0
  556. package/dist/examples/streaming/recordings.d.ts +16 -0
  557. package/dist/examples/streaming/recordings.d.ts.map +1 -0
  558. package/dist/examples/streaming/simulcast.d.ts +19 -0
  559. package/dist/examples/streaming/simulcast.d.ts.map +1 -0
  560. package/dist/examples/streaming/stream-access-control.d.ts +30 -0
  561. package/dist/examples/streaming/stream-access-control.d.ts.map +1 -0
  562. package/dist/examples/streaming/stream-control.d.ts +25 -0
  563. package/dist/examples/streaming/stream-control.d.ts.map +1 -0
  564. package/dist/examples/streaming/stream-countdown.d.ts +31 -0
  565. package/dist/examples/streaming/stream-countdown.d.ts.map +1 -0
  566. package/dist/examples/streaming/stream-enable-disable.d.ts +31 -0
  567. package/dist/examples/streaming/stream-enable-disable.d.ts.map +1 -0
  568. package/dist/examples/streaming/stream-key-management.d.ts +21 -0
  569. package/dist/examples/streaming/stream-key-management.d.ts.map +1 -0
  570. package/dist/examples/streaming/stream-recording-management.d.ts +29 -0
  571. package/dist/examples/streaming/stream-recording-management.d.ts.map +1 -0
  572. package/dist/examples/streaming/stream-simulcast-multi-platform.d.ts +38 -0
  573. package/dist/examples/streaming/stream-simulcast-multi-platform.d.ts.map +1 -0
  574. package/dist/examples/streaming/stream-viewer-analytics.d.ts +43 -0
  575. package/dist/examples/streaming/stream-viewer-analytics.d.ts.map +1 -0
  576. package/dist/examples/streaming/streaming-lifecycle.d.ts +26 -0
  577. package/dist/examples/streaming/streaming-lifecycle.d.ts.map +1 -0
  578. package/dist/examples/streaming-premium/stream-monetization-setup.d.ts +47 -0
  579. package/dist/examples/streaming-premium/stream-monetization-setup.d.ts.map +1 -0
  580. package/dist/examples/streaming-premium/stream-revenue-analytics.d.ts +56 -0
  581. package/dist/examples/streaming-premium/stream-revenue-analytics.d.ts.map +1 -0
  582. package/dist/examples/streaming-premium/stream-vip-management.d.ts +56 -0
  583. package/dist/examples/streaming-premium/stream-vip-management.d.ts.map +1 -0
  584. package/dist/examples/swap-monitoring/arbitrage-monitor.d.ts +20 -0
  585. package/dist/examples/swap-monitoring/arbitrage-monitor.d.ts.map +1 -0
  586. package/dist/examples/swap-monitoring/e2e-trading-demo.d.ts +50 -0
  587. package/dist/examples/swap-monitoring/e2e-trading-demo.d.ts.map +1 -0
  588. package/dist/examples/swap-monitoring/health-monitor.d.ts +10 -0
  589. package/dist/examples/swap-monitoring/health-monitor.d.ts.map +1 -0
  590. package/dist/examples/swap-monitoring/volume-monitor.d.ts +20 -0
  591. package/dist/examples/swap-monitoring/volume-monitor.d.ts.map +1 -0
  592. package/dist/examples/testing/demo-test-runner.d.ts +33 -0
  593. package/dist/examples/testing/demo-test-runner.d.ts.map +1 -0
  594. package/dist/examples/testing/error-classifier.d.ts +23 -0
  595. package/dist/examples/testing/error-classifier.d.ts.map +1 -0
  596. package/dist/examples/testing/index.d.ts +14 -0
  597. package/dist/examples/testing/index.d.ts.map +1 -0
  598. package/dist/examples/testing/memory-manager.d.ts +31 -0
  599. package/dist/examples/testing/memory-manager.d.ts.map +1 -0
  600. package/dist/examples/testing/report-generator.d.ts +31 -0
  601. package/dist/examples/testing/report-generator.d.ts.map +1 -0
  602. package/dist/examples/testing/test-result-types.d.ts +158 -0
  603. package/dist/examples/testing/test-result-types.d.ts.map +1 -0
  604. package/dist/examples/token-bans/token-ban-management.d.ts +32 -0
  605. package/dist/examples/token-bans/token-ban-management.d.ts.map +1 -0
  606. package/dist/examples/token-creation/token-launch-complete.d.ts +20 -0
  607. package/dist/examples/token-creation/token-launch-complete.d.ts.map +1 -0
  608. package/dist/examples/token-creation/token-validation-comprehensive.d.ts +22 -0
  609. package/dist/examples/token-creation/token-validation-comprehensive.d.ts.map +1 -0
  610. package/dist/examples/token-info/token-name-resolution.d.ts +30 -0
  611. package/dist/examples/token-info/token-name-resolution.d.ts.map +1 -0
  612. package/dist/examples/token-info/token-operations-comprehensive.d.ts +22 -0
  613. package/dist/examples/token-info/token-operations-comprehensive.d.ts.map +1 -0
  614. package/dist/examples/token-metadata/token-description-versioning.d.ts +33 -0
  615. package/dist/examples/token-metadata/token-description-versioning.d.ts.map +1 -0
  616. package/dist/examples/token-metadata/token-image-management.d.ts +34 -0
  617. package/dist/examples/token-metadata/token-image-management.d.ts.map +1 -0
  618. package/dist/examples/token-metadata/token-social-links-management.d.ts +34 -0
  619. package/dist/examples/token-metadata/token-social-links-management.d.ts.map +1 -0
  620. package/dist/examples/trading/buy-sell-aliases.d.ts +20 -0
  621. package/dist/examples/trading/buy-sell-aliases.d.ts.map +1 -0
  622. package/dist/examples/trading/volume-data-demo.d.ts +20 -0
  623. package/dist/examples/trading/volume-data-demo.d.ts.map +1 -0
  624. package/dist/examples/trading-advanced/dollar-cost-averaging.d.ts +35 -0
  625. package/dist/examples/trading-advanced/dollar-cost-averaging.d.ts.map +1 -0
  626. package/dist/examples/trading-advanced/limit-orders-advanced.d.ts +34 -0
  627. package/dist/examples/trading-advanced/limit-orders-advanced.d.ts.map +1 -0
  628. package/dist/examples/trading-advanced/stop-loss-orders.d.ts +34 -0
  629. package/dist/examples/trading-advanced/stop-loss-orders.d.ts.map +1 -0
  630. package/dist/examples/trading-advanced/trading-history-analysis.d.ts +35 -0
  631. package/dist/examples/trading-advanced/trading-history-analysis.d.ts.map +1 -0
  632. package/dist/examples/users/balance-queries.d.ts +28 -0
  633. package/dist/examples/users/balance-queries.d.ts.map +1 -0
  634. package/dist/examples/users/fetch-user-balances.d.ts +19 -0
  635. package/dist/examples/users/fetch-user-balances.d.ts.map +1 -0
  636. package/dist/examples/users/fetch-user-report.d.ts +21 -0
  637. package/dist/examples/users/fetch-user-report.d.ts.map +1 -0
  638. package/dist/examples/users/profile-images.d.ts +24 -0
  639. package/dist/examples/users/profile-images.d.ts.map +1 -0
  640. package/dist/examples/users/profile-management.d.ts +22 -0
  641. package/dist/examples/users/profile-management.d.ts.map +1 -0
  642. package/dist/examples/users/referrals-comprehensive.d.ts +26 -0
  643. package/dist/examples/users/referrals-comprehensive.d.ts.map +1 -0
  644. package/dist/examples/users/wallet-balances-external.d.ts +28 -0
  645. package/dist/examples/users/wallet-balances-external.d.ts.map +1 -0
  646. package/dist/examples/utilities/account.d.ts +19 -0
  647. package/dist/examples/utilities/account.d.ts.map +1 -0
  648. package/dist/examples/utilities/balance.d.ts +5 -0
  649. package/dist/examples/utilities/balance.d.ts.map +1 -0
  650. package/dist/examples/utilities/balances.d.ts +7 -0
  651. package/dist/examples/utilities/balances.d.ts.map +1 -0
  652. package/dist/examples/utilities/demo-cache.d.ts +13 -0
  653. package/dist/examples/utilities/demo-cache.d.ts.map +1 -0
  654. package/dist/examples/utilities/demo-token-supply.d.ts +14 -0
  655. package/dist/examples/utilities/demo-token-supply.d.ts.map +1 -0
  656. package/dist/examples/utilities/key-derivation.d.ts +12 -0
  657. package/dist/examples/utilities/key-derivation.d.ts.map +1 -0
  658. package/dist/examples/utilities/multi-token-portfolio.d.ts +18 -0
  659. package/dist/examples/utilities/multi-token-portfolio.d.ts.map +1 -0
  660. package/dist/examples/utilities/pool-discovery-advanced.d.ts +36 -0
  661. package/dist/examples/utilities/pool-discovery-advanced.d.ts.map +1 -0
  662. package/dist/examples/utilities/pool-pair-analysis.d.ts +37 -0
  663. package/dist/examples/utilities/pool-pair-analysis.d.ts.map +1 -0
  664. package/dist/examples/utilities/price-history.d.ts +22 -0
  665. package/dist/examples/utilities/price-history.d.ts.map +1 -0
  666. package/dist/examples/utilities/referrals.d.ts +21 -0
  667. package/dist/examples/utilities/referrals.d.ts.map +1 -0
  668. package/dist/examples/utilities/token-classification.d.ts +38 -0
  669. package/dist/examples/utilities/token-classification.d.ts.map +1 -0
  670. package/dist/examples/utilities/token-discovery.d.ts +26 -0
  671. package/dist/examples/utilities/token-discovery.d.ts.map +1 -0
  672. package/dist/examples/utilities/token-metadata-advanced.d.ts +37 -0
  673. package/dist/examples/utilities/token-metadata-advanced.d.ts.map +1 -0
  674. package/dist/examples/utilities/token-validation-complete.d.ts +41 -0
  675. package/dist/examples/utilities/token-validation-complete.d.ts.map +1 -0
  676. package/dist/examples/utilities/trade-history.d.ts +19 -0
  677. package/dist/examples/utilities/trade-history.d.ts.map +1 -0
  678. package/dist/examples/utilities/transfers.d.ts +29 -0
  679. package/dist/examples/utilities/transfers.d.ts.map +1 -0
  680. package/dist/examples/utilities/validation-and-error-handling.d.ts +27 -0
  681. package/dist/examples/utilities/validation-and-error-handling.d.ts.map +1 -0
  682. package/dist/examples/utilities/wrappable-tokens.d.ts +27 -0
  683. package/dist/examples/utilities/wrappable-tokens.d.ts.map +1 -0
  684. package/dist/examples/utility/auth-utilities.d.ts +30 -0
  685. package/dist/examples/utility/auth-utilities.d.ts.map +1 -0
  686. package/dist/examples/utility/pool-utilities.d.ts +29 -0
  687. package/dist/examples/utility/pool-utilities.d.ts.map +1 -0
  688. package/dist/examples/utility/sdk-configuration.d.ts +29 -0
  689. package/dist/examples/utility/sdk-configuration.d.ts.map +1 -0
  690. package/dist/examples/utility/wallet-management-advanced.d.ts +32 -0
  691. package/dist/examples/utility/wallet-management-advanced.d.ts.map +1 -0
  692. package/dist/examples/utils/auth-bootstrap.d.ts +123 -0
  693. package/dist/examples/utils/auth-bootstrap.d.ts.map +1 -0
  694. package/dist/examples/utils/balance-checking.d.ts +158 -0
  695. package/dist/examples/utils/balance-checking.d.ts.map +1 -0
  696. package/dist/examples/utils/bridge-formatters.d.ts +188 -0
  697. package/dist/examples/utils/bridge-formatters.d.ts.map +1 -0
  698. package/dist/examples/utils/bridge-setup.d.ts +235 -0
  699. package/dist/examples/utils/bridge-setup.d.ts.map +1 -0
  700. package/dist/examples/utils/bridge-transaction-logger.d.ts +42 -0
  701. package/dist/examples/utils/bridge-transaction-logger.d.ts.map +1 -0
  702. package/dist/examples/utils/cli-input.d.ts +41 -0
  703. package/dist/examples/utils/cli-input.d.ts.map +1 -0
  704. package/dist/examples/utils/demo-config.d.ts +155 -0
  705. package/dist/examples/utils/demo-config.d.ts.map +1 -0
  706. package/dist/examples/utils/demo-registry.d.ts +155 -0
  707. package/dist/examples/utils/demo-registry.d.ts.map +1 -0
  708. package/dist/examples/utils/error-handler.d.ts +85 -0
  709. package/dist/examples/utils/error-handler.d.ts.map +1 -0
  710. package/dist/examples/utils/formatting.d.ts +195 -0
  711. package/dist/examples/utils/formatting.d.ts.map +1 -0
  712. package/dist/examples/utils/get-environment.d.ts +17 -0
  713. package/dist/examples/utils/get-environment.d.ts.map +1 -0
  714. package/dist/examples/utils/index.d.ts +44 -0
  715. package/dist/examples/utils/index.d.ts.map +1 -0
  716. package/dist/examples/utils/indexing.d.ts +48 -0
  717. package/dist/examples/utils/indexing.d.ts.map +1 -0
  718. package/dist/examples/utils/load-env.d.ts +90 -0
  719. package/dist/examples/utils/load-env.d.ts.map +1 -0
  720. package/dist/examples/utils/pool-helpers.d.ts +226 -0
  721. package/dist/examples/utils/pool-helpers.d.ts.map +1 -0
  722. package/dist/examples/utils/punchlist.d.ts +104 -0
  723. package/dist/examples/utils/punchlist.d.ts.map +1 -0
  724. package/dist/examples/utils/sdk-setup.d.ts +423 -0
  725. package/dist/examples/utils/sdk-setup.d.ts.map +1 -0
  726. package/dist/examples/utils/suppress-logging.d.ts +11 -0
  727. package/dist/examples/utils/suppress-logging.d.ts.map +1 -0
  728. package/dist/examples/utils/token-naming.d.ts +117 -0
  729. package/dist/examples/utils/token-naming.d.ts.map +1 -0
  730. package/dist/examples/utils/trade-helpers.d.ts +195 -0
  731. package/dist/examples/utils/trade-helpers.d.ts.map +1 -0
  732. package/dist/examples/utils/transaction-helpers.d.ts +92 -0
  733. package/dist/examples/utils/transaction-helpers.d.ts.map +1 -0
  734. package/dist/examples/wallet/wallet-initialization-complete.d.ts +31 -0
  735. package/dist/examples/wallet/wallet-initialization-complete.d.ts.map +1 -0
  736. package/dist/examples/wallet/wallet-key-rotation.d.ts +28 -0
  737. package/dist/examples/wallet/wallet-key-rotation.d.ts.map +1 -0
  738. package/dist/examples/wallet/wallet-recovery-patterns.d.ts +29 -0
  739. package/dist/examples/wallet/wallet-recovery-patterns.d.ts.map +1 -0
  740. package/dist/examples/wallet/wallet-signature-operations.d.ts +28 -0
  741. package/dist/examples/wallet/wallet-signature-operations.d.ts.map +1 -0
  742. package/dist/examples/wallet-tracking/wallet-balance-monitoring.d.ts +21 -0
  743. package/dist/examples/wallet-tracking/wallet-balance-monitoring.d.ts.map +1 -0
  744. package/dist/examples/wallet-tracking/wallet-portfolio-alerts.d.ts +21 -0
  745. package/dist/examples/wallet-tracking/wallet-portfolio-alerts.d.ts.map +1 -0
  746. package/dist/examples/wallet-tracking/wallet-transaction-tracking.d.ts +21 -0
  747. package/dist/examples/wallet-tracking/wallet-transaction-tracking.d.ts.map +1 -0
  748. package/dist/examples/websocket/websocket-chat-advanced.d.ts +26 -0
  749. package/dist/examples/websocket/websocket-chat-advanced.d.ts.map +1 -0
  750. package/dist/examples/websocket/websocket-chat-events-detailed.d.ts +28 -0
  751. package/dist/examples/websocket/websocket-chat-events-detailed.d.ts.map +1 -0
  752. package/dist/examples/websocket/websocket-chat-events.d.ts +26 -0
  753. package/dist/examples/websocket/websocket-chat-events.d.ts.map +1 -0
  754. package/dist/examples/websocket/websocket-combined-events.d.ts +28 -0
  755. package/dist/examples/websocket/websocket-combined-events.d.ts.map +1 -0
  756. package/dist/examples/websocket/websocket-comprehensive.d.ts +25 -0
  757. package/dist/examples/websocket/websocket-comprehensive.d.ts.map +1 -0
  758. package/dist/examples/websocket/websocket-connected-clients.d.ts +30 -0
  759. package/dist/examples/websocket/websocket-connected-clients.d.ts.map +1 -0
  760. package/dist/examples/websocket/websocket-connection-management.d.ts +28 -0
  761. package/dist/examples/websocket/websocket-connection-management.d.ts.map +1 -0
  762. package/dist/examples/websocket/websocket-content-events.d.ts +28 -0
  763. package/dist/examples/websocket/websocket-content-events.d.ts.map +1 -0
  764. package/dist/examples/websocket/websocket-core-events.d.ts +27 -0
  765. package/dist/examples/websocket/websocket-core-events.d.ts.map +1 -0
  766. package/dist/examples/websocket/websocket-dex-events.d.ts +40 -0
  767. package/dist/examples/websocket/websocket-dex-events.d.ts.map +1 -0
  768. package/dist/examples/websocket/websocket-dex-pools.d.ts +23 -0
  769. package/dist/examples/websocket/websocket-dex-pools.d.ts.map +1 -0
  770. package/dist/examples/websocket/websocket-download-recording.d.ts +26 -0
  771. package/dist/examples/websocket/websocket-download-recording.d.ts.map +1 -0
  772. package/dist/examples/websocket/websocket-interactions.d.ts +25 -0
  773. package/dist/examples/websocket/websocket-interactions.d.ts.map +1 -0
  774. package/dist/examples/websocket/websocket-moderation-events.d.ts +26 -0
  775. package/dist/examples/websocket/websocket-moderation-events.d.ts.map +1 -0
  776. package/dist/examples/websocket/websocket-recording-events.d.ts +24 -0
  777. package/dist/examples/websocket/websocket-recording-events.d.ts.map +1 -0
  778. package/dist/examples/websocket/websocket-room-events.d.ts +27 -0
  779. package/dist/examples/websocket/websocket-room-events.d.ts.map +1 -0
  780. package/dist/examples/websocket/websocket-room-management.d.ts +27 -0
  781. package/dist/examples/websocket/websocket-room-management.d.ts.map +1 -0
  782. package/dist/examples/websocket/websocket-simulcast-events.d.ts +26 -0
  783. package/dist/examples/websocket/websocket-simulcast-events.d.ts.map +1 -0
  784. package/dist/examples/websocket/websocket-stream-auth.d.ts +23 -0
  785. package/dist/examples/websocket/websocket-stream-auth.d.ts.map +1 -0
  786. package/dist/examples/websocket/websocket-stream-countdown.d.ts +38 -0
  787. package/dist/examples/websocket/websocket-stream-countdown.d.ts.map +1 -0
  788. package/dist/examples/websocket/websocket-stream-events.d.ts +26 -0
  789. package/dist/examples/websocket/websocket-stream-events.d.ts.map +1 -0
  790. package/dist/examples/websocket/websocket-stream-status.d.ts +39 -0
  791. package/dist/examples/websocket/websocket-stream-status.d.ts.map +1 -0
  792. package/dist/examples/websocket/websocket-subscription-management.d.ts +27 -0
  793. package/dist/examples/websocket/websocket-subscription-management.d.ts.map +1 -0
  794. package/dist/examples/websocket/websocket-token-creation-events.d.ts +22 -0
  795. package/dist/examples/websocket/websocket-token-creation-events.d.ts.map +1 -0
  796. package/dist/examples/websocket/websocket-token-events.d.ts +24 -0
  797. package/dist/examples/websocket/websocket-token-events.d.ts.map +1 -0
  798. package/dist/examples/websocket/websocket-token-subscription.d.ts +26 -0
  799. package/dist/examples/websocket/websocket-token-subscription.d.ts.map +1 -0
  800. package/dist/examples/websocket/websocket-token-viewers.d.ts +29 -0
  801. package/dist/examples/websocket/websocket-token-viewers.d.ts.map +1 -0
  802. package/dist/examples/websocket/websocket-unsubscribe.d.ts +25 -0
  803. package/dist/examples/websocket/websocket-unsubscribe.d.ts.map +1 -0
  804. package/dist/examples/websocket/websocket-user-events.d.ts +40 -0
  805. package/dist/examples/websocket/websocket-user-events.d.ts.map +1 -0
  806. package/dist/examples/websocket/websocket-user-presence.d.ts +29 -0
  807. package/dist/examples/websocket/websocket-user-presence.d.ts.map +1 -0
  808. package/dist/examples/websocket/websocket-viewer-analytics.d.ts +38 -0
  809. package/dist/examples/websocket/websocket-viewer-analytics.d.ts.map +1 -0
  810. package/dist/examples/wrap/wrap-status-tracking.d.ts +19 -0
  811. package/dist/examples/wrap/wrap-status-tracking.d.ts.map +1 -0
  812. package/dist/examples/wrap/wrap-token-discovery.d.ts +20 -0
  813. package/dist/examples/wrap/wrap-token-discovery.d.ts.map +1 -0
  814. package/dist/helpers/sdk.d.ts +87 -0
  815. package/dist/helpers/sdk.d.ts.map +1 -0
  816. package/dist/helpers/wallet.d.ts +151 -0
  817. package/dist/helpers/wallet.d.ts.map +1 -0
  818. package/dist/index.browser.d.ts +149 -0
  819. package/dist/index.browser.d.ts.map +1 -0
  820. package/dist/index.browser.esm.js +1 -0
  821. package/dist/index.cjs +1 -0
  822. package/dist/index.d.ts +6 -115
  823. package/dist/index.d.ts.map +1 -1
  824. package/dist/index.esm.js +1 -1
  825. package/dist/index.js +1 -1
  826. package/dist/index.node.d.ts +13 -0
  827. package/dist/index.node.d.ts.map +1 -0
  828. package/dist/native.cjs +1 -0
  829. package/dist/native.d.ts +22 -0
  830. package/dist/native.d.ts.map +1 -0
  831. package/dist/native.esm.js +1 -0
  832. package/dist/polyfills/file-global.d.ts +12 -0
  833. package/dist/polyfills/file-global.d.ts.map +1 -0
  834. package/dist/react/WalletContext.d.ts +60 -0
  835. package/dist/react/WalletContext.d.ts.map +1 -0
  836. package/dist/react/index.d.ts +65 -0
  837. package/dist/react/index.d.ts.map +1 -0
  838. package/dist/react/types.d.ts +76 -0
  839. package/dist/react/types.d.ts.map +1 -0
  840. package/dist/react/useWallet.d.ts +123 -0
  841. package/dist/react/useWallet.d.ts.map +1 -0
  842. package/dist/react/useWalletConnection.d.ts +89 -0
  843. package/dist/react/useWalletConnection.d.ts.map +1 -0
  844. package/dist/react/useWalletDetection.d.ts +81 -0
  845. package/dist/react/useWalletDetection.d.ts.map +1 -0
  846. package/dist/react.cjs +1 -0
  847. package/dist/react.esm.js +1 -0
  848. package/dist/schemas/files.d.ts +83 -0
  849. package/dist/schemas/files.d.ts.map +1 -0
  850. package/dist/schemas/index.d.ts +83 -0
  851. package/dist/schemas/index.d.ts.map +1 -0
  852. package/dist/schemas/launchpad.d.ts +135 -0
  853. package/dist/schemas/launchpad.d.ts.map +1 -0
  854. package/dist/schemas/pagination.d.ts +107 -0
  855. package/dist/schemas/pagination.d.ts.map +1 -0
  856. package/dist/schemas/primitives.d.ts +142 -0
  857. package/dist/schemas/primitives.d.ts.map +1 -0
  858. package/dist/schemas/trade.d.ts +140 -0
  859. package/dist/schemas/trade.d.ts.map +1 -0
  860. package/dist/schemas/user.d.ts +99 -0
  861. package/dist/schemas/user.d.ts.map +1 -0
  862. package/dist/schemas/validators.d.ts +332 -0
  863. package/dist/schemas/validators.d.ts.map +1 -0
  864. package/dist/scripts/derive-public-key-from-private-key.d.ts +8 -0
  865. package/dist/scripts/derive-public-key-from-private-key.d.ts.map +1 -0
  866. package/dist/scripts/eslint-fixer.d.ts +7 -0
  867. package/dist/scripts/eslint-fixer.d.ts.map +1 -0
  868. package/dist/scripts/final-fixer.d.ts +7 -0
  869. package/dist/scripts/final-fixer.d.ts.map +1 -0
  870. package/dist/scripts/fix-all-remaining-boolean.d.ts +7 -0
  871. package/dist/scripts/fix-all-remaining-boolean.d.ts.map +1 -0
  872. package/dist/scripts/fix-boolean-expressions-advanced.d.ts +7 -0
  873. package/dist/scripts/fix-boolean-expressions-advanced.d.ts.map +1 -0
  874. package/dist/scripts/fix-boolean-expressions-ast.d.ts +9 -0
  875. package/dist/scripts/fix-boolean-expressions-ast.d.ts.map +1 -0
  876. package/dist/scripts/fix-boolean-expressions-auto.d.ts +7 -0
  877. package/dist/scripts/fix-boolean-expressions-auto.d.ts.map +1 -0
  878. package/dist/scripts/fix-final-aggressive.d.ts +6 -0
  879. package/dist/scripts/fix-final-aggressive.d.ts.map +1 -0
  880. package/dist/scripts/fix-final-boolean.d.ts +7 -0
  881. package/dist/scripts/fix-final-boolean.d.ts.map +1 -0
  882. package/dist/scripts/fix-remaining-boolean.d.ts +7 -0
  883. package/dist/scripts/fix-remaining-boolean.d.ts.map +1 -0
  884. package/dist/scripts/fix-strict-boolean-comprehensive.d.ts +3 -0
  885. package/dist/scripts/fix-strict-boolean-comprehensive.d.ts.map +1 -0
  886. package/dist/scripts/fix-strict-boolean-expressions.d.ts +2 -0
  887. package/dist/scripts/fix-strict-boolean-expressions.d.ts.map +1 -0
  888. package/dist/scripts/fix-strict-boolean-final.d.ts +13 -0
  889. package/dist/scripts/fix-strict-boolean-final.d.ts.map +1 -0
  890. package/dist/scripts/fixer-aggressive.d.ts +7 -0
  891. package/dist/scripts/fixer-aggressive.d.ts.map +1 -0
  892. package/dist/scripts/fixer-conservative.d.ts +7 -0
  893. package/dist/scripts/fixer-conservative.d.ts.map +1 -0
  894. package/dist/scripts/fixer-direct.d.ts +7 -0
  895. package/dist/scripts/fixer-direct.d.ts.map +1 -0
  896. package/dist/scripts/generate-demo-registry.d.ts +14 -0
  897. package/dist/scripts/generate-demo-registry.d.ts.map +1 -0
  898. package/dist/scripts/inject-version.d.ts +8 -0
  899. package/dist/scripts/inject-version.d.ts.map +1 -0
  900. package/dist/scripts/strict-boolean-fixer.d.ts +9 -0
  901. package/dist/scripts/strict-boolean-fixer.d.ts.map +1 -0
  902. package/dist/scripts/validate-demo-registry.d.ts +17 -0
  903. package/dist/scripts/validate-demo-registry.d.ts.map +1 -0
  904. package/dist/services/AIModerationService.d.ts +217 -0
  905. package/dist/services/AIModerationService.d.ts.map +1 -0
  906. package/dist/services/AbstractCacheService.d.ts +227 -0
  907. package/dist/services/AbstractCacheService.d.ts.map +1 -0
  908. package/dist/services/AbstractTokenFetchService.d.ts +150 -0
  909. package/dist/services/AbstractTokenFetchService.d.ts.map +1 -0
  910. package/dist/services/ApiKeyService.d.ts +211 -0
  911. package/dist/services/ApiKeyService.d.ts.map +1 -0
  912. package/dist/services/BanService.d.ts +312 -0
  913. package/dist/services/BanService.d.ts.map +1 -0
  914. package/dist/services/BaseService.d.ts +116 -0
  915. package/dist/services/BaseService.d.ts.map +1 -0
  916. package/dist/services/BatchedCacheService.d.ts +133 -0
  917. package/dist/services/BatchedCacheService.d.ts.map +1 -0
  918. package/dist/services/BridgeableTokenCache.d.ts +120 -0
  919. package/dist/services/BridgeableTokenCache.d.ts.map +1 -0
  920. package/dist/services/BridgeableTokenService.d.ts +218 -0
  921. package/dist/services/BridgeableTokenService.d.ts.map +1 -0
  922. package/dist/services/BundleService.d.ts +245 -0
  923. package/dist/services/BundleService.d.ts.map +1 -0
  924. package/dist/services/BundlerClientFactory.d.ts +32 -0
  925. package/dist/services/BundlerClientFactory.d.ts.map +1 -0
  926. package/dist/services/ChartService.d.ts +106 -0
  927. package/dist/services/ChartService.d.ts.map +1 -0
  928. package/dist/services/ClientConfigService.d.ts +61 -0
  929. package/dist/services/ClientConfigService.d.ts.map +1 -0
  930. package/dist/services/ContentFlagService.d.ts +218 -0
  931. package/dist/services/ContentFlagService.d.ts.map +1 -0
  932. package/dist/services/ContentReactionService.d.ts +175 -0
  933. package/dist/services/ContentReactionService.d.ts.map +1 -0
  934. package/dist/services/DexBackendClient.d.ts +225 -0
  935. package/dist/services/DexBackendClient.d.ts.map +1 -0
  936. package/dist/services/DexBackendTradeClient.d.ts +34 -0
  937. package/dist/services/DexBackendTradeClient.d.ts.map +1 -0
  938. package/dist/services/DexPoolService.d.ts +137 -0
  939. package/dist/services/DexPoolService.d.ts.map +1 -0
  940. package/dist/services/DexQuoteService.d.ts +446 -0
  941. package/dist/services/DexQuoteService.d.ts.map +1 -0
  942. package/dist/services/DexService.d.ts +433 -0
  943. package/dist/services/DexService.d.ts.map +1 -0
  944. package/dist/services/EventsBatcherService.d.ts +111 -0
  945. package/dist/services/EventsBatcherService.d.ts.map +1 -0
  946. package/dist/services/GSwapAssetService.d.ts +96 -0
  947. package/dist/services/GSwapAssetService.d.ts.map +1 -0
  948. package/dist/services/GSwapLiquidityMutationService.d.ts +138 -0
  949. package/dist/services/GSwapLiquidityMutationService.d.ts.map +1 -0
  950. package/dist/services/GSwapLiquidityQueryService.d.ts +75 -0
  951. package/dist/services/GSwapLiquidityQueryService.d.ts.map +1 -0
  952. package/dist/services/GSwapPoolCalculationService.d.ts +187 -0
  953. package/dist/services/GSwapPoolCalculationService.d.ts.map +1 -0
  954. package/dist/services/GSwapPoolQueryService.d.ts +114 -0
  955. package/dist/services/GSwapPoolQueryService.d.ts.map +1 -0
  956. package/dist/services/GSwapService.d.ts +1207 -0
  957. package/dist/services/GSwapService.d.ts.map +1 -0
  958. package/dist/services/GSwapSwapService.d.ts +66 -0
  959. package/dist/services/GSwapSwapService.d.ts.map +1 -0
  960. package/dist/services/GalaChainBalanceService.d.ts +155 -0
  961. package/dist/services/GalaChainBalanceService.d.ts.map +1 -0
  962. package/dist/services/GalaChainLockService.d.ts +144 -0
  963. package/dist/services/GalaChainLockService.d.ts.map +1 -0
  964. package/dist/services/GalaChainService.d.ts +399 -0
  965. package/dist/services/GalaChainService.d.ts.map +1 -0
  966. package/dist/services/GalaChainTokenService.d.ts +108 -0
  967. package/dist/services/GalaChainTokenService.d.ts.map +1 -0
  968. package/dist/services/GalaChainTransferService.d.ts +205 -0
  969. package/dist/services/GalaChainTransferService.d.ts.map +1 -0
  970. package/dist/services/GdexStreamService.d.ts +133 -0
  971. package/dist/services/GdexStreamService.d.ts.map +1 -0
  972. package/dist/services/HolderService.d.ts +181 -0
  973. package/dist/services/HolderService.d.ts.map +1 -0
  974. package/dist/services/ImageService.d.ts +173 -0
  975. package/dist/services/ImageService.d.ts.map +1 -0
  976. package/dist/services/IntervalRegistry.d.ts +79 -0
  977. package/dist/services/IntervalRegistry.d.ts.map +1 -0
  978. package/dist/services/LaunchpadService.d.ts +343 -0
  979. package/dist/services/LaunchpadService.d.ts.map +1 -0
  980. package/dist/services/MessagesService.d.ts +251 -0
  981. package/dist/services/MessagesService.d.ts.map +1 -0
  982. package/dist/services/ModeratorService.d.ts +311 -0
  983. package/dist/services/ModeratorService.d.ts.map +1 -0
  984. package/dist/services/MultiPoolStateManager.d.ts +289 -0
  985. package/dist/services/MultiPoolStateManager.d.ts.map +1 -0
  986. package/dist/services/NetworkKeyedCacheService.d.ts +185 -0
  987. package/dist/services/NetworkKeyedCacheService.d.ts.map +1 -0
  988. package/dist/services/NftCollectionService.d.ts +121 -0
  989. package/dist/services/NftCollectionService.d.ts.map +1 -0
  990. package/dist/services/NotificationService.d.ts +113 -0
  991. package/dist/services/NotificationService.d.ts.map +1 -0
  992. package/dist/services/OEmbedService.d.ts +152 -0
  993. package/dist/services/OEmbedService.d.ts.map +1 -0
  994. package/dist/services/OverseerService.d.ts +524 -0
  995. package/dist/services/OverseerService.d.ts.map +1 -0
  996. package/dist/services/PlatformConfigService.d.ts +149 -0
  997. package/dist/services/PlatformConfigService.d.ts.map +1 -0
  998. package/dist/services/PlatformStatsService.d.ts +72 -0
  999. package/dist/services/PlatformStatsService.d.ts.map +1 -0
  1000. package/dist/services/PoolCacheManager.d.ts +258 -0
  1001. package/dist/services/PoolCacheManager.d.ts.map +1 -0
  1002. package/dist/services/PoolService.d.ts +316 -0
  1003. package/dist/services/PoolService.d.ts.map +1 -0
  1004. package/dist/services/PoolStateManager.d.ts +176 -0
  1005. package/dist/services/PoolStateManager.d.ts.map +1 -0
  1006. package/dist/services/PriceHistoryService.d.ts +207 -0
  1007. package/dist/services/PriceHistoryService.d.ts.map +1 -0
  1008. package/dist/services/RestrictedNamesService.d.ts +80 -0
  1009. package/dist/services/RestrictedNamesService.d.ts.map +1 -0
  1010. package/dist/services/SignatureService.d.ts +113 -0
  1011. package/dist/services/SignatureService.d.ts.map +1 -0
  1012. package/dist/services/StreamChatService.d.ts +259 -0
  1013. package/dist/services/StreamChatService.d.ts.map +1 -0
  1014. package/dist/services/StreamTokenServiceBase.d.ts +404 -0
  1015. package/dist/services/StreamTokenServiceBase.d.ts.map +1 -0
  1016. package/dist/services/StreamWebSocketService.d.ts +586 -0
  1017. package/dist/services/StreamWebSocketService.d.ts.map +1 -0
  1018. package/dist/services/StreamingEventService.d.ts +441 -0
  1019. package/dist/services/StreamingEventService.d.ts.map +1 -0
  1020. package/dist/services/StreamingService.d.ts +573 -0
  1021. package/dist/services/StreamingService.d.ts.map +1 -0
  1022. package/dist/services/SwapEventQueue.d.ts +192 -0
  1023. package/dist/services/SwapEventQueue.d.ts.map +1 -0
  1024. package/dist/services/TokenBanService.d.ts +217 -0
  1025. package/dist/services/TokenBanService.d.ts.map +1 -0
  1026. package/dist/services/TokenClassKeyService.d.ts +162 -0
  1027. package/dist/services/TokenClassKeyService.d.ts.map +1 -0
  1028. package/dist/services/TokenMetadataCache.d.ts +310 -0
  1029. package/dist/services/TokenMetadataCache.d.ts.map +1 -0
  1030. package/dist/services/TokenMetadataService.d.ts +509 -0
  1031. package/dist/services/TokenMetadataService.d.ts.map +1 -0
  1032. package/dist/services/TokenResolverService.d.ts +329 -0
  1033. package/dist/services/TokenResolverService.d.ts.map +1 -0
  1034. package/dist/services/TradeService.d.ts +286 -0
  1035. package/dist/services/TradeService.d.ts.map +1 -0
  1036. package/dist/services/TradingQuotesService.d.ts +162 -0
  1037. package/dist/services/TradingQuotesService.d.ts.map +1 -0
  1038. package/dist/services/UserService.d.ts +352 -0
  1039. package/dist/services/UserService.d.ts.map +1 -0
  1040. package/dist/services/WebSocketAdminService.d.ts +587 -0
  1041. package/dist/services/WebSocketAdminService.d.ts.map +1 -0
  1042. package/dist/services/WebSocketService.d.ts +189 -0
  1043. package/dist/services/WebSocketService.d.ts.map +1 -0
  1044. package/dist/services/WeeklyChallengeService.d.ts +114 -0
  1045. package/dist/services/WeeklyChallengeService.d.ts.map +1 -0
  1046. package/dist/services/WrapService.d.ts +172 -0
  1047. package/dist/services/WrapService.d.ts.map +1 -0
  1048. package/dist/services/WrappableTokenCache.d.ts +100 -0
  1049. package/dist/services/WrappableTokenCache.d.ts.map +1 -0
  1050. package/dist/services/WrappableTokenService.d.ts +130 -0
  1051. package/dist/services/WrappableTokenService.d.ts.map +1 -0
  1052. package/dist/services/__mocks__/logger.mock.d.ts +24 -0
  1053. package/dist/services/__mocks__/logger.mock.d.ts.map +1 -0
  1054. package/dist/services/shared/cache-helpers.d.ts +188 -0
  1055. package/dist/services/shared/cache-helpers.d.ts.map +1 -0
  1056. package/dist/services/shared/http-helpers.d.ts +146 -0
  1057. package/dist/services/shared/http-helpers.d.ts.map +1 -0
  1058. package/dist/services/shared/pagination-helpers.d.ts +167 -0
  1059. package/dist/services/shared/pagination-helpers.d.ts.map +1 -0
  1060. package/dist/services/shared/service-validators.d.ts +137 -0
  1061. package/dist/services/shared/service-validators.d.ts.map +1 -0
  1062. package/dist/services/shared/websocket-helpers.d.ts +158 -0
  1063. package/dist/services/shared/websocket-helpers.d.ts.map +1 -0
  1064. package/dist/setup.d.ts +8 -0
  1065. package/dist/setup.d.ts.map +1 -0
  1066. package/dist/src/LaunchpadSDK.d.ts +2414 -497
  1067. package/dist/src/LaunchpadSDK.d.ts.map +1 -1
  1068. package/dist/src/api/LaunchpadAPI.d.ts +15 -8
  1069. package/dist/src/api/LaunchpadAPI.d.ts.map +1 -1
  1070. package/dist/src/api/dto/BondingCurveDTOs.d.ts.map +1 -1
  1071. package/dist/src/api/dto/BurnTokensDto.d.ts +1 -1
  1072. package/dist/src/api/dto/BurnTokensDto.d.ts.map +1 -1
  1073. package/dist/src/api/dto/LockTokenDto.d.ts +1 -1
  1074. package/dist/src/api/dto/LockTokenDto.d.ts.map +1 -1
  1075. package/dist/src/api/dto/TransferTokenDto.d.ts +1 -1
  1076. package/dist/src/api/dto/TransferTokenDto.d.ts.map +1 -1
  1077. package/dist/src/api/dto/UnlockTokenDto.d.ts +1 -1
  1078. package/dist/src/api/dto/UnlockTokenDto.d.ts.map +1 -1
  1079. package/dist/src/auth/JwtAuth.d.ts +43 -5
  1080. package/dist/src/auth/JwtAuth.d.ts.map +1 -1
  1081. package/dist/src/auth/SessionAuthService.d.ts +11 -6
  1082. package/dist/src/auth/SessionAuthService.d.ts.map +1 -1
  1083. package/dist/src/auth/SignatureAuth.d.ts +64 -3
  1084. package/dist/src/auth/SignatureAuth.d.ts.map +1 -1
  1085. package/dist/src/auth/storage.d.ts +66 -0
  1086. package/dist/src/auth/storage.d.ts.map +1 -0
  1087. package/dist/src/auth/types.d.ts +11 -2
  1088. package/dist/src/auth/types.d.ts.map +1 -1
  1089. package/dist/src/bridge/BridgeService.d.ts +1 -1
  1090. package/dist/src/bridge/BridgeService.d.ts.map +1 -1
  1091. package/dist/src/bridge/GalaConnectClient.d.ts +1 -1
  1092. package/dist/src/bridge/GalaConnectClient.d.ts.map +1 -1
  1093. package/dist/src/bridge/constants/tokens.d.ts +1 -1
  1094. package/dist/src/bridge/constants/tokens.d.ts.map +1 -1
  1095. package/dist/src/bridge/index.d.ts +10 -10
  1096. package/dist/src/bridge/index.d.ts.map +1 -1
  1097. package/dist/src/bridge/strategies/BridgeStrategy.d.ts.map +1 -1
  1098. package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts +1 -1
  1099. package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -1
  1100. package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts +1 -1
  1101. package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts.map +1 -1
  1102. package/dist/src/bridge/utils/addressValidation.d.ts.map +1 -1
  1103. package/dist/src/bridge/utils/balanceHelpers.d.ts +1 -1
  1104. package/dist/src/bridge/utils/balanceHelpers.d.ts.map +1 -1
  1105. package/dist/src/bridge/utils/bridgeErrors.d.ts.map +1 -1
  1106. package/dist/src/bridge/utils/bridgeOutHelpers.d.ts +1 -1
  1107. package/dist/src/bridge/utils/bridgeOutHelpers.d.ts.map +1 -1
  1108. package/dist/src/bridge/utils/bridgePayload.d.ts +2 -11
  1109. package/dist/src/bridge/utils/bridgePayload.d.ts.map +1 -1
  1110. package/dist/src/bridge/utils/bridgeStatusParser.d.ts.map +1 -1
  1111. package/dist/src/bridge/utils/eip712Helpers.d.ts.map +1 -1
  1112. package/dist/src/bridge/utils/index.d.ts +9 -9
  1113. package/dist/src/bridge/utils/index.d.ts.map +1 -1
  1114. package/dist/src/bridge/utils/tokenIdUtils.d.ts +1 -1
  1115. package/dist/src/bridge/utils/tokenIdUtils.d.ts.map +1 -1
  1116. package/dist/src/bridge/utils/tokenMetadataResolver.d.ts +1 -1
  1117. package/dist/src/bridge/utils/tokenMetadataResolver.d.ts.map +1 -1
  1118. package/dist/src/config/environments.d.ts +3 -1
  1119. package/dist/src/config/environments.d.ts.map +1 -1
  1120. package/dist/src/constants/endpoints.d.ts +566 -260
  1121. package/dist/src/constants/endpoints.d.ts.map +1 -1
  1122. package/dist/src/constants/events.d.ts +53 -0
  1123. package/dist/src/constants/events.d.ts.map +1 -0
  1124. package/dist/src/constants/pagination.d.ts +23 -13
  1125. package/dist/src/constants/pagination.d.ts.map +1 -1
  1126. package/dist/src/constants/version.generated.d.ts +1 -1
  1127. package/dist/src/constants/version.generated.d.ts.map +1 -1
  1128. package/dist/src/helpers/sdk.d.ts.map +1 -1
  1129. package/dist/src/helpers/wallet.d.ts.map +1 -1
  1130. package/dist/src/index.browser.d.ts +149 -0
  1131. package/dist/src/index.browser.d.ts.map +1 -0
  1132. package/dist/src/index.d.ts +6 -115
  1133. package/dist/src/index.d.ts.map +1 -1
  1134. package/dist/src/index.node.d.ts +13 -0
  1135. package/dist/src/index.node.d.ts.map +1 -0
  1136. package/dist/src/native.d.ts +22 -0
  1137. package/dist/src/native.d.ts.map +1 -0
  1138. package/dist/src/react/WalletContext.d.ts +60 -0
  1139. package/dist/src/react/WalletContext.d.ts.map +1 -0
  1140. package/dist/src/react/index.d.ts +65 -0
  1141. package/dist/src/react/index.d.ts.map +1 -0
  1142. package/dist/src/react/types.d.ts +76 -0
  1143. package/dist/src/react/types.d.ts.map +1 -0
  1144. package/dist/src/react/useWallet.d.ts +123 -0
  1145. package/dist/src/react/useWallet.d.ts.map +1 -0
  1146. package/dist/src/react/useWalletConnection.d.ts +89 -0
  1147. package/dist/src/react/useWalletConnection.d.ts.map +1 -0
  1148. package/dist/src/react/useWalletDetection.d.ts +81 -0
  1149. package/dist/src/react/useWalletDetection.d.ts.map +1 -0
  1150. package/dist/src/schemas/files.d.ts.map +1 -1
  1151. package/dist/src/schemas/index.d.ts +4 -3
  1152. package/dist/src/schemas/index.d.ts.map +1 -1
  1153. package/dist/src/schemas/launchpad.d.ts +1 -0
  1154. package/dist/src/schemas/launchpad.d.ts.map +1 -1
  1155. package/dist/src/schemas/pagination.d.ts +16 -19
  1156. package/dist/src/schemas/pagination.d.ts.map +1 -1
  1157. package/dist/src/schemas/primitives.d.ts +1 -1
  1158. package/dist/src/schemas/primitives.d.ts.map +1 -1
  1159. package/dist/src/schemas/trade.d.ts +2 -2
  1160. package/dist/src/schemas/trade.d.ts.map +1 -1
  1161. package/dist/src/schemas/user.d.ts +2 -2
  1162. package/dist/src/schemas/user.d.ts.map +1 -1
  1163. package/dist/src/schemas/validators.d.ts +6 -5
  1164. package/dist/src/schemas/validators.d.ts.map +1 -1
  1165. package/dist/src/services/AIModerationService.d.ts +217 -0
  1166. package/dist/src/services/AIModerationService.d.ts.map +1 -0
  1167. package/dist/src/services/AbstractTokenFetchService.d.ts +1 -1
  1168. package/dist/src/services/AbstractTokenFetchService.d.ts.map +1 -1
  1169. package/dist/src/services/ApiKeyService.d.ts +14 -9
  1170. package/dist/src/services/ApiKeyService.d.ts.map +1 -1
  1171. package/dist/src/services/BanService.d.ts +132 -16
  1172. package/dist/src/services/BanService.d.ts.map +1 -1
  1173. package/dist/src/services/BaseService.d.ts +1 -1
  1174. package/dist/src/services/BaseService.d.ts.map +1 -1
  1175. package/dist/src/services/BatchedCacheService.d.ts.map +1 -1
  1176. package/dist/src/services/BridgeableTokenCache.d.ts +1 -1
  1177. package/dist/src/services/BridgeableTokenCache.d.ts.map +1 -1
  1178. package/dist/src/services/BridgeableTokenService.d.ts +4 -4
  1179. package/dist/src/services/BridgeableTokenService.d.ts.map +1 -1
  1180. package/dist/src/services/BundleService.d.ts +5 -5
  1181. package/dist/src/services/BundleService.d.ts.map +1 -1
  1182. package/dist/src/services/BundlerClientFactory.d.ts.map +1 -1
  1183. package/dist/src/services/ChartService.d.ts +106 -0
  1184. package/dist/src/services/ChartService.d.ts.map +1 -0
  1185. package/dist/src/services/ClientConfigService.d.ts +61 -0
  1186. package/dist/src/services/ClientConfigService.d.ts.map +1 -0
  1187. package/dist/src/services/ContentFlagService.d.ts +13 -7
  1188. package/dist/src/services/ContentFlagService.d.ts.map +1 -1
  1189. package/dist/src/services/ContentReactionService.d.ts +3 -3
  1190. package/dist/src/services/ContentReactionService.d.ts.map +1 -1
  1191. package/dist/src/services/DexBackendClient.d.ts +1 -1
  1192. package/dist/src/services/DexBackendClient.d.ts.map +1 -1
  1193. package/dist/src/services/DexBackendTradeClient.d.ts +34 -0
  1194. package/dist/src/services/DexBackendTradeClient.d.ts.map +1 -0
  1195. package/dist/src/services/DexPoolService.d.ts +9 -11
  1196. package/dist/src/services/DexPoolService.d.ts.map +1 -1
  1197. package/dist/src/services/DexQuoteService.d.ts +23 -24
  1198. package/dist/src/services/DexQuoteService.d.ts.map +1 -1
  1199. package/dist/src/services/DexService.d.ts +6 -6
  1200. package/dist/src/services/DexService.d.ts.map +1 -1
  1201. package/dist/src/services/EventsBatcherService.d.ts +111 -0
  1202. package/dist/src/services/EventsBatcherService.d.ts.map +1 -0
  1203. package/dist/src/services/GSwapAssetService.d.ts +18 -2
  1204. package/dist/src/services/GSwapAssetService.d.ts.map +1 -1
  1205. package/dist/src/services/GSwapLiquidityMutationService.d.ts +6 -8
  1206. package/dist/src/services/GSwapLiquidityMutationService.d.ts.map +1 -1
  1207. package/dist/src/services/GSwapLiquidityQueryService.d.ts +4 -16
  1208. package/dist/src/services/GSwapLiquidityQueryService.d.ts.map +1 -1
  1209. package/dist/src/services/GSwapPoolCalculationService.d.ts +0 -13
  1210. package/dist/src/services/GSwapPoolCalculationService.d.ts.map +1 -1
  1211. package/dist/src/services/GSwapPoolQueryService.d.ts +7 -9
  1212. package/dist/src/services/GSwapPoolQueryService.d.ts.map +1 -1
  1213. package/dist/src/services/GSwapService.d.ts +16 -16
  1214. package/dist/src/services/GSwapService.d.ts.map +1 -1
  1215. package/dist/src/services/GSwapSwapService.d.ts +2 -4
  1216. package/dist/src/services/GSwapSwapService.d.ts.map +1 -1
  1217. package/dist/src/services/GalaChainBalanceService.d.ts +2 -2
  1218. package/dist/src/services/GalaChainBalanceService.d.ts.map +1 -1
  1219. package/dist/src/services/GalaChainLockService.d.ts +3 -3
  1220. package/dist/src/services/GalaChainLockService.d.ts.map +1 -1
  1221. package/dist/src/services/GalaChainService.d.ts +10 -13
  1222. package/dist/src/services/GalaChainService.d.ts.map +1 -1
  1223. package/dist/src/services/GalaChainTokenService.d.ts +3 -3
  1224. package/dist/src/services/GalaChainTokenService.d.ts.map +1 -1
  1225. package/dist/src/services/GalaChainTransferService.d.ts +4 -4
  1226. package/dist/src/services/GalaChainTransferService.d.ts.map +1 -1
  1227. package/dist/src/services/GdexStreamService.d.ts +133 -0
  1228. package/dist/src/services/GdexStreamService.d.ts.map +1 -0
  1229. package/dist/src/services/HolderService.d.ts +181 -0
  1230. package/dist/src/services/HolderService.d.ts.map +1 -0
  1231. package/dist/src/services/ImageService.d.ts +2 -15
  1232. package/dist/src/services/ImageService.d.ts.map +1 -1
  1233. package/dist/src/services/IntervalRegistry.d.ts +79 -0
  1234. package/dist/src/services/IntervalRegistry.d.ts.map +1 -0
  1235. package/dist/src/services/LaunchpadService.d.ts +67 -24
  1236. package/dist/src/services/LaunchpadService.d.ts.map +1 -1
  1237. package/dist/src/services/MessagesService.d.ts +251 -0
  1238. package/dist/src/services/MessagesService.d.ts.map +1 -0
  1239. package/dist/src/services/ModeratorService.d.ts +58 -22
  1240. package/dist/src/services/ModeratorService.d.ts.map +1 -1
  1241. package/dist/src/services/MultiPoolStateManager.d.ts +17 -10
  1242. package/dist/src/services/MultiPoolStateManager.d.ts.map +1 -1
  1243. package/dist/src/services/NetworkKeyedCacheService.d.ts.map +1 -1
  1244. package/dist/src/services/NftCollectionService.d.ts +3 -5
  1245. package/dist/src/services/NftCollectionService.d.ts.map +1 -1
  1246. package/dist/src/services/NotificationService.d.ts +113 -0
  1247. package/dist/src/services/NotificationService.d.ts.map +1 -0
  1248. package/dist/src/services/OEmbedService.d.ts +152 -0
  1249. package/dist/src/services/OEmbedService.d.ts.map +1 -0
  1250. package/dist/src/services/OverseerService.d.ts +230 -35
  1251. package/dist/src/services/OverseerService.d.ts.map +1 -1
  1252. package/dist/src/services/PlatformConfigService.d.ts +149 -0
  1253. package/dist/src/services/PlatformConfigService.d.ts.map +1 -0
  1254. package/dist/src/services/PlatformStatsService.d.ts +72 -0
  1255. package/dist/src/services/PlatformStatsService.d.ts.map +1 -0
  1256. package/dist/src/services/PoolCacheManager.d.ts +3 -10
  1257. package/dist/src/services/PoolCacheManager.d.ts.map +1 -1
  1258. package/dist/src/services/PoolService.d.ts +108 -25
  1259. package/dist/src/services/PoolService.d.ts.map +1 -1
  1260. package/dist/src/services/PoolStateManager.d.ts +2 -2
  1261. package/dist/src/services/PoolStateManager.d.ts.map +1 -1
  1262. package/dist/src/services/PriceHistoryService.d.ts +11 -12
  1263. package/dist/src/services/PriceHistoryService.d.ts.map +1 -1
  1264. package/dist/src/services/RestrictedNamesService.d.ts +80 -0
  1265. package/dist/src/services/RestrictedNamesService.d.ts.map +1 -0
  1266. package/dist/src/services/SignatureService.d.ts.map +1 -1
  1267. package/dist/src/services/StreamChatService.d.ts +68 -187
  1268. package/dist/src/services/StreamChatService.d.ts.map +1 -1
  1269. package/dist/src/services/StreamTokenServiceBase.d.ts +45 -12
  1270. package/dist/src/services/StreamTokenServiceBase.d.ts.map +1 -1
  1271. package/dist/src/services/StreamWebSocketService.d.ts +335 -17
  1272. package/dist/src/services/StreamWebSocketService.d.ts.map +1 -1
  1273. package/dist/src/services/StreamingEventService.d.ts +16 -6
  1274. package/dist/src/services/StreamingEventService.d.ts.map +1 -1
  1275. package/dist/src/services/StreamingService.d.ts +66 -40
  1276. package/dist/src/services/StreamingService.d.ts.map +1 -1
  1277. package/dist/src/services/SwapEventQueue.d.ts +1 -1
  1278. package/dist/src/services/SwapEventQueue.d.ts.map +1 -1
  1279. package/dist/src/services/TokenBanService.d.ts +18 -16
  1280. package/dist/src/services/TokenBanService.d.ts.map +1 -1
  1281. package/dist/src/services/TokenClassKeyService.d.ts.map +1 -1
  1282. package/dist/src/services/TokenMetadataCache.d.ts.map +1 -1
  1283. package/dist/src/services/TokenMetadataService.d.ts +4 -4
  1284. package/dist/src/services/TokenMetadataService.d.ts.map +1 -1
  1285. package/dist/src/services/TokenResolverService.d.ts +197 -24
  1286. package/dist/src/services/TokenResolverService.d.ts.map +1 -1
  1287. package/dist/src/services/TradeService.d.ts +19 -19
  1288. package/dist/src/services/TradeService.d.ts.map +1 -1
  1289. package/dist/src/services/TradingQuotesService.d.ts +162 -0
  1290. package/dist/src/services/TradingQuotesService.d.ts.map +1 -0
  1291. package/dist/src/services/UserService.d.ts +83 -23
  1292. package/dist/src/services/UserService.d.ts.map +1 -1
  1293. package/dist/src/services/WebSocketAdminService.d.ts +587 -0
  1294. package/dist/src/services/WebSocketAdminService.d.ts.map +1 -0
  1295. package/dist/src/services/WebSocketService.d.ts +7 -1
  1296. package/dist/src/services/WebSocketService.d.ts.map +1 -1
  1297. package/dist/src/services/WeeklyChallengeService.d.ts +114 -0
  1298. package/dist/src/services/WeeklyChallengeService.d.ts.map +1 -0
  1299. package/dist/src/services/WrapService.d.ts +5 -5
  1300. package/dist/src/services/WrapService.d.ts.map +1 -1
  1301. package/dist/src/services/WrappableTokenService.d.ts +3 -3
  1302. package/dist/src/services/WrappableTokenService.d.ts.map +1 -1
  1303. package/dist/src/services/__mocks__/logger.mock.d.ts.map +1 -1
  1304. package/dist/src/services/shared/cache-helpers.d.ts.map +1 -1
  1305. package/dist/src/services/shared/http-helpers.d.ts.map +1 -1
  1306. package/dist/src/services/shared/pagination-helpers.d.ts +19 -19
  1307. package/dist/src/services/shared/pagination-helpers.d.ts.map +1 -1
  1308. package/dist/src/services/shared/service-validators.d.ts +1 -1
  1309. package/dist/src/services/shared/service-validators.d.ts.map +1 -1
  1310. package/dist/src/setup.d.ts +2 -2
  1311. package/dist/src/types/ai-moderation.dto.d.ts +294 -0
  1312. package/dist/src/types/ai-moderation.dto.d.ts.map +1 -0
  1313. package/dist/src/types/api-key.dto.d.ts +82 -9
  1314. package/dist/src/types/api-key.dto.d.ts.map +1 -1
  1315. package/dist/src/types/ban.dto.d.ts +174 -3
  1316. package/dist/src/types/ban.dto.d.ts.map +1 -1
  1317. package/dist/src/types/cache-management.dto.d.ts +44 -0
  1318. package/dist/src/types/cache-management.dto.d.ts.map +1 -0
  1319. package/dist/src/types/chat-messages.dto.d.ts +7 -7
  1320. package/dist/src/types/chat-messages.dto.d.ts.map +1 -1
  1321. package/dist/src/types/client-config.dto.d.ts +43 -0
  1322. package/dist/src/types/client-config.dto.d.ts.map +1 -0
  1323. package/dist/src/types/comment.dto.d.ts +3 -7
  1324. package/dist/src/types/comment.dto.d.ts.map +1 -1
  1325. package/dist/src/types/comments.dto.d.ts +9 -9
  1326. package/dist/src/types/comments.dto.d.ts.map +1 -1
  1327. package/dist/src/types/common.d.ts +117 -27
  1328. package/dist/src/types/common.d.ts.map +1 -1
  1329. package/dist/src/types/composite-pool.dto.d.ts +4 -6
  1330. package/dist/src/types/composite-pool.dto.d.ts.map +1 -1
  1331. package/dist/src/types/constraints.d.ts +6 -2
  1332. package/dist/src/types/constraints.d.ts.map +1 -1
  1333. package/dist/src/types/content-flag.dto.d.ts +43 -4
  1334. package/dist/src/types/content-flag.dto.d.ts.map +1 -1
  1335. package/dist/src/types/content-reactions.dto.d.ts +4 -4
  1336. package/dist/src/types/content-reactions.dto.d.ts.map +1 -1
  1337. package/dist/src/types/dex-pool.dto.d.ts +20 -7
  1338. package/dist/src/types/dex-pool.dto.d.ts.map +1 -1
  1339. package/dist/src/types/dto.d.ts +5 -1
  1340. package/dist/src/types/dto.d.ts.map +1 -1
  1341. package/dist/src/types/engagement-stats.dto.d.ts +62 -0
  1342. package/dist/src/types/engagement-stats.dto.d.ts.map +1 -0
  1343. package/dist/src/types/events.dto.d.ts +80 -0
  1344. package/dist/src/types/events.dto.d.ts.map +1 -0
  1345. package/dist/src/types/global-feed.dto.d.ts +203 -0
  1346. package/dist/src/types/global-feed.dto.d.ts.map +1 -0
  1347. package/dist/src/types/gswap-responses.types.d.ts +14 -14
  1348. package/dist/src/types/gswap-responses.types.d.ts.map +1 -1
  1349. package/dist/src/types/gswap.dto.d.ts +12 -5
  1350. package/dist/src/types/gswap.dto.d.ts.map +1 -1
  1351. package/dist/src/types/holder.types.d.ts +106 -0
  1352. package/dist/src/types/holder.types.d.ts.map +1 -0
  1353. package/dist/src/types/launchpad.dto.d.ts +154 -77
  1354. package/dist/src/types/launchpad.dto.d.ts.map +1 -1
  1355. package/dist/src/types/launchpad.validation.d.ts.map +1 -1
  1356. package/dist/src/types/lock.dto.d.ts +1 -1
  1357. package/dist/src/types/lock.dto.d.ts.map +1 -1
  1358. package/dist/src/types/messages.dto.d.ts +386 -0
  1359. package/dist/src/types/messages.dto.d.ts.map +1 -0
  1360. package/dist/src/types/moderator.dto.d.ts +38 -5
  1361. package/dist/src/types/moderator.dto.d.ts.map +1 -1
  1362. package/dist/src/types/notification.dto.d.ts +92 -0
  1363. package/dist/src/types/notification.dto.d.ts.map +1 -0
  1364. package/dist/src/types/oembed.dto.d.ts +160 -0
  1365. package/dist/src/types/oembed.dto.d.ts.map +1 -0
  1366. package/dist/src/types/options.dto.d.ts +9 -1
  1367. package/dist/src/types/options.dto.d.ts.map +1 -1
  1368. package/dist/src/types/overseer.dto.d.ts +152 -35
  1369. package/dist/src/types/overseer.dto.d.ts.map +1 -1
  1370. package/dist/src/types/platform-config.dto.d.ts +89 -0
  1371. package/dist/src/types/platform-config.dto.d.ts.map +1 -0
  1372. package/dist/src/types/platform-stats.dto.d.ts +40 -0
  1373. package/dist/src/types/platform-stats.dto.d.ts.map +1 -0
  1374. package/dist/src/types/pool-state-delta.dto.d.ts.map +1 -1
  1375. package/dist/src/types/pool.dto.d.ts +6 -1
  1376. package/dist/src/types/pool.dto.d.ts.map +1 -1
  1377. package/dist/src/types/priceHistory.dto.d.ts +6 -2
  1378. package/dist/src/types/priceHistory.dto.d.ts.map +1 -1
  1379. package/dist/src/types/restricted-names.dto.d.ts +50 -0
  1380. package/dist/src/types/restricted-names.dto.d.ts.map +1 -0
  1381. package/dist/src/types/session-auth.dto.d.ts +9 -1
  1382. package/dist/src/types/session-auth.dto.d.ts.map +1 -1
  1383. package/dist/src/types/stream-chat.dto.d.ts +4 -9
  1384. package/dist/src/types/stream-chat.dto.d.ts.map +1 -1
  1385. package/dist/src/types/streaming-events.dto.d.ts +20 -1
  1386. package/dist/src/types/streaming-events.dto.d.ts.map +1 -1
  1387. package/dist/src/types/streaming.dto.d.ts +64 -20
  1388. package/dist/src/types/streaming.dto.d.ts.map +1 -1
  1389. package/dist/src/types/token-ban.dto.d.ts +7 -8
  1390. package/dist/src/types/token-ban.dto.d.ts.map +1 -1
  1391. package/dist/src/types/token-config.dto.d.ts +117 -0
  1392. package/dist/src/types/token-config.dto.d.ts.map +1 -0
  1393. package/dist/src/types/token.types.d.ts +336 -0
  1394. package/dist/src/types/token.types.d.ts.map +1 -0
  1395. package/dist/src/types/trade.dto.d.ts +5 -1
  1396. package/dist/src/types/trade.dto.d.ts.map +1 -1
  1397. package/dist/src/types/trades-query.dto.d.ts +8 -2
  1398. package/dist/src/types/trades-query.dto.d.ts.map +1 -1
  1399. package/dist/src/types/transfer.dto.d.ts.map +1 -1
  1400. package/dist/src/types/user.dto.d.ts +218 -48
  1401. package/dist/src/types/user.dto.d.ts.map +1 -1
  1402. package/dist/src/types/websocket-admin.dto.d.ts +390 -0
  1403. package/dist/src/types/websocket-admin.dto.d.ts.map +1 -0
  1404. package/dist/src/types/websocket-events.dto.d.ts +472 -0
  1405. package/dist/src/types/websocket-events.dto.d.ts.map +1 -0
  1406. package/dist/src/types/weekly-challenge.dto.d.ts +130 -0
  1407. package/dist/src/types/weekly-challenge.dto.d.ts.map +1 -0
  1408. package/dist/src/types/wrappable-token.dto.d.ts +1 -1
  1409. package/dist/src/types/wrappable-token.dto.d.ts.map +1 -1
  1410. package/dist/src/utils/LiquidityEventExtractor.d.ts +7 -0
  1411. package/dist/src/utils/LiquidityEventExtractor.d.ts.map +1 -1
  1412. package/dist/src/utils/Logger.d.ts.map +1 -1
  1413. package/dist/src/utils/MonitoringMetrics.d.ts +0 -1
  1414. package/dist/src/utils/MonitoringMetrics.d.ts.map +1 -1
  1415. package/dist/src/utils/SignatureHelper.d.ts.map +1 -1
  1416. package/dist/src/utils/SwapEventExtractor.d.ts.map +1 -1
  1417. package/dist/src/utils/adapters.d.ts +1 -1
  1418. package/dist/src/utils/adapters.d.ts.map +1 -1
  1419. package/dist/src/utils/address-formatter.d.ts +7 -6
  1420. package/dist/src/utils/address-formatter.d.ts.map +1 -1
  1421. package/dist/src/utils/agent-config.d.ts.map +1 -1
  1422. package/dist/src/utils/amount-validator.d.ts.map +1 -1
  1423. package/dist/src/utils/api-patterns.d.ts +1 -1
  1424. package/dist/src/utils/api-patterns.d.ts.map +1 -1
  1425. package/dist/src/utils/assetUrls.d.ts +450 -0
  1426. package/dist/src/utils/assetUrls.d.ts.map +1 -0
  1427. package/dist/src/utils/auto-pagination.d.ts +89 -0
  1428. package/dist/src/utils/auto-pagination.d.ts.map +1 -1
  1429. package/dist/src/utils/bignumber-helpers.d.ts.map +1 -1
  1430. package/dist/src/utils/bignumber-pool-cache.d.ts.map +1 -1
  1431. package/dist/src/utils/composite-pool-converter.d.ts +4 -4
  1432. package/dist/src/utils/composite-pool-converter.d.ts.map +1 -1
  1433. package/dist/src/utils/crypto-compat.d.ts +40 -0
  1434. package/dist/src/utils/crypto-compat.d.ts.map +1 -0
  1435. package/dist/src/utils/delimiter-parser.d.ts +1 -1
  1436. package/dist/src/utils/delimiter-parser.d.ts.map +1 -1
  1437. package/dist/src/utils/error-factories.d.ts +1 -1
  1438. package/dist/src/utils/error-factories.d.ts.map +1 -1
  1439. package/dist/src/utils/error-handling-patterns.d.ts +1 -1
  1440. package/dist/src/utils/error-handling-patterns.d.ts.map +1 -1
  1441. package/dist/src/utils/error-patterns.d.ts.map +1 -1
  1442. package/dist/src/utils/error-utils.d.ts +6 -1
  1443. package/dist/src/utils/error-utils.d.ts.map +1 -1
  1444. package/dist/src/utils/errors.d.ts +6 -2
  1445. package/dist/src/utils/errors.d.ts.map +1 -1
  1446. package/dist/src/utils/http.d.ts +2 -2
  1447. package/dist/src/utils/http.d.ts.map +1 -1
  1448. package/dist/src/utils/load-env.d.ts.map +1 -1
  1449. package/dist/src/utils/multipart.d.ts.map +1 -1
  1450. package/dist/src/utils/nft-helpers.d.ts.map +1 -1
  1451. package/dist/src/utils/numeric-patterns.d.ts.map +1 -1
  1452. package/dist/src/utils/numeric-wrappers.d.ts +3 -0
  1453. package/dist/src/utils/numeric-wrappers.d.ts.map +1 -1
  1454. package/dist/src/utils/pagination-validation.d.ts +88 -0
  1455. package/dist/src/utils/pagination-validation.d.ts.map +1 -0
  1456. package/dist/src/utils/pool-state-validator.d.ts +1 -1
  1457. package/dist/src/utils/pool-state-validator.d.ts.map +1 -1
  1458. package/dist/src/utils/primitives.d.ts +76 -0
  1459. package/dist/src/utils/primitives.d.ts.map +1 -0
  1460. package/dist/src/utils/query-params.d.ts +6 -6
  1461. package/dist/src/utils/query-params.d.ts.map +1 -1
  1462. package/dist/src/utils/response-handlers.d.ts.map +1 -1
  1463. package/dist/src/utils/response-normalizers.d.ts.map +1 -1
  1464. package/dist/src/utils/safe-parsers.d.ts.map +1 -1
  1465. package/dist/src/utils/service-validators.d.ts.map +1 -1
  1466. package/dist/src/utils/slippage-utils.d.ts.map +1 -1
  1467. package/dist/src/utils/string-patterns.d.ts +3 -3
  1468. package/dist/src/utils/string-patterns.d.ts.map +1 -1
  1469. package/dist/src/utils/swap-delta-calculator.d.ts +2 -2
  1470. package/dist/src/utils/swap-delta-calculator.d.ts.map +1 -1
  1471. package/dist/src/utils/tick-crossing-handler.d.ts.map +1 -1
  1472. package/dist/src/utils/token-format-converter.d.ts +1 -1
  1473. package/dist/src/utils/token-format-converter.d.ts.map +1 -1
  1474. package/dist/src/utils/token-stringification.d.ts.map +1 -1
  1475. package/dist/src/utils/tokenNormalizer.d.ts +1 -1
  1476. package/dist/src/utils/tokenNormalizer.d.ts.map +1 -1
  1477. package/dist/src/utils/trade-transformers.d.ts +1 -1
  1478. package/dist/src/utils/trade-transformers.d.ts.map +1 -1
  1479. package/dist/src/utils/validation-helpers.d.ts +5 -97
  1480. package/dist/src/utils/validation-helpers.d.ts.map +1 -1
  1481. package/dist/src/utils/validation-patterns.d.ts.map +1 -1
  1482. package/dist/src/utils/validation.d.ts +1 -1
  1483. package/dist/src/utils/validation.d.ts.map +1 -1
  1484. package/dist/src/utils/wallet.d.ts.map +1 -1
  1485. package/dist/src/utils/websocket-patterns.d.ts +1 -2
  1486. package/dist/src/utils/websocket-patterns.d.ts.map +1 -1
  1487. package/dist/src/utils/websocket-validators.d.ts +1 -1
  1488. package/dist/src/utils/websocket-validators.d.ts.map +1 -1
  1489. package/dist/src/wallet/ExternalWalletProvider.d.ts +109 -0
  1490. package/dist/src/wallet/ExternalWalletProvider.d.ts.map +1 -0
  1491. package/dist/src/wallet/GalaChainConnectProvider.d.ts +125 -0
  1492. package/dist/src/wallet/GalaChainConnectProvider.d.ts.map +1 -0
  1493. package/dist/src/wallet/GalaWalletProvider.d.ts +141 -0
  1494. package/dist/src/wallet/GalaWalletProvider.d.ts.map +1 -0
  1495. package/dist/src/wallet/PrivateKeyProvider.d.ts +90 -0
  1496. package/dist/src/wallet/PrivateKeyProvider.d.ts.map +1 -0
  1497. package/dist/src/wallet/detection.d.ts +107 -0
  1498. package/dist/src/wallet/detection.d.ts.map +1 -0
  1499. package/dist/src/wallet/index.d.ts +52 -0
  1500. package/dist/src/wallet/index.d.ts.map +1 -0
  1501. package/dist/src/wallet/types.d.ts +267 -0
  1502. package/dist/src/wallet/types.d.ts.map +1 -0
  1503. package/dist/src/wallet/utils.d.ts +117 -0
  1504. package/dist/src/wallet/utils.d.ts.map +1 -0
  1505. package/dist/test-constants.d.ts +29 -0
  1506. package/dist/test-constants.d.ts.map +1 -0
  1507. package/dist/types/ai-moderation.dto.d.ts +294 -0
  1508. package/dist/types/ai-moderation.dto.d.ts.map +1 -0
  1509. package/dist/types/api-key.dto.d.ts +373 -0
  1510. package/dist/types/api-key.dto.d.ts.map +1 -0
  1511. package/dist/types/backend-responses.d.ts +235 -0
  1512. package/dist/types/backend-responses.d.ts.map +1 -0
  1513. package/dist/types/ban.dto.d.ts +577 -0
  1514. package/dist/types/ban.dto.d.ts.map +1 -0
  1515. package/dist/types/burn.dto.d.ts +170 -0
  1516. package/dist/types/burn.dto.d.ts.map +1 -0
  1517. package/dist/types/cache-management.dto.d.ts +44 -0
  1518. package/dist/types/cache-management.dto.d.ts.map +1 -0
  1519. package/dist/types/chat-messages.dto.d.ts +193 -0
  1520. package/dist/types/chat-messages.dto.d.ts.map +1 -0
  1521. package/dist/types/client-config.dto.d.ts +43 -0
  1522. package/dist/types/client-config.dto.d.ts.map +1 -0
  1523. package/dist/types/comment.dto.d.ts +176 -0
  1524. package/dist/types/comment.dto.d.ts.map +1 -0
  1525. package/dist/types/comments.dto.d.ts +198 -0
  1526. package/dist/types/comments.dto.d.ts.map +1 -0
  1527. package/dist/types/common.d.ts +604 -0
  1528. package/dist/types/common.d.ts.map +1 -0
  1529. package/dist/types/composite-pool.dto.d.ts +101 -0
  1530. package/dist/types/composite-pool.dto.d.ts.map +1 -0
  1531. package/dist/types/constraints.d.ts +378 -0
  1532. package/dist/types/constraints.d.ts.map +1 -0
  1533. package/dist/types/content-flag.dto.d.ts +337 -0
  1534. package/dist/types/content-flag.dto.d.ts.map +1 -0
  1535. package/dist/types/content-reactions.dto.d.ts +132 -0
  1536. package/dist/types/content-reactions.dto.d.ts.map +1 -0
  1537. package/dist/types/dex-pool.dto.d.ts +214 -0
  1538. package/dist/types/dex-pool.dto.d.ts.map +1 -0
  1539. package/dist/types/dto.d.ts +183 -0
  1540. package/dist/types/dto.d.ts.map +1 -0
  1541. package/dist/types/engagement-stats.dto.d.ts +62 -0
  1542. package/dist/types/engagement-stats.dto.d.ts.map +1 -0
  1543. package/dist/types/events.dto.d.ts +80 -0
  1544. package/dist/types/events.dto.d.ts.map +1 -0
  1545. package/dist/types/galachain-api.types.d.ts +297 -0
  1546. package/dist/types/galachain-api.types.d.ts.map +1 -0
  1547. package/dist/types/global-feed.dto.d.ts +203 -0
  1548. package/dist/types/global-feed.dto.d.ts.map +1 -0
  1549. package/dist/types/gswap-responses.types.d.ts +369 -0
  1550. package/dist/types/gswap-responses.types.d.ts.map +1 -0
  1551. package/dist/types/gswap.dto.d.ts +448 -0
  1552. package/dist/types/gswap.dto.d.ts.map +1 -0
  1553. package/dist/types/holder.types.d.ts +106 -0
  1554. package/dist/types/holder.types.d.ts.map +1 -0
  1555. package/dist/types/launchpad.dto.d.ts +1264 -0
  1556. package/dist/types/launchpad.dto.d.ts.map +1 -0
  1557. package/dist/types/launchpad.validation.d.ts +43 -0
  1558. package/dist/types/launchpad.validation.d.ts.map +1 -0
  1559. package/dist/types/liquidity-monitor.dto.d.ts +177 -0
  1560. package/dist/types/liquidity-monitor.dto.d.ts.map +1 -0
  1561. package/dist/types/lock.dto.d.ts +261 -0
  1562. package/dist/types/lock.dto.d.ts.map +1 -0
  1563. package/dist/types/messages.dto.d.ts +386 -0
  1564. package/dist/types/messages.dto.d.ts.map +1 -0
  1565. package/dist/types/moderator.dto.d.ts +607 -0
  1566. package/dist/types/moderator.dto.d.ts.map +1 -0
  1567. package/dist/types/nft.dto.d.ts +155 -0
  1568. package/dist/types/nft.dto.d.ts.map +1 -0
  1569. package/dist/types/notification.dto.d.ts +92 -0
  1570. package/dist/types/notification.dto.d.ts.map +1 -0
  1571. package/dist/types/oembed.dto.d.ts +160 -0
  1572. package/dist/types/oembed.dto.d.ts.map +1 -0
  1573. package/dist/types/options.dto.d.ts +485 -0
  1574. package/dist/types/options.dto.d.ts.map +1 -0
  1575. package/dist/types/overseer.dto.d.ts +530 -0
  1576. package/dist/types/overseer.dto.d.ts.map +1 -0
  1577. package/dist/types/platform-config.dto.d.ts +89 -0
  1578. package/dist/types/platform-config.dto.d.ts.map +1 -0
  1579. package/dist/types/platform-stats.dto.d.ts +40 -0
  1580. package/dist/types/platform-stats.dto.d.ts.map +1 -0
  1581. package/dist/types/pool-state-delta.dto.d.ts +246 -0
  1582. package/dist/types/pool-state-delta.dto.d.ts.map +1 -0
  1583. package/dist/types/pool.dto.d.ts +111 -0
  1584. package/dist/types/pool.dto.d.ts.map +1 -0
  1585. package/dist/types/priceHistory.dto.d.ts +165 -0
  1586. package/dist/types/priceHistory.dto.d.ts.map +1 -0
  1587. package/dist/types/restricted-names.dto.d.ts +50 -0
  1588. package/dist/types/restricted-names.dto.d.ts.map +1 -0
  1589. package/dist/types/result.types.d.ts +104 -0
  1590. package/dist/types/result.types.d.ts.map +1 -0
  1591. package/dist/types/session-auth.dto.d.ts +99 -0
  1592. package/dist/types/session-auth.dto.d.ts.map +1 -0
  1593. package/dist/types/stream-chat.dto.d.ts +810 -0
  1594. package/dist/types/stream-chat.dto.d.ts.map +1 -0
  1595. package/dist/types/streaming-events.dto.d.ts +605 -0
  1596. package/dist/types/streaming-events.dto.d.ts.map +1 -0
  1597. package/dist/types/streaming.dto.d.ts +1178 -0
  1598. package/dist/types/streaming.dto.d.ts.map +1 -0
  1599. package/dist/types/swap-monitor.dto.d.ts +256 -0
  1600. package/dist/types/swap-monitor.dto.d.ts.map +1 -0
  1601. package/dist/types/token-ban.dto.d.ts +194 -0
  1602. package/dist/types/token-ban.dto.d.ts.map +1 -0
  1603. package/dist/types/token-config.dto.d.ts +117 -0
  1604. package/dist/types/token-config.dto.d.ts.map +1 -0
  1605. package/dist/types/token.types.d.ts +336 -0
  1606. package/dist/types/token.types.d.ts.map +1 -0
  1607. package/dist/types/trade.dto.d.ts +457 -0
  1608. package/dist/types/trade.dto.d.ts.map +1 -0
  1609. package/dist/types/trades-query.dto.d.ts +133 -0
  1610. package/dist/types/trades-query.dto.d.ts.map +1 -0
  1611. package/dist/types/transfer.dto.d.ts +156 -0
  1612. package/dist/types/transfer.dto.d.ts.map +1 -0
  1613. package/dist/types/user.dto.d.ts +880 -0
  1614. package/dist/types/user.dto.d.ts.map +1 -0
  1615. package/dist/types/websocket-admin.dto.d.ts +390 -0
  1616. package/dist/types/websocket-admin.dto.d.ts.map +1 -0
  1617. package/dist/types/websocket-data.types.d.ts +35 -0
  1618. package/dist/types/websocket-data.types.d.ts.map +1 -0
  1619. package/dist/types/websocket-events.dto.d.ts +472 -0
  1620. package/dist/types/websocket-events.dto.d.ts.map +1 -0
  1621. package/dist/types/websocket.types.d.ts +118 -0
  1622. package/dist/types/websocket.types.d.ts.map +1 -0
  1623. package/dist/types/weekly-challenge.dto.d.ts +130 -0
  1624. package/dist/types/weekly-challenge.dto.d.ts.map +1 -0
  1625. package/dist/types/wrappable-token.dto.d.ts +305 -0
  1626. package/dist/types/wrappable-token.dto.d.ts.map +1 -0
  1627. package/dist/utils/LiquidityEventExtractor.d.ts +106 -0
  1628. package/dist/utils/LiquidityEventExtractor.d.ts.map +1 -0
  1629. package/dist/utils/Logger.d.ts +136 -0
  1630. package/dist/utils/Logger.d.ts.map +1 -0
  1631. package/dist/utils/MonitoringMetrics.d.ts +151 -0
  1632. package/dist/utils/MonitoringMetrics.d.ts.map +1 -0
  1633. package/dist/utils/PoolKeyNormalizer.d.ts +135 -0
  1634. package/dist/utils/PoolKeyNormalizer.d.ts.map +1 -0
  1635. package/dist/utils/ReconnectionManager.d.ts +142 -0
  1636. package/dist/utils/ReconnectionManager.d.ts.map +1 -0
  1637. package/dist/utils/SignatureHelper.d.ts +140 -0
  1638. package/dist/utils/SignatureHelper.d.ts.map +1 -0
  1639. package/dist/utils/SwapEventExtractor.d.ts +152 -0
  1640. package/dist/utils/SwapEventExtractor.d.ts.map +1 -0
  1641. package/dist/utils/adapters.d.ts +111 -0
  1642. package/dist/utils/adapters.d.ts.map +1 -0
  1643. package/dist/utils/address-formatter.d.ts +318 -0
  1644. package/dist/utils/address-formatter.d.ts.map +1 -0
  1645. package/dist/utils/agent-config.d.ts +288 -0
  1646. package/dist/utils/agent-config.d.ts.map +1 -0
  1647. package/dist/utils/amount-validator.d.ts +268 -0
  1648. package/dist/utils/amount-validator.d.ts.map +1 -0
  1649. package/dist/utils/api-patterns.d.ts +347 -0
  1650. package/dist/utils/api-patterns.d.ts.map +1 -0
  1651. package/dist/utils/array-helpers.d.ts +115 -0
  1652. package/dist/utils/array-helpers.d.ts.map +1 -0
  1653. package/dist/utils/assetUrls.d.ts +450 -0
  1654. package/dist/utils/assetUrls.d.ts.map +1 -0
  1655. package/dist/utils/async-patterns.d.ts +272 -0
  1656. package/dist/utils/async-patterns.d.ts.map +1 -0
  1657. package/dist/utils/auto-pagination.d.ts +549 -0
  1658. package/dist/utils/auto-pagination.d.ts.map +1 -0
  1659. package/dist/utils/bignumber-helpers.d.ts +446 -0
  1660. package/dist/utils/bignumber-helpers.d.ts.map +1 -0
  1661. package/dist/utils/bignumber-pool-cache.d.ts +169 -0
  1662. package/dist/utils/bignumber-pool-cache.d.ts.map +1 -0
  1663. package/dist/utils/bondingCurveCalculations.d.ts +144 -0
  1664. package/dist/utils/bondingCurveCalculations.d.ts.map +1 -0
  1665. package/dist/utils/cacheWarmingHelpers.d.ts +110 -0
  1666. package/dist/utils/cacheWarmingHelpers.d.ts.map +1 -0
  1667. package/dist/utils/composite-pool-converter.d.ts +121 -0
  1668. package/dist/utils/composite-pool-converter.d.ts.map +1 -0
  1669. package/dist/utils/crypto-compat.d.ts +40 -0
  1670. package/dist/utils/crypto-compat.d.ts.map +1 -0
  1671. package/dist/utils/data-transform-patterns.d.ts +393 -0
  1672. package/dist/utils/data-transform-patterns.d.ts.map +1 -0
  1673. package/dist/utils/date-utils.d.ts +205 -0
  1674. package/dist/utils/date-utils.d.ts.map +1 -0
  1675. package/dist/utils/delimiter-parser.d.ts +139 -0
  1676. package/dist/utils/delimiter-parser.d.ts.map +1 -0
  1677. package/dist/utils/error-factories.d.ts +701 -0
  1678. package/dist/utils/error-factories.d.ts.map +1 -0
  1679. package/dist/utils/error-handling-patterns.d.ts +390 -0
  1680. package/dist/utils/error-handling-patterns.d.ts.map +1 -0
  1681. package/dist/utils/error-patterns.d.ts +360 -0
  1682. package/dist/utils/error-patterns.d.ts.map +1 -0
  1683. package/dist/utils/error-utils.d.ts +463 -0
  1684. package/dist/utils/error-utils.d.ts.map +1 -0
  1685. package/dist/utils/error-wrapper.d.ts +208 -0
  1686. package/dist/utils/error-wrapper.d.ts.map +1 -0
  1687. package/dist/utils/errors.d.ts +552 -0
  1688. package/dist/utils/errors.d.ts.map +1 -0
  1689. package/dist/utils/http-factory.d.ts +36 -0
  1690. package/dist/utils/http-factory.d.ts.map +1 -0
  1691. package/dist/utils/http.d.ts +97 -0
  1692. package/dist/utils/http.d.ts.map +1 -0
  1693. package/dist/utils/load-env.d.ts +31 -0
  1694. package/dist/utils/load-env.d.ts.map +1 -0
  1695. package/dist/utils/multipart-helpers.d.ts +38 -0
  1696. package/dist/utils/multipart-helpers.d.ts.map +1 -0
  1697. package/dist/utils/multipart.d.ts +63 -0
  1698. package/dist/utils/multipart.d.ts.map +1 -0
  1699. package/dist/utils/nft-helpers.d.ts +62 -0
  1700. package/dist/utils/nft-helpers.d.ts.map +1 -0
  1701. package/dist/utils/numeric-patterns.d.ts +289 -0
  1702. package/dist/utils/numeric-patterns.d.ts.map +1 -0
  1703. package/dist/utils/numeric-wrappers.d.ts +149 -0
  1704. package/dist/utils/numeric-wrappers.d.ts.map +1 -0
  1705. package/dist/utils/object-extractors.d.ts +115 -0
  1706. package/dist/utils/object-extractors.d.ts.map +1 -0
  1707. package/dist/utils/object-patterns.d.ts +81 -0
  1708. package/dist/utils/object-patterns.d.ts.map +1 -0
  1709. package/dist/utils/pagination-helpers.d.ts +161 -0
  1710. package/dist/utils/pagination-helpers.d.ts.map +1 -0
  1711. package/dist/utils/pagination-validation.d.ts +88 -0
  1712. package/dist/utils/pagination-validation.d.ts.map +1 -0
  1713. package/dist/utils/pool-pair-parser.d.ts +57 -0
  1714. package/dist/utils/pool-pair-parser.d.ts.map +1 -0
  1715. package/dist/utils/pool-state-validator.d.ts +207 -0
  1716. package/dist/utils/pool-state-validator.d.ts.map +1 -0
  1717. package/dist/utils/position-filters.d.ts +252 -0
  1718. package/dist/utils/position-filters.d.ts.map +1 -0
  1719. package/dist/utils/primitives.d.ts +76 -0
  1720. package/dist/utils/primitives.d.ts.map +1 -0
  1721. package/dist/utils/query-params.d.ts +89 -0
  1722. package/dist/utils/query-params.d.ts.map +1 -0
  1723. package/dist/utils/response-handlers.d.ts +225 -0
  1724. package/dist/utils/response-handlers.d.ts.map +1 -0
  1725. package/dist/utils/response-helpers.d.ts +28 -0
  1726. package/dist/utils/response-helpers.d.ts.map +1 -0
  1727. package/dist/utils/response-normalizers.d.ts +115 -0
  1728. package/dist/utils/response-normalizers.d.ts.map +1 -0
  1729. package/dist/utils/safe-parsers.d.ts +487 -0
  1730. package/dist/utils/safe-parsers.d.ts.map +1 -0
  1731. package/dist/utils/service-validators.d.ts +268 -0
  1732. package/dist/utils/service-validators.d.ts.map +1 -0
  1733. package/dist/utils/slippage-utils.d.ts +70 -0
  1734. package/dist/utils/slippage-utils.d.ts.map +1 -0
  1735. package/dist/utils/string-patterns.d.ts +404 -0
  1736. package/dist/utils/string-patterns.d.ts.map +1 -0
  1737. package/dist/utils/string-transforms.d.ts +89 -0
  1738. package/dist/utils/string-transforms.d.ts.map +1 -0
  1739. package/dist/utils/string-utils.d.ts +108 -0
  1740. package/dist/utils/string-utils.d.ts.map +1 -0
  1741. package/dist/utils/swap-delta-calculator.d.ts +231 -0
  1742. package/dist/utils/swap-delta-calculator.d.ts.map +1 -0
  1743. package/dist/utils/tick-crossing-handler.d.ts +250 -0
  1744. package/dist/utils/tick-crossing-handler.d.ts.map +1 -0
  1745. package/dist/utils/token-format-converter.d.ts +175 -0
  1746. package/dist/utils/token-format-converter.d.ts.map +1 -0
  1747. package/dist/utils/token-parser.d.ts +235 -0
  1748. package/dist/utils/token-parser.d.ts.map +1 -0
  1749. package/dist/utils/token-stringification.d.ts +168 -0
  1750. package/dist/utils/token-stringification.d.ts.map +1 -0
  1751. package/dist/utils/tokenNameNormalizer.d.ts +96 -0
  1752. package/dist/utils/tokenNameNormalizer.d.ts.map +1 -0
  1753. package/dist/utils/tokenNormalizer.d.ts +167 -0
  1754. package/dist/utils/tokenNormalizer.d.ts.map +1 -0
  1755. package/dist/utils/trade-transformers.d.ts +28 -0
  1756. package/dist/utils/trade-transformers.d.ts.map +1 -0
  1757. package/dist/utils/transfer-validation.d.ts +58 -0
  1758. package/dist/utils/transfer-validation.d.ts.map +1 -0
  1759. package/dist/utils/type-guard-factory.d.ts +260 -0
  1760. package/dist/utils/type-guard-factory.d.ts.map +1 -0
  1761. package/dist/utils/unique-key-generator.d.ts +148 -0
  1762. package/dist/utils/unique-key-generator.d.ts.map +1 -0
  1763. package/dist/utils/validation-helpers.d.ts +1074 -0
  1764. package/dist/utils/validation-helpers.d.ts.map +1 -0
  1765. package/dist/utils/validation-patterns.d.ts +768 -0
  1766. package/dist/utils/validation-patterns.d.ts.map +1 -0
  1767. package/dist/utils/validation.d.ts +140 -0
  1768. package/dist/utils/validation.d.ts.map +1 -0
  1769. package/dist/utils/wallet.d.ts +185 -0
  1770. package/dist/utils/wallet.d.ts.map +1 -0
  1771. package/dist/utils/websocket-errors.d.ts +30 -0
  1772. package/dist/utils/websocket-errors.d.ts.map +1 -0
  1773. package/dist/utils/websocket-patterns.d.ts +680 -0
  1774. package/dist/utils/websocket-patterns.d.ts.map +1 -0
  1775. package/dist/utils/websocket-validators.d.ts +30 -0
  1776. package/dist/utils/websocket-validators.d.ts.map +1 -0
  1777. package/dist/wallet/ExternalWalletProvider.d.ts +109 -0
  1778. package/dist/wallet/ExternalWalletProvider.d.ts.map +1 -0
  1779. package/dist/wallet/GalaChainConnectProvider.d.ts +125 -0
  1780. package/dist/wallet/GalaChainConnectProvider.d.ts.map +1 -0
  1781. package/dist/wallet/GalaWalletProvider.d.ts +141 -0
  1782. package/dist/wallet/GalaWalletProvider.d.ts.map +1 -0
  1783. package/dist/wallet/PrivateKeyProvider.d.ts +90 -0
  1784. package/dist/wallet/PrivateKeyProvider.d.ts.map +1 -0
  1785. package/dist/wallet/detection.d.ts +107 -0
  1786. package/dist/wallet/detection.d.ts.map +1 -0
  1787. package/dist/wallet/index.d.ts +52 -0
  1788. package/dist/wallet/index.d.ts.map +1 -0
  1789. package/dist/wallet/types.d.ts +267 -0
  1790. package/dist/wallet/types.d.ts.map +1 -0
  1791. package/dist/wallet/utils.d.ts +117 -0
  1792. package/dist/wallet/utils.d.ts.map +1 -0
  1793. package/dist/wallet.cjs +1 -0
  1794. package/dist/wallet.esm.js +1 -0
  1795. package/package.json +177 -41
  1796. package/dist/examples/utils/orchestrator-base.d.ts +0 -313
  1797. package/dist/examples/utils/orchestrator-base.d.ts.map +0 -1
  1798. package/dist/index.cjs.js +0 -1
  1799. package/dist/src/services/ChatMessagesService.d.ts +0 -152
  1800. package/dist/src/services/ChatMessagesService.d.ts.map +0 -1
  1801. package/dist/src/services/CommentService.d.ts +0 -119
  1802. package/dist/src/services/CommentService.d.ts.map +0 -1
  1803. package/dist/src/services/CommentsService.d.ts +0 -155
  1804. package/dist/src/services/CommentsService.d.ts.map +0 -1
  1805. package/dist/src/services/GalaChainGatewayClient.d.ts +0 -227
  1806. package/dist/src/services/GalaChainGatewayClient.d.ts.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=require("ethers"),t=require("@gala-chain/connect"),n=require("uuid"),r=require("zod"),o=require("bignumber.js"),i=require("@gala-chain/api"),s=require("@gala-chain/dex"),a=require("axios"),c=require("socket.io-client"),l=require("dotenv"),u=require("fs"),d=require("path");function h(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var g=h(n),p=h(l),f=h(u),m=h(d);const y={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",GET_TOKEN_BADGES:"/v1/tokens/:tokenName/badges",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",USER_BALANCES:"/v1/users/:address/balances",USER_REPORT:"/v1/users/:address/report",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},w="/v1/users/referrals/url",b="/v1/users/referrals",k="/v1/users/referrals/summary",v="/v1/tokens/:tokenName/start-stream",S="/v1/tokens/:tokenName/stop-stream",A="/v1/tokens/:tokenName/stream/disable",E="/v1/tokens/:tokenName/stream/enable",T="/v1/tokens/:tokenName/reset-key",I="/v1/tokens/:tokenName/recordings",C="/v1/tokens/:tokenName/recordings/:assetId/download",x="/v1/tokens/:tokenName/recordings/:assetId",N="/v1/tokens/:tokenName/stream/simulcast",_="/v1/tokens/:tokenName/stream/simulcast",D="/v1/tokens/:tokenName/stream/simulcast/:targetId",P="/v1/config",R="/v1/config",B="/v1/config",M="/v1/tokens/:tokenName/role",O="/v1/roles",L="/v1/tokens/:tokenName/access",U="/v1/tokens/:tokenName/credentials",F="/auth/login",$="/auth/logout",q="/auth/refresh",K="/auth/session",G="/v1/tokens/:tokenName/bans",H="/v1/tokens/:tokenName/bans",W="/v1/tokens/:tokenName/bans/:userAddress",z="/v1/tokens/:tokenName/bans/:userAddress",V="/v1/tokens/:tokenName/active-users",j="/v1/user-bans",X="/v1/user-bans",Q="/v1/user-bans/:userAddress",Y="/v1/user-bans/:userAddress",J={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Z="/v1/moderator-invites",ee="/v1/moderator-invites/claim",te="/v1/moderated-tokens",ne="/v1/moderator-invites",re="/v1/moderator-invites/:id",oe="/v1/moderator-invites/:id/role",ie="/v1/moderator-invites/:id",se="/v1/moderator-invites/code/:code",ae={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},ce="/v1/overseer-invites",le="/v1/overseer-invites",ue="/v1/overseer-invites/code/:code",de="/v1/overseer-invites/claim",he="/v1/overseer-invites/:id",ge="/v1/overseers",pe="/v1/overseers",fe="/v1/overseers/:address",me="/v1/overseers/me",ye="/v1/overseer-summary",we="/v1/overseer-summary/bans",be="/v1/overseer-summary/token-bans",ke="/v1/overseer-summary/invites",ve="/v1/overseer-summary/flags",Se="/v1/overseer-summary/users",Ae="/v1/users",Ee="/v1/users/:address/summary",Te="/v1/cache/flush/address/:address",Ie="/v1/cache/flush/token/:tokenName",Ce="/v1/cache/flush/all",xe="/v1/cache/flush/wallet-aliases/:address",Ne="/v1/cache/flush/wallet-aliases",_e="/v1/token-bans",De="/v1/token-bans",Pe="/v1/token-bans/:tokenName",Re="/v1/token-bans/:tokenName",Be="/v1/reactions",Me="/v1/reactions",Oe="/v1/trades",Le={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/unpin",GET_MESSAGE_STATS:"/v1/messages/stats"},Ue="/v1/restricted-token-names",Fe="/v1/restricted-token-names",$e="/live/:tokenName/chat",qe="/live/:tokenName/chat",Ke="/live/:tokenName/chat",Ge="/live/chat",He="/live/chat",We="/live/chat",ze="/live/:tokenName/chat/slow-mode",Ve="/live/:tokenName/engagement-stats",je={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},Xe="/v1/stats",Qe="/v1/trading/fee",Ye="/v1/trading/sale-details",Je="/v1/trading/quote",Ze="/v1/trading/premint-quote",et={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},tt="/v1/notifications/register",nt="/v1/notifications/unregister",rt="/v1/notifications/preferences",ot="/v1/notifications/preferences",it="/v1/config/client-flags",st={NATIVE:"native",EXACT:"exact"},at={LOCAL:"local",EXTERNAL:"external"};class ct extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function lt(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 ut(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&lt(t.token0ClassKey)&&lt(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}const dt={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 ht extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class gt extends ht{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}class pt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class ft extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class mt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class yt extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class wt extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class bt 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 kt extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class vt extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class St extends ht{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class At extends ht{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function Et(e){return e instanceof Error}function Tt(e){return Et(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function It(e){return"object"==typeof e&&null!==e?e:void 0}function Ct(e,t){const n=It(e),r=It(n?.launchpadError),o=_t(e)?e.response:void 0,i=It(o?.data),s=e instanceof ct?e.status:"number"==typeof r?.statusCode?r.statusCode:o?.status,a="string"==typeof i?.message?i.message:"string"==typeof i?.Message?i.Message:Tt(e);if(403===s)return new gt(""!==a?a:"One or both tokens are restricted (blacklisted or not yet graduated).");if(404===s)return"pool"===t?new At(""!==a?a:"DEX pool not found"):new ct(404,""!==a?a:"Position not found",i);if(429===s){const t=o?.headers?.["retry-after"],n="string"==typeof t||"number"==typeof t?String(t):void 0;return new pt(`Trade backend per-IP rate limit exceeded (100 requests per 60 seconds).${void 0===n?"":` Retry-After: ${n}.`}`,429,e instanceof Error?e:void 0)}if(502===s)return new pt("Trade backend upstream chain unavailable",502,e instanceof Error?e:void 0);if(e instanceof ct)return e;if(_t(e)){const e=It(i?.Data)??i;return new ct(s??500,`${t}: ${a}`,e)}return new ct(500,`${t}: ${Tt(e)}`)}function xt(e){return Et(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Nt(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 _t(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Dt(e,t){if(null==e||"object"!=typeof e)throw new Error(`${t}: No response - expected object, got ${typeof e}`);const n=e;if(!("Status"in n))throw new Error(`${t}: Response missing 'Status' property`);const r=n.Status;if("number"!=typeof r)throw new Error(`${t}: Response Status must be a number, got ${typeof r}`);if(1!==r)throw new Error(`${t}: Response status indicates failure (Status: ${r})`);return n}function Pt(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function Rt(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 Bt="Token name is required and must be a string",Mt=e=>`Could not find vault address for token: ${e}`;function Ot(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Lt(e,t){return new ht(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Ut(e,t){const n=Ot(e,t);return new ht(`${n} is required`,e,"REQUIRED")}function Ft(e,t,n){const r=Ot(e,n);return new ht(`${r} must be ${t}`,e,"INVALID_FORMAT")}function $t(e,t,n){return new pt(e,t,n)}function qt(e,t){return new ft(e,t)}function Kt(e,t,n){return new mt(e,t,n)}function Gt(e,t,n,r){n&&n.error(`${t}:`,e);const o=_t(e)?e.response?.status:void 0;return $t(`${t}: ${Tt(e)}`,o,Et(e)?e:void 0)}function Ht(e,t,n,r,o){const i=Ot(e,o);return new ht(`${i} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function Wt(e,t,n,r){const o=Ot(e,r);return new ht(`${o} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function zt(e,t,n,r){const o=Ot(e,r);return new ht(`${o} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Vt(e,t,n,r){const o=Ot(e,r),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new ht(`${o} must be ${t}${i}`,e,"INVALID_TYPE")}function jt(e,t,n){const r=Ot(e,n);return new ht(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Xt(e){return new ht(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function Qt(e,t,n,r){const o=Ot(e,r);return new ht(`Invalid ${o}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Yt(e,t){if(e.length<2)return Ut(void 0!==e[0]&&""!==e[0]?e[0]:"field");let n;if(2===e.length)n=e.join(" or ");else{n=`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}return new ht(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function Jt(e,t,n,r){const o=Ot(e,r);return new ht(`${o} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Zt(e,t){const n=Ot(e,t);return new ht(`${n} cannot be empty`,e,"EMPTY_STRING")}function en(e){return null!=e&&"object"==typeof e&&"data"in e}function tn(e,t,n=!1){const r=!0===e.error,o=n&&(null===e.data||void 0===e.data);if(r||o){const n=e?.statusCode??e.status??void 0;throw $t(e?.message??t,n)}}function nn(e){if(en(e))return e.data}function rn(e,t="No data found in response"){if(!en(e))throw $t(t);const n=e.data;if(null==n)throw $t(t);return n}async function on(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:o=!1}=t;o&&r&&r.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new ht(`${n}: No response from server`,"response","NO_RESPONSE");if(tn(t,n,!0),o&&r&&r.debug(`${n}: completed successfully`),void 0===t.data)throw new ht(`${n}: No data returned from API`,"data","NO_DATA");return t.data}catch(e){throw r&&r.error(n,{error:e}),e}}async function sn(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:o=!1}=t;o&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return o&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function an(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:o=!1}=t;o&&r&&r.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new ht(`${n}: No response from server`,"response","NO_RESPONSE");return tn(t,n,!0),o&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}class cn{}function ln(e){return e.trim().toLowerCase()}function un(e){return e.trim().toUpperCase()}function dn(e){return e.trim().toUpperCase()}var hn;cn.BASE_PRICE=1650667151e-14,cn.PRICE_SCALING_FACTOR=1166069e-12,cn.TRADING_FEE_FACTOR=.001,cn.GAS_FEE="1",cn.MIN_UNBONDING_FEE_FACTOR=0,cn.MAX_UNBONDING_FEE_FACTOR=.5,cn.NET_UNBONDING_FEE_FACTOR=.5,cn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7,function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(hn||(hn={}));class gn{constructor(e){this.levelPriority={[hn.DEBUG]:0,[hn.INFO]:1,[hn.WARN]:2,[hn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?hn.DEBUG:hn.INFO)}debug(e,t){this.log(hn.DEBUG,e,t)}info(e,t){this.log(hn.INFO,e,t)}warn(e,t){this.log(hn.WARN,e,t)}error(e,t){this.log(hn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===hn.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,o=this.getConsoleMethod(e);void 0!==n?Et(n)?o(`${r} ${t}`,n.message,xt(n)??""):o(`${r} ${t}`,n):o(`${r} ${t}`)}getConsoleMethod(e){switch(e){case hn.DEBUG:return console.debug;case hn.INFO:return console.info;case hn.WARN:return console.warn;case hn.ERROR:return console.error;default:return console.log}}child(e){return new gn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[hn.DEBUG]>=this.levelPriority[this.minLevel]}}function pn(e){return"string"==typeof e&&e.trim().length>0}function fn(e){return null==e||""===e}function mn(e){return null==e}const yn=new gn({debug:!1,context:"DateUtils"});function wn(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(yn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return yn.warn(`Date parsing error for "${e}":`,t),new Date}}function bn(e){if(null==e)return!1;if(e instanceof Date)return!isNaN(e.getTime());if("string"!=typeof e)return!1;const t=new Date(e);return!isNaN(t.getTime())}function kn(e){return Date.now()-e}const vn={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},Sn={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},An={MIN_LENGTH:1,MAX_LENGTH:50},En=100,Tn=20,In={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},Cn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},xn={MAX_LENGTH:100},Nn={COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},_n={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})$/}},Dn=60,Pn=31536e3,Rn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Bn={PATTERN:/^[a-fA-F0-9]{64}$/},Mn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},On=50,Ln=1,Un=100,Fn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function $n(e,t){if(fn(e))return t;try{return JSON.parse(e)}catch{return t}}function qn(e,t=0){if(fn(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 Kn(e,t,n){if(mn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function Gn(e,t=0){if(fn(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 Hn(e,t,n){if(mn(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function Wn(e,t="0"){if(fn(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 zn(e,t){if(mn(e)||""===e)throw Ut(t);if(o.isBigNumber(e)){if(e.isNaN())throw jt(t,"NaN");return e}try{const n=new o(e);if(n.isNaN())throw jt(t,e);if(!n.isFinite())throw jt(t,e);return n}catch(n){if(n instanceof ht)throw n;throw jt(t,e)}}function Vn(e,t=0){if(mn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return qn(String(e).replace("%","").trim(),t)}function jn(e,t=18){const n=qn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Xn(e){return jn(e,8)}function Qn(e){return jn(e,18)}function Yn(e,t,n,r){if("number"!=typeof e)throw Vt(r,"a number",e,r);if(e<t||e>n)throw Ht(r,t,n,e)}function Jn(e,t,n){if("string"!=typeof e)throw Vt(n,"a string",e,n);if(e.length>t)throw zt(n,t,e.length)}function Zn(e,t){if("number"!=typeof e)throw Vt(t,"a number",e,t);if(!Number.isInteger(e))throw Vt(t,"an integer",e,t);if(e<=0)throw Wt(t,1,e,t)}function er(e,t,n="range"){const r="number"==typeof e?e:Number(e),o="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(o))throw Vt(n,"numeric values",void 0,n);if(r>o)throw new ht(`Minimum value (${r}) must be less than or equal to maximum value (${o}) for ${n}`,n,dt.INVALID_RANGE)}function tr(e,t,n=!1){if("string"!=typeof e)throw Vt(t,"a string",e,t);if(!n&&0===e.trim().length)throw Ut(t,`${t} (non-empty string)`)}function nr(e,t){if("ASC"!==e&&"DESC"!==e)throw new ht(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function rr(e,t,n){const r="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new ht(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(o))throw new ht(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new ht(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(o>.5)throw new ht(`${n} maxFee must be <= 0.5, received ${o}`,n,"INVALID_FEE_MAXIMUM");if(r>o)throw new ht(`${n} minFee (${r}) must be <= maxFee (${o})`,n,"INVALID_FEE_RANGE")}const or={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},ir=pn,sr=fn,ar=mn;function cr(e,t,n=100,r,o){if(void 0!==o&&"string"!=typeof o)throw new ht("cursor must be a string","cursor",dt.INVALID_TYPE);const i=r??t,s=void 0!==r?"pageSize":"limit";if(void 0!==i&&(Zn(i,s),i>n))throw new ht(`${s} must be at most ${n}`,s,dt.TOO_LARGE)}function lr(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function ur(e){return Object.values(e)}function dr(e,t,n,r={}){const{description:o="parameter",treatEmptyAsNull:i=!0}=r,s=e[t],a=e[n],c=null!=s&&(!i||""!==s),l=null!=a&&(!i||""!==a);if(!c&&!l)throw qt(`Either ${t} or ${n} must be provided (${o})`,n);if(c&&l)throw qt(`Cannot provide both ${t} and ${n}. Provide exactly one (${o}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function hr(e,t="tokenName",n=vn){if(!ir(e))throw Ut(t);const r=e.trim();if(0===r.length)throw Ut(t);if(r.length<n.MIN_LENGTH)throw Ht(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw Ht(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new ht(`${t} must contain only alphanumeric characters`,t,dt.INVALID_FORMAT)}function gr(e,t="tokenName",n=vn){if(null==e)throw Ut(t,t);if("string"!=typeof e)throw Vt(t,"a string",e);const r=e.trim();if(0===r.length)throw Ut(t,t);if(!n.PATTERN.test(r))throw new ht(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,dt.INVALID_FORMAT)}function pr(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:o=!1,optional:i=!1,validator:s}of e){const e=n[t];if((!i||void 0!==e)&&(!o||null!==e)){if(typeof e!==r)return!1;if(s&&!s(e))return!1}}return!0}}const fr={requiredString:e=>t=>ar(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!sr(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!ar(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>ar(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!ar(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>ar(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!ar(t))return"string"!=typeof t?`${e} must be a string`:bn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(ar(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return or.ETH_ADDRESS.test(n)||or.BACKEND_ADDRESS.test(n)||or.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function mr(e){return""===e||0===e.trim().length}function yr(e,t,n){if(!ar(e)){if("string"!=typeof e)throw Vt(t,"a string",e,t);if(e.length>n)throw new ht(`${t} must be at most ${n} characters`,t,dt.TOO_LARGE)}}function wr(e,t){if(ar(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 Vt(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new ht(`${t} must be a valid date`,t,dt.INVALID_FORMAT)}function br(e,t,n){try{Zn(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new ht(`${e} failed: ${t}`,n,r)}(n,"must be a positive integer",t)}}function kr(e,t,n="status"){void 0!==e&&function(e,t,n){const r=Object.values(t);if(!r.includes(e))throw new ht(`${n} must be one of: ${r.join(", ")}`,n,dt.INVALID_FORMAT)}(e,t,n)}class vr{constructor(e,t=!1,n){this.http=e,this.logger=new gn({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){if("test"===process.env.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new ft("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=xt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){br(e,t,n)}}class Sr{constructor(e=!1,t){this.logger=t||new gn({debug:e,context:this.constructor.name})}}class Ar extends Sr{constructor(e=!1){super(e),this.cache=new Map}get(e){const t=this.normalizeKey(e);return this.cache.get(t)}set(e,t){const n=this.normalizeKey(e);this.cache.set(n,t)}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(){this.cache.clear(),this.logger.debug("Cleared cache")}dump(){return new Map(this.cache)}size(){return this.cache.size}isEmpty(){return 0===this.cache.size}buildBaseStats(){return{totalItems:this.cache.size}}}class Er extends Ar{constructor(e=!1){super(e)}normalizeKey(e){return ln(e).replace(/\s+/g," ").replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g,"")}getLRUKey(){return this.cache.keys().next().value??null}updateCacheEntry(e,t){const n=this.cache.get(e);if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=Er.MAX_CACHE_SIZE){const e=this.getLRUKey();null!==e&&this.cache.delete(e)}this.cache.set(e,{...n??{},...t,lastUpdated:Date.now()})}warmFromPoolData(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}set(e,t){const n=this.normalizeKey(e);this.updateCacheEntry(n,t)}getByName(e){const t=this.normalizeKey(e);return this.cache.get(t)}getMaxSupply(e){const t=this.normalizeKey(e),n=this.cache.get(t);return n?.maxSupply??cn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let 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,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(o+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(o+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(o+=2*n.symbol.length),o+=32,t+=o}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${ln(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${ln(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${ln(e)}`;return this.cache.has(t)}}Er.MAX_CACHE_SIZE=1e4;class Tr extends t.ChainCallDTO{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,void 0!==e.websiteUrl&&(this.websiteUrl=e.websiteUrl),void 0!==e.telegramUrl&&(this.telegramUrl=e.telegramUrl),void 0!==e.twitterUrl&&(this.twitterUrl=e.twitterUrl),void 0!==e.instagramUrl&&(this.instagramUrl=e.instagramUrl),void 0!==e.facebookUrl&&(this.facebookUrl=e.facebookUrl),void 0!==e.redditUrl&&(this.redditUrl=e.redditUrl),void 0!==e.tiktokUrl&&(this.tiktokUrl=e.tiktokUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration),void 0!==e.saleStartTime&&(this.saleStartTime=e.saleStartTime)}}function Ir(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}const Cr={ETHEREUM:or.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:or.BACKEND_ADDRESS,CLIENT:or.CLIENT_ADDRESS};class xr{toBackendFormat(t){if(!ir(t))throw new ht("Address is required and must be a string","address","REQUIRED");let n=t;if(t.startsWith("eth|")){if(n=t.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new ht(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Ir(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new ht(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!ir(e))throw new ht("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 ht(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],r=void 0!==n&&""!==n?6:4;return`0x${e.substring(r)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!Cr.CLIENT.test(e))throw new ht(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!Cr.BACKEND.test(e))throw new ht(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!ir(e)&&(!!Cr.ETHEREUM.test(e)||(!!Cr.ETHEREUM_NO_PREFIX.test(e)||(!!Cr.BACKEND.test(e)||!!Cr.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new ht(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return ir(e)?Cr.ETHEREUM.test(e)||Cr.ETHEREUM_NO_PREFIX.test(e)?"ethereum":Cr.BACKEND.test(e)?"backend":Cr.CLIENT.test(e)?"client":null:null}normalize(e){if(void 0!==e&&""!==e)return e.toLowerCase()}extractHex(e){if(e.startsWith("eth|"))return e.substring(4).toLowerCase();if(e.startsWith("0x"))return Ir(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new ht(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Nr=new xr,_r=Ir;function Dr(e){return Nr.toBackendFormat(e)}function Pr(e){return Nr.toEthereumFormat(e)}function Rr(e){return Nr.normalizeInput(e)}function Br(e){return Nr.isValid(e)}function Mr(e,t="address"){Nr.assertValid(e,t)}function Or(e){const t="string"==typeof e?e:e.address;return Nr.toBackendFormat(t)}function Lr(e){return Nr.detectFormat(e)}var Ur=Object.freeze({__proto__:null,AddressFormatter:xr,assertValidWalletAddress:Mr,detectFormat:Lr,fromBackendAddressFormat:Pr,isValidAddress:Br,normalizeAddressInput:Rr,stripHexPrefix:_r,toBackendAddressFormat:Dr,toBackendAddressFromEthers:Or});const Fr=r.z.string({message:"Token name is required"}).min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),$r=r.z.string({message:"Token symbol is required"}).min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),qr=r.z.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Kr=r.z.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Gr=r.z.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Hr=r.z.string().min(1,"Full name is required").max(100,"Full name must be at most 100 characters").regex(/^[a-zA-Z\s]+$/,"Full name can only contain letters and spaces"),Wr=r.z.string().regex(or.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),zr=r.z.string().regex(or.ETH_ADDRESS,"Invalid Ethereum address format"),Vr=r.z.string().refine(e=>or.BACKEND_ADDRESS.test(e)||or.ETH_ADDRESS.test(e)||or.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new xr).normalizeInput(e)??e),jr=r.z.string().refine(e=>or.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Xr=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>qn(e,0)>0,"Amount must be greater than zero"),Qr=r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>qn(e,0)>=0,"Amount must be zero or greater"),Yr=r.z.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),Jr=r.z.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),Zr=r.z.number().int("Page must be an integer").min(1,"Page must be at least 1").max(1e3,"Page must be at most 1000").default(1);function eo(e=100){return r.z.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(e,`Limit must be at most ${e}`).default(10)}const to=eo(100),no=eo(20),ro=eo(20),oo=r.z.number().int("File size must be an integer").min(1,"File must be at least 1 byte").max(10485760,"File must be at most 10MB"),io=r.z.string().max(255,"Filename must be at most 255 characters"),so=r.z.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),ao=r.z.string().datetime("Must be a valid ISO 8601 date string"),co=r.z.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),lo=r.z.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),uo=r.z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,"Transaction ID must be in UUID format"),ho=r.z.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),go=[".png",".jpg",".jpeg",".gif",".webp",".svg"],po=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),name:io,size:oo,type:so}),fo=r.z.instanceof(File).refine(e=>e.size>=1&&e.size<=10485760,"File size must be between 1 byte and 10MB").refine(e=>["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"].includes(e.type),"File must be a valid image type (PNG, JPG, JPEG, GIF, WebP, or SVG)").refine(e=>e.name.length<=255,"Filename must be at most 255 characters"),mo=r.z.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),yo=r.z.union([fo,mo]),wo=r.z.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),bo=io.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return go.includes(t)},`Filename must end with one of: ${go.join(", ")}`),ko=r.z.object({websiteUrl:Jr,telegramUrl:Jr,twitterUrl:Jr,instagramUrl:Jr,facebookUrl:Jr,redditUrl:Jr,tiktokUrl:Jr}).refine(e=>void 0!==e.websiteUrl||void 0!==e.telegramUrl||void 0!==e.twitterUrl||void 0!==e.instagramUrl||void 0!==e.facebookUrl||void 0!==e.redditUrl||void 0!==e.tiktokUrl,"At least one social URL (website, telegram, twitter, instagram, facebook, reddit, or tiktok) is required"),vo=r.z.string().min(1,"Token category must not be empty").default("Unit"),So=r.z.string().min(1,"Token collection must not be empty").default("Token"),Ao=r.z.object({minFeePortion:r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>qn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>qn(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:r.z.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>qn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>qn(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>qn(e.maxFeePortion,0)>=qn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Eo=r.z.object({tokenName:Fr,tokenSymbol:$r,tokenDescription:qr,tokenImage:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer),r.z.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Qr.default("0"),websiteUrl:Jr,telegramUrl:Jr,twitterUrl:Jr,instagramUrl:Jr,facebookUrl:Jr,redditUrl:Jr,tiktokUrl:Jr,tokenCategory:vo,tokenCollection:So,reverseBondingCurveConfiguration:Ao.optional(),saleStartTime:r.z.number().int().positive().optional(),privateKey:lo.optional()}),To=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),tokenName:Fr}),Io=r.z.enum(["RECENT","POPULAR"]),Co=r.z.object({tokenName:Fr.optional(),symbol:$r.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),xo=r.z.enum(["NATIVE","MEME"]),No=r.z.enum(["IN","OUT"]),_o=r.z.object({from:r.z.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:r.z.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:r.z.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Fr}),Do=r.z.object({tokenName:Fr,slippageToleranceFactor:r.z.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:r.z.number().min(0).max(1).optional(),privateKey:lo.optional()}),Po=r.z.object({offset:r.z.number().int().min(0).default(0),pageSize:r.z.number().int().min(1).max(100).default(10)}),Ro=r.z.object({offset:r.z.number().int().min(0).default(0),pageSize:r.z.number().int().min(1).max(20).default(10)}),Bo=r.z.object({offset:r.z.number().int().min(0).default(0),pageSize:r.z.number().int().min(1).max(20).default(10)}),Mo=Po.extend({type:r.z.enum(["RECENT","POPULAR"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),Oo=Ro.extend({tokenName:r.z.string().min(1).max(50).optional(),search:r.z.string().min(1).max(100).optional()}),Lo=Bo.extend({tradeType:r.z.enum(["BUY","SELL"]).optional(),tokenName:r.z.string().min(1).max(50).optional(),userAddress:r.z.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:r.z.string().datetime().optional(),endDate:r.z.string().datetime().optional(),sortOrder:r.z.enum(["ASC","DESC"]).default("DESC")}),Uo=r.z.object({page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()});const Fo=r.z.enum(["buy","sell"]),$o=r.z.enum(["BUY","SELL"]),qo=r.z.object({tradeType:Fo,tokenAmount:Xr,vaultAddress:jr,userAddress:Vr,slippageTolerance:Xr.optional(),deadline:r.z.number().int().positive().optional()}),Ko=r.z.object({tokenSymbol:$r,nativeTokenQuantity:Xr,expectedToken:Xr,maxAcceptableReverseBondingCurveFee:Qr.default("0").optional()}),Go=r.z.object({tokenSymbol:$r,tokenQuantity:Xr,expectedNativeToken:Xr,maxAcceptableReverseBondingCurveFee:Qr.default("0").optional()}),Ho=Bo.extend({tokenName:Kr.optional()}),Wo=r.z.object({page:r.z.number().int().min(1).max(1e3).default(1).optional(),limit:r.z.number().int().min(1).max(20).default(10).optional()}),zo=r.z.enum(["NATIVE","MEME"]),Vo=r.z.enum(["IN","OUT"]),jo=r.z.object({type:zo,method:Vo,vaultAddress:jr,amount:Xr}),Xo=r.z.object({nativeTokenQuantity:Xr}),Qo=r.z.object({vaultAddress:jr}),Yo=r.z.object({minFeePortion:Xr,maxFeePortion:Xr}),Jo=r.z.enum(["all","DEFI","ASSET"]),Zo=Ro.extend({type:Jo.optional(),address:Vr.optional(),search:Gr.optional(),tokenName:Kr.optional()}),ei=r.z.object({address:Vr.optional(),refresh:r.z.boolean().optional()}),ti=r.z.object({profileImage:r.z.string(),fullName:Hr,address:Vr,privateKey:lo.optional()}),ni=r.z.object({file:r.z.union([r.z.instanceof(File),r.z.instanceof(Buffer)]),address:Vr.optional(),privateKey:lo.optional()}),ri=r.z.object({created:r.z.number(),createdBy:r.z.string(),expires:r.z.number(),instanceId:r.z.string(),lockAuthority:r.z.string(),name:r.z.string(),quantity:r.z.string(),vestingPeriodStart:r.z.number()}),oi=r.z.object({address:Vr,tokenId:r.z.union([r.z.string(),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string()}),r.z.object({collection:r.z.string(),category:r.z.string(),type:r.z.string(),additionalKey:r.z.string(),instance:r.z.string()})]).optional(),tokenName:Kr.optional(),withExpired:r.z.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function ii(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}const si=ii(Fr),ai=ii($r),ci=ii(qr),li=ii(Vr),ui=ii(jr),di=ii(Xr),hi=ii(Hr),gi=ii(Gr),pi=ii(Kr),fi=ii(Eo),mi=ii(ko),yi=ii(To),wi=ii(Co),bi=ii(Zo),ki=ii(ei),vi=ii(ti),Si=ii(ni),Ai=ii(oi),Ei=ii(qo),Ti=ii(Ko),Ii=ii(Go),Ci=ii(Ho),xi=ii(Wo),Ni=ii(jo),_i=ii(Xo),Di=ii(Qo);function Pi(e){const t=fi(e);return t.success?[]:t.errors??["Unknown validation error"]}function Ri(e){const t=Pi(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function Bi(e,t){return"string"==typeof e[t]}function Mi(e,t){return void 0===e[t]||"string"==typeof e[t]}function Oi(e,t){return void 0===e[t]||"number"==typeof e[t]}function Li(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Bi(t,"tokenName")&&Oi(t,"from")&&Oi(t,"to")&&Oi(t,"resolution")}function Ui(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 Fi(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,r]of Object.entries(e)){if(!Ui(n[t],r))return!1}return!0}}lr({BUY:"buy",SELL:"sell"});const $i=Fi({vaultAddress:"string"}),qi=Fi({nativeTokenQuantity:"string"});function Ki(e){if(ar(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))ar(r)||(ir(r)?t[n]=r:"number"==typeof r||"boolean"==typeof r?t[n]=r.toString():Array.isArray(r)?t[n]=r.join(","):t[n]="object"==typeof r?JSON.stringify(r):String(r));return t}var Gi=Object.freeze({__proto__:null,adaptQueryParams:Ki});function Hi(e,t="0"){return Wn(e,t)}function Wi(e,t){return void 0!==t?Hi(e).toFixed(t):Hi(e).toFixed()}function zi(e,t=.01){const n=Hi(e),r=new o(1).minus(t);return n.multipliedBy(r)}function Vi(e=.01){return new o(1).minus(e)}function ji(e=.01){return new o(1).plus(e)}function Xi(e){const t=Hi(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function Qi(e,t=!1){const n=Hi(e),r=new o(1).dividedBy(n);return t?r.toFixed():r}function Yi(){return new o(2).pow(96)}function Ji(e,t){return o.min(Hi(e),Hi(t))}function Zi(e,t){return o.max(Hi(e),Hi(t))}function es(e){return Hi(e).isZero()}function ts(e){return Hi(e).isGreaterThan(0)}function ns(e){return Hi(e).isLessThan(0)}function rs(e,t){return Hi(e).isLessThan(Hi(t))}function os(e,t){return Hi(e).multipliedBy(t).dividedBy(100)}function is(...e){e.forEach(e=>{if(e.isNaN())throw jt("value","NaN");if(!e.isFinite())throw zt("value","finite");if(e.isLessThanOrEqualTo(0))throw Wt("value","0",e.toString())})}function ss(...e){e.forEach(e=>{if(e.isNaN())throw jt("value","NaN");if(!e.isFinite())throw zt("value","finite");if(e.isLessThan(0))throw Wt("value","0",e.toString())})}function as(e,t,n){if(e.isNaN())throw jt(t,"NaN");if(!e.isFinite())throw zt(t,"finite");if(e.isLessThanOrEqualTo(0))throw Wt(t,"0",e.toString())}function cs(e,t,n="0"){const r=Hi(t);return es(r)?Hi(n):Hi(e).dividedBy(r)}function ls(e,t){return Math.floor(e/t)*t}class us{static calculateBuyWithExact(e,t){const n=qn(e),r=qn(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:a}=cn,c=this.roundUp(o*(Math.exp((r+n)*i)-Math.exp(r*i))/i,8),l=Wi(Hi(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateBuyWithNative(e,t){const n=qn(e),r=qn(t),{BASE_PRICE:o,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:s,GAS_FEE:a}=cn,c=Math.log(n*i/o+Math.exp(r*i))/i-r,l=Wi(Hi(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateSellWithExact(e,t,n,r,o){const i=qn(e),s=qn(t),a=qn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=cn,h=c*(Math.exp(s*l)-Math.exp((s-i)*l))/l,g=Hi(h),p=r+s/a*(o-r),f=Wi(g.multipliedBy(p),8),m=Wi(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:m,gasFee:d}}static calculateSellWithNative(e,t,n,r,o){const i=qn(e),s=qn(t),a=qn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=cn;if(i>=c*(Math.exp(s*l)-1)/l){const e=Hi(i),t=r+s/a*(o-r),n=Wi(e.multipliedBy(t),8),c=Wi(e.multipliedBy(u));return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=s-Math.log(Math.exp(s*l)-i*l/c)/l,g=Hi(i),p=r+s/a*(o-r),f=Wi(g.multipliedBy(p),8),m=Wi(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:m,gasFee:d}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class ds extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function hs(e,t,n){if(null==e)throw new ds("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=fo.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new ds(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new ds("Filename is required when uploading Buffer objects",t,n);const r=mo.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new ds(e,t,n)}try{Jn(t,255,"filename")}catch(e){throw new ds(e.message,t,n)}const o=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!o.includes(n))throw new ds(`Invalid file type "${n}" is not allowed. Allowed types: ${o.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(i))throw new ds(`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 ds(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new ds("File must be a File object (browser) or Buffer (Node.js)",t,n)}function gs(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const r=e.trim();return r.length<n?null:r}function ps(e,t){return e.toLowerCase()===t.toLowerCase()}function fs(e,t){return e.toLowerCase().includes(t.toLowerCase())}function ms(e,t,n,r){return e===n&&t===r||e===r&&t===n}function ys(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 ws(e){return e.startsWith("0x")?e.slice(2):e}class bs{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:o,maxDecimals:i=bs.MAX_DECIMAL_PLACES,fieldName:s="amount"}=t;if(!ir(e))throw new ht(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new ht(`${s} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,s,"INVALID_NUMERIC_STRING");const a=qn(e,NaN);if(isNaN(a))throw new ht(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new ht(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new ht(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new ht(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=Hi(e),l=c.decimalPlaces()??0;if(l>i)throw new ht(`${s} cannot exceed ${i} decimal places. Received: ${l} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==r&&rs(c,r))throw new ht(`${s} must be at least ${r}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==o&&(u=o,Hi(c).isGreaterThan(Hi(u))))throw new ht(`${s} cannot exceed ${o}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return Hi(e,t)}isValid(e,t={}){try{return null==e||""===e?!1!==t.allowZero:(this.validate(e,t),!0)}catch{return!1}}formatAmount(e,t){return Wi(e,t)}clampAmount(e,t,n){const r=Hi(e),o=Hi(t),i=Hi(n);return function(e,t,n){const r=Hi(e),o=Hi(t),i=Hi(n);return r.isGreaterThanOrEqualTo(o)&&r.isLessThanOrEqualTo(i)}(r,o,i)?Wi(r):rs(r,o)?Wi(o):Wi(i)}}function ks(e,t){throw new ht(e.join("; "),t,"VALIDATION_ERROR")}function vs(e){const t=si(e);!t.success&&t.errors&&ks(t.errors,"tokenName")}function Ss(e){const t=wi(e);!t.success&&t.errors&&ks(t.errors,"options")}function As(e){const t=_o.safeParse(e);var n;t.success||ks((n=t.error.issues,Array.isArray(n)?n.map(e=>null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:String(e)).filter(e=>""!==e):[]),"options")}function Es(e,t,n=!0){Ts.validate(e,{fieldName:t,allowZero:n})}bs.MAX_DECIMAL_PLACES=18,bs.MIN_POSITIVE="0.00000000000000001";const Ts=new bs;class Is{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 Er}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;vs(t);const r=`${t}.png`;hs(n.file,r,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw Ft("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,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(void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status)throw $t(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const o=nn(r);if(!o?.imageUrl)throw $t("Image upload failed - no URL returned",r.status);return o.imageUrl}catch(e){if(Et(e)&&e.message.includes("FormData"))throw qt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){void 0!==e.pageSize&&cr(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&vs(e.tokenName);const t={pageSize:String(e.pageSize??10)};void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search),void 0!==e.hasUpcomingShows&&(t.hasUpcomingShows=e.hasUpcomingShows.toString()),void 0!==e.language&&(t.language=e.language),void 0!==e.recentlyStreamed&&(t.recentlyStreamed=e.recentlyStreamed.toString());const n=Ki(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status)throw $t(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const o=nn(r);if(null==o)throw $t("Failed to fetch pools - no data returned",r.status);let i=[];if(o.tokens)if(Array.isArray(o.tokens))i=o.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!es(t)||!es(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}});else{const e=o.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!es(t)||!es(n);i=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}]}else o.pools&&Array.isArray(o.pools)&&(i=o.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!es(t)||!es(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:r,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return bI});i.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=o.count??o.total??0,l={hasNextPage:o.hasNextPage??!1};return void 0!==o.hasPrevPage&&(l.hasPrevPage=o.hasPrevPage),void 0!==o.nextCursor&&(l.nextCursor=o.nextCursor),void 0!==o.prevCursor&&(l.prevCursor=o.prevCursor),c>0&&(l.totalCount=c),{items:i,pageInfo:l}}async checkPool(e){Ss(e),void 0!==e.tokenName&&""!==e.tokenName&&vs(e.tokenName);const t=Ki(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw $t(void 0!==n.message&&""!==n.message?n.message:"Failed to check pool",n.status);const r=n.data;return void 0!==e.symbol&&""!==e.symbol?r?.isSymbolExist??!1:void 0!==e.tokenName&&""!==e.tokenName?r?.isNameExist??!1:r?.exists??!1}async fetchVolumeData(e){if(!Li(e))throw Ft("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:r,resolution:o}=e;if(vs(t),null==n||null==r||null==o)throw Ut("graphOptions","Graph options (from, to, resolution)");const i={tokenName:t,from:n,to:r,resolution:o};As(i);const s=Ki(i),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw $t(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch graph data",a.status);const c=nn(a);if(!c)throw $t("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={pageSize:e.pageSize??10};return void 0!==e.cursor&&(n.cursor=e.cursor),void 0!==e.search&&""!==e.search&&(n.search=e.search),void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),null!=t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),void 0!==e.language&&""!==e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}async 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(null==e||"object"!=typeof e)throw Ft("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:o}=e,i=e.mode??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw Vt("mode",'"local" or "external"',i);if(!ir(t))throw Ut("tokenName","Token name");if(!ir(n))throw Ut("amount","Amount");if(r!==st.NATIVE&&r!==st.EXACT)throw Vt("type",'"native" or "exact"',r);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;if("string"!=typeof t||""===t)throw new ht("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof n||""===n)throw new ht("Amount must be a non-empty string","amount","INVALID_AMOUNT");return"exact"===r?on(()=>this.http.get(Je,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):on(()=>this.http.get(Je,{tokenName:t,amount:n,type:"NATIVE",method:"IN"}),{errorContext:`Failed to calculate buy amount for ${t} (native/GALA budget)`})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw Vt("mode",'"local" or "external"',c);if(!ir(t))throw Ut("tokenName","Token name");if(!ir(n))throw Ut("amount","Amount");if(r!==st.EXACT&&r!==st.NATIVE)throw Vt("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!==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;if("string"!=typeof t||""===t)throw new ht("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof n||""===n)throw new ht("Amount must be a non-empty string","amount","INVALID_AMOUNT");return"exact"===r?on(()=>this.http.get(Je,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):on(()=>this.http.get(Je,{tokenName:t,amount:n,type:"NATIVE",method:"OUT"}),{errorContext:`Failed to calculate sell amount for ${t} (native/GALA target)`})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o}=e;if(!ir(n))throw Ut("amount","Amount");if(r!==st.NATIVE&&r!==st.EXACT)throw Vt("type",'"native" or "exact"',r);void 0!==o&&Es(o,"currentSupply");const i=null==o||""===o;if(i&&(null==t||""===t))throw Ut("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&vs(t);let s=o;if(i){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===st.EXACT?us.calculateBuyWithExact(n,s):us.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:o,maxSupply:i,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!ir(n))throw Ut("amount","Amount");if(r!==st.EXACT&&r!==st.NATIVE)throw Vt("type",'"exact" or "native"',r);void 0!==o&&Es(o,"currentSupply");const c=null==o||""===o||null==i||""===i||void 0===s||void 0===a;if(c&&(null==t||""===t))throw Ut("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&vs(t);let l=o,u=i,d=s,h=a;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);u=u??this.metadataCache.getMaxSupply(t),d=d??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===d||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);d=d??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return r===st.EXACT?us.calculateSellWithExact(n,l,u,h,d):us.calculateSellWithNative(n,l,u,h,d)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Bi(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Mi(t,"currentSupply")}(e))throw Vt("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:o}=t;vs(n);const i=await this.tokenResolver.resolveTokenToVault(n);if(null==i||""===i)throw new ht(Mt(n),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw qt("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:i});if(1!==s.Status)throw $t(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=o??Wi(Hi(a.maxSupply).minus(a.sellingTokenQuantity)),l=a.sellingTokenQuantity;if("0"===l)throw Ut("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const u={tokenName:n,amount:l,type:"exact",currentSupply:c,...void 0!==r&&{mode:r}};return{...await this.calculateBuyAmount(u),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw qt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Ri(e);const r=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",o=qn(r);if(0===o&&"0"!==r)throw jt("preBuyQuantity",r,"Pre-buy quantity");if(o<0)throw jt("preBuyQuantity",r,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;rr(t,n,"reverseBondingCurve")}let i="https://via.placeholder.com/200?text=Token";if(void 0!==e.tokenImage&&null!==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(null==t||""===t)throw $t("Image upload failed: No URL returned");i=t}else"string"==typeof e.tokenImage&&(i=e.tokenImage);const s=`galaswap - operation - ${n.v4()}-${Date.now()}-${this.http.getAddress()}`,a=(void 0!==r&&""!==r?r:"0").toString(),c=void 0!==e.tokenCategory&&""!==e.tokenCategory?e.tokenCategory:"Unit",l=void 0!==e.tokenCollection&&""!==e.tokenCollection?e.tokenCollection:"Token",u={tokenName:e.tokenName.trim(),tokenSymbol:dn(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:i.trim(),preBuyQuantity:a,tokenCategory:c,tokenCollection:l,uniqueKey:s},d=gs(e.websiteUrl);null!==d&&(u.websiteUrl=d);const h=gs(e.telegramUrl);null!==h&&(u.telegramUrl=h);const g=gs(e.twitterUrl);null!==g&&(u.twitterUrl=g);const p=gs(e.instagramUrl);null!==p&&(u.instagramUrl=p);const f=gs(e.facebookUrl);null!==f&&(u.facebookUrl=f);const m=gs(e.redditUrl);null!==m&&(u.redditUrl=m);const y=gs(e.tiktokUrl);null!==y&&(u.tiktokUrl=y);const w=e.reverseBondingCurveConfiguration?.minFeePortion?.toString()??"0.1",b=e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()??"0.5";u.reverseBondingCurveConfiguration={minFeePortion:w,maxFeePortion:b},void 0!==e.saleStartTime&&null!==e.saleStartTime&&(u.saleStartTime=e.saleStartTime);const k=Object.fromEntries(Object.entries(u).filter(([e,t])=>void 0!==t)),v=new Tr(k),S=await this.http.signWithGalaChain("CreateSale",v,t.SigningType.SIGN_TYPED_DATA),{signature:A,types:E,domain:T,prefix:I}=S,C=null!=I?{prefix:I}:{},x=void 0!==v.reverseBondingCurveConfiguration&&null!==v.reverseBondingCurveConfiguration?{reverseBondingCurveConfiguration:v.reverseBondingCurveConfiguration}:{},N=void 0!==v.saleStartTime&&null!==v.saleStartTime?{saleStartTime:v.saleStartTime}:{},_={tokenName:v.tokenName,tokenSymbol:v.tokenSymbol,tokenDescription:v.tokenDescription,tokenImage:v.tokenImage,preBuyQuantity:v.preBuyQuantity,...void 0!==v.websiteUrl&&""!==v.websiteUrl?{websiteUrl:v.websiteUrl}:{},...void 0!==v.telegramUrl&&""!==v.telegramUrl?{telegramUrl:v.telegramUrl}:{},...void 0!==v.twitterUrl&&""!==v.twitterUrl?{twitterUrl:v.twitterUrl}:{},...void 0!==v.instagramUrl&&""!==v.instagramUrl?{instagramUrl:v.instagramUrl}:{},...void 0!==v.facebookUrl&&""!==v.facebookUrl?{facebookUrl:v.facebookUrl}:{},...void 0!==v.redditUrl&&""!==v.redditUrl?{redditUrl:v.redditUrl}:{},...void 0!==v.tiktokUrl&&""!==v.tiktokUrl?{tiktokUrl:v.tiktokUrl}:{},tokenCategory:v.tokenCategory,tokenCollection:v.tokenCollection,uniqueKey:v.uniqueKey,signature:A,types:E,domain:T,...C,...x,...N},D=`${e.tokenName.trim()}$Unit$none$none`,P="GALA$Unit$none$none";let R;if(qn(r,0)>0){const e=`$service$${D}$launchpad`;R=[e,`$token$${D}$${e}`,`$tokenBalance$${D}$${e}`,`$tokenBalance$${D}$${e}`,`$tokenBalance$${P}$${e}`,`$tokenBalance$${P}$${e}`]}else{const e=`$service$${D}$launchpad`;R=[e,`$token$${D}$${e}`,`$tokenBalance$${D}$${e}`]}const B={signedDto:_,stringsInstructions:R,method:"CreateSale"},M=await this.bundleHttp.post("/bundle",B);if(M.error)throw $t(void 0!==M.message&&""!==M.message?M.message:"Token launch failed");const O=nn(M);if(null==O||""===O)throw $t("Token launch failed - no transaction ID returned");return O}async fetchTokenDistribution(e){if(null==e||""===e)throw Ut("tokenName","Token name");vs(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw $t(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=nn(t);if(null==n)throw $t("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw $t("Invalid API response: expected array of holders",t.status);for(const e of n){if(void 0===e.owner||null===e.owner||""===e.owner||"string"!=typeof e.owner)throw $t("Invalid holder data: missing or invalid owner field",t.status);if(void 0===e.quantity||null===e.quantity||""===e.quantity||"string"!=typeof e.quantity)throw $t("Invalid holder data: missing or invalid quantity field",t.status);const n=qn(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw $t(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),Hi(0));return{holders:n.map(e=>{const t=cs(Hi(e.quantity),r,Hi(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:Wi(r),totalHolders:n.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(null==e||""===e)throw Ut("tokenName","Token name");vs(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw $t(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token badges");const n=nn(t);if(null==n)throw $t("Failed to fetch token badges - no data returned");return{volumeBadges:Array.isArray(n.volumeBadge)?n.volumeBadge:[],engagementBadges:Array.isArray(n.engagementBadge)?n.engagementBadge:[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(null==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(!qi(e))throw Ft("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw qt("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(!function(e){if(null==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}(n))throw $t("Malformed response data from GalaChain gateway");try{Dt(n,"Pre-mint calculation")}catch(e){throw $t(Tt(e),500)}const{calculatedQuantity:r,extraFees:o}=n.Data;return{amount:r,reverseBondingCurveFee:o.reverseBondingCurve,transactionFee:o.transactionFees,gasFee:"1"}}catch(e){if(Et(e)&&e instanceof pt)throw e;throw $t(Tt(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new ht(Mt(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw qt("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw $t(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=Wi(Hi(r.maxSupply).minus(r.sellingTokenQuantity)),i=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=.1;const l=r.reverseBondingCurveConfiguration;null!=l?.maxFeePortion&&(a=Vn(l.maxFeePortion,.5)),null!=l?.minFeePortion&&(c=Vn(l.minFeePortion,.1)),void 0===l&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, 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){vs(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new ht(Mt(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw qt("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw $t(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,o=Wi(Hi(r.maxSupply).minus(r.sellingTokenQuantity)),i=r.maxSupply;return this.metadataCache.set(e,{maxSupply:i}),o}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Dr(e)}validateTokenName(e){return vs(e)}validatePagination(e){void 0!==e.pageSize&&cr(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw qt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw Ut("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return void 0!==e.tokens&&null!==e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{void 0!==e.currentPrices&&null!==e.currentPrices&&void 0!==e.symbol&&null!==e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw $t(`Failed to fetch token prices: ${Tt(e)}`,void 0,Et(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const Cs={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class xs{constructor(){this.data=new Map}async get(e){return this.data.get(e)??null}async set(e,t){this.data.set(e,t)}async remove(e){this.data.delete(e)}}var Ns,_s;exports.AuthErrorType=void 0,(Ns=exports.AuthErrorType||(exports.AuthErrorType={})).WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",Ns.SIGNATURE_FAILED="SIGNATURE_FAILED",Ns.INVALID_ADDRESS="INVALID_ADDRESS",Ns.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED";class Ds extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Ps{constructor(e,t=Cs.REFRESH_THRESHOLD_MS){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new xs,this.refreshThresholdMs=t}setToken(e,t){if(!ir(e))throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t},this.storage.set(this.STORAGE_KEYS.ACCESS_TOKEN,e.trim()),this.storage.set(this.STORAGE_KEYS.ACCESS_EXPIRES,String(this.tokenState.expiresAt))}async setTokens(e,t,n,r){if(this.setToken(e,t),n){const e=Date.now()+1e3*(r??7776e3);if(!this.tokenState)throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Access token must be set before refresh token");this.tokenState.refreshToken=n.trim(),this.tokenState.refreshExpiresAt=e,await this.storage.set(this.STORAGE_KEYS.REFRESH_TOKEN,n.trim()),await this.storage.set(this.STORAGE_KEYS.REFRESH_EXPIRES,String(e))}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${Cs.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Cs.AUTH_HEADER]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!=this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const r=Date.now();this.tokenState={token:e,issuedAt:r,expiresAt:n};const o=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(o&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=o,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function Rs(e,t,n,r){try{return await e()}catch(e){throw r?(r(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Gt(e,t,n))}}function Bs(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),Gt(e,t,n))}}class Ms{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new gn({debug:r,context:"SessionAuthService"})}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return Rs(async()=>{const e=Date.now(),t=`${Cs.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),r=this.signatureAuth.getAddress();Mr(r,"address");const o={address:r,message:t,signature:n.signature};let i;try{this.logger.debug("Sending login request with refresh token support",{address:r,message:t}),i=await this.http.post(F,{...o,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),i=await this.http.post(F,o)}const s=this.extractLoginData(i);return await this.jwtAuth.setTokens(s.accessToken,s.expiresIn,s.refreshToken,s.refreshExpiresIn),this.logger.debug("Login successful",{address:s.address,expiresIn:s.expiresIn,hasRefreshToken:!!s.refreshToken}),s},"SessionAuthService.performLogin",this.logger,(e,t,n)=>{if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,`Login failed: ${Tt(e)}`,Et(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(!this.jwtAuth.hasToken())throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return Rs(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.jwtAuth.getRefreshToken();if(e){this.logger.debug("Using refresh token flow");const t=await this.http.post(q,{refreshToken:e}),n=this.extractLoginData(t);return await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),this.logger.debug("Token refreshed successfully via refresh token",{address:n.address,expiresIn:n.expiresIn,hasNewRefreshToken:!!n.refreshToken}),n}this.logger.debug("Using legacy access token refresh");const t=await this.http.post(q,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,(e,t,n)=>{if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,`Token refresh failed: ${Tt(e)}`,Et(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post($,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${Tt(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Rs(async()=>{const e=await this.http.get(K,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(e,t,n)=>{if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,`Failed to get session: ${Tt(e)}`,Et(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(!this.jwtAuth.hasToken())throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${Tt(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,""!==Tt(e)?Tt(e):"Authentication failed");const t=rn(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:o,refreshToken:i,refreshExpiresIn:s}=t;if(!ir(n))throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:o,...void 0!==i&&{refreshToken:i},...void 0!==s&&{refreshExpiresIn:s}}}extractSessionData(e){if(e.error)throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,""!==Tt(e)?Tt(e):"Failed to get session");return rn(e,"No data in session response")}}class Os extends Error{constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="WalletProviderError"}}!function(e){e.USER_REJECTED="USER_REJECTED",e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.SIGNING_FAILED="SIGNING_FAILED",e.PROVIDER_NOT_AVAILABLE="PROVIDER_NOT_AVAILABLE",e.PRIVATE_KEY_NOT_ACCESSIBLE="PRIVATE_KEY_NOT_ACCESSIBLE",e.INVALID_CONFIG="INVALID_CONFIG",e.CHAIN_MISMATCH="CHAIN_MISMATCH",e.UNKNOWN="UNKNOWN"}(_s||(_s={}));class Ls{constructor(t){this.providerType="privateKey",this.connected=!0;try{this.wallet=new e.Wallet(t)}catch(e){throw new Os("Invalid private key provided",_s.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new Ls(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new Os("Failed to sign message",_s.SIGNING_FAILED,e instanceof Error?e:void 0)}}async signTypedData(e,t,n){try{return await this.wallet.signTypedData(e,t,n)}catch(e){throw new Os("Failed to sign typed data",_s.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(e.getAddress(this.wallet.address))}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async connect(){return this.connected=!0,this.getAddress()}disconnect(){return this.connected=!1,Promise.resolve()}isConnected(){return this.connected}getPrivateKey(){return Promise.resolve(this.wallet.privateKey)}getWallet(){return this.wallet}}class Us{constructor(e){if(this.wallet=e.wallet,e.walletProvider?this.walletProvider=e.walletProvider:e.wallet,this.messagePrefix=e.messagePrefix??"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{tr(e.messagePrefix,"messagePrefix",!1)}catch{throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.walletProvider||void 0!==this.wallet}ensureWalletProvider(){if(this.wallet&&!this.walletProvider)try{this.walletProvider=Ls.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Dr(this.wallet.address)}catch(e){if(e instanceof Ds)throw e;if(e instanceof ht&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Ds(exports.AuthErrorType.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Ds(exports.AuthErrorType.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=Ls.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Dr(e.address)}else this.walletProvider=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0;this.wallet=e}setWalletProvider(e){this.walletProvider=e,this.wallet=void 0,this.cachedAddress=void 0,this.cachedGalaAddress=void 0}getWalletProvider(){return this.walletProvider}async cacheAddress(){this.walletProvider&&(this.cachedAddress=await this.walletProvider.getAddress(),this.cachedGalaAddress=await this.walletProvider.getGalaAddress())}async generateSignature(){await this.validateWalletAsync();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.walletProvider.signMessage(t);return{message:t,signature:n,address:await this.walletProvider.getGalaAddress(),timestamp:e}}catch(e){if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate signature for authentication",Et(e)?e:new Error(Tt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getGalaAddress()}getEthereumAddress(){if(this.validateWallet(),this.cachedAddress)return this.cachedAddress;if(this.wallet)return this.wallet.address;throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null==this.wallet.privateKey)throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if("privateKey"===this.walletProvider?.providerType){return this.walletProvider.getWallet().privateKey}throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.")}async getPrivateKeyAsync(){if(await this.validateWalletAsync(),!this.walletProvider.getPrivateKey)throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Et(e)?e:void 0)}}formatAddress(e){try{return Dr(e)}catch{throw new Ds(exports.AuthErrorType.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,Tt(e),Et(e)?e:new Error(Tt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,o=await this.walletProvider.signMessage(r);return{"x-signature":o,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate authentication headers",Et(e)?e:new Error(Tt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const r={};for(const[e,n]of Object.entries(t))r[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,r,n)}catch(e){if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to sign typed data",Et(e)?e:new Error(Tt(e)))}}async generateCustomSignature(e){if(!ir(e))throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Custom message must be a non-empty string");await this.validateWalletAsync();try{const t=await this.walletProvider.signMessage(e);return{message:e,signature:t,address:await this.walletProvider.getGalaAddress(),timestamp:Date.now()}}catch(e){if(e instanceof Ds)throw e;throw new Ds(exports.AuthErrorType.SIGNATURE_FAILED,"Failed to generate custom message signature",Et(e)?e:new Error(Tt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Ds(exports.AuthErrorType.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Fs={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",gdexWebSocketUrl:"wss://dex-backend-prod1.defi.gala.com/ws",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",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"},QA1:{launchpadBaseUrl:"https://lpad-backend-qa1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-qa1.defi.gala.com",webSocketUrl:"https://bundle-backend-qa1.defi.gala.com",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-qa1.defi.gala.com"}};function $s(e){return Fs[e]}function qs(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Ks(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function Gs(e){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const Hs={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Ws={ASSET:1,MUSIC:3};const zs="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Vs="0x6a1734E09f3099a3675645D214ce547080ea67e0",js="https://dex-api-platform-dex-prod-gala.gala.com",Xs=[{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}],Qs=[{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 Ys(e){return"PROD"===e?Xs:Qs}function Js(e){return"PROD"===e?zs:Vs}const Zs=Xs,ea=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],ta={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"}},na=["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)"],ra=["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"],oa={BRIDGE_OUT:Buffer.from([27,194,57,119,215,165,247,150]),BRIDGE_OUT_NATIVE:Buffer.from([243,44,75,224,249,206,98,79])};function ia(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function sa(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var aa,ca={},la={};function ua(){if(aa)return la;aa=1,la.byteLength=function(e){var t=i(e),n=t[0],r=t[1];return 3*(n+r)/4-r},la.toByteArray=function(e){var r,o,s=i(e),a=s[0],c=s[1],l=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),u=0,d=c>0?a-4:a;for(o=0;o<d;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)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=255&r;2===c&&(r=t[e.charCodeAt(o)]<<2|t[e.charCodeAt(o+1)]>>4,l[u++]=255&r);1===c&&(r=t[e.charCodeAt(o)]<<10|t[e.charCodeAt(o+1)]<<4|t[e.charCodeAt(o+2)]>>2,l[u++]=r>>8&255,l[u++]=255&r);return l},la.fromByteArray=function(t){for(var n,r=t.length,o=r%3,i=[],s=16383,c=0,l=r-o;c<l;c+=s)i.push(a(t,c,c+s>l?l: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,la}var da,ha,ga={};function pa(){return da||(da=1,ga.read=function(e,t,n,r,o){var i,s,a=8*o-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?o-1:0,h=n?-1:1,g=e[t+d];for(d+=h,i=g&(1<<-u)-1,g>>=-u,u+=a;u>0;i=256*i+e[t+d],d+=h,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=r;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===i)i=1-l;else{if(i===c)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,r),i-=l}return(g?-1:1)*s*Math.pow(2,i-r)},ga.write=function(e,t,n,r,o,i){var s,a,c,l=8*i-o-1,u=(1<<l)-1,d=u>>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:i-1,p=r?1:-1,f=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,o),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;e[n+g]=255&a,g+=p,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;e[n+g]=255&s,g+=p,s/=256,l-=8);e[n+g-p]|=128*f}),ga}function fa(){return ha||(ha=1,function(e){const t=ua(),n=pa(),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 l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=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(V(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(V(e,ArrayBuffer)||e&&V(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(V(e,SharedArrayBuffer)||e&&V(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const o=function(e){if(s.isBuffer(e)){const t=0|h(e.length),n=i(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||j(e.length)?i(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(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 l(e){return c(e),i(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=i(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function h(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function g(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||V(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(o)return r?-1:H(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 E(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 N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function f(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),j(n=+n)&&(n=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 l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(o){let r=-1;for(i=n;i<a;i++)if(l(e,i)===l(t,-1===r?0:i-r)){if(-1===r&&(r=i),i-r+1===c)return r*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(l(e,i+r)!==l(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(j(r))return s;e[n+s]=r}return s}function b(e,t,n,r){return z(H(t,e.length-n),e,n,r)}function k(e,t,n,r){return z(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return z(W(t),e,n,r)}function S(e,t,n,r){return z(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 A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function E(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<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=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 l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(V(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),V(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(V(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=g,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)f(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)f(this,t,t+3),f(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)f(this,t,t+7),f(this,t+1,t+6),f(this,t+2,t+5),f(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?E(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(V(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),l=this.slice(r,o),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){i=l[e],a=u[e];break}return i<a?-1:a<i?1:0},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 S(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 T=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 C(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 N(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 _(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 D(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 P(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 R(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 B(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 M(e,t,r,o,i){return t=+t,r>>>=0,i||B(e,0,r,4),n.write(e,t,r,o,23,4),r+4}function O(e,t,r,o,i){return t=+t,r>>>=0,i||B(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||_(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||_(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||_(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,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||_(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||_(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||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(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){D(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||D(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||D(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||D(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||D(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||D(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);D(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);D(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||D(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||D(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||D(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||D(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||D(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 M(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return 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 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 L={};function U(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,r,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 L.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 L.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}U("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),U("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),U("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=F(String(n)):"bigint"==typeof n&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=F(o)),o+="n"),r+=` It must be ${t}. Received ${o}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function H(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(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(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 V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function j(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let o=0;o<16;++o)t[r+o]=e[n]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?Y:e}function Y(){throw new Error("BigInt not supported")}}(ca)),ca}var ma=fa();const ya="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function wa(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ba(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ka(e,...t){if(!wa(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 va(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ba(e.outputLen),ba(e.blockLen)}function Sa(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 Aa(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ea(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ta(e,t){return e<<32-t|e>>>t}const Ia=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ca=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function xa(e){if(ka(e),Ia)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ca[e[n]];return t}const Na=48,_a=57,Da=65,Pa=70,Ra=97,Ba=102;function Ma(e){return e>=Na&&e<=_a?e-Na:e>=Da&&e<=Pa?e-(Da-10):e>=Ra&&e<=Ba?e-(Ra-10):void 0}function Oa(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Ia)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,o=0;t<n;t++,o+=2){const n=Ma(e.charCodeAt(o)),i=Ma(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 La(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),ka(e),e}function Ua(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];ka(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 Fa{}function $a(e){const t=t=>e().update(La(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function qa(e=32){if(ya&&"function"==typeof ya.getRandomValues)return ya.getRandomValues(new Uint8Array(e));if(ya&&"function"==typeof ya.randomBytes)return Uint8Array.from(ya.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Ka(e,t,n){return e&t^~e&n}function Ga(e,t,n){return e&t^e&n^t&n}class Ha extends Fa{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Ea(this.buffer)}update(e){Sa(this),ka(e=La(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=Ea(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){Sa(this),function(e,t){ka(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,Aa(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,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),o),this.process(n,0);const s=Ea(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,l[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 Wa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),za=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Va=BigInt(2**32-1),ja=BigInt(32);function Xa(e,t=!1){return t?{h:Number(e&Va),l:Number(e>>ja&Va)}:{h:0|Number(e>>ja&Va),l:0|Number(e&Va)}}const Qa=(e,t,n)=>e>>>n,Ya=(e,t,n)=>e<<32-n|t>>>n,Ja=(e,t,n)=>e>>>n|t<<32-n,Za=(e,t,n)=>e<<32-n|t>>>n,ec=(e,t,n)=>e<<64-n|t>>>n-32,tc=(e,t,n)=>e>>>n-32|t<<64-n;function nc(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}const rc=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),oc=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,ic=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),sc=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,ac=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),cc=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,lc=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),uc=new Uint32Array(64);class dc extends Ha{constructor(e=32){super(64,e,8,!1),this.A=0|Wa[0],this.B=0|Wa[1],this.C=0|Wa[2],this.D=0|Wa[3],this.E=0|Wa[4],this.F=0|Wa[5],this.G=0|Wa[6],this.H=0|Wa[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)uc[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=uc[e-15],n=uc[e-2],r=Ta(t,7)^Ta(t,18)^t>>>3,o=Ta(n,17)^Ta(n,19)^n>>>10;uc[e]=o+uc[e-7]+r+uc[e-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Ta(s,6)^Ta(s,11)^Ta(s,25))+Ka(s,a,c)+lc[e]+uc[e]|0,u=(Ta(n,2)^Ta(n,13)^Ta(n,22))+Ga(n,r,o)|0;l=c,c=a,a=s,s=i+t|0,i=o,o=r,r=n,n=t+u|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,l=l+this.H|0,this.set(n,r,o,i,s,a,c,l)}roundClean(){Aa(uc)}destroy(){this.set(0,0,0,0,0,0,0,0),Aa(this.buffer)}}const hc=(()=>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}=Xa(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))))(),gc=(()=>hc[0])(),pc=(()=>hc[1])(),fc=new Uint32Array(80),mc=new Uint32Array(80);class yc extends Ha{constructor(e=64){super(128,e,16,!1),this.Ah=0|za[0],this.Al=0|za[1],this.Bh=0|za[2],this.Bl=0|za[3],this.Ch=0|za[4],this.Cl=0|za[5],this.Dh=0|za[6],this.Dl=0|za[7],this.Eh=0|za[8],this.El=0|za[9],this.Fh=0|za[10],this.Fl=0|za[11],this.Gh=0|za[12],this.Gl=0|za[13],this.Hh=0|za[14],this.Hl=0|za[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:p,Hl:f}=this;return[e,t,n,r,o,i,s,a,c,l,u,d,h,g,p,f]}set(e,t,n,r,o,i,s,a,c,l,u,d,h,g,p,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|i,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|g,this.Hh=0|p,this.Hl=0|f}process(e,t){for(let n=0;n<16;n++,t+=4)fc[n]=e.getUint32(t),mc[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|fc[e-15],n=0|mc[e-15],r=Ja(t,n,1)^Ja(t,n,8)^Qa(t,0,7),o=Za(t,n,1)^Za(t,n,8)^Ya(t,n,7),i=0|fc[e-2],s=0|mc[e-2],a=Ja(i,s,19)^ec(i,s,61)^Qa(i,0,6),c=Za(i,s,19)^tc(i,s,61)^Ya(i,s,6),l=ic(o,c,mc[e-7],mc[e-16]),u=sc(l,r,a,fc[e-7],fc[e-16]);fc[e]=0|u,mc[e]=0|l}let{Ah:n,Al:r,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:p,Gl:f,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Ja(u,d,14)^Ja(u,d,18)^ec(u,d,41),w=Za(u,d,14)^Za(u,d,18)^tc(u,d,41),b=u&h^~u&p,k=ac(y,w,d&g^~d&f,pc[e],mc[e]),v=cc(k,m,t,b,gc[e],fc[e]),S=0|k,A=Ja(n,r,28)^ec(n,r,34)^ec(n,r,39),E=Za(n,r,28)^tc(n,r,34)^tc(n,r,39),T=n&o^n&s^o&s,I=r&i^r&a^i&a;m=0|p,y=0|f,p=0|h,f=0|g,h=0|u,g=0|d,({h:u,l:d}=nc(0|c,0|l,0|v,0|S)),c=0|s,l=0|a,s=0|o,a=0|i,o=0|n,i=0|r;const C=rc(S,E,I);n=oc(C,v,A,T),r=0|C}({h:n,l:r}=nc(0|this.Ah,0|this.Al,0|n,0|r)),({h:o,l:i}=nc(0|this.Bh,0|this.Bl,0|o,0|i)),({h:s,l:a}=nc(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:l}=nc(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=nc(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=nc(0|this.Fh,0|this.Fl,0|h,0|g)),({h:p,l:f}=nc(0|this.Gh,0|this.Gl,0|p,0|f)),({h:m,l:y}=nc(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,o,i,s,a,c,l,u,d,h,g,p,f,m,y)}roundClean(){Aa(fc,mc)}destroy(){Aa(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const wc=$a(()=>new dc),bc=$a(()=>new yc),kc=BigInt(0),vc=BigInt(1);function Sc(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Ac(e,t,n=""){const r=wa(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 Ec(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Tc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?kc:BigInt("0x"+e)}function Ic(e){return Tc(xa(e))}function Cc(e){return ka(e),Tc(xa(Uint8Array.from(e).reverse()))}function xc(e,t){return Oa(e.toString(16).padStart(2*t,"0"))}function Nc(e,t){return xc(e,t).reverse()}function _c(e,t,n){let r;if("string"==typeof t)try{r=Oa(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!wa(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 Dc(e){return Uint8Array.from(e)}const Pc=e=>"bigint"==typeof e&&kc<=e;function Rc(e,t,n,r){if(!function(e,t,n){return Pc(e)&&Pc(t)&&Pc(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Bc(e){let t;for(t=0;e>kc;e>>=vc,t+=1);return t}const Mc=e=>(vc<<BigInt(e))-vc;function Oc(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 Lc(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 Uc=BigInt(0),Fc=BigInt(1),$c=BigInt(2),qc=BigInt(3),Kc=BigInt(4),Gc=BigInt(5),Hc=BigInt(7),Wc=BigInt(8),zc=BigInt(9),Vc=BigInt(16);function jc(e,t){const n=e%t;return n>=Uc?n:t+n}function Xc(e,t,n){let r=e;for(;t-- >Uc;)r*=r,r%=n;return r}function Qc(e,t){if(e===Uc)throw new Error("invert: expected non-zero number");if(t<=Uc)throw new Error("invert: expected positive modulus, got "+t);let n=jc(e,t),r=t,o=Uc,i=Fc;for(;n!==Uc;){const e=r%n,t=o-i*(r/n);r=n,n=e,o=i,i=t}if(r!==Fc)throw new Error("invert: does not exist");return jc(o,t)}function Yc(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Jc(e,t){const n=(e.ORDER+Fc)/Kc,r=e.pow(t,n);return Yc(e,r,t),r}function Zc(e,t){const n=(e.ORDER-Gc)/Wc,r=e.mul(t,$c),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,$c),o),a=e.mul(i,e.sub(s,e.ONE));return Yc(e,a,t),a}function el(e){if(e<qc)throw new Error("sqrt is not defined for small field");let t=e-Fc,n=0;for(;t%$c===Uc;)t/=$c,n++;let r=$c;const o=sl(e);for(;1===ol(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Jc;let i=o.pow(r,t);const s=(t+Fc)/$c;return function(e,r){if(e.is0(r))return r;if(1!==ol(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,i),c=e.pow(r,t),l=e.pow(r,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===o)throw new Error("Cannot find square root");const r=Fc<<BigInt(o-t-1),i=e.pow(a,r);o=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function tl(e){return e%Kc===qc?Jc:e%Wc===Gc?Zc:e%Vc===zc?function(e){const t=sl(e),n=el(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+Hc)/Vc;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,o),l=e.mul(n,i),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),g=e.cmov(n,a,h);return Yc(e,g,t),g}}(e):el(e)}const nl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rl(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),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 ol(e,t){const n=(e.ORDER-Fc)/$c,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 il(e,t){void 0!==t&&ba(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function sl(e,t,n=!1,r={}){if(e<=Uc)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:l}=il(e,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:Mc(c),ZERO:Uc,ONE:Fc,allowedLengths:s,create:t=>jc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Uc<=t&&t<e},is0:e=>e===Uc,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Fc)===Fc,neg:t=>jc(-t,e),eql:(e,t)=>e===t,sqr:t=>jc(t*t,e),add:(t,n)=>jc(t+n,e),sub:(t,n)=>jc(t-n,e),mul:(t,n)=>jc(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Uc)throw new Error("invalid exponent, negatives unsupported");if(n===Uc)return e.ONE;if(n===Fc)return t;let r=e.ONE,o=t;for(;n>Uc;)n&Fc&&(r=e.mul(r,o)),o=e.sqr(o),n>>=Fc;return r}(d,e,t),div:(t,n)=>jc(t*Qc(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Qc(t,e),sqrt:i||(t=>(u||(u=tl(e)),u(d,t))),toBytes:e=>n?Nc(e,l):xc(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let o=n?Cc(t):Ic(t);if(a&&(o=jc(o,e)),!r&&!d.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o},invertBatch:e=>rl(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function al(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function cl(e){const t=al(e);return t+Math.ceil(t/2)}const ll=BigInt(0),ul=BigInt(1);function dl(e,t){const n=t.negate();return e?n:t}function hl(e,t){const n=rl(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function gl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function pl(e,t){gl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Mc(e),maxNumber:n,shiftBy:BigInt(e)}}function fl(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+=ul);const l=t*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const ml=new WeakMap,yl=new WeakMap;function wl(e){return yl.get(e)||1}function bl(e){if(e!==ll)throw new Error("invalid wNAF")}class kl{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>ll;)t&ul&&(n=n.add(r)),r=r.double(),t>>=ul;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=pl(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=pl(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=fl(n,e,i);n=s,c?o=o.add(dl(u,t[d])):r=r.add(dl(l,t[a]))}return bl(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=pl(e,this.bits);for(let e=0;e<o.windows&&n!==ll;e++){const{nextN:i,offset:s,isZero:a,isNeg:c}=fl(n,e,o);if(n=i,!a){const e=t[s];r=r.add(c?e.negate():e)}}return bl(n),r}getPrecomputes(e,t,n){let r=ml.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),ml.set(t,r))),r}cached(e,t,n){const r=wl(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=wl(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){gl(t,this.bits),yl.set(e,t),ml.delete(e)}hasCache(e){return 1!==wl(e)}}function vl(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=Bc(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Mc(c),u=new Array(Number(l)+1).fill(s);let d=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(s);for(let t=0;t<i;t++){const o=r[t],i=Number(o>>BigInt(e)&l);u[i]=u[i].add(n[t])}let t=s;for(let e=u.length-1,n=s;e>0;e--)n=n.add(u[e]),t=t.add(n);if(d=d.add(t),0!==e)for(let e=0;e<c;e++)d=d.double()}return d}function Sl(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Oc(e,nl.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return sl(e,{isLE:n})}function Al(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>ll))throw new Error(`CURVE.${e} must be positive bigint`)}const o=Sl(t.p,n.Fp,r),i=Sl(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 El=BigInt(0),Tl=BigInt(1),Il=BigInt(2),Cl=BigInt(8);function xl(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Oc(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||qa,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(Sc(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return s.create(Cc(e))}function d(e){const{head:n,prefix:r,scalar:i}=function(e){const n=m.secretKey;e=_c("private key",e,n);const r=_c("hashed private key",t(e),2*n),o=c(r.slice(0,n));return{head:o,prefix:r.slice(n,2*n),scalar:u(o)}}(e),s=o.multiply(i),a=s.toBytes();return{head:n,prefix:r,scalar:i,point:s,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const o=Ua(...n);return u(t(l(o,_c("context",e),!!r)))}const p={zip215:!0};const f=i.BYTES,m={secretKey:f,publicKey:f,signature:2*f,seed:f};function y(e=a(m.seed)){return Ac(e,m.seed,"seed")}const w={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return wa(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(Tl+n,Tl-n):i.div(n-Tl,n+Tl);return i.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;Ac(e,n);const r=t(e.subarray(0,n));return c(r).subarray(0,n)},randomPrivateKey:y,precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=w.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign:function(e,t,n={}){e=_c("message",e),r&&(e=r(e));const{prefix:i,scalar:a,pointBytes:c}=d(t),l=g(n.context,i,e),u=o.multiply(l).toBytes(),h=g(n.context,u,c,e),p=s.create(l+h*a);if(!s.isValid(p))throw new Error("sign failed: invalid s");return Ac(Ua(u,s.toBytes(p)),m.signature,"result")},verify:function(t,n,i,s=p){const{context:a,zip215:c}=s,l=m.signature;t=_c("signature",t,l),n=_c("message",n),i=_c("publicKey",i,m.publicKey),void 0!==c&&Sc(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=Cc(t.subarray(u,l));let f,y,w;try{f=e.fromBytes(i,c),y=e.fromBytes(d,c),w=o.multiplyUnsafe(h)}catch(e){return!1}if(!c&&f.isSmallOrder())return!1;const b=g(a,y.toBytes(),f.toBytes(),n);return y.add(f.multiplyUnsafe(b)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function Nl(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:sl(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=Al("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s}=i;Oc(t,{},{uvRatio:"function"});const a=Il<<BigInt(8*o.BYTES)-Tl,c=e=>r.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:El}}});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 u(e,t,n=!1){return Rc("coordinate "+e,t,n?Tl:El,a),t}function d(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=Lc((e,t)=>{const{X:n,Y:o,Z:i}=e,s=e.is0();null==t&&(t=s?Cl:r.inv(i));const a=c(n*t),l=c(o*t),u=r.mul(i,t);if(s)return{x:El,y:Tl};if(u!==Tl)throw new Error("invZ was invalid");return{x:a,y:l}}),g=Lc(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,l=c(r*r),u=c(o*o),d=c(s*s),h=c(d*d),g=c(l*t);if(c(d*c(g+u))!==c(h+c(n*c(l*u))))throw new Error("bad point: equation left != right (1)");if(c(r*o)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,n,r){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new p(t,n,Tl,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:o,d:s}=i;e=Dc(Ac(e,n,"point")),Sc(t,"zip215");const u=Dc(e),d=e[n-1];u[n-1]=-129&d;const h=Cc(u),g=t?a:r.ORDER;Rc("point.y",h,El,g);const f=c(h*h),m=c(f-Tl),y=c(s*f-o);let{isValid:w,value:b}=l(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&Tl)===Tl,v=!!(128&d);if(!t&&b===El&&v)throw new Error("bad point: x=0 and x_0=1");return v!==k&&(b=c(-b)),p.fromAffine({x:b,y:h})}static fromHex(e,t=!1){return p.fromBytes(_c("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return f.createCache(this,e),t||this.multiply(Il),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:o,Y:i,Z:s}=e,a=c(t*s),l=c(o*r),u=c(n*s),h=c(i*r);return a===l&&u===h}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:n,Z:r}=this,o=c(t*t),s=c(n*n),a=c(Il*c(r*r)),l=c(e*o),u=t+n,d=c(c(u*u)-o-s),h=l+s,g=h-a,f=l-s,m=c(d*g),y=c(h*f),w=c(d*f),b=c(g*h);return new p(m,y,b,w)}add(e){d(e);const{a:t,d:n}=i,{X:r,Y:o,Z:s,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,f=c(r*l),m=c(o*u),y=c(a*n*g),w=c(s*h),b=c((r+o)*(l+u)-f-m),k=w-y,v=w+y,S=c(m-t*f),A=c(b*k),E=c(v*S),T=c(b*S),I=c(k*v);return new p(A,E,I,T)}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}=f.cached(this,e,e=>hl(p,e));return hl(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===El?p.ZERO:this.is0()||e===Tl?this:f.unsafe(this,e,e=>hl(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return f.unsafe(this,i.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return s===Tl?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&Tl?128:0,n}toHex(){return xa(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return hl(p,e)}static msm(e,t){return vl(p,o,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,Tl,c(i.Gx*i.Gy)),p.ZERO=new p(El,Tl,Tl,El),p.Fp=r,p.Fn=o;const f=new kl(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,xl(i,r,o))}const _l=BigInt(1),Dl=BigInt(2);BigInt(3);const Pl=BigInt(5),Rl=BigInt(8),Bl=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ml=(()=>({p:Bl,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rl,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ol(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ll=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ul(e,t){const n=Bl,r=jc(t*t*t,n),o=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Bl,s=e*e%i*e%i,a=Xc(s,Dl,i)*s%i,c=Xc(a,_l,i)*e%i,l=Xc(c,Pl,i)*c%i,u=Xc(l,t,i)*l%i,d=Xc(u,n,i)*u%i,h=Xc(d,r,i)*d%i,g=Xc(h,o,i)*h%i,p=Xc(g,o,i)*h%i,f=Xc(p,t,i)*l%i;return{pow_p_5_8:Xc(f,Dl,i)*e%i,b2:s}}(e*jc(r*r*t,n)).pow_p_5_8;let i=jc(e*r*o,n);const s=jc(t*i*i,n),a=i,c=jc(i*Ll,n),l=s===e,u=s===jc(-e,n),d=s===jc(-e*Ll,n);return l&&(i=a),(u||d)&&(i=c),(jc(i,n)&Fc)===Fc&&(i=jc(-i,n)),{isValid:l||u,value:i}}const Fl=(()=>sl(Ml.p,{isLE:!0}))(),$l=(()=>({...Ml,Fp:Fl,hash:bc,adjustScalarBytes:Ol,uvRatio:Ul}))(),ql=(()=>Nl($l))();var Kl,Gl={exports:{}},Hl=sa(Object.freeze({__proto__:null,default:{}})),Wl=Gl.exports;function zl(){return Kl||(Kl=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function 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:Hl.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 l=e.charCodeAt(c)-48;i*=o,s=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&s<o,"Invalid character"),i+=s}return i}function l(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,l=0,u=n;u<a;u+=r)l=c(e,u,u+r,t),this.imuln(o),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(0!==s){var d=1;for(l=c(e,u,e.length,t),u=0;u<s;u++)d*=t;this.imuln(d),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},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){l(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")]=u}catch(e){o.prototype.inspect=u}else o.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],g=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function p(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var 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 l=1;l<r;l++){for(var u=c>>>26,d=67108863&c,h=Math.min(l,t.length-1),g=Math.max(0,l-e.length+1);g<=h;g++){var p=l-g|0;u+=(s=(o=0|e.words[p])*(i=0|t.words[g])+d)/67108864|0,d=67108863&s}n.words[l]=0|d,c=0|u}return 0!==c?n.words[l]=0|c:n.length--,n._strip()}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?d[6-c.length]+c+r:c+r}for(0!==i&&(r=i.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=h[e],u=g[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var f=p.modrn(u).toString(e);r=(p=p.idivn(u)).isZero()?f+r:d[l-f.length]+f+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},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)},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 f=function(e,t,n){var r,o,i,s=e.words,a=t.words,c=n.words,l=0,u=0|s[0],d=8191&u,h=u>>>13,g=0|s[1],p=8191&g,f=g>>>13,m=0|s[2],y=8191&m,w=m>>>13,b=0|s[3],k=8191&b,v=b>>>13,S=0|s[4],A=8191&S,E=S>>>13,T=0|s[5],I=8191&T,C=T>>>13,x=0|s[6],N=8191&x,_=x>>>13,D=0|s[7],P=8191&D,R=D>>>13,B=0|s[8],M=8191&B,O=B>>>13,L=0|s[9],U=8191&L,F=L>>>13,$=0|a[0],q=8191&$,K=$>>>13,G=0|a[1],H=8191&G,W=G>>>13,z=0|a[2],V=8191&z,j=z>>>13,X=0|a[3],Q=8191&X,Y=X>>>13,J=0|a[4],Z=8191&J,ee=J>>>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,le=ae>>>13,ue=0|a[8],de=8191&ue,he=ue>>>13,ge=0|a[9],pe=8191&ge,fe=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(l+(r=Math.imul(d,q))|0)+((8191&(o=(o=Math.imul(d,K))+Math.imul(h,q)|0))<<13)|0;l=((i=Math.imul(h,K))+(o>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(p,q),o=(o=Math.imul(p,K))+Math.imul(f,q)|0,i=Math.imul(f,K);var ye=(l+(r=r+Math.imul(d,H)|0)|0)+((8191&(o=(o=o+Math.imul(d,W)|0)+Math.imul(h,H)|0))<<13)|0;l=((i=i+Math.imul(h,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,H)|0,o=(o=o+Math.imul(p,W)|0)+Math.imul(f,H)|0,i=i+Math.imul(f,W)|0;var we=(l+(r=r+Math.imul(d,V)|0)|0)+((8191&(o=(o=o+Math.imul(d,j)|0)+Math.imul(h,V)|0))<<13)|0;l=((i=i+Math.imul(h,j)|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,H)|0,o=(o=o+Math.imul(y,W)|0)+Math.imul(w,H)|0,i=i+Math.imul(w,W)|0,r=r+Math.imul(p,V)|0,o=(o=o+Math.imul(p,j)|0)+Math.imul(f,V)|0,i=i+Math.imul(f,j)|0;var be=(l+(r=r+Math.imul(d,Q)|0)|0)+((8191&(o=(o=o+Math.imul(d,Y)|0)+Math.imul(h,Q)|0))<<13)|0;l=((i=i+Math.imul(h,Y)|0)+(o>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(A,q),o=(o=Math.imul(A,K))+Math.imul(E,q)|0,i=Math.imul(E,K),r=r+Math.imul(k,H)|0,o=(o=o+Math.imul(k,W)|0)+Math.imul(v,H)|0,i=i+Math.imul(v,W)|0,r=r+Math.imul(y,V)|0,o=(o=o+Math.imul(y,j)|0)+Math.imul(w,V)|0,i=i+Math.imul(w,j)|0,r=r+Math.imul(p,Q)|0,o=(o=o+Math.imul(p,Y)|0)+Math.imul(f,Q)|0,i=i+Math.imul(f,Y)|0;var ke=(l+(r=r+Math.imul(d,Z)|0)|0)+((8191&(o=(o=o+Math.imul(d,ee)|0)+Math.imul(h,Z)|0))<<13)|0;l=((i=i+Math.imul(h,ee)|0)+(o>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(I,q),o=(o=Math.imul(I,K))+Math.imul(C,q)|0,i=Math.imul(C,K),r=r+Math.imul(A,H)|0,o=(o=o+Math.imul(A,W)|0)+Math.imul(E,H)|0,i=i+Math.imul(E,W)|0,r=r+Math.imul(k,V)|0,o=(o=o+Math.imul(k,j)|0)+Math.imul(v,V)|0,i=i+Math.imul(v,j)|0,r=r+Math.imul(y,Q)|0,o=(o=o+Math.imul(y,Y)|0)+Math.imul(w,Q)|0,i=i+Math.imul(w,Y)|0,r=r+Math.imul(p,Z)|0,o=(o=o+Math.imul(p,ee)|0)+Math.imul(f,Z)|0,i=i+Math.imul(f,ee)|0;var ve=(l+(r=r+Math.imul(d,ne)|0)|0)+((8191&(o=(o=o+Math.imul(d,re)|0)+Math.imul(h,ne)|0))<<13)|0;l=((i=i+Math.imul(h,re)|0)+(o>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(N,q),o=(o=Math.imul(N,K))+Math.imul(_,q)|0,i=Math.imul(_,K),r=r+Math.imul(I,H)|0,o=(o=o+Math.imul(I,W)|0)+Math.imul(C,H)|0,i=i+Math.imul(C,W)|0,r=r+Math.imul(A,V)|0,o=(o=o+Math.imul(A,j)|0)+Math.imul(E,V)|0,i=i+Math.imul(E,j)|0,r=r+Math.imul(k,Q)|0,o=(o=o+Math.imul(k,Y)|0)+Math.imul(v,Q)|0,i=i+Math.imul(v,Y)|0,r=r+Math.imul(y,Z)|0,o=(o=o+Math.imul(y,ee)|0)+Math.imul(w,Z)|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(f,ne)|0,i=i+Math.imul(f,re)|0;var Se=(l+(r=r+Math.imul(d,ie)|0)|0)+((8191&(o=(o=o+Math.imul(d,se)|0)+Math.imul(h,ie)|0))<<13)|0;l=((i=i+Math.imul(h,se)|0)+(o>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,q),o=(o=Math.imul(P,K))+Math.imul(R,q)|0,i=Math.imul(R,K),r=r+Math.imul(N,H)|0,o=(o=o+Math.imul(N,W)|0)+Math.imul(_,H)|0,i=i+Math.imul(_,W)|0,r=r+Math.imul(I,V)|0,o=(o=o+Math.imul(I,j)|0)+Math.imul(C,V)|0,i=i+Math.imul(C,j)|0,r=r+Math.imul(A,Q)|0,o=(o=o+Math.imul(A,Y)|0)+Math.imul(E,Q)|0,i=i+Math.imul(E,Y)|0,r=r+Math.imul(k,Z)|0,o=(o=o+Math.imul(k,ee)|0)+Math.imul(v,Z)|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(f,ie)|0,i=i+Math.imul(f,se)|0;var Ae=(l+(r=r+Math.imul(d,ce)|0)|0)+((8191&(o=(o=o+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((i=i+Math.imul(h,le)|0)+(o>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(M,q),o=(o=Math.imul(M,K))+Math.imul(O,q)|0,i=Math.imul(O,K),r=r+Math.imul(P,H)|0,o=(o=o+Math.imul(P,W)|0)+Math.imul(R,H)|0,i=i+Math.imul(R,W)|0,r=r+Math.imul(N,V)|0,o=(o=o+Math.imul(N,j)|0)+Math.imul(_,V)|0,i=i+Math.imul(_,j)|0,r=r+Math.imul(I,Q)|0,o=(o=o+Math.imul(I,Y)|0)+Math.imul(C,Q)|0,i=i+Math.imul(C,Y)|0,r=r+Math.imul(A,Z)|0,o=(o=o+Math.imul(A,ee)|0)+Math.imul(E,Z)|0,i=i+Math.imul(E,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,le)|0)+Math.imul(f,ce)|0,i=i+Math.imul(f,le)|0;var Ee=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(o=(o=o+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((i=i+Math.imul(h,he)|0)+(o>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(U,q),o=(o=Math.imul(U,K))+Math.imul(F,q)|0,i=Math.imul(F,K),r=r+Math.imul(M,H)|0,o=(o=o+Math.imul(M,W)|0)+Math.imul(O,H)|0,i=i+Math.imul(O,W)|0,r=r+Math.imul(P,V)|0,o=(o=o+Math.imul(P,j)|0)+Math.imul(R,V)|0,i=i+Math.imul(R,j)|0,r=r+Math.imul(N,Q)|0,o=(o=o+Math.imul(N,Y)|0)+Math.imul(_,Q)|0,i=i+Math.imul(_,Y)|0,r=r+Math.imul(I,Z)|0,o=(o=o+Math.imul(I,ee)|0)+Math.imul(C,Z)|0,i=i+Math.imul(C,ee)|0,r=r+Math.imul(A,ne)|0,o=(o=o+Math.imul(A,re)|0)+Math.imul(E,ne)|0,i=i+Math.imul(E,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,le)|0)+Math.imul(w,ce)|0,i=i+Math.imul(w,le)|0,r=r+Math.imul(p,de)|0,o=(o=o+Math.imul(p,he)|0)+Math.imul(f,de)|0,i=i+Math.imul(f,he)|0;var Te=(l+(r=r+Math.imul(d,pe)|0)|0)+((8191&(o=(o=o+Math.imul(d,fe)|0)+Math.imul(h,pe)|0))<<13)|0;l=((i=i+Math.imul(h,fe)|0)+(o>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(U,H),o=(o=Math.imul(U,W))+Math.imul(F,H)|0,i=Math.imul(F,W),r=r+Math.imul(M,V)|0,o=(o=o+Math.imul(M,j)|0)+Math.imul(O,V)|0,i=i+Math.imul(O,j)|0,r=r+Math.imul(P,Q)|0,o=(o=o+Math.imul(P,Y)|0)+Math.imul(R,Q)|0,i=i+Math.imul(R,Y)|0,r=r+Math.imul(N,Z)|0,o=(o=o+Math.imul(N,ee)|0)+Math.imul(_,Z)|0,i=i+Math.imul(_,ee)|0,r=r+Math.imul(I,ne)|0,o=(o=o+Math.imul(I,re)|0)+Math.imul(C,ne)|0,i=i+Math.imul(C,re)|0,r=r+Math.imul(A,ie)|0,o=(o=o+Math.imul(A,se)|0)+Math.imul(E,ie)|0,i=i+Math.imul(E,se)|0,r=r+Math.imul(k,ce)|0,o=(o=o+Math.imul(k,le)|0)+Math.imul(v,ce)|0,i=i+Math.imul(v,le)|0,r=r+Math.imul(y,de)|0,o=(o=o+Math.imul(y,he)|0)+Math.imul(w,de)|0,i=i+Math.imul(w,he)|0;var Ie=(l+(r=r+Math.imul(p,pe)|0)|0)+((8191&(o=(o=o+Math.imul(p,fe)|0)+Math.imul(f,pe)|0))<<13)|0;l=((i=i+Math.imul(f,fe)|0)+(o>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(U,V),o=(o=Math.imul(U,j))+Math.imul(F,V)|0,i=Math.imul(F,j),r=r+Math.imul(M,Q)|0,o=(o=o+Math.imul(M,Y)|0)+Math.imul(O,Q)|0,i=i+Math.imul(O,Y)|0,r=r+Math.imul(P,Z)|0,o=(o=o+Math.imul(P,ee)|0)+Math.imul(R,Z)|0,i=i+Math.imul(R,ee)|0,r=r+Math.imul(N,ne)|0,o=(o=o+Math.imul(N,re)|0)+Math.imul(_,ne)|0,i=i+Math.imul(_,re)|0,r=r+Math.imul(I,ie)|0,o=(o=o+Math.imul(I,se)|0)+Math.imul(C,ie)|0,i=i+Math.imul(C,se)|0,r=r+Math.imul(A,ce)|0,o=(o=o+Math.imul(A,le)|0)+Math.imul(E,ce)|0,i=i+Math.imul(E,le)|0,r=r+Math.imul(k,de)|0,o=(o=o+Math.imul(k,he)|0)+Math.imul(v,de)|0,i=i+Math.imul(v,he)|0;var Ce=(l+(r=r+Math.imul(y,pe)|0)|0)+((8191&(o=(o=o+Math.imul(y,fe)|0)+Math.imul(w,pe)|0))<<13)|0;l=((i=i+Math.imul(w,fe)|0)+(o>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(U,Q),o=(o=Math.imul(U,Y))+Math.imul(F,Q)|0,i=Math.imul(F,Y),r=r+Math.imul(M,Z)|0,o=(o=o+Math.imul(M,ee)|0)+Math.imul(O,Z)|0,i=i+Math.imul(O,ee)|0,r=r+Math.imul(P,ne)|0,o=(o=o+Math.imul(P,re)|0)+Math.imul(R,ne)|0,i=i+Math.imul(R,re)|0,r=r+Math.imul(N,ie)|0,o=(o=o+Math.imul(N,se)|0)+Math.imul(_,ie)|0,i=i+Math.imul(_,se)|0,r=r+Math.imul(I,ce)|0,o=(o=o+Math.imul(I,le)|0)+Math.imul(C,ce)|0,i=i+Math.imul(C,le)|0,r=r+Math.imul(A,de)|0,o=(o=o+Math.imul(A,he)|0)+Math.imul(E,de)|0,i=i+Math.imul(E,he)|0;var xe=(l+(r=r+Math.imul(k,pe)|0)|0)+((8191&(o=(o=o+Math.imul(k,fe)|0)+Math.imul(v,pe)|0))<<13)|0;l=((i=i+Math.imul(v,fe)|0)+(o>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(U,Z),o=(o=Math.imul(U,ee))+Math.imul(F,Z)|0,i=Math.imul(F,ee),r=r+Math.imul(M,ne)|0,o=(o=o+Math.imul(M,re)|0)+Math.imul(O,ne)|0,i=i+Math.imul(O,re)|0,r=r+Math.imul(P,ie)|0,o=(o=o+Math.imul(P,se)|0)+Math.imul(R,ie)|0,i=i+Math.imul(R,se)|0,r=r+Math.imul(N,ce)|0,o=(o=o+Math.imul(N,le)|0)+Math.imul(_,ce)|0,i=i+Math.imul(_,le)|0,r=r+Math.imul(I,de)|0,o=(o=o+Math.imul(I,he)|0)+Math.imul(C,de)|0,i=i+Math.imul(C,he)|0;var Ne=(l+(r=r+Math.imul(A,pe)|0)|0)+((8191&(o=(o=o+Math.imul(A,fe)|0)+Math.imul(E,pe)|0))<<13)|0;l=((i=i+Math.imul(E,fe)|0)+(o>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(U,ne),o=(o=Math.imul(U,re))+Math.imul(F,ne)|0,i=Math.imul(F,re),r=r+Math.imul(M,ie)|0,o=(o=o+Math.imul(M,se)|0)+Math.imul(O,ie)|0,i=i+Math.imul(O,se)|0,r=r+Math.imul(P,ce)|0,o=(o=o+Math.imul(P,le)|0)+Math.imul(R,ce)|0,i=i+Math.imul(R,le)|0,r=r+Math.imul(N,de)|0,o=(o=o+Math.imul(N,he)|0)+Math.imul(_,de)|0,i=i+Math.imul(_,he)|0;var _e=(l+(r=r+Math.imul(I,pe)|0)|0)+((8191&(o=(o=o+Math.imul(I,fe)|0)+Math.imul(C,pe)|0))<<13)|0;l=((i=i+Math.imul(C,fe)|0)+(o>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(U,ie),o=(o=Math.imul(U,se))+Math.imul(F,ie)|0,i=Math.imul(F,se),r=r+Math.imul(M,ce)|0,o=(o=o+Math.imul(M,le)|0)+Math.imul(O,ce)|0,i=i+Math.imul(O,le)|0,r=r+Math.imul(P,de)|0,o=(o=o+Math.imul(P,he)|0)+Math.imul(R,de)|0,i=i+Math.imul(R,he)|0;var De=(l+(r=r+Math.imul(N,pe)|0)|0)+((8191&(o=(o=o+Math.imul(N,fe)|0)+Math.imul(_,pe)|0))<<13)|0;l=((i=i+Math.imul(_,fe)|0)+(o>>>13)|0)+(De>>>26)|0,De&=67108863,r=Math.imul(U,ce),o=(o=Math.imul(U,le))+Math.imul(F,ce)|0,i=Math.imul(F,le),r=r+Math.imul(M,de)|0,o=(o=o+Math.imul(M,he)|0)+Math.imul(O,de)|0,i=i+Math.imul(O,he)|0;var Pe=(l+(r=r+Math.imul(P,pe)|0)|0)+((8191&(o=(o=o+Math.imul(P,fe)|0)+Math.imul(R,pe)|0))<<13)|0;l=((i=i+Math.imul(R,fe)|0)+(o>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(U,de),o=(o=Math.imul(U,he))+Math.imul(F,de)|0,i=Math.imul(F,he);var Re=(l+(r=r+Math.imul(M,pe)|0)|0)+((8191&(o=(o=o+Math.imul(M,fe)|0)+Math.imul(O,pe)|0))<<13)|0;l=((i=i+Math.imul(O,fe)|0)+(o>>>13)|0)+(Re>>>26)|0,Re&=67108863;var Be=(l+(r=Math.imul(U,pe))|0)+((8191&(o=(o=Math.imul(U,fe))+Math.imul(F,pe)|0))<<13)|0;return l=((i=Math.imul(F,fe))+(o>>>13)|0)+(Be>>>26)|0,Be&=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]=Ee,c[9]=Te,c[10]=Ie,c[11]=Ce,c[12]=xe,c[13]=Ne,c[14]=_e,c[15]=De,c[16]=Pe,c[17]=Re,c[18]=Be,0!==l&&(c[19]=l,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,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),l=Math.max(0,i-e.length+1);l<=c;l++){var u=i-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),o+=(s=(s=s+(d/67108864|0)|0)+(h>>>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||(f=p),o.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?f(this,e,t):n<63?p(this,e,t):n<1024?m(this,e,t):y(this,e,t)},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++),this.length=0===e?1: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 l=0;l<s;l++)c.words[l]=this.words[l];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,l=0;l<this.length;l++)this.words[l]=this.words[l+s];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=o);l--){var d=0|this.words[l];this.words[l]=u<<26-i|d>>>i,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},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 0===this.length&&(this.words[0]=0,this.length=1),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 l=0;l<a.length;l++)a.words[l]=0}var u=r.clone()._ishlnsubmul(i,1,c);0===u.negative&&(r=u,a&&(a.words[c]=1));for(var d=c-1;d>=0;d--){var h=67108864*(0|r.words[i.length+d])+(0|r.words[i.length+d-1]);for(h=Math.min(h/s|0,67108863),r._ishlnsubmul(i,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(i,1,d),r.isZero()||(r.negative^=1);a&&(a.words[d]=h)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},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),l=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++l;for(var u=r.clone(),d=t.clone();!t.isZero();){for(var h=0,g=1;0===(t.words[0]&g)&&h<26;++h,g<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(i.isOdd()||s.isOdd())&&(i.iadd(u),s.isub(d)),i.iushrn(1),s.iushrn(1);for(var p=0,f=1;0===(r.words[0]&f)&&p<26;++p,f<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(d)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(a),s.isub(c)):(r.isub(t),a.isub(i),c.isub(s))}return{a:a,b:c,gcd:r.iushln(l)}},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 l=0,u=1;0===(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var d=0,h=1;0===(r.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(r.iushrn(d);d-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(a)):(r.isub(t),a.isub(s))}return(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 E(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 S(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function A(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(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 T(e){E.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(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,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 S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new A}return w[e]=t,t},E.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},E.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")},E.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},E.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},E.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)},E.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},E.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)},E.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},E.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},E.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},E.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},E.prototype.isqr=function(e){return this.imul(e,e.clone())},E.prototype.sqr=function(e){return this.mul(e,e)},E.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(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new o(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,i),h=this.pow(e,i.addn(1).iushrn(1)),g=this.pow(e,i),p=s;0!==g.cmp(a);){for(var f=g,m=0;0!==f.cmp(a);m++)f=f.redSqr();n(m<p);var y=this.pow(d,new o(1).iushln(p-m-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),p=m}return h},E.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},E.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 l=t.words[r],u=c-1;u>=0;u--){var d=l>>u&1;i!==n[0]&&(i=this.sqr(i)),0!==d||0!==s?(s<<=1,s|=d,(4===++a||0===r&&0===u)&&(i=this.mul(i,n[s]),a=0,s=0)):a=0}c=26}return i},E.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},E.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new T(e)},r(T,E),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),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)},T.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)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(Gl,Wl)),Gl.exports}var Vl,jl,Xl,Ql,Yl,Jl=ia(zl()),Zl={exports:{}};function eu(){return Vl||(Vl=1,function(e,t){var n=fa(),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),i.prototype=Object.create(r.prototype),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)}}(Zl,Zl.exports)),Zl.exports}function tu(){if(Xl)return jl;Xl=1;var e=eu().Buffer;return jl=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),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,o=0,i=0;t[r]===c;)o++,r++;for(var s=(t.length-r)*l+1>>>0,u=new Uint8Array(s);r<t.length;){var d=t.charCodeAt(r);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,p=s-1;(0!==h||g<i)&&-1!==p;p--,g++)h+=a*u[p]>>>0,u[p]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");i=g,r++}for(var f=s-i;f!==s&&0===u[f];)f++;var m=e.allocUnsafe(o+(s-f));m.fill(0,0,o);for(var y=o;f!==s;)m[y++]=u[f++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,o=0,i=0,s=n.length;i!==s&&0===n[i];)i++,r++;for(var l=(s-i)*u+1>>>0,d=new Uint8Array(l);i!==s;){for(var h=n[i],g=0,p=l-1;(0!==h||g<o)&&-1!==p;p--,g++)h+=256*d[p]>>>0,d[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");o=g,i++}for(var f=l-o;f!==l&&0===d[f];)f++;for(var m=c.repeat(r);f<l;++f)m+=t.charAt(d[f]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},jl}function nu(){if(Yl)return Ql;Yl=1;return Ql=tu()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}var ru=ia(nu());const ou=wc;var iu={};function su(e,t,n){return t<=e&&e<=n}function au(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function cu(e){this.tokens=[].slice.call(e)}cu.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var lu=-1;function uu(e,t){if(e)throw TypeError("Decoder error");return t||65533}var du="utf-8";function hu(e,t){if(!(this instanceof hu))return new hu(e,t);if((e=void 0!==e?String(e).toLowerCase():du)!==du)throw new Error("Encoding not supported. Only utf-8 is supported");t=au(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(t.fatal),this._ignoreBOM=Boolean(t.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function gu(e,t){if(!(this instanceof gu))return new gu(e,t);if((e=void 0!==e?String(e).toLowerCase():du)!==du)throw new Error("Encoding not supported. Only utf-8 is supported");t=au(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function pu(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,uu(t);if(-1===a)return lu;if(0===o){if(su(a,0,127))return a;if(su(a,194,223))o=1,n=a-192;else if(su(a,224,239))224===a&&(i=160),237===a&&(s=159),o=2,n=a-224;else{if(!su(a,240,244))return uu(t);240===a&&(i=144),244===a&&(s=143),o=3,n=a-240}return n<<=6*o,null}if(!su(a,i,s))return n=o=r=0,i=128,s=191,e.prepend(a),uu(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 fu(e){e.fatal,this.handler=function(e,t){if(-1===t)return lu;if(su(t,0,127))return t;var n,r;su(t,128,2047)?(n=1,r=192):su(t,2048,65535)?(n=2,r=224):su(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}}hu.prototype={decode:function(e,t){var n;n="object"==typeof e&&e instanceof ArrayBuffer?new Uint8Array(e):"object"==typeof e&&"buffer"in e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(0),t=au(t),this._streaming||(this._decoder=new pu({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,o=new cu(n),i=[];!o.endOfStream()&&(r=this._decoder.handler(o,o.read()))!==lu;)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()))===lu)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)}},gu.prototype={encode:function(e,t){e=e?String(e):"",t=au(t),this._streaming||(this._encoder=new fu(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],o=new cu(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()))!==lu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(o,o.read()))!==lu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var mu,yu=sa(Object.freeze({__proto__:null,TextDecoder:hu,TextEncoder:gu}));function wu(){if(mu)return iu;mu=1;var e=iu&&iu.__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=iu&&iu.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=iu&&iu.__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=iu&&iu.__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=iu&&iu.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(iu,"__esModule",{value:!0}),iu.deserializeUnchecked=iu.deserialize=iu.serialize=iu.BinaryReader=iu.BinaryWriter=iu.BorshError=iu.baseDecode=iu.baseEncode=void 0;const i=o(zl()),s=o(nu()),a=r(yu),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});iu.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},iu.baseDecode=function(e){return Buffer.from(s.default.decode(e))};const l=1024;class u extends Error{constructor(e){super(e),this.fieldPath=[],this.originalMessage=e}addToFieldPath(e){this.fieldPath.splice(0,0,e),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}iu.BorshError=u;class d{constructor(){this.buf=Buffer.alloc(l),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(l)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new i.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(l)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function h(e,t,n){const r=n.value;n.value=function(...e){try{return r.apply(this,e)}catch(e){if(e instanceof RangeError){const t=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(t)>=0)throw new u("Reached the end of buffer when deserializing")}throw e}}}iu.BinaryWriter=d;class g{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new i.default(e,"le")}readU128(){const e=this.readBuffer(16);return new i.default(e,"le")}readU256(){const e=this.readBuffer(32);return new i.default(e,"le")}readU512(){const e=this.readBuffer(64);return new i.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new u(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new u(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let r=0;r<t;++r)n.push(e());return n}}function p(e){return e.charAt(0).toUpperCase()+e.slice(1)}function f(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 u(`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 u(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)f(e,null,n[t],r[0],o)}else o.writeArray(n,n=>{f(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),f(e,t,n,r.type,o));break;case"map":o.writeU32(n.size),n.forEach((n,i)=>{f(e,t,i,r.key,o),f(e,t,n,r.value,o)});break;default:throw new u(`FieldType ${r} unrecognized`)}else m(e,n,o)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new u(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,o])=>{f(e,r,t[r],o,n)});else{if("enum"!==r.kind)throw new u(`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),f(e,s,t[s],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${p(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return r.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let 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 u&&e.addToFieldPath(t),e}}function w(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new u(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[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 u(`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 u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([h],g.prototype,"readU8",null),n([h],g.prototype,"readU16",null),n([h],g.prototype,"readU32",null),n([h],g.prototype,"readU64",null),n([h],g.prototype,"readU128",null),n([h],g.prototype,"readU256",null),n([h],g.prototype,"readU512",null),n([h],g.prototype,"readString",null),n([h],g.prototype,"readFixedArray",null),n([h],g.prototype,"readArray",null),iu.BinaryReader=g,iu.serialize=function(e,t,n=d){const r=new n;return m(e,t,r),r.toArray()},iu.deserialize=function(e,t,n,r=g){const o=new r(n),i=w(e,t,o);if(o.offset<n.length)throw new u(`Unexpected ${n.length-o.offset} bytes after deserialized data`);return i},iu.deserializeUnchecked=function(e,t,n,r=g){return w(e,t,new r(n))},iu}var bu,ku=wu(),vu={};function Su(){if(bu)return vu;bu=1,Object.defineProperty(vu,"__esModule",{value:!0}),vu.s16=vu.s8=vu.nu64be=vu.u48be=vu.u40be=vu.u32be=vu.u24be=vu.u16be=vu.nu64=vu.u48=vu.u40=vu.u32=vu.u24=vu.u16=vu.u8=vu.offset=vu.greedy=vu.Constant=vu.UTF8=vu.CString=vu.Blob=vu.Boolean=vu.BitField=vu.BitStructure=vu.VariantLayout=vu.Union=vu.UnionLayoutDiscriminator=vu.UnionDiscriminator=vu.Structure=vu.Sequence=vu.DoubleBE=vu.Double=vu.FloatBE=vu.Float=vu.NearInt64BE=vu.NearInt64=vu.NearUInt64BE=vu.NearUInt64=vu.IntBE=vu.Int=vu.UIntBE=vu.UInt=vu.OffsetLayout=vu.GreedyCount=vu.ExternalLayout=vu.bindConstructorLayout=vu.nameWithProperty=vu.Layout=vu.uint8ArrayToBuffer=vu.checkUint8Array=void 0,vu.constant=vu.utf8=vu.cstr=vu.blob=vu.unionLayoutDiscriminator=vu.union=vu.seq=vu.bits=vu.struct=vu.f64be=vu.f64=vu.f32be=vu.f32=vu.ns64be=vu.s48be=vu.s40be=vu.s32be=vu.s24be=vu.s16be=vu.ns64=vu.s48=vu.s40=vu.s32=vu.s24=void 0;const e=fa();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)}vu.checkUint8Array=t,vu.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}vu.Layout=r,vu.nameWithProperty=o,vu.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")}}vu.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}}vu.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 l}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}vu.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}}vu.UInt=c;class l extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readUIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeUIntBE(e,r,this.span),this.span}}vu.UIntBE=l;class u extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntLE(t,this.span)}encode(e,t,r=0){return n(t).writeIntLE(e,r,this.span),this.span}}vu.Int=u;class d extends r{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return n(e).readIntBE(t,this.span)}encode(e,t,r=0){return n(t).writeIntBE(e,r,this.span),this.span}}vu.IntBE=d;const h=Math.pow(2,32);function g(e){const t=Math.floor(e/h);return{hi32:t,lo32:e-t*h}}function p(e,t){return e*h+t}class f extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),o=r.readUInt32LE(t);return p(r.readUInt32LE(t+4),o)}encode(e,t,r=0){const o=g(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeUInt32LE(o.hi32,r+4),8}}vu.NearUInt64=f;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return p(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const o=g(e),i=n(t);return i.writeUInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}vu.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=g(e),i=n(t);return i.writeUInt32LE(o.lo32,r),i.writeInt32LE(o.hi32,r+4),8}}vu.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=g(e),i=n(t);return i.writeInt32BE(o.hi32,r),i.writeUInt32BE(o.lo32,r+4),8}}vu.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}}vu.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}}vu.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}}vu.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}}vu.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 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}}vu.Sequence=A;class E 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)}}}vu.Structure=E;class T{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}vu.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof i&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}vu.UnionLayoutDiscriminator=I;class C extends r{constructor(e,t,n){let o;if(e instanceof c||e instanceof l)o=new I(new a(e));else if(e instanceof i&&e.isCount())o=new I(e);else{if(!(e instanceof T))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 l)&&(s+=o.layout.span)),super(s,n),this.discriminator=o,this.usesPrefixDiscriminator=e instanceof c||e instanceof l,this.defaultLayout=t,this.registry={};let u=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return u(e)},this.configGetSourceVariant=function(e){u=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const n=this.getVariant(e,t);if(!n)throw new Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw new Error("unable to infer src variant")}decode(e,t=0){let n;const r=this.discriminator,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]}}vu.Union=C;class x extends r{constructor(e,t,n,o){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===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 N(e){return 0>e&&(e+=4294967296),e}vu.VariantLayout=x;class _ extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof l))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,n),this.word=e,this.msb=!!t,this.fields=[];let r=0;this._packedSetValue=function(e){return r=N(e),this},this._packedGetValue=function(){return r}}decode(e,t=0){const n=this.makeDestinationObject(),r=this.word.decode(e,t);this._packedSetValue(r);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const r=this.word.decode(t,n);this._packedSetValue(r);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new D(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}}vu.BitStructure=_;class D{constructor(e,t,n){if(!(e instanceof _))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,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=N(this.valueMask<<this.start),this.property=n}decode(e,t){return N(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==N(e&this.valueMask))throw new TypeError(o("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=N(e<<this.start);this.container._packedSetValue(N(t&~this.wordMask)|n)}}vu.BitField=D;class P extends D{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)}}vu.Boolean=P;class R 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}}vu.Blob=R;class B 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}}vu.CString=B;class M extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,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}}vu.UTF8=M;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 vu.Constant=O,vu.greedy=(e,t)=>new s(e,t),vu.offset=(e,t,n)=>new a(e,t,n),vu.u8=e=>new c(1,e),vu.u16=e=>new c(2,e),vu.u24=e=>new c(3,e),vu.u32=e=>new c(4,e),vu.u40=e=>new c(5,e),vu.u48=e=>new c(6,e),vu.nu64=e=>new f(e),vu.u16be=e=>new l(2,e),vu.u24be=e=>new l(3,e),vu.u32be=e=>new l(4,e),vu.u40be=e=>new l(5,e),vu.u48be=e=>new l(6,e),vu.nu64be=e=>new m(e),vu.s8=e=>new u(1,e),vu.s16=e=>new u(2,e),vu.s24=e=>new u(3,e),vu.s32=e=>new u(4,e),vu.s40=e=>new u(5,e),vu.s48=e=>new u(6,e),vu.ns64=e=>new y(e),vu.s16be=e=>new d(2,e),vu.s24be=e=>new d(3,e),vu.s32be=e=>new d(4,e),vu.s40be=e=>new d(5,e),vu.s48be=e=>new d(6,e),vu.ns64be=e=>new w(e),vu.f32=e=>new b(e),vu.f32be=e=>new k(e),vu.f64=e=>new v(e),vu.f64be=e=>new S(e),vu.struct=(e,t,n)=>new E(e,t,n),vu.bits=(e,t,n)=>new _(e,t,n),vu.seq=(e,t,n)=>new A(e,t,n),vu.union=(e,t,n)=>new C(e,t,n),vu.unionLayoutDiscriminator=(e,t)=>new I(e,t),vu.blob=(e,t)=>new R(e,t),vu.cstr=e=>new B(e),vu.utf8=(e,t)=>new M(e,t),vu.constant=(e,t)=>new O(e,t),vu}var Au=Su(),Eu=1,Tu=2,Iu=3,Cu=4,xu=5,Nu=6,_u=7,Du=8,Pu=9,Ru=10,Bu=-32700,Mu=-32603,Ou=-32602,Lu=-32601,Uu=-32600,Fu=-32016,$u=-32015,qu=-32014,Ku=-32013,Gu=-32012,Hu=-32011,Wu=-32010,zu=-32009,Vu=-32008,ju=-32007,Xu=-32006,Qu=-32005,Yu=-32004,Ju=-32003,Zu=-32002,ed=-32001,td=28e5,nd=2800001,rd=2800002,od=2800003,id=2800004,sd=2800005,ad=2800006,cd=2800007,ld=2800008,ud=2800009,dd=2800010,hd=2800011,gd=323e4,pd=32300001,fd=3230002,md=3230003,yd=3230004,wd=361e4,bd=3610001,kd=3610002,vd=3610003,Sd=3610004,Ad=3610005,Ed=3610006,Td=3610007,Id=3611e3,Cd=3704e3,xd=3704001,Nd=3704002,_d=3704003,Dd=3704004,Pd=4128e3,Rd=4128001,Bd=4128002,Md=4615e3,Od=4615001,Ld=4615002,Ud=4615003,Fd=4615004,$d=4615005,qd=4615006,Kd=4615007,Gd=4615008,Hd=4615009,Wd=4615010,zd=4615011,Vd=4615012,jd=4615013,Xd=4615014,Qd=4615015,Yd=4615016,Jd=4615017,Zd=4615018,eh=4615019,th=4615020,nh=4615021,rh=4615022,oh=4615023,ih=4615024,sh=4615025,ah=4615026,ch=4615027,lh=4615028,uh=4615029,dh=4615030,hh=4615031,gh=4615032,ph=4615033,fh=4615034,mh=4615035,yh=4615036,wh=4615037,bh=4615038,kh=4615039,vh=4615040,Sh=4615041,Ah=4615042,Eh=4615043,Th=4615044,Ih=4615045,Ch=4615046,xh=4615047,Nh=4615048,_h=4615049,Dh=4615050,Ph=4615051,Rh=4615052,Bh=4615053,Mh=4615054,Oh=5508e3,Lh=5508001,Uh=5508002,Fh=5508003,$h=5508004,qh=5508005,Kh=5508006,Gh=5508007,Hh=5508008,Wh=5508009,zh=5508010,Vh=5508011,jh=5663e3,Xh=5663001,Qh=5663002,Yh=5663003,Jh=5663004,Zh=5663005,eg=5663006,tg=5663007,ng=5663008,rg=5663009,og=5663010,ig=5663011,sg=5663012,ag=5663013,cg=5663014,lg=5663015,ug=5663016,dg=5663017,hg=5663018,gg=5663019,pg=5663020,fg=705e4,mg=7050001,yg=7050002,wg=7050003,bg=7050004,kg=7050005,vg=7050006,Sg=7050007,Ag=7050008,Eg=7050009,Tg=7050010,Ig=7050011,Cg=7050012,xg=7050013,Ng=7050014,_g=7050015,Dg=7050016,Pg=7050017,Rg=7050018,Bg=7050019,Mg=7050020,Og=7050021,Lg=7050022,Ug=7050023,Fg=7050024,$g=7050025,qg=7050026,Kg=7050027,Gg=7050028,Hg=7050029,Wg=7050030,zg=7050031,Vg=7050032,jg=7050033,Xg=7050034,Qg=7050035,Yg=7050036,Jg=8078e3,Zg=8078001,ep=8078002,tp=8078003,np=8078004,rp=8078005,op=8078006,ip=8078007,sp=8078008,ap=8078009,cp=8078010,lp=8078011,up=8078012,dp=8078013,hp=8078014,gp=8078015,pp=8078016,fp=8078017,mp=8078018,yp=8078019,wp=8078020,bp=8078021,kp=8078022,vp=81e5,Sp=8100001,Ap=8100002,Ep=8100003,Tp=819e4,Ip=8190001,Cp=8190002,xp=8190003,Np=8190004,_p=99e5,Dp=9900001,Pp=9900002,Rp=9900003,Bp=9900004;function Mp(e){if(Array.isArray(e)){return"%5B"+e.map(Mp).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Op([e,t]){return`${e}=${Mp(t)}`}var Lp={[gd]:"Account not found at address: $address",[yd]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[md]:"Expected decoded account at address: $address",[fd]:"Failed to decode account data at address: $address",[pd]:"Accounts not found at addresses: $addresses",[ud]:"Unable to find a viable program address bump seed.",[rd]:"$putativeAddress is not a base58-encoded address.",[td]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[od]:"The `CryptoKey` must be an `Ed25519` public key.",[hd]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[ld]:"Invalid seeds; point must fall off the Ed25519 curve.",[id]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[ad]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[cd]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[sd]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[dd]:"Program address cannot end with PDA marker.",[nd]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Cu]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[Eu]:"The network has progressed past the last block for which this transaction could have been committed.",[Jg]:"Codec [$codecDescription] cannot decode empty byte arrays.",[kp]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[wp]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[rp]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[op]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[np]:"Encoder and decoder must either both be fixed-size or variable-size.",[sp]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[ep]:"Expected a fixed-size codec, got a variable-size one.",[dp]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[tp]:"Expected a variable-size codec, got a fixed-size one.",[yp]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Zg]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[mp]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[ap]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[cp]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[gp]:"Invalid literal union variant. Expected one of [$variants], got $value.",[ip]:"Expected [$codecDescription] to have $expected items, got $actual.",[up]:"Invalid value $value for base $base with alphabet $alphabet.",[pp]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[lp]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[hp]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[bp]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[fp]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[Id]:"No random values implementation could be found.",[Hd]:"instruction requires an uninitialized account",[oh]:"instruction tries to borrow reference for an account which is already borrowed",[ih]:"instruction left account with an outstanding borrowed reference",[nh]:"program other than the account's owner changed the size of the account data",[$d]:"account data too small for instruction",[rh]:"instruction expected an executable account",[Ch]:"An account does not have enough lamports to be rent-exempt",[Nh]:"Program arithmetic overflowed",[Ih]:"Failed to serialize or deserialize account data: $encodedData",[Mh]:"Builtin programs must consume compute units",[gh]:"Cross-program invocation call depth too deep",[bh]:"Computational budget exceeded",[ah]:"custom program error: #$code",[Jd]:"instruction contains duplicate accounts",[sh]:"instruction modifications of multiply-passed account differ",[dh]:"executable accounts must be rent exempt",[lh]:"instruction changed executable accounts data",[uh]:"instruction changed the balance of an executable account",[Zd]:"instruction changed executable bit of an account",[Xd]:"instruction modified data of an account it does not own",[jd]:"instruction spent from the balance of an account it does not own",[Od]:"generic instruction error",[Dh]:"Provided owner is not allowed",[Eh]:"Account is immutable",[Th]:"Incorrect authority provided",[Kd]:"incorrect program id for instruction",[qd]:"insufficient funds for instruction",[Fd]:"invalid account data for instruction",[xh]:"Invalid account owner",[Ld]:"invalid program argument",[ch]:"program returned invalid error code",[Ud]:"invalid instruction data",[wh]:"Failed to reallocate account data",[yh]:"Provided seeds do not result in a valid address",[Ph]:"Accounts data allocations exceeded the maximum allowed per transaction",[Rh]:"Max accounts exceeded",[Bh]:"Max instruction trace length exceeded",[mh]:"Length of the seed is too long for address generation",[ph]:"An account required by the instruction is missing",[Gd]:"missing required signature for instruction",[Vd]:"instruction illegally modified the program id of an account",[th]:"insufficient account keys for instruction",[kh]:"Cross-program invocation with unauthorized signer or writable account",[vh]:"Failed to create program execution environment",[Ah]:"Program failed to compile",[Sh]:"Program failed to complete",[Yd]:"instruction modified data of a read-only account",[Qd]:"instruction changed the balance of a read-only account",[fh]:"Cross-program invocation reentrancy not allowed for this instruction",[eh]:"instruction modified rent epoch of an account",[zd]:"sum of account balances before and after instruction do not match",[Wd]:"instruction requires an initialized account",[Md]:"",[hh]:"Unsupported program id",[_h]:"Unsupported sysvar",[Pd]:"The instruction does not have any accounts.",[Rd]:"The instruction does not have any data.",[Bd]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[xu]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[Tu]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[Pp]:"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",[Bp]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[Dp]:"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",[_p]:"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",[Rp]:"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",[Mu]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Ou]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Uu]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Lu]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Bu]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Gu]:"$__serverMessage",[ed]:"$__serverMessage",[Yu]:"$__serverMessage",[qu]:"$__serverMessage",[Wu]:"$__serverMessage",[zu]:"$__serverMessage",[Fu]:"Minimum context slot has not been reached",[Qu]:"Node is unhealthy; behind by $numSlotsBehind slots",[Vu]:"No snapshot",[Zu]:"Transaction simulation failed",[ju]:"$__serverMessage",[Hu]:"Transaction history is not available from this node",[Xu]:"$__serverMessage",[Ku]:"Transaction signature length mismatch",[Ju]:"Transaction signature verification failure",[$u]:"$__serverMessage",[Cd]:"Key pair bytes must be of length 64, got $byteLength.",[xd]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Nd]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Dd]:"The provided private key does not match the provided public key.",[_d]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Nu]:"Lamports value must be in the range [0, 2e64-1]",[_u]:"`$value` cannot be parsed as a `BigInt`",[Ru]:"$message",[Du]:"`$value` cannot be parsed as a `Number`",[Iu]:"No nonce account could be found at address `$nonceAccountAddress`",[Tp]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[Cp]:"WebSocket was closed before payload could be added to the send buffer",[xp]:"WebSocket connection closed",[Np]:"WebSocket failed to connect",[Ip]:"Failed to obtain a subscription id from the server",[Ep]:"Could not find an API plan for RPC method: `$method`",[vp]:"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`.",[Ap]:"HTTP error ($statusCode): $message",[Sp]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Oh]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Lh]:"The provided value does not implement the `KeyPairSigner` interface",[Fh]:"The provided value does not implement the `MessageModifyingSigner` interface",[$h]:"The provided value does not implement the `MessagePartialSigner` interface",[Uh]:"The provided value does not implement any of the `MessageSigner` interfaces",[Kh]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Gh]:"The provided value does not implement the `TransactionPartialSigner` interface",[Hh]:"The provided value does not implement the `TransactionSendingSigner` interface",[qh]:"The provided value does not implement any of the `TransactionSigner` interfaces",[Wh]:"More than one `TransactionSendingSigner` was identified.",[zh]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Vh]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Td]:"Cannot export a non-extractable key.",[bd]:"No digest implementation could be found.",[wd]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[kd]:"This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",[vd]:"No signature verification implementation could be found.",[Sd]:"No key generation implementation could be found.",[Ad]:"No signing implementation could be found.",[Ed]:"No key export implementation could be found.",[Pu]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Dg]:"Transaction processing left an account with an outstanding borrowed reference",[mg]:"Account in use",[yg]:"Account loaded twice",[wg]:"Attempt to debit an account but found no record of a prior credit.",[Ug]:"Transaction loads an address table account that doesn't exist",[Sg]:"This transaction has already been processed",[Ag]:"Blockhash not found",[Eg]:"Loader call chain is too deep",[_g]:"Transactions are currently disabled due to cluster maintenance",[Wg]:"Transaction contains a duplicate instruction ($index) that is not allowed",[kg]:"Insufficient funds for fee",[zg]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[vg]:"This account may not be used to pay transaction fees",[Ig]:"Transaction contains an invalid account reference",[$g]:"Transaction loads an address table account with invalid data",[qg]:"Transaction address table lookup uses an invalid index",[Fg]:"Transaction loads an address table account with an invalid owner",[jg]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[xg]:"This program may not be used for executing instructions",[Kg]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Bg]:"Transaction loads a writable account that cannot be written",[Vg]:"Transaction exceeded max loaded accounts data size cap",[Tg]:"Transaction requires a fee but has no signature present",[bg]:"Attempt to load a program that does not exist",[Qg]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Xg]:"ResanitizationNeeded",[Ng]:"Transaction failed to sanitize accounts offsets correctly",[Cg]:"Transaction did not pass signature verification",[Lg]:"Transaction locked too many accounts",[Yg]:"Sum of account balances before and after transaction do not match",[fg]:"The transaction failed with the error `$errorName`",[Rg]:"Transaction version is unsupported",[Og]:"Transaction would exceed account data limit within the block",[Hg]:"Transaction would exceed total account data limit",[Mg]:"Transaction would exceed max account limit within the block",[Pg]:"Transaction would exceed max Block Cost Limit",[Gg]:"Transaction would exceed max Vote Cost Limit",[lg]:"Attempted to sign a transaction with an address that is not a signer for it",[og]:"Transaction is missing an address at index: $index.",[ug]:"Transaction has no expected signers therefore it cannot be encoded",[pg]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Qh]:"Transaction does not have a blockhash lifetime",[Yh]:"Transaction is not a durable nonce transaction",[Zh]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[eg]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[ng]:"No fee payer set in CompiledTransaction",[tg]:"Could not find program address at index $index",[hg]:"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",[gg]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[ig]:"Transaction is missing a fee payer.",[sg]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[cg]:"Transaction first instruction is not advance nonce account instruction.",[ag]:"Transaction with no instructions cannot be durable nonce transaction.",[jh]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Xh]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[dg]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[rg]:"Transaction is missing signatures for addresses: $addresses.",[Jh]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Up="i",Fp="t";function $p(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Lp[e];if(0===n.length)return"";let r;function o(e){if(2===r[Fp]){const o=n.slice(r[Up]+1,e);i.push(o in t?`${t[o]}`:`$${o}`)}else 1===r[Fp]&&i.push(n.slice(r[Up],e))}const i=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Up]:0,[Fp]:"\\"===n[0]?0:"$"===n[0]?2:1});let i;switch(r[Fp]){case 0:i={[Up]:t,[Fp]:1};break;case 1:"\\"===e?i={[Up]:t,[Fp]:0}:"$"===e&&(i={[Up]:t,[Fp]:2});break;case 2:"\\"===e?i={[Up]:t,[Fp]:0}:"$"===e?i={[Up]:t,[Fp]:2}:e.match(/\w/)||(i={[Up]:t,[Fp]: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(Op).join("&");return btoa(t)}(t)}'`),`${n}\``}}var qp=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($p(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Kp(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Gp(e){return 1!==e?.endian}function Hp(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new qp(lp,{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,Gp(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 Wp(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new qp(Jg,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const o=n.length-r;if(o<t)throw new qp(Zg,{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,Gp(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var zp=(e={})=>function(e,t){if(Kp(e)!==Kp(t))throw new qp(np);if(Kp(e)&&Kp(t)&&e.fixedSize!==t.fixedSize)throw new qp(rp,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Kp(e)&&!Kp(t)&&e.maxSize!==t.maxSize)throw new qp(op,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Hp({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Wp({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Vp 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 jp(e){return"object"==typeof e&&null!=e}function Xp(e){return jp(e)&&!Array.isArray(e)}function Qp(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Yp(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: \`${Qp(r)}\``}=e;return{value:r,type:s,refinement:a,key:o[o.length-1],path:o,branch:i,...e,message:c}}function*Jp(e,t,n,r){var o;jp(o=e)&&"function"==typeof o[Symbol.iterator]||(e=[e]);for(const o of e){const e=Yp(o,t,n,r);e&&(yield e)}}function*Zp(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[l,u,d]of t.entries(e,a)){const t=Zp(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?o:[...o,u],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&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):jp(e)&&(void 0!==u||l in e)&&(e[l]=u))}if("not_valid"!==c)for(const r of t.refiner(e,a))r.explanation=n.message,c="not_refined",yield[r,void 0];"valid"===c&&(yield[void 0,e])}let ef=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)=>Jp(r(e,t),t,this,e):()=>[],this.refiner=o?(e,t)=>Jp(o(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=rf(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return tf(e,this,t)}is(e){return nf(e,this)}mask(e,t){return function(e,t,n){const r=rf(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return rf(e,this,t)}};function tf(e,t,n){const r=rf(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function nf(e,t){return!rf(e,t)[0]}function rf(e,t,n={}){const r=Zp(e,t,n),o=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(o[0]){return[new Vp(o[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,o[1]]}function of(e,t){return new ef({type:e,schema:null,validator:t})}function sf(e){return new ef({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: ${Qp(e)}`})}function af(){return of("boolean",e=>"boolean"==typeof e)}function cf(e){return of("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Qp(t)}`)}function lf(e){const t=Qp(e),n=typeof e;return new ef({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Qp(n)}`})}function uf(e){return new ef({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function df(){return of("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Qp(e)}`)}function hf(e){return new ef({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function gf(e,t){return new ef({type:"record",schema:null,*entries(n){if(jp(n))for(const r in n){const o=n[r];yield[r,r,e],yield[r,o,t]}},validator:e=>Xp(e)||`Expected an object, but received: ${Qp(e)}`,coercer:e=>Xp(e)?{...e}:e})}function pf(){return of("string",e=>"string"==typeof e||`Expected a string, but received: ${Qp(e)}`)}function ff(e){const t=of("never",()=>!1);return new ef({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: ${Qp(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function mf(e){const t=Object.keys(e);return new ef({type:"type",schema:e,*entries(n){if(jp(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Xp(e)||`Expected an object, but received: ${Qp(e)}`,coercer:e=>Xp(e)?{...e}:e})}function yf(e){const t=e.map(e=>e.type).join(" | ");return new ef({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]=Zp(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: ${Qp(n)}`,...o]}})}function wf(){return of("unknown",()=>!0)}function bf(e,t,n){return new ef({...e,coercer:(r,o)=>nf(r,t)?e.coercer(n(r,o),o):e.coercer(r,o)})}var kf,vf,Sf,Af,Ef=sa(g);function Tf(){if(vf)return kf;vf=1;const e=Ef.v4;return kf=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}}function If(){if(Af)return Sf;Af=1;const e=Ef.v4,t=Tf(),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 Sf=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 void o(e);throw e}if(!i)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return void 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 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)}},Sf}var Cf,xf=ia(If()),Nf={exports:{}};function _f(){return Cf||(Cf=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,l,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,o),!0;case 5:return u.fn.call(u.context,t,r,o,i),!0;case 6:return u.fn.call(u.context,t,r,o,i,s),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var h,g=u.length;for(l=0;l<g;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),d){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,r);break;case 4:u[l].fn.call(u[l].context,t,r,o);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,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,l=[],u=a.length;c<u;c++)(a[c].fn!==t||o&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l: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}(Nf)),Nf.exports}var Df=ia(_f()),Pf=class extends Df{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 Rf=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Bf=class extends Df{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 Rf,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=ma.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 Mf extends Fa{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,va(e);const n=La(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,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),Aa(o)}update(e){return Sa(this),this.iHash.update(e),this}digestInto(e){Sa(this),ka(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 Of=(e,t,n)=>new Mf(e,t).update(n).digest();Of.create=(e,t)=>new Mf(e,t);const Lf=(e,t)=>(e+(e>=0?t:-t)/Hf)/t;function Uf(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Ff(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return Sc(n.lowS,"lowS"),Sc(n.prehash,"prehash"),void 0!==n.format&&Uf(n.format),n}class $f extends Error{constructor(e=""){super(e)}}const qf={Err:$f,_tlv:{encode:(e,t)=>{const{Err:n}=qf;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=Ec(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Ec(o.length/2|128):"";return Ec(e)+i+o+t},decode(e,t){const{Err:n}=qf;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}=qf;if(e<Kf)throw new t("integer: negative integers are not allowed");let n=Ec(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=qf;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Ic(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=qf,o=_c("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:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=qf,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Kf=BigInt(0),Gf=BigInt(1),Hf=BigInt(2),Wf=BigInt(3),zf=BigInt(4);function Vf(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let o=_c("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 jf(e,t={}){const n=Al("weierstrass",e,t),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s,n:a}=i;Oc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Qf(r,o);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,n){const{x:o,y:i}=t.toAffine(),s=r.toBytes(o);if(Sc(n,"isCompressed"),n){u();return Ua(Xf(!r.isOdd(i)),s)}return Ua(Uint8Array.of(4),s,r.toBytes(i))},h=t.fromBytes||function(e){Ac(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,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=g(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}u();return!(1&~i)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function g(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,i.a)),i.b)}function p(e,t){const n=r.sqr(t),o=g(e);return r.eql(n,o)}if(!p(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=r.mul(r.pow(i.a,Wf),zf),m=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(f,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof A))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,o],[i,s]]=t,a=Lf(s*e,n),c=Lf(-o*e,n);let l=e-a*r-c*i,u=-a*o-c*s;const d=l<Kf,h=u<Kf;d&&(l=-l),h&&(u=-u);const g=Mc(Math.ceil(Bc(n)/2))+Gf;if(l<Kf||l>=g||u<Kf||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,o.ORDER)}const k=Lc((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),l=r.mul(i,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=Lc(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 S(e,t,n,o,i){return n=new A(r.mul(n.X,e),n.Y,n.Z),t=dl(o,t),n=dl(i,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 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 A)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?A.ZERO:new A(t,n,r.ONE)}static fromBytes(e){const t=A.fromAffine(h(Ac(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(_c("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return T.createCache(this,e),t||this.multiply(Wf),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)),l=r.eql(r.mul(n,a),r.mul(s,o));return c&&l}negate(){return new A(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=r.mul(t,Wf),{X:o,Y:s,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(o,o),h=r.mul(s,s),g=r.mul(a,a),p=r.mul(o,s);return p=r.add(p,p),u=r.mul(o,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,g),l=r.add(c,l),c=r.sub(h,l),l=r.add(h,l),l=r.mul(c,l),c=r.mul(p,c),u=r.mul(n,u),g=r.mul(e,g),p=r.sub(d,g),p=r.mul(e,p),p=r.add(p,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,g),d=r.mul(d,p),l=r.add(l,d),g=r.mul(s,a),g=r.add(g,g),d=r.mul(g,p),c=r.sub(c,d),u=r.mul(g,h),u=r.add(u,u),u=r.add(u,u),new A(c,l,u)}add(e){w(e);const{X:t,Y:n,Z:o}=this,{X:s,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=i.a,g=r.mul(i.b,Wf);let p=r.mul(t,s),f=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,f),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),l=r.add(a,c),k=r.mul(k,l),l=r.add(f,m),k=r.sub(k,l),d=r.mul(h,b),l=r.mul(g,m),d=r.add(l,d),l=r.sub(f,d),d=r.add(f,d),u=r.mul(l,d),f=r.add(p,p),f=r.add(f,p),m=r.mul(h,m),b=r.mul(g,b),f=r.add(f,m),m=r.sub(p,m),m=r.mul(h,m),b=r.add(b,m),p=r.mul(f,b),u=r.add(u,p),p=r.mul(k,b),l=r.mul(y,l),l=r.sub(l,p),p=r.mul(y,f),d=r.mul(k,d),d=r.add(d,p),new A(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:n}=t;if(!o.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,i;const s=e=>T.cached(this,e,e=>hl(A,e));if(n){const{k1neg:t,k1:o,k2neg:a,k2:c}=b(e),{p:l,f:u}=s(o),{p:d,f:h}=s(c);i=u.add(h),r=S(n.beta,l,d,t,a)}else{const{p:t,f:n}=s(e);r=t,i=n}return hl(A,[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===Kf||r.is0())return A.ZERO;if(e===Gf)return r;if(T.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>ll||r>ll;)n&ul&&(i=i.add(o)),r&ul&&(s=s.add(o)),o=o.double(),n>>=ul,r>>=ul;return{p1:i,p2:s}}(A,r,o,s);return S(n.beta,a,c,t,i)}return T.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){const r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return k(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===Gf||(e?e(A,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Gf?this:e?e(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Sc(e,"isCompressed"),this.assertValidity(),d(A,this,e)}toHex(e=!0){return xa(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return hl(A,e)}static msm(e,t){return vl(A,o,e,t)}static fromPrivateKey(e){return A.BASE.multiply(Vf(o,e))}}A.BASE=new A(i.Gx,i.Gy,r.ONE),A.ZERO=new A(r.ZERO,r.ONE,r.ZERO),A.Fp=r,A.Fn=o;const E=o.BITS,T=new kl(A,t.endo?Math.ceil(E/2):E);return A.BASE.precompute(8),A}function Xf(e){return Uint8Array.of(e?2:3)}function Qf(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Yf(e,t={}){const{Fn:n}=e,r=t.randomBytes||qa,o=Object.assign(Qf(e.Fp,n),{seed:cl(n.ORDER)});function i(e){try{return!!Vf(n,e)}catch(e){return!1}}function s(e=r(o.seed)){return function(e,t,n=!1){const r=e.length,o=al(t),i=cl(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const s=jc(n?Cc(e):Ic(e),t-Fc)+Fc;return n?Nc(s,o):xc(s,o)}(Ac(e,o.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Vf(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=_c("key",t).length;return a===i||a===s}const l={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=>Vf(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=Vf(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:l,lengths:o})}function Jf(e,t,n={}){va(t),Oc(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||qa,o=n.hmac||((e,...n)=>Of(t,e,Ua(...n))),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=Yf(e,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},f="compact";function m(e){return e>a>>Gf}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=f){let n;if(function(e,t){Uf(t);const n=g.signature;Ac(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=qf.toSig(Ac(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(Oa(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*Hf<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!i.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),d=e.fromBytes(Ua(Xf(!(1&c)),u)),h=s.inv(l),g=k(_c("msgHash",t)),p=s.create(-g*h),f=s.create(o*h),m=e.BASE.multiplyUnsafe(p).add(d.multiplyUnsafe(f));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=f){if(Uf(e),"der"===e)return Oa(qf.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 Ua(Uint8Array.of(this.recovery),t,n)}return Ua(t,n)}toHex(e){return xa(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(_c("sig",e),"compact")}static fromDER(e){return w.fromBytes(_c("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 xa(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return xa(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Ic(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},k=n.bits2int_modN||function(e){return s.create(b(e))},v=Mc(c);function S(e){return Rc("num < 2^"+c,e,Kf,v),s.toBytes(e)}function A(e,n){return Ac(e,void 0,"message"),n?Ac(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g,Point:e,sign:function(n,i,a={}){n=_c("message",n);const{seed:c,k2sig:l}=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}=Ff(o,p);t=A(t,a);const l=k(t),u=Vf(s,n),d=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(_c("extraEntropy",e))}const h=Ua(...d),f=l;return{seed:h,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===Kf)return;const c=s.create(r*s.create(f+a*u));if(c===Kf)return;let l=(o.x===a?0:2)|Number(o.y&Gf),d=c;return i&&m(c)&&(d=s.neg(c),l^=1),new w(a,d,l)}}}(n,i,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),o=e=>Uint8Array.of(e);let i=r(e),s=r(e),a=0;const c=()=>{i.fill(1),s.fill(0),a=0},l=(...e)=>n(s,i,...e),u=(e=r(0))=>{s=l(o(0),e),i=l(),0!==e.length&&(s=l(o(1),e),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=l();const t=i.slice();n.push(t),e+=i.length}return Ua(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,s.BYTES,o)(c,l)},verify:function(t,n,r,o={}){const{lowS:i,prehash:a,format:c}=Ff(o,p);if(r=_c("publicKey",r),n=A(_c("message",n),a),"strict"in o)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||wa(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(_c("sig",e),"der")}catch(e){if(!(e instanceof qf.Err))throw e}if(!t)try{t=w.fromBytes(_c("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(_c("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(i&&l.hasHighS())return!1;const{r:o,s:a}=l,c=k(n),u=s.inv(a),d=s.create(c*u),h=s.create(o*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return s.create(g.x)===o}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Ff(n,p);return t=A(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Zf(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:sl(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function em(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=Zf(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,il(n.Fn.ORDER,n.Fn.BITS))})}(e,Jf(jf(t,n),r,o))}const tm={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},rm=BigInt(2);const om=sl(tm.p,{sqrt:function(e){const t=tm.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Xc(u,n,t)*u%t,h=Xc(d,n,t)*u%t,g=Xc(h,rm,t)*l%t,p=Xc(g,o,t)*g%t,f=Xc(p,i,t)*p%t,m=Xc(f,a,t)*f%t,y=Xc(m,c,t)*m%t,w=Xc(y,a,t)*f%t,b=Xc(w,n,t)*u%t,k=Xc(b,s,t)*p%t,v=Xc(k,r,t)*l%t,S=Xc(v,rm,t);if(!om.eql(om.sqr(S),e))throw new Error("Cannot find square root");return S}}),im=function(e,t){const n=t=>em({...e,hash:t});return{...n(t),create:n}}({...tm,Fp:om,lowS:!0,endo:nm},wc);ql.utils.randomPrivateKey;const sm=()=>{const e=ql.utils.randomPrivateKey(),t=am(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},am=ql.getPublicKey;function cm(e){try{return ql.ExtendedPoint.fromHex(e),!0}catch{return!1}}const lm=ql.verify,um=e=>ma.Buffer.isBuffer(e)?e:e instanceof Uint8Array?ma.Buffer.from(e.buffer,e.byteOffset,e.byteLength):ma.Buffer.from(e);class dm{constructor(e){Object.assign(this,e)}encode(){return ma.Buffer.from(ku.serialize(hm,this))}static decode(e){return ku.deserialize(hm,this,e)}static decodeUnchecked(e){return ku.deserializeUnchecked(hm,this,e)}}const hm=new Map;var gm;const pm=32;let fm=1;class mm extends dm{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=ru.decode(e);if(t.length!=pm)throw new Error("Invalid public key input");this._bn=new Jl(t)}else this._bn=new Jl(e);if(this._bn.byteLength()>pm)throw new Error("Invalid public key input")}}static unique(){const e=new mm(fm);return fm+=1,new mm(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return ru.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(ma.Buffer);if(e.length===pm)return e;const t=ma.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=ma.Buffer.concat([e.toBuffer(),ma.Buffer.from(t),n.toBuffer()]),o=ou(r);return new mm(o)}static createProgramAddressSync(e,t){let n=ma.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=ma.Buffer.concat([n,um(e)])}),n=ma.Buffer.concat([n,t.toBuffer(),ma.Buffer.from("ProgramDerivedAddress")]);const r=ou(n);if(cm(r))throw new Error("Invalid seeds, address must fall off the curve");return new mm(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const o=e.concat(ma.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 cm(new mm(e).toBytes())}}gm=mm,mm.default=new gm("11111111111111111111111111111111"),hm.set(mm,{kind:"struct",fields:[["_bn","u256"]]}),new mm("BPFLoader1111111111111111111111111111111111");const ym=1232;class wm extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(wm.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class bm 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(bm.prototype,"name",{value:"TransactionExpiredTimeoutError"});class km extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(km.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class vm{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 Sm=(e="publicKey")=>Au.blob(32,e),Am=(e="string")=>{const t=Au.struct([Au.u32("length"),Au.u32("lengthPadding"),Au.blob(Au.offset(Au.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:ma.Buffer.from(e,"utf8")};return r(o,t,n)},o.alloc=e=>Au.u32().span+Au.u32().span+ma.Buffer.from(e,"utf8").length,o};function Em(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 Em({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function Tm(e){let t=0,n=0;for(;;){let r=e.shift();if(t|=(127&r)<<7*n,n+=1,!(128&r))break}return t}function Im(e,t){let n=t;for(;;){let t=127&n;if(n>>=7,0==n){e.push(t);break}t|=128,e.push(t)}}function Cm(e,t){if(!e)throw new Error(t||"Assertion failed")}class xm{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 xm(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];Cm(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),o=e.filter(([,e])=>!e.isSigner&&!e.isWritable),i={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:o.length};{Cm(t.length>0,"Expected at least one writable signer key");const[e]=t[0];Cm(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[i,[...t.map(([e])=>new mm(e)),...n.map(([e])=>new mm(e)),...r.map(([e])=>new mm(e)),...o.map(([e])=>new mm(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 mm(o),i=e.findIndex(e=>e.equals(t));i>=0&&(Cm(i<256,"Max lookup table index exceeded"),n.push(i),r.push(t),this.keyMetaMap.delete(o))}return[n,r]}}const Nm="Reached end of buffer unexpectedly";function _m(e){if(0===e.length)throw new Error(Nm);return e.shift()}function Dm(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(Nm);return e.splice(...t)}class Pm{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new mm(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:ru.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new vm(this.staticAccountKeys)}static compile(e){const t=xm.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),o=new vm(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:ru.encode(e.data)}));return new Pm({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=[];Im(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(ru.decode(e.data));let o=[];Im(o,t.length);let i=[];return Im(i,r.length),{programIdIndex:n,keyIndicesCount:ma.Buffer.from(o),keyIndices:t,dataLength:ma.Buffer.from(i),data:r}});let r=[];Im(r,n.length);let o=ma.Buffer.alloc(ym);ma.Buffer.from(r).copy(o);let i=r.length;n.forEach(e=>{const t=Au.struct([Au.u8("programIdIndex"),Au.blob(e.keyIndicesCount.length,"keyIndicesCount"),Au.seq(Au.u8("keyIndex"),e.keyIndices.length,"keyIndices"),Au.blob(e.dataLength.length,"dataLength"),Au.seq(Au.u8("userdatum"),e.data.length,"data")]).encode(e,o,i);i+=t}),o=o.slice(0,i);const s=Au.struct([Au.blob(1,"numRequiredSignatures"),Au.blob(1,"numReadonlySignedAccounts"),Au.blob(1,"numReadonlyUnsignedAccounts"),Au.blob(t.length,"keyCount"),Au.seq(Sm("key"),e,"keys"),Sm("recentBlockhash")]),a={numRequiredSignatures:ma.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:ma.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:ma.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:ma.Buffer.from(t),keys:this.accountKeys.map(e=>um(e.toBytes())),recentBlockhash:ru.decode(this.recentBlockhash)};let c=ma.Buffer.alloc(2048);const l=s.encode(a,c);return o.copy(c,l),c.slice(0,l+o.length)}static from(e){let t=[...e];const n=_m(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=_m(t),o=_m(t),i=Tm(t);let s=[];for(let e=0;e<i;e++){const e=Dm(t,0,pm);s.push(new mm(ma.Buffer.from(e)))}const a=Dm(t,0,pm),c=Tm(t);let l=[];for(let e=0;e<c;e++){const e=_m(t),n=Dm(t,0,Tm(t)),r=Dm(t,0,Tm(t)),o=ru.encode(ma.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:o})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:o},recentBlockhash:ru.encode(ma.Buffer.from(a)),accountKeys:s,instructions:l};return new Pm(u)}}class Rm{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 vm(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=xm.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 vm(s,r).compileInstructions(e.instructions);return new Rm({header:i,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();Im(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();Im(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),o=Array();Im(o,this.addressTableLookups.length);const i=Au.struct([Au.u8("prefix"),Au.struct([Au.u8("numRequiredSignatures"),Au.u8("numReadonlySignedAccounts"),Au.u8("numReadonlyUnsignedAccounts")],"header"),Au.blob(e.length,"staticAccountKeysLength"),Au.seq(Sm(),this.staticAccountKeys.length,"staticAccountKeys"),Sm("recentBlockhash"),Au.blob(n.length,"instructionsLength"),Au.blob(t.length,"serializedInstructions"),Au.blob(o.length,"addressTableLookupsLength"),Au.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(ym),a=i.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:ru.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(o),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(ym);for(const n of this.compiledInstructions){const r=Array();Im(r,n.accountKeyIndexes.length);const o=Array();Im(o,n.data.length);e+=Au.struct([Au.u8("programIdIndex"),Au.blob(r.length,"encodedAccountKeyIndexesLength"),Au.seq(Au.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),Au.blob(o.length,"encodedDataLength"),Au.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(ym);for(const n of this.addressTableLookups){const r=Array();Im(r,n.writableIndexes.length);const o=Array();Im(o,n.readonlyIndexes.length);e+=Au.struct([Sm("accountKey"),Au.blob(r.length,"encodedWritableIndexesLength"),Au.seq(Au.u8(),n.writableIndexes.length,"writableIndexes"),Au.blob(o.length,"encodedReadonlyIndexesLength"),Au.seq(Au.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=_m(t),r=127&n;Cm(n!==r,"Expected versioned message but received legacy message");Cm(0===r,`Expected versioned message with version 0 but found version ${r}`);const o={numRequiredSignatures:_m(t),numReadonlySignedAccounts:_m(t),numReadonlyUnsignedAccounts:_m(t)},i=[],s=Tm(t);for(let e=0;e<s;e++)i.push(new mm(Dm(t,0,pm)));const a=ru.encode(Dm(t,0,pm)),c=Tm(t),l=[];for(let e=0;e<c;e++){const e=_m(t),n=Dm(t,0,Tm(t)),r=Tm(t),o=new Uint8Array(Dm(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:o})}const u=Tm(t),d=[];for(let e=0;e<u;e++){const e=new mm(Dm(t,0,pm)),n=Dm(t,0,Tm(t)),r=Dm(t,0,Tm(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new Rm({header:o,staticAccountKeys:i,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}let Bm=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 Mm=ma.Buffer.alloc(64).fill(0);class Om{constructor(e){this.keys=void 0,this.programId=void 0,this.data=ma.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 Lm{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 Om(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 mm(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,l=0;const u=[],d=[];i.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(u.push(e.toString()),a+=1,n||(c+=1)):(d.push(e.toString()),n||(l+=1))});const h=u.concat(d),g=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:h.indexOf(n.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:ru.encode(t)}});return g.forEach(e=>{Cm(e.programIdIndex>=0),e.accounts.forEach(e=>Cm(e>=0))}),new Pm({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:l},accountKeys:h,recentBlockhash:e,instructions:g})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,n)=>t[n].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const n=e.toString();return!t.has(n)&&(t.add(n),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));const r=this._compile();this._partialSign(r,...n)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const r of e){const e=r.publicKey.toString();t.has(e)||(t.add(e),n.push(r))}const r=this._compile();this._partialSign(r,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(e=>{const t=((e,t)=>ql.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,um(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){Cm(64===t.length);const n=this.signatures.findIndex(t=>e.equals(t.publicKey));if(n<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[n].signature=ma.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):lm(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=[];Im(n,t.length);const r=n.length+64*t.length+e.length,o=ma.Buffer.alloc(r);return Cm(t.length<256),ma.Buffer.from(n).copy(o,0),t.forEach(({signature:e},t)=>{null!==e&&(Cm(64===e.length,"signature has invalid length"),ma.Buffer.from(e).copy(o,n.length+64*t))}),e.copy(o,n.length+64*t.length),Cm(o.length<=ym,`Transaction too large: ${o.length} > 1232`),o}get keys(){return Cm(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return Cm(1===this.instructions.length),this.instructions[0].programId}get data(){return Cm(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=Tm(t);let r=[];for(let e=0;e<n;e++){const e=Dm(t,0,64);r.push(ru.encode(ma.Buffer.from(e)))}return Lm.populate(Pm.from(t),r)}static populate(e,t=[]){const n=new Lm;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const o={signature:t==ru.encode(Mm)?null:ru.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 Om({keys:r,programId:e.accountKeys[t.programIdIndex],data:ru.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new mm("SysvarC1ock11111111111111111111111111111111"),new mm("SysvarEpochSchedu1e111111111111111111111111"),new mm("Sysvar1nstructions1111111111111111111111111");const Um=new mm("SysvarRecentB1ockHashes11111111111111111111"),Fm=new mm("SysvarRent111111111111111111111111111111111");new mm("SysvarRewards111111111111111111111111111111"),new mm("SysvarS1otHashes111111111111111111111111111"),new mm("SysvarS1otHistory11111111111111111111111111"),new mm("SysvarStakeHistory1111111111111111111111111");class $m 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 qm 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 Km(e){return new Promise(t=>setTimeout(t,e))}function Gm(e,t){const n=e.layout.span>=0?e.layout.span:Em(e,t),r=ma.Buffer.alloc(n),o=Object.assign({instruction:e.index},t);return e.layout.encode(o,r),r}const Hm=Au.nu64("lamportsPerSignature"),Wm=Au.struct([Au.u32("version"),Au.u32("state"),Sm("authorizedPubkey"),Sm("nonce"),Au.struct([Hm],"feeCalculator")]),zm=Wm.span;class Vm{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=Wm.decode(um(e),0);return new Vm({authorizedPubkey:new mm(t.authorizedPubkey),nonce:new mm(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function jm(e){const t=Au.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),o=t,i=zp();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 Xm=Object.freeze({Create:{index:0,layout:Au.struct([Au.u32("instruction"),Au.ns64("lamports"),Au.ns64("space"),Sm("programId")])},Assign:{index:1,layout:Au.struct([Au.u32("instruction"),Sm("programId")])},Transfer:{index:2,layout:Au.struct([Au.u32("instruction"),jm("lamports")])},CreateWithSeed:{index:3,layout:Au.struct([Au.u32("instruction"),Sm("base"),Am("seed"),Au.ns64("lamports"),Au.ns64("space"),Sm("programId")])},AdvanceNonceAccount:{index:4,layout:Au.struct([Au.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:Au.struct([Au.u32("instruction"),Au.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:Au.struct([Au.u32("instruction"),Sm("authorized")])},AuthorizeNonceAccount:{index:7,layout:Au.struct([Au.u32("instruction"),Sm("authorized")])},Allocate:{index:8,layout:Au.struct([Au.u32("instruction"),Au.ns64("space")])},AllocateWithSeed:{index:9,layout:Au.struct([Au.u32("instruction"),Sm("base"),Am("seed"),Au.ns64("space"),Sm("programId")])},AssignWithSeed:{index:10,layout:Au.struct([Au.u32("instruction"),Sm("base"),Am("seed"),Sm("programId")])},TransferWithSeed:{index:11,layout:Au.struct([Au.u32("instruction"),jm("lamports"),Am("seed"),Sm("programId")])},UpgradeNonceAccount:{index:12,layout:Au.struct([Au.u32("instruction")])}});class Qm{constructor(){}static createAccount(e){const t=Gm(Xm.Create,{lamports:e.lamports,space:e.space,programId:um(e.programId.toBuffer())});return new Om({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=Gm(Xm.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=Gm(Xm.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new Om({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Gm(Xm.AssignWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Gm(Xm.Assign,{programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Om({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Gm(Xm.CreateWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:um(e.programId.toBuffer())});let n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||n.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new Om({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Lm;"basePubkey"in e&&"seed"in e?t.add(Qm.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:zm,programId:this.programId})):t.add(Qm.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:zm,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Gm(Xm.InitializeNonceAccount,{authorized:um(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Um,isSigner:!1,isWritable:!1},{pubkey:Fm,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new Om(n)}static nonceAdvance(e){const t=Gm(Xm.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Um,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new Om(n)}static nonceWithdraw(e){const t=Gm(Xm.WithdrawNonceAccount,{lamports:e.lamports});return new Om({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Um,isSigner:!1,isWritable:!1},{pubkey:Fm,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Gm(Xm.AuthorizeNonceAccount,{authorized:um(e.newAuthorizedPubkey.toBuffer())});return new Om({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=Gm(Xm.AllocateWithSeed,{base:um(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:um(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Gm(Xm.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new Om({keys:n,programId:this.programId,data:t})}}function Ym(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jm,Zm;function ey(){if(Zm)return Jm;Zm=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,l,u,d;if(!0===r)return"true";if(!1===r)return"false";switch(typeof r){case"object":if(null===r)return null;if(r.toJSON&&"function"==typeof r.toJSON)return n(r.toJSON(),o);if("[object Array]"===(d=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]"===d){for(s=(c=t(r).sort()).length,a="",i=0;i<s;)void 0!==(u=n(r[l=c[i]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),i++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return o?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return Jm=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}Qm.programId=new mm("11111111111111111111111111111111"),new mm("BPFLoader2111111111111111111111111111111111");var ty=Ym(ey());function ny(e){let t=0;for(;e>1;)e/=2,t++;return t}class ry{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=ny(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)))-ny(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+ny(32)):this.slotsPerEpoch}}var oy=globalThis.fetch;class iy extends Bf{constructor(e,t,n){super(e=>{const n=function(e,t){return new Pf(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 sy{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}(ay,e),n=e.length-56;Cm(n>=0,"lookup table is invalid"),Cm(n%32==0,"lookup table is invalid");const r=n/32,{addresses:o}=Au.struct([Au.seq(Sm(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new mm(t.authority[0]):void 0,addresses:o.map(e=>new mm(e))}}}const ay={index:1,layout:Au.struct([Au.u32("typeIndex"),jm("deactivationSlot"),Au.nu64("lastExtendedSlot"),Au.u8("lastExtendedStartIndex"),Au.u8(),Au.seq(Sm(),Au.offset(Au.u8(),-1),"authority")])},cy=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const ly=bf(cf(mm),pf(),e=>new mm(e)),uy=ff([pf(),lf("base64")]),dy=bf(cf(ma.Buffer),uy,e=>ma.Buffer.from(e[0],"base64"));function hy(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 gy(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function py(e){return yf([mf({jsonrpc:lf("2.0"),id:pf(),result:e}),mf({jsonrpc:lf("2.0"),id:pf(),error:mf({code:wf(),message:pf(),data:hf(of("any",()=>!0))})})])}const fy=py(wf());function my(e){return bf(py(e),fy,t=>"error"in t?t:{...t,result:tf(t.result,e)})}function yy(e){return my(mf({context:mf({slot:df()}),value:e}))}function wy(e){return mf({context:mf({slot:df()}),value:e})}function by(e,t){return 0===e?new Rm({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new mm(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:ru.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new Pm(t)}const ky=mf({foundation:df(),foundationTerm:df(),initial:df(),taper:df(),terminal:df()}),vy=my(sf(uf(mf({epoch:df(),effectiveSlot:df(),amount:df(),postBalance:df(),commission:hf(uf(df()))})))),Sy=sf(mf({slot:df(),prioritizationFee:df()})),Ay=mf({total:df(),validator:df(),foundation:df(),epoch:df()}),Ey=mf({epoch:df(),slotIndex:df(),slotsInEpoch:df(),absoluteSlot:df(),blockHeight:hf(df()),transactionCount:hf(df())}),Ty=mf({slotsPerEpoch:df(),leaderScheduleSlotOffset:df(),warmup:af(),firstNormalEpoch:df(),firstNormalSlot:df()}),Iy=gf(pf(),sf(df())),Cy=uf(yf([mf({}),pf()])),xy=mf({err:Cy}),Ny=lf("receivedSignature"),_y=mf({"solana-core":pf(),"feature-set":hf(df())}),Dy=mf({program:pf(),programId:ly,parsed:wf()}),Py=mf({programId:ly,accounts:sf(ly),data:pf()}),Ry=yy(mf({err:uf(yf([mf({}),pf()])),logs:uf(sf(pf())),accounts:hf(uf(sf(uf(mf({executable:af(),owner:pf(),lamports:df(),data:sf(pf()),rentEpoch:hf(df())}))))),unitsConsumed:hf(df()),returnData:hf(uf(mf({programId:pf(),data:ff([pf(),lf("base64")])}))),innerInstructions:hf(uf(sf(mf({index:df(),instructions:sf(yf([Dy,Py]))}))))})),By=yy(mf({byIdentity:gf(pf(),sf(df())),range:mf({firstSlot:df(),lastSlot:df()})}));const My=my(ky),Oy=my(Ay),Ly=my(Sy),Uy=my(Ey),Fy=my(Ty),$y=my(Iy),qy=my(df()),Ky=yy(mf({total:df(),circulating:df(),nonCirculating:df(),nonCirculatingAccounts:sf(ly)})),Gy=mf({amount:pf(),uiAmount:uf(df()),decimals:df(),uiAmountString:hf(pf())}),Hy=yy(sf(mf({address:ly,amount:pf(),uiAmount:uf(df()),decimals:df(),uiAmountString:hf(pf())}))),Wy=yy(sf(mf({pubkey:ly,account:mf({executable:af(),owner:ly,lamports:df(),data:dy,rentEpoch:df()})}))),zy=mf({program:pf(),parsed:wf(),space:df()}),Vy=yy(sf(mf({pubkey:ly,account:mf({executable:af(),owner:ly,lamports:df(),data:zy,rentEpoch:df()})}))),jy=yy(sf(mf({lamports:df(),address:ly}))),Xy=mf({executable:af(),owner:ly,lamports:df(),data:dy,rentEpoch:df()}),Qy=mf({pubkey:ly,account:Xy}),Yy=bf(yf([cf(ma.Buffer),zy]),yf([uy,zy]),e=>Array.isArray(e)?tf(e,dy):e),Jy=mf({executable:af(),owner:ly,lamports:df(),data:Yy,rentEpoch:df()}),Zy=mf({pubkey:ly,account:Jy}),ew=mf({state:yf([lf("active"),lf("inactive"),lf("activating"),lf("deactivating")]),active:df(),inactive:df()}),tw=my(sf(mf({signature:pf(),slot:df(),err:Cy,memo:uf(pf()),blockTime:hf(uf(df()))}))),nw=my(sf(mf({signature:pf(),slot:df(),err:Cy,memo:uf(pf()),blockTime:hf(uf(df()))}))),rw=mf({subscription:df(),result:wy(Xy)}),ow=mf({pubkey:ly,account:Xy}),iw=mf({subscription:df(),result:wy(ow)}),sw=mf({parent:df(),slot:df(),root:df()}),aw=mf({subscription:df(),result:sw}),cw=yf([mf({type:yf([lf("firstShredReceived"),lf("completed"),lf("optimisticConfirmation"),lf("root")]),slot:df(),timestamp:df()}),mf({type:lf("createdBank"),parent:df(),slot:df(),timestamp:df()}),mf({type:lf("frozen"),slot:df(),timestamp:df(),stats:mf({numTransactionEntries:df(),numSuccessfulTransactions:df(),numFailedTransactions:df(),maxTransactionsPerEntry:df()})}),mf({type:lf("dead"),slot:df(),timestamp:df(),err:pf()})]),lw=mf({subscription:df(),result:cw}),uw=mf({subscription:df(),result:wy(yf([xy,Ny]))}),dw=mf({subscription:df(),result:df()}),hw=mf({pubkey:pf(),gossip:uf(pf()),tpu:uf(pf()),rpc:uf(pf()),version:uf(pf())}),gw=mf({votePubkey:pf(),nodePubkey:pf(),activatedStake:df(),epochVoteAccount:af(),epochCredits:sf(ff([df(),df(),df()])),commission:df(),lastVote:df(),rootSlot:uf(df())}),pw=my(mf({current:sf(gw),delinquent:sf(gw)})),fw=yf([lf("processed"),lf("confirmed"),lf("finalized")]),mw=mf({slot:df(),confirmations:uf(df()),err:Cy,confirmationStatus:hf(fw)}),yw=yy(sf(uf(mw))),ww=my(df()),bw=mf({accountKey:ly,writableIndexes:sf(df()),readonlyIndexes:sf(df())}),kw=mf({signatures:sf(pf()),message:mf({accountKeys:sf(pf()),header:mf({numRequiredSignatures:df(),numReadonlySignedAccounts:df(),numReadonlyUnsignedAccounts:df()}),instructions:sf(mf({accounts:sf(df()),data:pf(),programIdIndex:df()})),recentBlockhash:pf(),addressTableLookups:hf(sf(bw))})}),vw=mf({pubkey:ly,signer:af(),writable:af(),source:hf(yf([lf("transaction"),lf("lookupTable")]))}),Sw=mf({accountKeys:sf(vw),signatures:sf(pf())}),Aw=mf({parsed:wf(),program:pf(),programId:ly}),Ew=mf({accounts:sf(ly),data:pf(),programId:ly}),Tw=bf(yf([Ew,Aw]),yf([mf({parsed:wf(),program:pf(),programId:pf()}),mf({accounts:sf(pf()),data:pf(),programId:pf()})]),e=>tf(e,"accounts"in e?Ew:Aw)),Iw=mf({signatures:sf(pf()),message:mf({accountKeys:sf(vw),instructions:sf(Tw),recentBlockhash:pf(),addressTableLookups:hf(uf(sf(bw)))})}),Cw=mf({accountIndex:df(),mint:pf(),owner:hf(pf()),programId:hf(pf()),uiTokenAmount:Gy}),xw=mf({writable:sf(ly),readonly:sf(ly)}),Nw=mf({err:Cy,fee:df(),innerInstructions:hf(uf(sf(mf({index:df(),instructions:sf(mf({accounts:sf(df()),data:pf(),programIdIndex:df()}))})))),preBalances:sf(df()),postBalances:sf(df()),logMessages:hf(uf(sf(pf()))),preTokenBalances:hf(uf(sf(Cw))),postTokenBalances:hf(uf(sf(Cw))),loadedAddresses:hf(xw),computeUnitsConsumed:hf(df()),costUnits:hf(df())}),_w=mf({err:Cy,fee:df(),innerInstructions:hf(uf(sf(mf({index:df(),instructions:sf(Tw)})))),preBalances:sf(df()),postBalances:sf(df()),logMessages:hf(uf(sf(pf()))),preTokenBalances:hf(uf(sf(Cw))),postTokenBalances:hf(uf(sf(Cw))),loadedAddresses:hf(xw),computeUnitsConsumed:hf(df()),costUnits:hf(df())}),Dw=yf([lf(0),lf("legacy")]),Pw=mf({pubkey:pf(),lamports:df(),postBalance:uf(df()),rewardType:uf(pf()),commission:hf(uf(df()))}),Rw=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),transactions:sf(mf({transaction:kw,meta:uf(Nw),version:hf(Dw)})),rewards:hf(sf(Pw)),blockTime:uf(df()),blockHeight:uf(df())}))),Bw=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),rewards:hf(sf(Pw)),blockTime:uf(df()),blockHeight:uf(df())}))),Mw=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),transactions:sf(mf({transaction:Sw,meta:uf(Nw),version:hf(Dw)})),rewards:hf(sf(Pw)),blockTime:uf(df()),blockHeight:uf(df())}))),Ow=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),transactions:sf(mf({transaction:Iw,meta:uf(_w),version:hf(Dw)})),rewards:hf(sf(Pw)),blockTime:uf(df()),blockHeight:uf(df())}))),Lw=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),transactions:sf(mf({transaction:Sw,meta:uf(_w),version:hf(Dw)})),rewards:hf(sf(Pw)),blockTime:uf(df()),blockHeight:uf(df())}))),Uw=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),rewards:hf(sf(Pw)),blockTime:uf(df()),blockHeight:uf(df())}))),Fw=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),transactions:sf(mf({transaction:kw,meta:uf(Nw)})),rewards:hf(sf(Pw)),blockTime:uf(df())}))),$w=my(uf(mf({blockhash:pf(),previousBlockhash:pf(),parentSlot:df(),signatures:sf(pf()),blockTime:uf(df())}))),qw=my(uf(mf({slot:df(),meta:uf(Nw),blockTime:hf(uf(df())),transaction:kw,version:hf(Dw)}))),Kw=my(uf(mf({slot:df(),transaction:Iw,meta:uf(_w),blockTime:hf(uf(df())),version:hf(Dw)}))),Gw=yy(mf({blockhash:pf(),lastValidBlockHeight:df()})),Hw=yy(af()),Ww=my(sf(mf({slot:df(),numTransactions:df(),numSlots:df(),samplePeriodSecs:df()}))),zw=yy(uf(mf({feeCalculator:mf({lamportsPerSignature:df()})}))),Vw=my(pf()),jw=my(pf()),Xw=mf({err:Cy,logs:sf(pf()),signature:pf()}),Qw=mf({result:wy(Xw),subscription:df()}),Yw={"solana-client":"js/1.0.0-maintenance"};class Jw{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}=hy(t),o=this._buildArgs([],n,void 0,r),i=ty(o);return e[i]=e[i]??(async()=>{try{const e=tf(await this._rpcRequest("getBlockHeight",o),my(df()));if("error"in e)throw new qm(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(cy);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||oy;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 xf(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Yw)};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 Km(c),c*=2;const l=await t.text();t.ok?r(null,l):r(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,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 iy(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}=hy(t),o=this._buildArgs([e.toBase58()],n,void 0,r),i=tf(await this._rpcRequest("getBalance",o),yy(df()));if("error"in i)throw new qm(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=tf(await this._rpcRequest("getBlockTime",[e]),my(uf(df())));if("error"in t)throw new qm(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=tf(await this._rpcRequest("minimumLedgerSlot",[]),my(df()));if("error"in e)throw new qm(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=tf(await this._rpcRequest("getFirstAvailableBlock",[]),qy);if("error"in e)throw new qm(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=tf(await this._rpcRequest("getSupply",[t]),Ky);if("error"in n)throw new qm(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=tf(await this._rpcRequest("getTokenSupply",n),yy(Gy));if("error"in r)throw new qm(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=tf(await this._rpcRequest("getTokenAccountBalance",n),yy(Gy));if("error"in r)throw new qm(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:o}=hy(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=tf(await this._rpcRequest("getTokenAccountsByOwner",s),Wy);if("error"in a)throw new qm(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=tf(await this._rpcRequest("getTokenAccountsByOwner",o),Vy);if("error"in i)throw new qm(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=tf(await this._rpcRequest("getLargestAccounts",n),jy);if("error"in r)throw new qm(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=tf(await this._rpcRequest("getTokenLargestAccounts",n),Hy);if("error"in r)throw new qm(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgs([e.toBase58()],n,"base64",r),i=tf(await this._rpcRequest("getAccountInfo",o),yy(uf(Xy)));if("error"in i)throw new qm(i.error,`failed to get info about account ${e.toBase58()}`);return i.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=tf(await this._rpcRequest("getAccountInfo",o),yy(uf(Jy)));if("error"in i)throw new qm(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}=hy(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"jsonParsed",r),s=tf(await this._rpcRequest("getMultipleAccounts",i),yy(sf(uf(Jy))));if("error"in s)throw new qm(s.error,`failed to get info for accounts ${o}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=hy(t),o=e.map(e=>e.toBase58()),i=this._buildArgs([o],n,"base64",r),s=tf(await this._rpcRequest("getMultipleAccounts",i),yy(sf(uf(Xy))));if("error"in s)throw new qm(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}=hy(t),i=this._buildArgs([e.toBase58()],r,void 0,{...o,epoch:null!=n?n:o?.epoch}),s=tf(await this._rpcRequest("getStakeActivation",i),my(ew));if("error"in s)throw new qm(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=hy(t),{encoding:o,...i}=r||{},s=this._buildArgs([e.toBase58()],n,o||"base64",{...i,...i.filters?{filters:gy(i.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=sf(Qy),l=!0===i.withContext?tf(a,yy(c)):tf(a,my(c));if("error"in l)throw new qm(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgs([e.toBase58()],n,"jsonParsed",r),i=tf(await this._rpcRequest("getProgramAccounts",o),my(sf(Zy)));if("error"in i)throw new qm(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=ru.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return Cm(64===r.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r,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:Bm.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:Bm.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 Km(1e3),o)return;if(e=await r(),o)return}t({__type:Bm.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,i]);if(e.__type!==Bm.PROCESSED)throw new wm(r);l=e.response}finally{o=!0,s()}return l}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:Bm.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Km(2e3),s)return;if(i=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===Bm.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(i);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Km(400)}if(!r?.value)throw new km(i);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new km(i);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new km(i);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new km(i)}d={context:r.context,value:{err:r.value.err}}}}}finally{s=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const r=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:Bm.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!==Bm.PROCESSED)throw new bm(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),o()}return s}async getClusterNodes(){const e=tf(await this._rpcRequest("getClusterNodes",[]),my(sf(hw)));if("error"in e)throw new qm(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=tf(await this._rpcRequest("getVoteAccounts",t),pw);if("error"in n)throw new qm(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=hy(e),r=this._buildArgs([],t,void 0,n),o=tf(await this._rpcRequest("getSlot",r),my(df()));if("error"in o)throw new qm(o.error,"failed to get slot");return o.result}async getSlotLeader(e){const{commitment:t,config:n}=hy(e),r=this._buildArgs([],t,void 0,n),o=tf(await this._rpcRequest("getSlotLeader",r),my(pf()));if("error"in o)throw new qm(o.error,"failed to get slot leader");return o.result}async getSlotLeaders(e,t){const n=[e,t],r=tf(await this._rpcRequest("getSlotLeaders",n),my(sf(ly)));if("error"in r)throw new qm(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);Cm(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=tf(await this._rpcRequest("getSignatureStatuses",n),yw);if("error"in r)throw new qm(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=hy(e),r=this._buildArgs([],t,void 0,n),o=tf(await this._rpcRequest("getTransactionCount",r),my(df()));if("error"in o)throw new qm(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=tf(await this._rpcRequest("getInflationGovernor",t),My);if("error"in n)throw new qm(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:o}=hy(n),i=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...o,epoch:null!=t?t:o?.epoch}),s=tf(await this._rpcRequest("getInflationReward",i),vy);if("error"in s)throw new qm(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=tf(await this._rpcRequest("getInflationRate",[]),Oy);if("error"in e)throw new qm(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=hy(e),r=this._buildArgs([],t,void 0,n),o=tf(await this._rpcRequest("getEpochInfo",r),Uy);if("error"in o)throw new qm(o.error,"failed to get epoch info");return o.result}async getEpochSchedule(){const e=tf(await this._rpcRequest("getEpochSchedule",[]),Fy);if("error"in e)throw new qm(e.error,"failed to get epoch schedule");const t=e.result;return new ry(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=tf(await this._rpcRequest("getLeaderSchedule",[]),$y);if("error"in e)throw new qm(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=tf(await this._rpcRequest("getMinimumBalanceForRentExemption",n),ww);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=tf(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),Ww);if("error"in t)throw new qm(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=tf(await this._rpcRequest("getFeeCalculatorForBlockhash",n),zw);if("error"in r)throw new qm(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=um(e.serialize()).toString("base64"),r=this._buildArgs([n],t),o=tf(await this._rpcRequest("getFeeForMessage",r),yy(uf(df())));if("error"in o)throw new qm(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=tf(await this._rpcRequest("getRecentPrioritizationFees",n),Ly);if("error"in r)throw new qm(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}=hy(e),r=this._buildArgs([],t,void 0,n),o=tf(await this._rpcRequest("getLatestBlockhash",r),Gw);if("error"in o)throw new qm(o.error,"failed to get latest blockhash");return o.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgs([e],n,void 0,r),i=tf(await this._rpcRequest("isBlockhashValid",o),Hw);if("error"in i)throw new qm(i.error,"failed to determine if the blockhash `"+e+"`is valid");return i.result}async getVersion(){const e=tf(await this._rpcRequest("getVersion",[]),my(_y));if("error"in e)throw new qm(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=tf(await this._rpcRequest("getGenesisHash",[]),my(pf()));if("error"in e)throw new qm(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=tf(i,Mw);if("error"in e)throw e.error;return e.result}case"none":{const e=tf(i,Bw);if("error"in e)throw e.error;return e.result}default:{const e=tf(i,Rw);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:by(n,e.message)},version:n}))}:null}}}catch(e){throw new qm(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=await this._rpcRequest("getBlock",o);try{switch(r?.transactionDetails){case"accounts":{const e=tf(i,Lw);if("error"in e)throw e.error;return e.result}case"none":{const e=tf(i,Uw);if("error"in e)throw e.error;return e.result}default:{const e=tf(i,Ow);if("error"in e)throw e.error;return e.result}}}catch(e){throw new qm(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=tf(await this._rpcRequest("getBlockProduction",r),By);if("error"in o)throw new qm(o.error,"failed to get block production information");return o.result}async getTransaction(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgsAtLeastConfirmed([e],n,void 0,r),i=tf(await this._rpcRequest("getTransaction",o),qw);if("error"in i)throw new qm(i.error,"failed to get transaction");const s=i.result;return s?{...s,transaction:{...s.transaction,message:by(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=hy(t),o=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),i=tf(await this._rpcRequest("getTransaction",o),Kw);if("error"in i)throw new qm(i.error,"failed to get transaction");return i.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=hy(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=tf(e,Kw);if("error"in t)throw new qm(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=hy(t),o=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(o)).map(e=>{const t=tf(e,qw);if("error"in t)throw new qm(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:by(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=tf(await this._rpcRequest("getBlock",n),Fw);if("error"in r)throw new qm(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 Pm(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...i,transactions:i.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Lm.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),o=tf(await this._rpcRequest("getBlocks",r),my(sf(df())));if("error"in o)throw new qm(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=tf(await this._rpcRequest("getBlock",n),$w);if("error"in r)throw new qm(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=tf(await this._rpcRequest("getBlock",n),$w);if("error"in r)throw new qm(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=tf(await this._rpcRequest("getTransaction",n),qw);if("error"in r)throw new qm(r.error,"failed to get transaction");const o=r.result;if(!o)return o;const i=new Pm(o.transaction.message),s=o.transaction.signatures;return{...o,transaction:Lm.populate(i,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=tf(await this._rpcRequest("getTransaction",n),Kw);if("error"in r)throw new qm(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=tf(e,Kw);if("error"in t)throw new qm(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=tf(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),tw);if("error"in o)throw new qm(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=tf(await this._rpcRequest("getSignaturesForAddress",r),nw);if("error"in o)throw new qm(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 sy({key:e,state:sy.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=Vm.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=tf(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Vw);if("error"in n)throw new qm(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Km(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 Km(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}=hy(e),r=this._buildArgs([],t,"base64",n),o=tf(await this._rpcRequest("getStakeMinimumDelegation",r),yy(df()));if("error"in o)throw new qm(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=ma.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=tf(await this._rpcRequest("simulateTransaction",s),Ry);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Lm){let t=e;r=new Lm,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Lm.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 l=[a,c],u=tf(await this._rpcRequest("simulateTransaction",l),Ry);if("error"in u){let e;if("data"in u.error&&(e=u.error.data.logs,e&&Array.isArray(e))){const t="\n ";e.join(t)}throw new $m({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(e.nonceInfo)e.sign(...r);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...r),!e.signature)throw new Error("!signature");const 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=um(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=tf(await this._rpcRequest("sendTransaction",i),jw);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new $m({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}=tf(e,rw);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=ty([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];Cm(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const{commitment:r,config:o}=hy(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}=tf(e,iw);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:o,config:i}=hy(n),s=this._buildArgs([e.toBase58()],o||this._commitment||"finalized","base64",i||(r?{filters:gy(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}=tf(e,Qw);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=tf(e,aw);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}=tf(e,lw);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}=tf(e,uw);"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}=tf(e,dw);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 Zw{constructor(e){this._keypair=void 0,this._keypair=e??sm()}static generate(){return new Zw(sm())}static fromSecretKey(e,t){if(64!==e.byteLength)throw new Error("bad secret key size");const n=e.slice(32,64);if(!t||!t.skipValidation){const t=e.slice(0,32),r=am(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new Zw({publicKey:n,secretKey:e})}static fromSeed(e){const t=am(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Zw({publicKey:t,secretKey:n})}get publicKey(){return new mm(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:Au.struct([Au.u32("instruction"),jm("recentSlot"),Au.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:Au.struct([Au.u32("instruction")])},ExtendLookupTable:{index:2,layout:Au.struct([Au.u32("instruction"),jm(),Au.seq(Sm(),Au.offset(Au.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:Au.struct([Au.u32("instruction")])},CloseLookupTable:{index:4,layout:Au.struct([Au.u32("instruction")])}}),new mm("AddressLookupTab1e1111111111111111111111111");const eb=Object.freeze({RequestUnits:{index:0,layout:Au.struct([Au.u8("instruction"),Au.u32("units"),Au.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:Au.struct([Au.u8("instruction"),Au.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:Au.struct([Au.u8("instruction"),Au.u32("units")])},SetComputeUnitPrice:{index:3,layout:Au.struct([Au.u8("instruction"),jm("microLamports")])}});class tb{constructor(){}static requestUnits(e){const t=Gm(eb.RequestUnits,e);return new Om({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Gm(eb.RequestHeapFrame,e);return new Om({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Gm(eb.SetComputeUnitLimit,e);return new Om({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Gm(eb.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new Om({keys:[],programId:this.programId,data:t})}}var nb;tb.programId=new mm("ComputeBudget111111111111111111111111111111"),Au.struct([Au.u8("numSignatures"),Au.u8("padding"),Au.u16("signatureOffset"),Au.u16("signatureInstructionIndex"),Au.u16("publicKeyOffset"),Au.u16("publicKeyInstructionIndex"),Au.u16("messageDataOffset"),Au.u16("messageDataSize"),Au.u16("messageInstructionIndex")]),new mm("Ed25519SigVerify111111111111111111111111111"),im.utils.isValidPrivateKey,Au.struct([Au.u8("numSignatures"),Au.u16("signatureOffset"),Au.u8("signatureInstructionIndex"),Au.u16("ethAddressOffset"),Au.u8("ethAddressInstructionIndex"),Au.u16("messageDataOffset"),Au.u16("messageDataSize"),Au.u8("messageInstructionIndex"),Au.blob(20,"ethAddress"),Au.blob(64,"signature"),Au.u8("recoveryId")]),new mm("KeccakSecp256k11111111111111111111111111111"),new mm("StakeConfig11111111111111111111111111111111");class rb{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}}nb=rb,rb.default=new nb(0,0,mm.default),Object.freeze({Initialize:{index:0,layout:Au.struct([Au.u32("instruction"),((e="authorized")=>Au.struct([Sm("staker"),Sm("withdrawer")],e))(),((e="lockup")=>Au.struct([Au.ns64("unixTimestamp"),Au.ns64("epoch"),Sm("custodian")],e))()])},Authorize:{index:1,layout:Au.struct([Au.u32("instruction"),Sm("newAuthorized"),Au.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:Au.struct([Au.u32("instruction")])},Split:{index:3,layout:Au.struct([Au.u32("instruction"),Au.ns64("lamports")])},Withdraw:{index:4,layout:Au.struct([Au.u32("instruction"),Au.ns64("lamports")])},Deactivate:{index:5,layout:Au.struct([Au.u32("instruction")])},Merge:{index:7,layout:Au.struct([Au.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:Au.struct([Au.u32("instruction"),Sm("newAuthorized"),Au.u32("stakeAuthorizationType"),Am("authoritySeed"),Sm("authorityOwner")])}}),new mm("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:Au.struct([Au.u32("instruction"),((e="voteInit")=>Au.struct([Sm("nodePubkey"),Sm("authorizedVoter"),Sm("authorizedWithdrawer"),Au.u8("commission")],e))()])},Authorize:{index:1,layout:Au.struct([Au.u32("instruction"),Sm("newAuthorized"),Au.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:Au.struct([Au.u32("instruction"),Au.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:Au.struct([Au.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:Au.struct([Au.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>Au.struct([Au.u32("voteAuthorizationType"),Sm("currentAuthorityDerivedKeyOwnerPubkey"),Am("currentAuthorityDerivedKeySeed"),Sm("newAuthorized")],e))()])}}),new mm("Vote111111111111111111111111111111111111111"),new mm("Va1idator1nfo111111111111111111111111111111"),mf({name:pf(),website:hf(pf()),details:hf(pf()),iconUrl:hf(pf()),keybaseUsername:hf(pf())}),new mm("Vote111111111111111111111111111111111111111"),Au.struct([Sm("nodePubkey"),Sm("authorizedWithdrawer"),Au.u8("commission"),Au.nu64(),Au.seq(Au.struct([Au.nu64("slot"),Au.u32("confirmationCount")]),Au.offset(Au.u32(),-8),"votes"),Au.u8("rootSlotValid"),Au.nu64("rootSlot"),Au.nu64(),Au.seq(Au.struct([Au.nu64("epoch"),Sm("authorizedVoter")]),Au.offset(Au.u32(),-8),"authorizedVoters"),Au.struct([Au.seq(Au.struct([Sm("authorizedPubkey"),Au.nu64("epochOfLastAuthorizedSwitch"),Au.nu64("targetEpoch")]),32,"buf"),Au.nu64("idx"),Au.u8("isEmpty")],"priorVoters"),Au.nu64(),Au.seq(Au.struct([Au.nu64("epoch"),Au.nu64("credits"),Au.nu64("prevCredits")]),Au.offset(Au.u32(),-8),"epochCredits"),Au.struct([Au.nu64("slot"),Au.nu64("timestamp")],"lastTimestamp")]);function ob(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function ib(e){const t=new Map;for(const n of e)t.set(un(n.symbol),n);return t}function sb(e,t,n){const r=function(e,t){return e.get(un(t))}(e,t);if(!r){throw qt(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function ab(e){if(null==e||!ob(e))throw Ft("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function cb(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function lb(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function ub(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function db(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw Ut("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const hb={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function gb(e,t,n){if(void 0===e)throw qt(n??hb[t],`${t.toLowerCase()}Strategy`);return e}function pb(e){return{direction:"inbound",fromChain:e.fromChain,toChain:"GalaChain",transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}const fb="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",mb="Bridge request ID missing from RequestTokenBridgeOut response",yb="BridgeTokenOut response missing transaction hash";function wb(e){if(void 0===e||""===e)throw qt(fb,"tokenSymbol");return e}function bb(t,n){if(!e.isAddress(t)){throw Ft(n??"address","a valid 0x-prefixed Ethereum address",t)}}function kb(e,t){try{return new mm(e)}catch{throw Ft(t??"address","a valid Solana address (base58)",e)}}function vb(e){try{return new mm(e)}catch{throw Ft("address","a valid Solana address (base58)",e)}}function Sb(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=Sb(r):t[n]=r);return t}function Ab(e,t){const n=qn(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}function Eb(e){const t="string"==typeof e.timestamp?Hn(e.timestamp,0):e.timestamp;return{estimatedFeeInGala:e.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:e.estimatedTotalTxFeeInExternalToken,feeToken:e.bridgeToken,pricePerUnit:e.estimatedPricePerTxFeeUnit,estimatedGasUnits:e.estimatedTxFeeUnitsTotal,exchangeRate:e.galaExchangeRate?.exchangeRate??"0",timestamp:t,raw:e}}var Tb,Ib,Cb,xb,Nb,_b;function Db(){return Ib?Tb:(Ib=1,Tb={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify})}function Pb(){return xb?Cb:(xb=1,Cb={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys})}function Rb(){if(_b)return Nb;_b=1;const e=Db(),t=Pb().isFunction,n=Pb().isBoolean,r=Pb().isObject,o=Pb().isArray,i=Pb().isRegex,s=Pb().assign,a=Pb().keys;return Nb=function(c,l){l=l||s({},e),t(l)&&(l={compare:l});const u=l.space||e.space,d=n(l.cycles)?l.cycles:e.cycles,h=l.replacer||e.replacer,g=l.stringify||e.stringify,p=l.compare&&(f=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},o={key:n,value:e[n]};return f(r,o)}});var f;d||g(c);const m=[];return function e(t,n,s,c){const l=u?"\n"+new Array(c+1).join(u):"",f=u?": ":":";if(s=function(e){return null==e?e:i(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=h.call(t,n,s))){if(!r(s)||null===s)return g(s);if(o(s)){const t=[];for(let n=0;n<s.length;n++){const r=e(s,n,s[n],c+1)||g(null);t.push(l+u+r)}return"["+t.join(",")+l+"]"}{if(d){if(-1!==m.indexOf(s))return g("[Circular]");m.push(s)}const t=a(s).sort(p&&p(s)),n=[];for(let r=0;r<t.length;r++){const o=t[r],i=e(s,o,s[o],c+1);if(!i)continue;const a=g(o)+f+i;n.push(l+u+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},Nb}var Bb=ia(Rb());let Mb=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{Mb=require("crypto")}catch{}function Ob(){if(void 0!==Mb?.randomUUID)try{return Mb.randomUUID()}catch{}if(void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Lb(e){if(void 0!==Mb?.createHash)try{const t=Mb.createHash("sha256");return t.update(e).digest("hex").substring(0,16)}catch{}return function(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return Math.abs(t).toString(16).padStart(16,"0").substring(0,16)}(e)}const Ub={name:"GalaConnect",chainId:1},Fb=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],$b=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],qb=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Kb=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Gb={GalaTransaction:Fb,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:$b,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:qb,externalQuoteToken:Kb,tokenInstance:qb},Hb={GalaTransaction:Fb,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:$b,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:Kb,externalQuoteToken:Kb,externalCrossRateToken:Kb,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:qb,tokenInstance:qb};function Wb(e){return e?Hb:Gb}const zb={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:qb};async function Vb(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${Ob()}`,o="string"==typeof e.destinationChainId?Hn(e.destinationChainId,1):e.destinationChainId,i=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Hn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Hn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Hn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Hn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Hn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Hn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(i.galaExchangeCrossRate),a={destinationChainId:o,destinationChainTxFee:Sb(s?{...i,galaExchangeRate:void 0}:{...i,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=Wb(s),l=await n.signTypedData(Ub,c,a),u=`Ethereum Signed Message:\n${Bb({domain:Ub,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:Ub}}async function jb(e,t){const{amount:n,recipientAddress:r,tokenSymbol:o}=e,{galaConnectClient:i,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=wb(o);Ab(n,d),u(r,"recipient");const h=await s.getTokenMetadata(d),g=await i.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),p=function(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:"0"}}}({destinationChainId:c,bridgeFee:g,amount:n,recipientAddress:r,tokenDescriptor:h.descriptor}),f=await Vb(p,{wallet:a}),m=function(e){if(void 0===e||""===e)throw qt(mb,"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 i.requestBridgeOut(f)));return function(e){return{direction:"outbound",fromChain:"GalaChain",toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}({toChain:l,transactionHash:function(e){const t=e.Hash??e.hash??"";if(""===t)throw qt(yb,"transactionHash");return t}(await i.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:i.getBaseUrl()})}const Xb=5,Qb=6,Yb=7;function Jb(e){const t=Hn(e.status,0);return{status:t,statusDescription:e.statusDescription,fromChain:e.fromChain,toChain:e.toChain,quantity:e.quantity,transactionHash:e.emitterTransactionHash,tokenInstance:e.tokenInstance,isComplete:t===Xb,isFailed:t===Qb||t===Yb}}class Zb{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw Wt("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,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(Et(e)?e:new Error(Tt(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}const ek={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},tk=new Set([408,429,500,502,503,504]),nk=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function rk(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return tk.has(t.status);if("number"==typeof t.statusCode)return tk.has(t.statusCode);const n=Nt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=Tt(e);return nk.some(e=>e.test(t))}function ok(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 ik(e){return new Promise(t=>setTimeout(t,e))}function sk(e,t){return gb(e.get("Ethereum"),"Ethereum",t)}function ak(e,t){return gb(e.get("Solana"),"Solana",t)}function ck(e,t){return e??t.getWalletAddress()}function lk(e,t,n){const r=void 0!==n?` (${n})`:"";try{if(!ir(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,o,i,...s]=n;if(""===r||""===o||""===i)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:o,type:i,additionalKey:a}}catch(n){const o=e?.split?.(t)??[];throw new ht(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${o.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${o.map(e=>`"${e}"`).join(", ")}]. Error: ${Tt(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function uk(e){if("object"==typeof e&&null!==e)return function(e){if(null===e||"object"!=typeof e)throw new ht("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(!ir(t))throw new ht("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!ir(n))throw new ht("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!ir(r))throw new ht("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!ir(o))throw new ht("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(null==e)throw new ht(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new ht("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(hk(e))return dk(e);if(gk(e))return function(e){return function(e,t,n){const r=` (${n})`;try{if(!ir(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);const r=n[n.length-1],o=n[n.length-2],i=n[n.length-3],s=n.slice(0,n.length-3).join(t);if(""===s||""===i||""===o||""===r)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:s,category:i,type:o,additionalKey:r}}catch(n){const o=e?.split?.(t)??[];throw new ht(`Invalid dollar-delimited token: "${e}" (${o.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${o.map(e=>`"${e}"`).join(", ")}]. Error: ${Tt(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new ht(`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 dk(e){return lk(e,"|","pipe-delimited token")}function hk(e){return ir(e)&&e.includes("|")}function gk(e){return"string"==typeof e&&e.includes("$")}function pk(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,r=t.category,o=t.type,i=t.additionalKey;return"string"==typeof n&&"string"==typeof r&&"string"==typeof o&&"string"==typeof i&&n.length>0&&r.length>0&&o.length>0&&i.length>0}function fk(e){let t;if("string"==typeof e)t=dk(e);else{if(!pk(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:qs(t)}}function mk(e,t){let n;try{n=zn(e,"amount")}catch(t){throw jt("amount",`${e} (${Tt(t)})`)}if(!n.isFinite())throw jt("amount",e);const r=n.multipliedBy(Hi(10).pow(t));if(!r.isInteger())throw jt("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function yk(e,t){return Hi(e.toString()).dividedBy(Hi(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class wk{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=dn(e),n=this.cache.get(t);if(n)return n;const r=ta[t];if(void 0!==r)return this.cache.set(t,r),r;const o=await this.fetchFromApi(e);return this.cache.set(t,o),o}hasMetadata(e){const t=dn(e);return this.cache.has(t)||t in ta}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>dn(e.symbol)===dn(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>dn(e.symbol)===dn(t)&&e.verified)),!r)throw new Error(`Unable to locate token metadata for ${e}`);return o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey},i=r.decimals,s=r.channel,{descriptor:{collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey},decimals:i,...void 0!==s?{channel:s}:{}};var o,i,s}}class bk extends Error{constructor(e,t,n){super(`GalaConnect request to ${t} failed with status ${e}${null!=n?`: ${JSON.stringify(n)}`:""}`),this.status=e,this.path=t,this.responseBody=n,this.name="GalaConnectHttpError"}}const kk=js,vk="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Sk=12,Ak=!0,Ek=3,Tk=1e3;class Ik{constructor(e){this.baseUrl=e.baseUrl??kk,this.galachainBaseUrl=e.galachainBaseUrl??vk,this.walletAddress=e.walletAddress,this.rateLimiter=new Zb(e.requestsPerSecond??Sk),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??Ak;this.retryOptions=t?{maxRetries:e.maxRetries??Ek,initialDelayMs:e.retryInitialDelayMs??Tk,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>rk(e instanceof bk?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Rs(async()=>{const t=new URL("/v1/connect/bridge-configurations",this.baseUrl);t.searchParams.set("searchprefix",e);const n=await this.request(t.toString(),{method:"GET"});if(!n.ok){const e=await n.text();let t;throw t=""!==e?$n(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new bk(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof bk)throw e;throw Gt(e,"GalaConnectClient.getBridgeConfigurations")})}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){return Rs(async()=>{const 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)});if(!s.ok){const t=await s.text(),n=500,r=$n(t,{rawBody:t.slice(0,n)});throw new bk(s.status,e,r)}const a=await s.text();if(""!==a){const t=function(e){if(fn(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: ${Tt(e)}`}}}(a);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${String(t.error)}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t,n)=>{if(e instanceof bk)throw e;throw Gt(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(),o=await this.safeParseJson(n);throw new bk(t,e,o)}}return r});return this.retryOptions?async function(e,t={}){const n={...ek,...t},r=t.shouldRetry??(e=>rk(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=ok(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 Ck;exports.BridgeStatusCode=void 0,(Ck=exports.BridgeStatusCode||(exports.BridgeStatusCode={}))[Ck.PENDING=0]="PENDING",Ck[Ck.SUBMITTED=1]="SUBMITTED",Ck[Ck.CONFIRMED=2]="CONFIRMED",Ck[Ck.PROCESSING=3]="PROCESSING",Ck[Ck.FINALIZING=4]="FINALIZING",Ck[Ck.COMPLETED=5]="COMPLETED",Ck[Ck.FAILED=6]="FAILED",Ck[Ck.DELIVERY_FAILED=7]="DELIVERY_FAILED";class xk{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:o}=t,i=Date.now();for(;;){const t=await this.getStatus(e);if(o&&o(t),t.status===exports.BridgeStatusCode.COMPLETED||t.status===exports.BridgeStatusCode.FAILED||t.status===exports.BridgeStatusCode.DELIVERY_FAILED)return t;if(kn(i)>r)throw Kt(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class Nk extends xk{constructor(t){super(),this.network="Ethereum",this.galaConnectClient=t.galaConnectClient,this.galaChainWalletAddress=t.galaChainWalletAddress,ab(t.ethereumPrivateKey);const n=t.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new e.JsonRpcProvider(n),this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=t.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=t.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const r=t.tokenConfigs??Zs;this.tokenConfigs=ib(r),this.tokenMetadataResolver=new wk({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Eb(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return jb(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Hs.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:bb})}async bridgeIn(t){const{amount:n,sourcePrivateKey:r,recipientAddress:o,tokenSymbol:i}=t,s=wb(i);if(Ab(n,s),void 0!==r&&""!==r&&!ob(r))throw Ft("sourcePrivateKey","0x-prefixed 64-character hex string",r.slice(0,10)+"...");const a=void 0!==r&&""!==r?new e.Wallet(r,this.ethereumProvider):this.ethereumWallet,c=sb(this.tokenConfigs,s,"Ethereum bridge"),l=await this.tokenMetadataResolver.getTokenMetadata(s),u=new e.Contract(c.contractAddress,na,a),d=Hn(await u.decimals(),18),h=mk(n,d),g=BigInt(await u.balanceOf(a.address));if(g<h){throw qt(`Insufficient ${s} balance on Ethereum. Needed ${yk(h,d)}, have ${yk(g,d)}`,"amount")}const p=function(t){const n=new xr;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(null==r)throw Ft("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const o=n.extractHex(r);return`eth|${e.getAddress("0x"+o).slice(2)}`}(o??this.galaChainWalletAddress);return pb({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:a,tokenContract:u,tokenConfig:c,amountBaseUnits:h,decimals:d,recipient:p,metadata:l})).txHash,tokenSymbol:s,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return Jb(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(un(e))}isValidAddress(e){return or.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(t,n){const r=sb(this.tokenConfigs,t,"Ethereum"),o=n??this.ethereumWalletAddress;bb(o);const i=new e.Contract(r.contractAddress,na,this.ethereumProvider);return yk(await i.balanceOf(o),r.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;bb(t);return yk(await this.ethereumProvider.getBalance(t),18)}async getEthereumTransactionStatus(e){!function(e){if(!function(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}(e))throw Ft("hash","a 0x-prefixed 64-character hex string (66 total characters)","Ethereum transaction hash")}(e);const t=e.toLowerCase();try{const e=await this.ethereumProvider.getTransactionReceipt(t);if(e){const n=await this.ethereumProvider.getBlockNumber()-e.blockNumber+1;if(!(1===e.status))return{confirmed:!1,status:"failed",blockNumber:e.blockNumber,confirmations:n,transactionHash:t,gasUsed:e.gasUsed.toString(),effectiveGasPrice:e.gasPrice?.toString(),error:"Transaction reverted during execution"};return{confirmed:!0,status:n>=Nk.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: ${Tt(e)}`}}}async executeBridgeDeposit(t){const n=new e.Contract(this.ethereumBridgeContract,ra,t.wallet),r=(new TextEncoder).encode(t.recipient);let o;o=t.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(t.wallet,t.tokenContract,t.tokenConfig,n,t.amountBaseUnits,r):await this.bridgeWithApproval(t.wallet,t.tokenContract,n,t.tokenConfig,t.amountBaseUnits,r);if(!await o.wait())throw qt("Bridge transaction receipt not available","ethereumRpcUrl");await ik(3e4);const i={collection:t.metadata.descriptor.collection,category:t.metadata.descriptor.category,type:t.metadata.descriptor.type,additionalKey:t.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:yk(t.amountBaseUnits,t.decimals),tokenInstance:i,fromChain:"Ethereum",toChain:"GC",hash:o.hash}),{txHash:o.hash}}async bridgeWithPermit(t,n,r,o,i,s){const a=await this.ethereumProvider.getNetwork(),c=await n.name(),l=await n.nonces(t.address),u=BigInt(Math.floor(Date.now()/1e3)+3600),d=await t.signTypedData({name:c,version:"1",chainId:Hn(a.chainId,1),verifyingContract:r.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:t.address,spender:this.ethereumBridgeContract,value:i,nonce:l,deadline:u}),h=e.Signature.from(d);return await o.bridgeOutWithPermit(r.contractAddress,i,Hs.GALA_CHAIN,s,u,h.v,h.r,h.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 await n.bridgeOut(r.contractAddress,o,0,Hs.GALA_CHAIN,i)}}Nk.ETHEREUM_FINALITY_THRESHOLD=12;const _k=new mm("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new mm("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const Dk=new mm("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new mm("So11111111111111111111111111111111111111112"),new mm("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const Pk=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var Rk,Bk={};function Mk(){if(Rk)return Bk;return Rk=1,Object.defineProperty(Bk,"__esModule",{value:!0}),Bk.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},Bk.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},Bk.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}},Bk.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}},Bk}var Ok=Mk();const Lk=(Uk=8,e=>{const t=Au.blob(Uk,e),{encode:n,decode:r}=Pk(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return Ok.toBigIntLE(Buffer.from(n))},o.encode=(e,t,r)=>{const o=Ok.toBufferLE(e,Uk);return n(o,t,r)},o});var Uk;const Fk=e=>{const t=Au.blob(32,e),{encode:n,decode:r}=Pk(t),o=t;return o.decode=(e,t)=>{const n=r(e,t);return new mm(n)},o.encode=(e,t,r)=>{const o=e.toBuffer();return n(o,t,r)},o};var $k;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}($k||($k={}));const qk=Au.struct([Fk("mint"),Fk("owner"),Lk("amount"),Au.u32("delegateOption"),Fk("delegate"),Au.u8("state"),Au.u32("isNativeOption"),Lk("isNative"),Lk("delegatedAmount"),Au.u32("closeAuthorityOption"),Fk("closeAuthority")]);qk.span;var Kk=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,l=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*l[e]>>>0,l[e]=o%256>>>0,o=o/256>>>0;if(0!==o)throw new Error("Non-zero carry");a=s,i++}let u=c-a;for(;u!==c&&0===l[u];)u++;const d=new Uint8Array(s+(c-u));let h=s;for(;u!==c;)d[h++]=l[u++];return d}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let o=0,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,o++;const l=(c-a)*i+1>>>0,u=new Uint8Array(l);for(;a!==c;){let e=t[a],r=0;for(let t=l-1;(0!==e||r<s)&&-1!==t;t--,r++)e+=256*u[t]>>>0,u[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");s=r,a++}let d=l-s;for(;d!==l&&0===u[d];)d++;let h=r.repeat(o);for(;d<l;++d)h+=e.charAt(u[d]);return h},decodeUnsafe:s,decode:function(e){const t=s(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function Gk(e,t,n,r,o){const[i]=mm.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],o);return i}class Hk extends xk{constructor(t){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=t.galaConnectClient,this.galaChainWalletAddress=t.galaChainWalletAddress,ab(t.ethereumPrivateKey);const n=new e.JsonRpcProvider("https://ethereum.publicnode.com");this.ethereumWallet=new e.Wallet(t.ethereumPrivateKey,n);const r=t.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let o;this.solanaConnection=new Jw(r,"confirmed");try{o=Kk.decode(t.solanaPrivateKeyBase58)}catch{throw Ft("solanaPrivateKeyBase58","base58-encoded string",t.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==o.length)throw Ft("solanaPrivateKeyBase58","64 bytes when decoded",`${o.length} bytes`);this.solanaKeypair=Zw.fromSecretKey(o);const i=t.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new mm(i),[this.solanaBridgeTokenAuthority]=mm.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=mm.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=mm.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const s=t.tokenConfigs??ea;this.tokenConfigs=ib(s),this.tokenMetadataResolver=new wk({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Eb(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return jb(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Hs.SOLANA,destinationChain:"Solana",validateRecipientAddress:kb})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:o}=e,i=wb(o);Ab(t,i);let s=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=Kk.decode(n)}catch{throw Ft("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Ft("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=Zw.fromSecretKey(e)}const a=sb(this.tokenConfigs,i,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(i),l=mk(t,c.decimals),u=r??this.galaChainWalletAddress;return pb({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:i,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return Jb(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(un(e))}isValidAddress(e){try{return new mm(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=sb(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),o=vb(r),i=Gk(new mm(n.mintAddress),o,0,_k,Dk);try{const e=await async function(e,t,n,r){const o=await e.getAccountInfo(t);if(!o)throw new Error(`could not find account ${t.toBase58()}`);if(!o.owner.equals(r))throw new Error(`account owner mismatch: expected ${r.toBase58()}, got ${o.owner.toBase58()}`);return{amount:qk.decode(o.data).amount,decimals:0}}(this.solanaConnection,i,0,_k),t=n.decimals??8;return yk(e.amount,t)}catch(t){if(Et(t)&&t.message.includes("could not find")){return yk(0n,n.decimals??8)}throw qt(`Failed to fetch ${e} balance for ${r}: ${Tt(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=vb(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return yk(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){Yn(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?vb(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw qt(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='STAGE' for devnet access.`,"solanaRpcUrl");const o=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,o)}async getSolanaTransactionStatus(e){if(!ir(e))throw Ft("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Ft("signature","a base58-encoded string (87-88 characters)",e.slice(0,20)+"...");const t=(await this.solanaConnection.getSignatureStatuses([e])).value[0];return t?null!==t.err&&void 0!==t.err?{confirmed:!1,status:"failed",slot:t.slot,error:JSON.stringify(t.err)}:{confirmed:!0,status:t.confirmationStatus??"processed",slot:t.slot}:{confirmed:!1,status:"not_found"}}async executeSolanaBridgeOut(e){const t=new mm(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),o=n?void 0:Gk(t,e.keypair.publicKey,0,_k,Dk),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),l=new Lm;l.add(tb.setComputeUnitPrice({microLamports:375e3}),tb.setComputeUnitLimit({units:2e5}),c),l.feePayer=e.keypair.publicKey;const u=await this.sendAndConfirmWithFallback(l,e.keypair),d={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:d,fromChain:"Solana",toChain:"GC",hash:u}),u}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let 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=Et(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const i=await this.solanaConnection.getSignatureStatuses([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=Et(e)?e:new Error(Tt(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 ik(i)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const o=Buffer.concat([oa.BRIDGE_OUT_NATIVE,t,n,r]);return new Om({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Qm.programId,isSigner:!1,isWritable:!1}],data:o})}buildTokenBridgeInstruction(e,t,n,r,o,i,s){const a=Buffer.concat([oa.BRIDGE_OUT,o,i,s]);return new Om({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:Qm.programId,isSigner:!1,isWritable:!1},{pubkey:_k,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=mm.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),o=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!o)throw qt(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!o.owner.equals(this.solanaBridgeProgramId))throw qt("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(o.data.length<40)throw qt("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const i={mintLookup:r,tokenBridge:new mm(o.data.slice(8,40)),bridgeTokenAccount:Gk(e,this.solanaBridgeTokenAuthority,0,_k,Dk)};return this.solanaBridgeAccountCache.set(t,i),i}}const Wk={PROD:{ethereum:"https://eth.gala.games",solana:"https://api.mainnet-beta.solana.com"},STAGE:{ethereum:"https://dev.eth.gala.games",solana:"https://api.devnet.solana.com"}},zk={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class Vk{static normalizeGalaChainAddress(e){const t=new xr;if("client"===t.detectFormat(e))return e;let n=e;(e.startsWith("eth|0x")||e.startsWith("eth|0X"))&&(n=e.substring(0,4)+e.substring(6));const r=t.normalizeInput(n);if(!r)throw qt(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const o=t.extractHex(r);return`eth|${Vk.checksumAddress(o)}`}static checksumAddress(t){const n=t.toLowerCase(),r=Ir(e.keccak256(e.toUtf8Bytes(n)));let o="";for(let e=0;e<n.length;e++){const t=n[e];parseInt(r[e],16)>=8?o+=t.toUpperCase():o+=t}return o}constructor(e){const t=Vk.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"PROD",r=Fs[n],o=Wk[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??Js(n),solanaBridgeProgram:e.solanaBridgeProgram??zk.solanaBridgeProgram,rateLimit:e.rateLimit??zk.rateLimit,pollInterval:e.pollInterval??zk.pollInterval,pollTimeout:e.pollTimeout??zk.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...i,solanaPrivateKey:e.solanaPrivateKey}:i,this.galaConnectClient=new Ik({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=Ys(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 Nk(t)),null!==this.config.solanaPrivateKey&&void 0!==this.config.solanaPrivateKey){const e={galaConnectClient:this.galaConnectClient,galaChainWalletAddress:this.config.galaChainWalletAddress,ethereumPrivateKey:this.config.ethereumPrivateKey,solanaPrivateKeyBase58:this.config.solanaPrivateKey,solanaRpcUrl:this.config.solanaRpcUrl,solanaBridgeProgram:this.config.solanaBridgeProgram,tokenConfigs:ea};this.strategies.set("Solana",new Hk(e))}}async resolveTokenSymbol(e,t){return Rs(async()=>{if(!this.bridgeableTokenService)throw qt("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=fk(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",o=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!o){throw qt([`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 o.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return Rs(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")},"BridgeService.estimateBridgeFee")}async bridgeOut(e){return Rs(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw qt(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw qt(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return Rs(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw qt(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return Rs(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let r;if(n)try{return await n.getStatus(e)}catch(e){r=Et(e)?e:new Error(Tt(e))}const o=this.strategies.get("Solana");if(o)try{return await o.getStatus(e)}catch(e){r=Et(e)?e:new Error(Tt(e))}const i=r?` (last error: ${r.message})`:"";throw Kt(`Unable to get status for transaction ${e}${i}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Rs(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},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 Kt(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=Ys(this.config.environment);if(null==e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of ea){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(null!=t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return Rs(async()=>sk(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Rs(async()=>sk(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Rs(async()=>ak(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Rs(async()=>ak(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Rs(async()=>{const n=sk(this.strategies),r=db(Ys(this.config.environment),e,"Ethereum"),o=ck(t,n);return lb(r,await n.getEthereumTokenBalance(e,o))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Rs(async()=>{const t=sk(this.strategies),n=ck(e,t);return cb("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Rs(async()=>{const n=ak(this.strategies),r=db(ea,e,"Solana"),o=ck(t,n);return ub(r,await n.getSolanaTokenBalance(e,o))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Rs(async()=>{const t=ak(this.strategies),n=ck(e,t);return cb("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Rs(async()=>ak(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Rs(async()=>ak(this.strategies,"Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.").getSolanaTransactionStatus(e),"BridgeService.getSolanaTransactionStatus")}async getEthereumTransactionStatus(e){return Rs(async()=>sk(this.strategies,"Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.").getEthereumTransactionStatus(e),"BridgeService.getEthereumTransactionStatus")}async fetchEthereumWalletAllBalances(e){return Rs(async()=>{const t=sk(this.strategies),n=ck(e,t),r=Ys(this.config.environment),[o,...i]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>lb(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:cb("ETH",o,18),tokens:i,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Rs(async()=>{const t=ak(this.strategies),n=ck(e,t),[r,...o]=await Promise.all([t.getSolanaNativeBalance(n),...ea.map(async e=>ub(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:cb("SOL",r,9),tokens:o,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw qt(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}const jk="5.1.0",Xk={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Qk(e,t=1,n=Xk.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Yk(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Vt("total","a non-negative integer",e);if(e<0)throw Ht("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Vt("limit","a non-negative integer",t);if(t<0)throw Ht("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Jk(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const r=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(r),n}function Zk(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=String(n))}return e}const ev="x-api-key";class tv extends vr{constructor(e,t,n,r=!1,o){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=o??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!ir(e))throw Ut("tokenName","Token name");const n=ln(e);if(!t.PATTERN.test(n))throw Ft("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!ir(e))throw Ut(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw Vt(t,"string",typeof e,n);if(e.length>r)throw zt(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,o,i,s){!function(e,t,n,r,o){if(null!=e){if("number"!=typeof e)throw Vt(t,"number",typeof e,n);if(e<r||e>o)throw Ht(t,r,o,e,n)}}(e,t,n,r,o)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!bn(e))throw Ft(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){br(e,t,n)}validateStatusFilter(e,t,n="status"){kr(e,t,n)}buildPaginationParams(e,t){return Jk(e,t)}addOptionalFilterParams(e,t,n){return Zk(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,r]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(r.toLowerCase()));return n}(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new ft("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ev]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new ft("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[ev]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return tn(e,"Backend request failed",!0),rn(e,"No data in backend response")}extractDataOrNull(e){return tn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),o=await this.http.post(r,{},this.getAdminHeaders()),i=this.extractData(o);return{enabled:i.enabled,tokenName:i.tokenName??ln(e)}}}class nv extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async getSettings(){return{settings:(await this.http.get(je.GET_SETTINGS,{},this.getDualAuthHeaders())).settings}}async updateSettings(e){const t={};void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.mode&&(t.mode=e.mode),void 0!==e.provider&&(t.provider=e.provider);return{settings:(await this.http.post(je.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=je.GET_MODERATION.replace(":flagId",String(e.flagId));return{moderation:(await this.http.get(t,{},this.getDualAuthHeaders())).analysis}}async triggerModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=je.TRIGGER_MODERATION.replace(":flagId",String(e.flagId)),n=await this.http.post(t,{},this.getDualAuthHeaders());return{queued:n.queued,message:n.message.length>0?n.message:"Moderation queued successfully"}}async getStatus(){return{status:(await this.http.get(je.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const rv={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},ov=ur(rv),iv={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},sv=Object.values(iv);function av(e){return ov.includes(e)}function cv(e){const t=[];void 0===e.role||null===e.role?t.push("Role is required"):av(e.role)||t.push(`Invalid role. Must be one of: ${ov.join(", ")}`);const n=t.length;if(Rt(t,()=>{yr(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Rt(t,()=>{if(!Array.isArray(e.tokenNames))throw Vt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Vt("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n.includes("array")?t[e]="tokenNames must be an array":n.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt){const n=t.length;Rt(t,()=>{wr(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function lv(e){const t=[];["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||av(e.role)||t.push(`Invalid role. Must be one of: ${ov.join(", ")}`);const n=t.length;if(Rt(t,()=>{yr(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Rt(t,()=>{if(!Array.isArray(e.tokenNames))throw Vt("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Vt("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n.includes("array")?t[e]="tokenNames must be an array":n.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&null!==e.expiresAt){const n=t.length;Rt(t,()=>{wr(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function uv(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>En))throw Vt("pageSize",`number between 1 and ${En}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Vt("cursor","non-empty string",typeof e.cursor)}const dv={[rv.MODERATOR]:1,[rv.TECHNICAL_PRODUCER]:1,[rv.MANAGER]:2,[rv.OWNER]:3};class hv extends vr{constructor(e,t,n=!1){super(e,n,t)}extractData(e){let t;t="error"in e?e.error:"success"in e&&!e.success;const n={status:200,error:t,data:e.data};return void 0!==e.message&&(n.message=e.message),tn(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=cv(e);if(t.length>0)throw new ht(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(J.CREATE,n,this.getJwtHeaders()),o=this.extractData(r);return this.logger.debug("API key created",{id:o.id,keyPrefix:o.keyPrefix}),o}async findAll(e={}){uv(e),this.logger.debug("Listing API keys",e);const t=Jk(e,En),n=await this.http.get(J.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=J.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=lv(t);if(n.length>0)throw new ht(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const o=J.UPDATE.replace(":id",String(e)),i=await this.http.patch(o,r,this.getJwtHeaders()),s=this.extractData(i);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=J.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...ov]}}const gv={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},pv=lr(gv),fv=pr([{field:"id",type:"number"},{field:"userAddress",type:"string"},{field:"bannedBy",type:"string"},{field:"createdAt",type:"string"},{field:"isPermanent",type:"boolean"},{field:"tokenName",type:"string",nullable:!0},{field:"reason",type:"string",nullable:!0},{field:"expiresAt",type:"string",nullable:!0}]),mv=pr([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),yv=pr([{field:"userAddress",type:"string"}]),wv=pr([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function bv(e){return null==e||""===e||"string"==typeof e&&(!mr(e)&&e.length<=Nn.BAN_REASON.MAX_LENGTH)}function kv(e){return!!ar(e)||"number"==typeof e&&(e>=Dn&&e<=Pn)}class vv extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async createBan(e){!function(e){if(hr(e.tokenName,"tokenName",vn),!ir(e.userAddress))throw Ut("userAddress");if(!bv(e.reason))throw new ht(`reason must be at most ${Nn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!kv(e.durationSeconds))throw new ht(`durationSeconds must be between ${Dn} and ${Pn} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(G,{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.getMultiAuthHeaders());return{ban:this.extractData(r),tokenName:ln(e.tokenName)}}async removeBan(e){!function(e){if(hr(e.tokenName,"tokenName",vn),!ir(e.userAddress))throw Ut("userAddress")}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:ln(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){hr(e.tokenName,"tokenName",vn),cr(0,void 0,En,e.pageSize)}(e);const t=this.buildEndpoint(H,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,En);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),o=this.extractData(r);return{items:o.bans,pageInfo:o.pageInfo}}async getBanStatus(e){!function(e){if(hr(e.tokenName,"tokenName",vn),!ir(e.userAddress))throw Ut("userAddress")}(e);const t=this.buildEndpoint(W,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:ln(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(hr(e.tokenName,"tokenName",vn),void 0!==e.type&&!pv(e.type))throw new ht(`type must be one of: ${Object.values(gv).join(", ")}`,"type",dt.INVALID_VALUE)}(e);const t=this.buildEndpoint(V,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(r)}async createGlobalBan(e){!function(e){if(!ir(e.userAddress))throw Ut("userAddress");if(!bv(e.reason))throw new ht(`reason must be at most ${Nn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!kv(e.durationSeconds))throw new ht(`durationSeconds must be between ${Dn} and ${Pn} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t={userAddress:e.userAddress};void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds);const n=await this.http.post(j,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!ir(e.userAddress))throw Ut("userAddress")}(e);const t=this.buildEndpoint(Y,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){cr(0,void 0,En,e.pageSize)}(t);const n=this.buildPaginationParams(t,En);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(X,n,this.getDualAuthHeaders()),o=this.extractData(r);return{items:o.bans,pageInfo:o.pageInfo}}async getGlobalBan(e){!function(e){if(!ir(e.userAddress))throw Ut("userAddress")}(e);const t=this.buildEndpoint(Q,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},userAddress:e.userAddress.toLowerCase()}}}async function Sv(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:o=20,concurrency:i=1,startPage:s=1}=t,a=[];let c=s;const l=s+n-1;let u=!0,d=0;if(i<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${o}`);const t=await e(c,o);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),d=t.total,r&&r.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){r&&r.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}u=t.hasNext,c++}else for(r&&r.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);u&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,o).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return r&&r.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:o,hasNext:!1,hasPrevious:!1};throw e})),s=await Promise.all(n);for(const e of s){if(null==e||!Array.isArray(e.items)){r&&r.warn("Auto-pagination: received invalid result structure in batch, stopping"),u=!1;break}if(0===e.items.length){r&&r.debug("Auto-pagination: empty page in batch, reached end of results"),u=!1;break}if(a.push(...e.items),d=e.total,!e.hasNext){u=!1;break}}c+=t.length,r&&r.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&r&&r.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),r&&r.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${d}`),{items:a,total:d}}function Av(e){if("string"==typeof e){if(!hk(e))throw new ht(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const t=e.split("|");if(t.length>=5){const e=dk(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...dk(e),instance:"0"}}if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!pk(e))throw new ht("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!pk(e))throw new ht("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new ht(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Ev(e){return function(e){try{if(!ir(e))throw new Error("Vault address must be a non-empty string");const[t,n]=e.split("|");if(""===n||void 0===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[o,i,s,...a]=r;if(""===o||""===i||""===s)throw new Error("Collection, category, and type must be non-empty");const c=a.slice(0,-1),l=c.length>0?c.join("$"):a[0];if(""===l||void 0===l)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:i,type:s,additionalKey:l}}catch(t){throw new ht(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Tt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Tv(e){return{...Ev(e),instance:"0"}}function Iv(e){return Ev(e).type}function Cv(e){return qs(Av(e))}var xv=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Iv,isTokenClassKeyStrict:pk,normalizeToTokenInstanceKey:Av,normalizeTokenIdToString:Cv,parseVaultAddressToTokenClassKey:Ev,parseVaultAddressToTokenInstance:Tv});class Nv{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new gn({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const r=Math.min(t,this.getMaxLimit()),o=this.buildApiParams(n),i=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...o,pageSize:r,offset:e}});if(ar(i)||!Array.isArray(i.tokens))throw new ht("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(i.tokens),rawCount:i.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages: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(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination (offset): received invalid result structure, stopping");break}i.push(...t.items),a=t.rawCount===n,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}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Gt(e,t,this.logger)}}class _v extends Sr{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return un(e)}has(e){const t=this.primaryIndex.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.primaryIndex.get(e);return t?Array.from(t.values()):[]}getByPrimaryKey(e,t){const n=this.normalizeKey(t);return this.primaryIndex.get(e)?.get(n)}getBySecondaryKey(e,t){const n=this.normalizeKey(t);return this.secondaryIndex.get(e)?.get(n)}set(e,t){const n=new Map,r=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const o=this.normalizeKey(this.extractSecondaryKey(e));r.set(o,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 o=this.normalizeKey(this.extractSecondaryKey(e));r.set(o,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={},o={};for(const t of e)r[t]=0;for(const[e,i]of this.primaryIndex){t.push(e),n+=i.size,r[e]=i.size;const s=this.fetchTimestamps.get(e);void 0!==s&&(o[e]=s)}return{networks:t,totalItems:n,itemsByNetwork:r,fetchTimestamps:o}}clear(e){void 0!==e&&""!==e?(this.primaryIndex.delete(e),this.secondaryIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared cache for ${e}`)):(this.primaryIndex.clear(),this.secondaryIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all caches"))}size(e){return this.primaryIndex.get(e)?.size??0}hasByPrimaryKey(e,t){return void 0!==this.getByPrimaryKey(e,t)}getCachedNetworks(){return Array.from(this.primaryIndex.keys())}dump(){const e={};for(const t of this.getCachedNetworks())e[t]=this.getAll(t);return e}}const Dv=["ETHEREUM","SOLANA"];class Pv extends _v{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(Dv);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class Rv extends Nv{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Pv(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),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 void 0!==t?.contractAddress&&(o.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(o.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(o.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(o.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(o.solanaSymbol=n.symbol),void 0!==e.image&&(o.image=e.image),void 0!==e.description&&(o.description=e.description),o})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=this.getDefaultLimit()}=e,o=Math.min(r,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${o})`),Rs(async()=>{const e=(await this.executePaginatedRequest(n,o,{network:t})).items;return 0===n?this.cache.set(t,e):this.cache.merge(t,e),{tokens:e,network:t,fetchedAt:Date.now(),tokenCount:e.length}},`Failed to fetch bridgeable tokens for ${t}`,this.logger)}async fetchAllBridgeableTokensByNetwork(e){return Rs(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:o,itemTypeName:i="items"}=e;if(n.has(t)){const e=n.getAll(t);return o&&o.debug(`Returning ${e.length} cached ${i} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}o&&o.debug(`Fetching all ${i} 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=Cv(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??dk(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)}}function Bv(e){return{maxAcceptableReverseBondingCurveFee:Xn(e.maxAcceptableReverseBondingCurveFee)}}class Mv extends t.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Xn(t),this.expectedToken=Qn(n),this.extraFees=Bv(r)}}class Ov extends t.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Qn(t),this.expectedNativeToken=Xn(n),this.extraFees=Bv(r)}}class Lv extends t.ChainCallDTO{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Qn(t),this.expectedNativeToken=Xn(n),this.extraFees=Bv(r)}}class Uv extends t.ChainCallDTO{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Xn(t),this.expectedToken=Qn(n),this.extraFees=Bv(r)}}const Fv={BuyNativeDto:Mv,BuyExactDto:Ov,SellExactDto:Lv,SellNativeDto:Uv};function $v(e,t,n){let r;Yn(t,0,1,"slippageToleranceFactor");try{r=zn(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const o=r.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=r.minus(o);break;case"buy-exact":case"sell-native":i=r.plus(o);break;default:throw new Error(`Unknown operation type: ${n}`)}return ns(i)&&(i=Hi(0)),Wi(i)}class qv extends Sr{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,n,r){try{this.logger.debug("🔐 Signing DTO:",{methodName:n,dtoKeys:Object.keys(e)});const r=this.generateEIP712Types(n,e),o=t.calculatePersonalSignPrefix(e),i={...e,prefix:o},{signature:s,domain:a}=await this.signWithEthersWallet(r,i),c={...e,signature:s,types:r,domain:a};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(c),signatureLength:s.length}),c}catch(e){this.logger.error("❌ Signature generation failed:",e);throw Kt(`Failed to sign DTO: ${Tt(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 qt("Wallet provider does not support typed data signing","walletProvider");{const o=await this.walletProvider.getNetwork();n={name:o.name,chainId:Hn(o.chainId,1)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw Kt(`Ethers.js signing failed: ${Tt(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)+"[]"}),void 0!==s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(void 0!==n[e])throw new ht(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).filter(([e,t])=>null!=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 ht(`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 Kv{toLaunchpadFormat(e){if(null==e)throw new ht('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(hk(e))return e;throw new ht(`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")}const t=e;return qs({collection:t.collection??t.symbol??"unknown",category:t.category??"Unit",type:t.type??"none",additionalKey:t.additionalKey??"none"})}toTokenClass(e){if("object"==typeof e&&null!==e){const t=e;return{collection:t.collection??"Token",category:t.category??"Unit",type:t.type??t.symbol??"unknown",additionalKey:t.additionalKey??"none"}}if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=lk(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return""===e?"":hk(e)?e:`${e}|Unit|none|none`}normalize(e){return"string"==typeof e&&hk(e)?e:this.toLaunchpadFormat(e)}}function Gv(e){if(!ir(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function Hv(e){return lk(e,"$","dollar-delimited token")}class Wv extends Sr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),r=this.createGalaInstance(),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=Tt(e);throw new ht(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new i.TokenClassKey;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new i.TokenClassKey;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!ir(e))throw Ut("vaultAddress","Vault address");try{const t=Iv(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof ht)throw Ft("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!ir(e))throw Ut("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Ft("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Ft("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!ir(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 Ft("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||!/^[A-Za-z]{1,10}$/.test(n))throw Ft("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,r){return`${e}$${t}$${n}$${r}`}parseTokenClassKeyString(e){try{return Hv(e)}catch(e){if(e instanceof ht)throw Ft("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}class zv extends vr{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",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=o&&(this.signatureService=new qv(this._walletProvider,n),this.tokenKeyService=new Wv(n))}async submitTransaction(e){try{this.validateBundleData(e),this.logger.debug("📦 Submitting bundle transaction:",{method:e.method,stringsInstructionsCount:e.stringsInstructions.length,signedDtoKeys:Object.keys(e.signedDto)});const t=this.formatBundleRequest(e);this.logger.debug("🚀 Bundle request payload:",{...t,signedDto:"[REDACTED - Contains signature]"});let n=null;try{n=await sn(()=>this.http.post(this.bundleEndpoint,t),{errorContext:"Bundle transaction submission failed",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==n?{success:!1,error:"No response from bundle API"}:(this.logger.debug("📥 Bundle API response:",{success:n.success,hasData:en(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof ht)return{success:!1,error:Tt(e)};throw e}}validateBundleData(e){if(null==e)throw Ut("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Ut("signedDto","Signed DTO");if(!ir(e.method))throw Ut("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Ft("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new ht("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Ft("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!ir(e))throw new ht(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!gk(e))throw new ht(`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=nn(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if(_t(e)&&null!==e.response&&void 0!==e.response){const t=nn(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return Tt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!ir(e))throw Ut("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await sn(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof ht)return{success:!1,error:Tt(e)};throw e}}async cancelTransaction(e){try{if(!ir(e))throw Ut("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await sn(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof ht)return{success:!1,error:Tt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await sn(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:o}=e,{effectiveSlippageFactor:i,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==o||""===o)throw new ht("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=$v(o,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:o,slippageFactor:i,adjustedMinTokens:e});const t=new Fv.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==o||""===o)throw new ht("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=$v(o,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:o,slippageFactor:i,adjustedMaxGalaCost:e});const t=new Fv.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(null==o||""===o)throw new ht("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=$v(o,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:o,slippageFactor:i,adjustedMinGala:e});const t=new Fv.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==o||""===o)throw new ht("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=$v(o,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:o,slippageFactor:i,adjustedMaxTokensToSell:e});const t=new Fv.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(null==s)throw Lt(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 null!=e&&(i=$v(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 qt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Ut("userAddress","User address")}async executeBundleTransaction(e,t,r){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${n.v4()}-${Date.now()}-${String(this.userAddress)}`;const o=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(r),s={stringsInstructions:i,method:t,signedDto:o};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(o)});const a=await this.submitTransaction(s);if(a.success){const e=nn(a);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const c="string"==typeof a.error?a.error:"Bundle transaction failed";throw new mt(c,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 Vv extends vr{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(it),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var jv,Xv,Qv,Yv;exports.ContentType=void 0,(jv=exports.ContentType||(exports.ContentType={})).CHAT_MESSAGE="CHAT_MESSAGE",jv.COMMENT="COMMENT",jv.STREAM="STREAM",jv.RECORDING="RECORDING",exports.FlagReason=void 0,(Xv=exports.FlagReason||(exports.FlagReason={})).INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",Xv.SPAM="SPAM",Xv.HARASSMENT="HARASSMENT",Xv.SCAM="SCAM",Xv.OTHER="OTHER",exports.FlagStatus=void 0,(Qv=exports.FlagStatus||(exports.FlagStatus={})).PENDING="PENDING",Qv.DISMISSED="DISMISSED",Qv.ACTIONED="ACTIONED",exports.FlagAction=void 0,(Yv=exports.FlagAction||(exports.FlagAction={})).DELETE_CONTENT="DELETE_CONTENT",Yv.BAN_USER="BAN_USER",Yv.DELETE_AND_BAN="DELETE_AND_BAN";const Jv={[exports.FlagReason.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[exports.FlagReason.SPAM]:"Spam",[exports.FlagReason.HARASSMENT]:"Harassment",[exports.FlagReason.SCAM]:"Scam",[exports.FlagReason.OTHER]:"Other"},Zv={[exports.FlagStatus.PENDING]:"Pending",[exports.FlagStatus.DISMISSED]:"Dismissed",[exports.FlagStatus.ACTIONED]:"Actioned"},eS={[exports.FlagAction.DELETE_CONTENT]:"Delete Content",[exports.FlagAction.BAN_USER]:"Ban User",[exports.FlagAction.DELETE_AND_BAN]:"Delete & Ban"},tS={[exports.ContentType.CHAT_MESSAGE]:"Chat Message",[exports.ContentType.COMMENT]:"Comment",[exports.ContentType.STREAM]:"Stream",[exports.ContentType.RECORDING]:"Recording"},nS=lr(exports.ContentType),rS=lr(exports.FlagReason),oS=lr(exports.FlagStatus),iS=lr(exports.FlagAction),sS=pr([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:nS},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:oS}]),aS={TOKEN_NAME:Sn,CONTENT_ID:Nn.CONTENT_ID,DETAILS:Nn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:En}};function cS(e,t="tokenName"){hr(e,t,aS.TOKEN_NAME)}class lS extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async createFlag(e){!function(e){if(cS(e.tokenName),void 0===e.contentType)throw Ut("contentType","Content type");if(!nS(e.contentType))throw Ft("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(!ir(e.contentId))throw Ut("contentId","Content ID");if(e.contentId.length>aS.CONTENT_ID.MAX_LENGTH)throw zt("contentId",aS.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!ir(e.reportedUserAddress))throw Ut("reportedUserAddress","Reported user address");if(Mr(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==exports.ContentType.STREAM&&e.contentType!==exports.ContentType.RECORDING||void 0!==e.reason&&null!==e.reason))throw Ut("reason","Reason");if(void 0!==e.reason&&!rS(e.reason))throw Ft("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`,"Reason");if(void 0!==e.details&&!ir(e.details))throw Vt("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>aS.DETAILS.MAX_LENGTH)throw zt("details",aS.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!=e.reason&&(t.reason=e.reason),null!=e.details&&(t.details=e.details);const n=await this.http.post(ae.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){!function(e){if(cS(e.tokenName),void 0!==e.contentType&&!nS(e.contentType))throw Ft("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!oS(e.status))throw Ft("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!rS(e.reason))throw Ft("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!ir(e.reporterAddress))throw Vt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Mr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!ir(e.reportedUserAddress))throw Vt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Mr(e.reportedUserAddress,"reportedUserAddress"),cr(0,void 0,aS.PAGINATION.MAX_LIMIT,e.pageSize)}(e);const t=Jk(e,En);Zk(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ae.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}async listGlobalFlags(e={}){!function(e){if(void 0!==e.tokenName&&cS(e.tokenName),void 0!==e.contentType&&!nS(e.contentType))throw Ft("contentType",`one of: ${Object.values(exports.ContentType).join(", ")}`,"Content type");if(void 0!==e.status&&!oS(e.status))throw Ft("status",`one of: ${Object.values(exports.FlagStatus).join(", ")}`);if(void 0!==e.reason&&!rS(e.reason))throw Ft("reason",`one of: ${Object.values(exports.FlagReason).join(", ")}`);if(void 0!==e.reporterAddress&&!ir(e.reporterAddress))throw Vt("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Mr(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!ir(e.reportedUserAddress))throw Vt("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Mr(e.reportedUserAddress,"reportedUserAddress"),cr(0,void 0,aS.PAGINATION.MAX_LIMIT,e.pageSize)}(e);const t=Jk(e,En);Zk(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ae.LIST,t,this.getMultiAuthHeaders()),r=this.extractData(n);return{items:r.flags,pageInfo:r.pageInfo}}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ut("flagId","Flag ID");try{Zn(e.flagId,"flagId")}catch{throw Ft("flagId","a positive integer","Flag ID")}}(e);const t=ae.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Ut("flagId","Flag ID");try{Zn(e.flagId,"flagId")}catch{throw Ft("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Ut("action","Action");if(!iS(e.action))throw Ft("action",`one of: ${Object.values(exports.FlagAction).join(", ")}`,"Action")}(e);const t=ae.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}}const uS=["heart","fire","laugh","wow","thumbs_up"];class dS extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}validateReactionTokenName(e){this.validateTokenName(e,Sn)}validateMessageId(e){if(!ir(e))throw Ut("messageId","Message ID");if(Jn(e,_n.CONTENT_REACTION.MAX_LENGTH,"messageId"),!_n.CONTENT_REACTION.PATTERN.test(e))throw Ft("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!ir(e))throw Ut("reactionType","Reaction type");if(!uS.includes(e))throw Ft("reactionType",`one of: ${uS.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Be,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=ln(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),o=this.extractData(r),{created:i,...s}=o;return{data:s,created:i}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${Me}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}class hS extends vr{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:Tt(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:Tt(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),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&&null!=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=>null!=e.token0Price&&null!=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=1,limit:i=Xk.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=Math.min(i,20),c=Math.max(o,1),l=new URLSearchParams({page:String(c),limit:String(a),sortBy:n,sortOrder:r});null!=t&&l.append("search",t);const u=`${this.dexBackendBaseUrl}/explore/pools?${l}`,d=await on(()=>this.http.get(u),{errorContext:"Failed to fetch DEX pools",logger:this.logger});let h=d.pools;const g=d.count??0,p=c*a<g,f=c>1;s&&(h=await this.enrichPoolsWithPricing(h)),this.logger.debug("DEX pools fetched successfully",{poolCount:h.length,totalCount:g,hasNextPage:p,withPrices:s});return{items:h,pageInfo:{hasNextPage:p,hasPrevPage:f,totalCount:g}}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=[];let n=1;for(;;){const r=await this.fetchDexPools({...e,page:n,limit:20});if(t.push(...r.items),!r.pageInfo.hasNextPage)break;n+=1}const r=t.length;return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.length,totalCount:r,withPrices:e.withPrices}),{items:t,pageInfo:{hasNextPage:!1,totalCount:r}}}}function gS(e){try{if(!ir(e))throw new Error("Token must be a non-empty string");return dk(e)}catch(t){throw new ht(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${Tt(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}class pS extends vr{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.dexBackendBaseUrl=t}validateFetchCompositePoolDataInput(e,t,n){if(!ir(e))throw new St("token0 must be a non-empty string",{token0:e});if(!ir(t))throw new St("token1 must be a non-empty string",{token1:t});try{dk(e),dk(t)}catch(n){throw new St(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${Tt(n)}`,{token0:e,token1:t})}try{Zn(n,"fee")}catch{throw new St(`fee must be a positive integer (got ${n})`,{fee:n})}const r=[500,3e3,1e4];if(!r.includes(n))throw new St(`fee must be one of: ${r.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!ir(e))throw new St("amount must be a non-empty string",{amount:e});const t=Hi(e);try{as(t,"amount")}catch(t){throw new St(t.message,{amount:e})}}convertTokenClassKey(e){const t=new i.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}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=gS(t),o=gS(n),a=this.convertTokenClassKey(e),c=this.convertTokenClassKey(o),l=new s.GetCompositePoolDto(a,c,r),u=`${this.dexBackendBaseUrl}/v1/trade/composite-pool/direct`,d=await this.http.post(u,l);Dt(d,`Pool not found: ${t}/${n} with fee ${r}`);const h=function(e){const t=e.token0Balance,n=e.token1Balance;return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:t,token1Balance:n,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=e.pool,n=new s.Pool(t.token0,t.token1,t.token0ClassKey,t.token1ClassKey,t.fee,Hi(t.sqrtPrice),t.protocolFees);n.bitmap=t.bitmap,n.grossPoolLiquidity=Hi(t.grossPoolLiquidity),n.liquidity=Hi(t.liquidity),n.feeGrowthGlobal0=Hi(t.feeGrowthGlobal0),n.feeGrowthGlobal1=Hi(t.feeGrowthGlobal1),n.protocolFeesToken0=Hi(t.protocolFeesToken0),n.protocolFeesToken1=Hi(t.protocolFeesToken1),n.tickSpacing=t.tickSpacing,n.maxLiquidityPerTick=Hi(t.maxLiquidityPerTick);const r={},o=e.tickDataMap;Object.keys(o).forEach(e=>{const t=o[e],n=t.initialised,i=t.liquidityNet,a=t.liquidityGross,c=t.feeGrowthOutside0,l=t.feeGrowthOutside1,u=new s.TickData(t.poolHash,t.tick);u.initialised=n,u.liquidityNet=Hi(i),u.liquidityGross=Hi(a),u.feeGrowthOutside0=Hi(c),u.feeGrowthOutside1=Hi(l),r[e]=u});const a=e.token0Balance,c=a.quantity,l={...a},u=new i.TokenBalance(l);u.quantity=Hi(c),Object.keys(l).forEach(e=>{e in u||(u[e]=l[e])});const d=e.token1Balance,h=d.quantity,g={...d},p=new i.TokenBalance(g);return p.quantity=Hi(h),Object.keys(g).forEach(e=>{e in p||(p[e]=g[e])}),new s.CompositePoolDto(n,r,u,p,e.token0Decimals,e.token1Decimals)}(d.Data),d.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:h.pool.liquidity.toString()}),h}catch(e){if(e instanceof At)throw e;this.logger.error("Failed to fetch composite pool data",e);throw Ct(e instanceof pt&&void 0!==e.originalError?e.originalError:e,"pool")}}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),null==t)throw new St("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),i=gS(n),a=gS(r),c=this.convertTokenClassKey(i),l=this.convertTokenClassKey(a),[u,d]=n<r?[c,l]:[l,c],h=new s.QuoteExactAmountDto(u,d,t.pool.fee,Hi(o),e,t.compositePoolDto),g=await s.quoteExactAmount(null,h);return this.logger.debug("Local quote calculated",{amount0:g.amount0,amount1:g.amount1}),{amount0:g.amount0.toString(),amount1:g.amount1.toString(),currentSqrtPrice:g.currentSqrtPrice.toString(),newSqrtPrice:g.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new St(`Local quote calculation failed: ${Tt(e)}`,{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),null==t)throw new St("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),i=gS(n),s=gS(r),a=`${this.dexBackendBaseUrl}/v1/trade/quote`,c=await this.http.get(a,{tokenIn:Ks(i),tokenOut:Ks(s),amountIn:o,fee:t.pool.fee});if(c.error||200!==c.status||void 0===c.data)throw new Error(c.message??"External quote failed");const l=c.data,u=Hi(l.amountOut).absoluteValue().negated().toString(),d=Hi(l.amountIn).absoluteValue().toString(),h=e?d:u,g=e?u:d;return this.logger.debug("External quote calculated",{amount0:h,amount1:g}),{amount0:h,amount1:g,currentSqrtPrice:Hi(l.currentSqrtPrice).toString(),newSqrtPrice:Hi(l.newSqrtPrice).toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new St(`External quote calculation failed: ${Tt(e)}`,{fromToken:n,toToken:r,amount:o})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class fS extends Sr{constructor(e,t,n,r=!1){super(r),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=dr(e,"tokenName","tokenId",{description:"token identifier"});if(!0===n&&null!=t)return this.logger.debug(`Fetching spot price by tokenId: ${String(t)}`),this._fetchDexTokenSpotPrice(t);throw new ht("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw Ut("tokenId","Token ID");try{const t=Av(e),n=qs(t),r=Gv(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw $t("DEX Backend API client not configured");const o=nn(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:r}}));if(null==o||"string"!=typeof o)throw new ht("Invalid price response: data must be a string, got "+typeof o,"data","INVALID_RESPONSE");const i=function(e,t){if(mn(e)||""===e)throw Ut(t);const n="number"==typeof e?e:parseFloat(String(e));if(isNaN(n))throw jt(t,e);if(!isFinite(n))throw jt(t,e);return n}(o,"price"),s=n;let a;try{if(null!==this.cache&&void 0!==this.cache){const e=this.cache.getByTokenId(s);if(null!=e?.symbol)return a=e.symbol,this.logger.debug(`DEX spot price for ${a} (cached): $${i}`),{symbol:a,price:i}}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}: $${i}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${Et(e)?e.message:String(e)}`),a=dn("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${a} (fallback): $${i}`)}return{symbol:a,price:i}}catch(e){if(e instanceof ht)throw e;throw $t(`Failed to fetch DEX spot price: ${Tt(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!ir(e))throw new ht(Bt,"tokenName",dt.REQUIRED);try{if(null!=n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);if(!0===t?.isGraduated){this.logger.debug(`Token ${e} is graduated, using DEX spot price`);const n=qs(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Tt(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(null==o)throw $t("GALA price not available");const i=qn(r.amount,0)/1e18;if(i<=0)throw new ht(`Invalid token amount calculation: ${i}`,"amount","INVALID_CALCULATION");const s=o.price/i;return{symbol:dn(e),price:s}}catch(t){if(Et(t))throw $t(`Failed to calculate launchpad token spot price for ${e}: ${Tt(t)}`);throw $t(`Failed to calculate launchpad token spot price for ${e}: ${Tt(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw $t("GalaChainService not available for token metadata fetch",500);const t=await this.galaChainService.fetchTokenClassFromChain(e),n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey,symbol:t.symbol,decimals:t.decimals,name:t.name,image:t.image,description:t.description,network:t.network,...void 0!==t.contractAddress&&{contractAddress:t.contractAddress}};return this.logger.debug(`Fetched token details for ${t.symbol} from GalaChain`),n}catch(t){if((t instanceof ht||Et(t))&&("NetworkError"===t.name||Tt(t).includes("Token not found")))throw t;throw $t(`Failed to fetch token details from GalaChain for ${String(e)}: ${Tt(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw $t("DEX Backend API client not configured");const e=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard/seasons"});let t;if(Array.isArray(e))t=e;else{if(null==e||"object"!=typeof e)return this.logger.warn("Seasons endpoint returned invalid data:",e),[];{const n=nn(e);if(Array.isArray(n))t=n;else if(null!=n&&"object"==typeof n&&Array.isArray(n.seasons))t=n.seasons;else{if(!Array.isArray(e.seasons))return this.logger.warn("Seasons endpoint returned unexpected structure:",e),[];t=e.seasons}}}const n=t.map(e=>{const t=e;return{id:t?.id??0,name:t?.name??"",start:wn(t?.start??null),end:wn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(Et(e)&&Tt(e).includes("not configured"))throw e;if(_t(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw $t(`Failed to fetch DEX seasons: ${Tt(e)}`)}}async fetchCurrentDexSeason(){const e=await this.fetchAllDexSeasons(),t=new Date,n=e.find(e=>t>=e.start&&t<=e.end);return n?this.logger.debug(`Current DEX season: ${n.name} (ID: ${n.id})`):this.logger.debug("No active DEX season found"),n??null}async fetchDexLeaderboardBySeasonId(e){try{Zn(e,"seasonId")}catch{throw Ut("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw $t("DEX Backend API client not configured");const t=await this.dexBackendHttp.request({method:"GET",url:"/leaderboard",params:{seasonId:e.toString()}});let n;if(Array.isArray(t))n=t;else{if(null==t||"object"!=typeof t)return this.logger.warn("Leaderboard endpoint returned invalid data:",t),{entries:[],seasonId:e,totalEntries:0};{const r=nn(t);if(null!=r&&"object"==typeof r&&Array.isArray(r.leaderboard))n=r.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(r))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=r}}}const r=n.map(e=>{const t=e,n=t?.mastery_titles??[];return{wallet:t?.wallet??"",rank:t?.rank??0,totalXp:String(t?.total_xp??0),distributionPercent:String(t?.distribution_percent??0),liquidityXp:String(t?.liquidity_xp??0),tradingXp:String(t?.trading_xp??0),masteryTitles:n.map(e=>{const t=e;return{name:t?.name??"",type:t?.type??"trade",order:t?.order??0}})}});return this.logger.debug(`Fetched leaderboard for season ${e} with ${r.length} entries`),{entries:r,seasonId:e,totalEntries:r.length}}catch(t){if(Et(t)&&Tt(t).includes("must be a positive number"))throw t;throw $t(`Failed to fetch DEX leaderboard for season ${e}: ${Tt(t)}`)}}async fetchCurrentDexLeaderboard(){const e=await this.fetchCurrentDexSeason();return e?this.fetchDexLeaderboardBySeasonId(e.id):(this.logger.debug("Cannot fetch current leaderboard - no active season"),null)}async fetchDexAggregatedVolumeSummary(){try{if(!this.dexBackendHttp)throw $t("DEX Backend API client not configured");const e=nn(await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}));if(!e)throw $t("No data in DEX volume response",500);const t={volume1d:e.volume1d,volume1dDelta:e.volume1dDelta,volume7d:e.volume7d,volume7dDelta:e.volume7dDelta,volume30d:e.volume30d,volume30dDelta:e.volume30dDelta};return this.logger.debug(`Fetched DEX volume summary: $${t.volume1d.toFixed(2)} (1d)`),t}catch(e){throw $t(`Failed to fetch DEX volume summary: ${Tt(e)}`)}}}const mS={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1};class yS{constructor(e,t={}){this.eventBuffer=[],this.flushTimer=null,this.isShuttingDown=!1,this.totalQueued=0,this.totalFlushed=0,this.totalDropped=0,this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.eventBuffer.length>0&&this.flushWithBeacon()},this.handleBeforeUnload=()=>{this.eventBuffer.length>0&&this.flushWithBeacon()},this.httpClient=e,this.logger=new gn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??mS.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??mS.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??mS.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??mS.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??mS.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??mS.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}function wS(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>o(e).plus(t.quantity).toString(),"0")}function bS(e,t){if(0===(e?.length??0))return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class kS extends vr{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(gk(e)?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const n=`/api/${this.getChannelForCollection(e.collection)}/token-contract/FetchBalances`,r=await this.http.post(n,e);if(null==r)return null;try{Dt(r,"Fetch balances")}catch{return null}if(0===(r.Data?.length??0))return null;const 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=qs(i),a={quantity:i.quantity,collection:i.collection,category:i.category,tokenId:s};if((i.inUseHolds?.length??0)>0){const e=bS(i.inUseHolds??[],t);e.length>0&&(a.inUseHolds=e,a.inUseQuantity=wS(e))}if((i.lockedHolds?.length??0)>0){const e=bS(i.lockedHolds??[],t);e.length>0&&(a.lockedHolds=e,a.lockedQuantity=wS(e))}return void 0===a.lockedQuantity&&void 0===a.inUseQuantity||(a.availableQuantity=function(e,t="0",n="0"){return o(e).minus(t).minus(n).toString()}(a.quantity,a.lockedQuantity,a.inUseQuantity)),a}catch(e){throw $t(`Failed to fetch token balance from GalaChain: ${Tt(e)}`,void 0,Et(e)?e:void 0)}}}function vS(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class SS extends t.ChainCallDTO{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),void 0!==e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,void 0!==e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,o){let i;if("string"==typeof r){i={...Hv(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new SS({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??vS()})}static forGALA(e,t,n,r){return new SS({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??vS()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Ks(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 AS extends t.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,null!=e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r){let o;if("string"==typeof n){o={...Hv(n),instance:"0"}}else o={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new AS({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:o}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??vS()})}static forGALA(e,t,n){return new AS({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??vS()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Ks(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function ES(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.amount)&&(void 0!==t.tokenId||ir(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 TS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.amount)&&(void 0!==t.tokenId||ir(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function IS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ES)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function CS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(TS)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var xS,NS;exports.LockErrorType=void 0,(xS=exports.LockErrorType||(exports.LockErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",xS.INVALID_AMOUNT="INVALID_AMOUNT",xS.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",xS.SIGNATURE_FAILED="SIGNATURE_FAILED",xS.NETWORK_ERROR="NETWORK_ERROR",xS.WALLET_REQUIRED="WALLET_REQUIRED",xS.VALIDATION_ERROR="VALIDATION_ERROR",xS.LOCK_NOT_FOUND="LOCK_NOT_FOUND",xS.LOCK_EXPIRED="LOCK_EXPIRED",xS.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",xS.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",xS.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH";class _S 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"}(NS||(NS={}));class DS extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}class PS{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 xr).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new xr).toEthereumFormat(e)}catch{try{return Pr(e)}catch{return e}}}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...Hv(e),instance:"0"}}}const RS=100,BS=100;class MS extends vr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new PS(t):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new _S("Wallet required for token lock operations",exports.LockErrorType.WALLET_REQUIRED);return Rs(async()=>{const t=Dr(this.wallet.address),n=[],r=[];let o=t;const i=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==i?.lockAuthority&&(o=Dr(i.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(void 0!==i.tokenId)e=Av(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(void 0===i.tokenName)throw new _S("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount,lockAuthority:void 0!==i.lockAuthority?Dr(i.lockAuthority):o})}const c=new SS({lockAuthority:o,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??vS()}),l=await this.signatureHelper.signLockToken(c.toSigningPayload()),u=new SS({...c.toSigningPayload(),signedPayload:l}),d=await this.http.post("/api/asset/token-contract/LockTokens",u);try{Dt(d,"Token lock failed")}catch(e){const t=Pt(d);throw new _S(`${Tt(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.extractLockResult(d,r)},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.signatureHelper)throw new _S("Wallet required for token unlock operations",exports.LockErrorType.WALLET_REQUIRED);return Rs(async()=>{const t=Dr(this.wallet.address),n=[],r=[],o=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(void 0!==o.tokenId)e=Av(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(void 0===o.tokenName)throw new _S("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount})}const i=new AS({tokenInstances:n,...void 0!==o?.name&&{name:o.name},uniqueKey:e.uniqueKey??vS()}),s=await this.signatureHelper.signUnlockToken(i.toSigningPayload()),a=new AS({...i.toSigningPayload(),signedPayload:s}),c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);try{Dt(c,"Token unlock failed")}catch(e){const t=Pt(c);throw new _S(`${Tt(e)}${t}`,exports.LockErrorType.NETWORK_ERROR)}return this.extractUnlockResult(c,r)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateLockTokensData(e){if(!IS(e))throw new _S("Invalid lock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>RS)throw new _S(`Batch size exceeds maximum limit of ${RS} tokens per lock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new _S("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{gr(t.tokenName,"tokenName")}catch{throw new _S("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=Hi(t.amount);try{is(e)}catch{throw new _S(Ft("lockAmount","a positive number","Lock amount").message,exports.LockErrorType.INVALID_AMOUNT,{amount:t.amount})}if(void 0!==t.lockAuthority&&!Br(t.lockAuthority))throw new _S("Invalid lock authority address format",exports.LockErrorType.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Zn(t.expires,"expires")}catch{throw new _S(Ft("expires","a positive integer (epoch milliseconds)","Expires").message,exports.LockErrorType.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!CS(e))throw new _S("Invalid unlock data: missing required fields",exports.LockErrorType.VALIDATION_ERROR);if(e.tokens.length>BS)throw new _S(`Batch size exceeds maximum limit of ${BS} tokens per unlock operation`,exports.LockErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new _S("Must provide either tokenId or tokenName for token identification",exports.LockErrorType.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{gr(t.tokenName,"tokenName")}catch{throw new _S("Invalid token name format",exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=Hi(t.amount);try{is(e)}catch{throw new _S(Ft("unlockAmount","a positive number","Unlock amount").message,exports.LockErrorType.INVALID_AMOUNT,{amount:t.amount})}}}extractLockResult(e,t){let n;if(void 0!==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(void 0!==e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId??t.txnId??t.TxnId??t.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof _S)return e;let r=t,o=exports.LockErrorType.NETWORK_ERROR;if(_t(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;void 0!==e.Message&&"string"==typeof e.Message&&(r=`${t}: ${e.Message}`);const i=String(e.Message??"").toLowerCase();i.includes("insufficient")||i.includes("balance")?o=exports.LockErrorType.INSUFFICIENT_BALANCE:i.includes("lock")&&i.includes("not found")?o=exports.LockErrorType.LOCK_NOT_FOUND:i.includes("not found")||i.includes("token")?o=exports.LockErrorType.TOKEN_NOT_FOUND:i.includes("authority")?o=exports.LockErrorType.NOT_LOCK_AUTHORITY:i.includes("expired")&&(o=exports.LockErrorType.LOCK_EXPIRED)}}else Et(e)&&(r=`${t}: ${Tt(e)}`);const i={};return void 0!==n?.tokens?.[0]?.tokenName&&(i.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(i.amount=n.tokens[0].amount),new _S(r,o,Object.keys(i).length>0?i:void 0)}async resolveTokenInstance(e){return Rs(async()=>{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!==t){const n=Tv(t);return this.logger.debug("[DEBUG] Token resolution (launchpad)",{tokenName:e,vaultAddress:t,tokenInstance:{collection:n.collection,category:n.category,type:n.type,instance:n.instance}}),n}const n={collection:un(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:n.collection,category:n.category,type:n.type}}),n},`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof DS)throw new _S(Tt(t),exports.LockErrorType.TOKEN_NOT_FOUND);throw new _S(`Failed to resolve token '${e}': ${Tt(t)}`,exports.LockErrorType.TOKEN_NOT_FOUND,{tokenName:e})})}}class OS extends vr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Av(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw Ut("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(Dt(r,"Failed to fetch token class from GalaChain"),null===r.Data||void 0===r.Data||0===r.Data.length)throw $t(`Token not found on GalaChain: ${qs(t)}`,404);return r.Data[0]}catch(e){if(e instanceof ht)throw e;if(_t(e)&&404===e.response?.status)throw $t("Token not found on GalaChain",404,Et(e)?e:void 0);if(Et(e)&&"Error"===e.name&&Tt(e).includes("status indicates failure"))throw $t(Tt(e),400,Et(e)?e:void 0);const t=Tt(e);if(t.includes("Token not found"))throw e;throw $t(`Failed to fetch token class from GalaChain: ${t}`,void 0,Et(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Ut("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw Ut("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(Dt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw $t("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof ht)throw e;if(_t(e)&&404===e.response?.status)throw $t("Token supply data not found on GalaChain",404,Et(e)?e:void 0);if(Et(e)&&"Error"===e.name&&Tt(e).includes("status indicates failure"))throw $t(Tt(e),400,Et(e)?e:void 0);const t=Tt(e);if(t.includes("Token not found"))throw e;throw $t(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,Et(e)?e:void 0)}}}class LS extends t.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,void 0!==e.signedPayload.prefix&&""!==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={...Hv(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 LS({tokenInstances:n,uniqueKey:t?.uniqueKey??vS()})}static fromTokenClassKey(e,t,n){return LS.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new LS({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??vS()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return Ks(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class US extends t.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,void 0!==e.signedPayload.prefix&&""!==e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,r,o){let i;if("string"==typeof r){i={...Hv(r),instance:"0"}}else i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new US({from:e,to:t,quantity:n,tokenInstance:i,uniqueKey:o??vS()})}static forGALA(e,t,n,r){return new US({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r??vS()})}getTokenClassKey(){return Ks(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function FS(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.amount)&&(void 0!==t.tokenId||ir(t.tokenName))}function $S(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(FS)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}var qS;exports.BurnErrorType=void 0,(qS=exports.BurnErrorType||(exports.BurnErrorType={})).TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",qS.INVALID_AMOUNT="INVALID_AMOUNT",qS.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",qS.SIGNATURE_FAILED="SIGNATURE_FAILED",qS.NETWORK_ERROR="NETWORK_ERROR",qS.WALLET_REQUIRED="WALLET_REQUIRED",qS.VALIDATION_ERROR="VALIDATION_ERROR";class KS extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}class GS{static validateAmount(e){const t=Hi(e);try{as(t,"amount")}catch(t){throw new DS(t.message,NS.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!ar(e)&&ir(e)){if(e.length>Rn.MAX_LENGTH)throw new ht(`Unique key too long. Maximum length: ${Rn.MAX_LENGTH}`);if(!Rn.PATTERN.test(e))throw new DS('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',NS.INVALID_AMOUNT,{uniqueKey:e})}}}const HS="gala-transfer-successful",WS="token-transfer-successful",zS="token-locked-successfully",VS="token-unlocked-successfully",jS="transfer-successful-no-id",XS=50;class QS extends vr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new PS(t):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new DS("Wallet required for GALA transfer operations",NS.WALLET_REQUIRED);try{const t=Dr(e.recipientAddress),n=Dr(this.wallet.address),r=US.forGALA(n,t,e.amount,e.uniqueKey),o=await this.signatureHelper.signTransferToken(r.toSigningPayload()),i=new US({...r.toSigningPayload(),signedPayload:o}),s=await this.http.post("/api/asset/token-contract/TransferToken",i);if(null==s)throw new DS("No response from GalaChain transfer service",NS.NETWORK_ERROR);return 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 DS("Wallet required for token transfer operations",NS.WALLET_REQUIRED);try{const t=Dr(e.to),n=Dr(this.wallet.address);let r;if(null!==e.tokenId&&void 0!==e.tokenId)r=Av(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:r.collection,category:r.category,type:r.type,instance:r.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new DS("Must provide either tokenId or tokenName for token identification",NS.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const o=new US({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey??vS()}),i=await this.signatureHelper.signTransferToken(o.toSigningPayload()),s=new US({...o.toSigningPayload(),signedPayload:i}),a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(null==a)throw new DS("No response from GalaChain transfer service",NS.NETWORK_ERROR);return 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}':`,{collection:t.collection,category:t.category,type:t.type}),t}catch(t){if(t instanceof DS)throw t;throw new DS(`Failed to resolve token class key for '${e}': ${Tt(t)}`,NS.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new KS("Wallet required for token burn operations",exports.BurnErrorType.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=Av(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new KS("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new LS({tokenInstances:t,uniqueKey:e.uniqueKey??vS()}),r=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),o=new LS({...n.toSigningPayload(),signedPayload:r}),i=await this.http.post("/api/asset/token-contract/BurnTokens",o);if(null==i)throw new KS("No response from GalaChain burn service",exports.BurnErrorType.NETWORK_ERROR);try{Dt(i,"Token burn operation")}catch(e){throw new pt(Tt(e),500)}return this.extractBurnResult(i)}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.recipientAddress)&&ir(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new ht("Invalid GALA transfer data: missing required fields");if(!Br(e.recipientAddress))throw new DS("Invalid recipient address format",NS.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});GS.validateAmount(e.amount),GS.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ir(t.to)&&ir(t.amount)&&(void 0!==t.tokenId||ir(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new ht("Invalid token transfer data: missing required fields");if(!Br(e.to))throw new DS("Invalid recipient address format",NS.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new DS("Must provide either tokenId or tokenName for token identification",NS.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{gr(e.tokenName,"tokenName")}catch{throw new DS("Invalid token name format",NS.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}GS.validateAmount(e.amount),GS.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!$S(e))throw new KS("Invalid burn data: missing required fields",exports.BurnErrorType.VALIDATION_ERROR);if(e.tokens.length>XS)throw new KS(`Batch size exceeds maximum limit of ${XS} tokens per burn operation`,exports.BurnErrorType.VALIDATION_ERROR);for(const t of e.tokens){if(!(null!==t.tokenId&&void 0!==t.tokenId||null!==t.tokenName&&void 0!==t.tokenName))throw new KS("Must provide either tokenId or tokenName for token identification",exports.BurnErrorType.TOKEN_NOT_FOUND);const e=Hi(t.amount);try{is(e)}catch{throw new KS("Burn amount must be a positive number",exports.BurnErrorType.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!=t){const n=Tv(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):`,{collection:n.collection,category:n.category,type:n.type,instance:n.instance}),n}const n={collection:un(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:n.collection,category:n.category,type:n.type}}),n}catch(t){if(t instanceof DS)throw t;throw new DS(`Failed to resolve token '${e}': ${Tt(t)}`,NS.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransactionIdFromResponse(e,t){if(null!=e&&"object"==typeof e){if("Status"in e&&"Data"in e)try{Dt(e,"Extract transaction ID");const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return HS;case"token":return WS;case"lock":return zS;case"unlock":return VS}return jS}catch{}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return e.transactionId}throw new DS("Operation succeeded but transaction ID could not be extracted",NS.NETWORK_ERROR)}extractBurnResult(e){const t=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const n of e.Data)t.push({collection:n.collection??"",category:n.category??"",type:n.type??"",additionalKey:n.additionalKey??"",instance:n.instance??"0",quantity:n.quantity??"0",burnedBy:n.burnedBy??""});let n;if(null!==e.Data&&void 0!==e.Data&&e.Data.length>0){const 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 DS)return e;if(e instanceof ht)return new DS(Tt(e),NS.INVALID_AMOUNT);if(_t(e)&&e.response){const t=e.response.status,r=e.response.data;if(400===t){const e="string"==typeof r?.message?r.message:void 0;return new DS(e??"Invalid transfer request",NS.INVALID_AMOUNT)}if(403===t)return new DS("Insufficient balance for transfer",NS.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new DS("Token not found",NS.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Nt(e)||"ETIMEDOUT"===Nt(e)))return new DS("Transfer request timed out",NS.NETWORK_ERROR);const r=""!==Tt(e)?Tt(e):t;return new DS(r,NS.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof KS)return e;let r=t,o=exports.BurnErrorType.NETWORK_ERROR;if(_t(e)){const n=e.response?.data;if("object"==typeof n&&"string"==typeof n.Message&&n.Message.length>0){r=`${t}: ${n.Message}`;const e=n.Message.toLowerCase();e.includes("insufficient")||e.includes("balance")?o=exports.BurnErrorType.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(o=exports.BurnErrorType.TOKEN_NOT_FOUND)}}else Et(e)&&(r=`${t}: ${Tt(e)}`);const i={};return void 0!==n?.tokens?.[0]?.tokenName&&(i.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(i.amount=n.tokens[0].amount),new KS(r,o,Object.keys(i).length>0?i:void 0)}}class YS extends vr{constructor(e,t,n,r=!1,o){super(e,r),this.balanceService=new kS(e,r),this.tokenService=new OS(e,r,o),this.lockService=new MS(e,t,n,r),this.transferService=new QS(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);Bs(()=>Dt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw $t(Tt(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",o=n?.maxFeePortion??"0",i=!es(r)||!es(o),s=t.Data;return s.reverseBondingCurveMinFeePortion=r,s.reverseBondingCurveMaxFeePortion=o,s.hasReverseBondingCurveFee=i,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return Bs(()=>Dt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw $t(Tt(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!$i(e))throw Ut("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw Ut("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new ht("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 JS{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 ZS extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class eA extends Sr{constructor(e={}){super(),this.nextRequestId=0,this.pending=new Map,this.subscriptionsByServerId=new Map,this.activeSubscriptions=new Set,this.intentionalClose=!1,this.reconnecting=!1,this.url=e.url??$s("PROD").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new JS({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3,useExponentialBackoff:!0});const t=e.webSocketImpl??globalThis.WebSocket;if("function"!=typeof t)throw new Error('GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).');this.webSocketConstructor=t}connect(){return this.isConnected()?Promise.resolve():(this.connectPromise||(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket()),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(new Error("GDEX stream disconnected"));const e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,"client disconnect")}isConnected(){return 1===this.socket?.readyState}request(e,t){if(!this.isConnected()||!this.socket)return Promise.reject(new Error("GDEX stream is not connected. Call connect() first."));const n=++this.nextRequestId,r={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(r.params=t),new Promise((t,o)=>{const i=setTimeout(()=>{this.pending.delete(n),o(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:o,timeout:i});try{this.socket?.send(JSON.stringify(r))}catch(e){clearTimeout(i),this.pending.delete(n),o(e instanceof Error?e:new Error(String(e)))}})}serverInfo(){return this.request("gdex_serverInfo")}ping(){return this.request("gdex_ping")}getPool(e){return this.request("gdex_getPool",e)}getBalance(e,t){return this.request("gdex_getBalance",void 0===t?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request("gdex_getPositions",e)}getBlockHeight(){return this.request("gdex_getBlockHeight")}quote(e){return this.request("gdex_quote",e)}getToken(e){return this.request("gdex_getToken",{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe("swap",e,t)}subscribePool(e,t,n={}){return this.subscribe("pool",t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe("balance",t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe("poolCreated",e,t)}subscribeBlocks(e,t={}){return this.subscribe("blocks",e,t)}openSocket(){return new Promise((e,t)=>{let n=!1;const r=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=r,r.onopen=()=>{this.socket===r&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},r.onmessage=e=>this.handleMessage(e.data),r.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},r.onclose=e=>{this.socket===r&&(this.socket=void 0,this.connectPromise=void 0,n||t(new Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(new Error(`GDEX stream connection closed (code ${e.code??0})`)),this.intentionalClose||this.reconnecting||this.startReconnectLoop())}})}handleMessage(e){if("string"!=typeof e)return void this.logger.warn("Ignoring non-text GDEX WebSocket frame");let t;try{t=JSON.parse(e)}catch{return void this.logger.warn("Ignoring invalid JSON from GDEX stream")}if("number"==typeof t.id){const e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){const n="number"==typeof t.error.code?t.error.code:-32603,r="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new ZS(n,r,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,r=t.params.result;if("string"!=typeof n||!this.isRecord(r))return;const o=this.subscriptionsByServerId.get(n);if(o?.active)try{o.callback(r)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const r={channel:e,...n},o=await this.request("gdex_subscribe",r);let i;const s={subscriptionId:o.subscriptionId,unsubscribe:async()=>this.unsubscribe(i)};return i={serverId:o.subscriptionId,params:r,callback:t,handle:s,active:!0},this.activeSubscriptions.add(i),this.subscriptionsByServerId.set(i.serverId,i),s}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request("gdex_unsubscribe",{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.reconnectionManager.shouldRetry();){const e=this.reconnectionManager.getNextDelay();if(this.reconnectionManager.recordAttempt(),this.logger.warn(`GDEX reconnect attempt ${this.reconnectionManager.getAttempts()}/${this.reconnectionManager.getMaxAttempts()} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{return await this.openSocket(),await this.resubscribeAll(),this.reconnectionManager.reset(),void(this.reconnecting=!1)}catch(e){this.logger.warn(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||this.logger.error("GDEX reconnection attempts exhausted")}async resubscribeAll(){this.subscriptionsByServerId.clear();for(const e of this.activeSubscriptions){if(!e.active)continue;const t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t);e.active?(e.serverId=n.subscriptionId,e.handle.subscriptionId=n.subscriptionId,this.subscriptionsByServerId.set(n.subscriptionId,e)):await this.request("gdex_unsubscribe",{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e){for(let t=0;;t++)try{return await this.request("gdex_subscribe",e)}catch(e){if(!(e instanceof ZS)||-32003!==e.code||t>=5)throw e;const n=this.readRetryAfterMs(e.data);this.logger.warn(`GDEX resubscribe rate limited; retrying in ${n}ms`),await new Promise(e=>setTimeout(e,n))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){void 0!==this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(const t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||"number"!=typeof e.retryAfterMs||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}function tA(e,t=3e4){return a.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}class nA{static createClient(e,t=6e4){return tA(e,t)}}class rA{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return Rs(async()=>{if(!ir(e))throw Ut("walletAddress","Wallet address");const r=Math.max(1,Math.floor(n/t)+1),o={};o.address=e,o.page=r,o.pageSize=t;const i=await this.http.get("/user/assets",o);if("object"!=typeof i||null===i)throw new ct(500,"Invalid response format: not an object");const s=nn(i);if(!s||"object"!=typeof s)throw new ct(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new ct(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 ct(500,"Invalid asset in response: asset must be an object");const t=e;if(!ir(t.symbol)||!ir(t.name))throw new ct(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 ct(500,"Invalid asset in response: decimals must be a number",t);const r={tokenId:"string"==typeof t.compositeKey&&t.compositeKey.length>0?t.compositeKey:`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:"string"==typeof t.quantity&&t.quantity.length>0?t.quantity:"0"};"string"==typeof t.image&&t.image.length>0&&(r.imageUrl=t.image),"boolean"==typeof t.verify&&t.verify&&(r.verified=t.verify),c.push(r)}const l={tokens:c,count:"number"==typeof s.count?s.count:c.length};return void 0!==s.totalValue&&(l.totalValue=String(s.totalValue)),l},`getUserAssets(${e})`,void 0,t=>{throw this.handleError(t,`getUserAssets(${e})`)})}async fetchTokenList(e={}){return Rs(async()=>{const{address:t,search:n,page:r=1,limit:o=20}=e,i={page:r,limit:Qk(o,1,20)};"string"==typeof t&&t.length>0&&(i.address=t),"string"==typeof n&&n.length>0&&(i.search=n);const s=await this.http.get("/user/token-list",i);if("object"!=typeof s||null===s)throw new ct(500,"Invalid response format: not an object");const a=nn(s);if(!a||"object"!=typeof a)throw new ct(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new ct(500,"Invalid response format: token array must be an array");const l=[];for(const e of c){if("object"!=typeof e||null===e)throw new ct(500,"Invalid token in response: must be an object");const t=e;if(!ir(t.symbol))throw new ct(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!ir(t.name))throw new ct(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new ct(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!ir(t.compositeKey))throw new ct(500,'Invalid token in response: missing required field "compositeKey"',{token:t});l.push({image:"string"==typeof t.image?t.image:"",name:t.name,symbol:t.symbol,decimals:String(n),description:"string"==typeof t.description?t.description:"",verify:"boolean"==typeof t.verify&&t.verify,compositeKey:t.compositeKey,additionalKey:"string"==typeof t.additionalKey?t.additionalKey:"",category:"string"==typeof t.category?t.category:"",type:"string"==typeof t.type?t.type:"",collection:"string"==typeof t.collection?t.collection:"",subscribePrice:"boolean"==typeof t.subscribePrice&&t.subscribePrice,quantity:"string"==typeof t.quantity?t.quantity:"0"})}return{token:l,count:"number"==typeof a.count?a.count:l.length}},"fetchTokenList",void 0,e=>{throw this.handleError(e,"fetchTokenList")})}handleError(e,t){if(e instanceof ct)return e;if(_t(e)){const n=e.response?.status??500,r=e.response?.data,o=r?.message??r?.Message??Tt(e),i=r?.Data??r?.data??void 0;return new ct(n,`${t}: ${String(o)}`,i)}return new ct(500,`${t}: ${Tt(e)}`)}}class oA{constructor(e){this.client=tA(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return Rs(async()=>{this.validateTokenObjects(e.token0,e.token1,"getPoolData");const t=await this.client.get("/v1/trade/pool",{params:this.poolParams(e)}),n=this.unwrapEnvelope(t);this.validateResponse(n);const r=n.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&lt(t.token0ClassKey)&&lt(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}(r))throw new ct(t.status,"Invalid pool data response format",r);return r},"DexBackendTradeClient.getPoolData",void 0,e=>{throw this.handleError(e,"pool")})}async getSlot0(e){return Rs(async()=>{this.validateTokenObjects(e.token0,e.token1,"getSlot0");const t=await this.client.get("/v1/trade/slot0",{params:this.poolParams(e)}),n=this.unwrapEnvelope(t);this.validateResponse(n);const r=n.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}(r))throw new ct(t.status,"Invalid slot0 data response format",r);return r},"DexBackendTradeClient.getSlot0",void 0,e=>{throw this.handleError(e,"pool")})}async getPositions(e){return Rs(async()=>{const t=this.positionParams(e),n=await this.client.get("/v1/trade/position",{params:t}),r=this.unwrapEnvelope(n);this.validateResponse(r);const o=this.normalizePositions(r.Data,n.status);return{positions:o,count:o.length}},"DexBackendTradeClient.getPositions",void 0,e=>{throw this.handleError(e,"position")})}async getPositionById(e,t,n,r,o,i,s){return Rs(async()=>{if(void 0===t||void 0===n||void 0===r||void 0===o||void 0===i)throw new ct(404,`Position not found: ${e}`);const a=this.toTokenClassKey(t),c=this.toTokenClassKey(n),l={token0:Ks(a),token1:Ks(c),fee:r,tickLower:o,tickUpper:i,owner:e};void 0!==s&&(l.positionId=s);const u=await this.client.get("/v1/trade/position",{params:this.toSearchParams(l)}),d=this.unwrapEnvelope(u);this.validateResponse(d);const h=this.normalizePositions(d.Data,u.status);if(0===h.length)throw new ct(404,`Position not found: ${e}`);const g={Data:h[0],Status:u.status};return void 0!==d.Message&&(g.Message=d.Message),g},"DexBackendTradeClient.getPositionById",void 0,e=>{throw this.handleError(e,"position")})}async getRemoveLiquidityEstimation(e){return Rs(async()=>{const t=await this.client.get("/v1/trade/remove-liq-estimate",{params:this.toSearchParams({token0:Ks(e.token0),token1:Ks(e.token1),fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount:e.amount,owner:e.owner})}),n=this.unwrapEnvelope(t);this.validateResponse(n);const r=n.Data;if("string"!=typeof r.amount0||"string"!=typeof r.amount1)throw new ct(t.status,"Invalid removal estimation response format",r);return r},"DexBackendTradeClient.getRemoveLiquidityEstimation",void 0,e=>{throw this.handleError(e,"position")})}async getUserPositions(e,t,n){return Rs(async()=>{const r={user:e,limit:Math.max(1,Math.min(10,t))};void 0!==n&&""!==n&&(r.bookMark=n);const o=await this.client.get("/v1/trade/positions",{params:this.toSearchParams(r)}),i=this.unwrapEnvelope(o);this.validateResponse(i);const s=this.asRecord(i.Data),a=this.normalizePositions(s.positions??[],o.status),c={positions:a,count:a.length};return"string"==typeof s.nextBookMark&&(c.nextBookMark=s.nextBookMark),c},"DexBackendTradeClient.getUserPositions",void 0,e=>{throw this.handleError(e,"position")})}poolParams(e){return this.toSearchParams({token0:Ks(e.token0),token1:Ks(e.token1),fee:e.fee})}positionParams(e){if(void 0===e.token0||void 0===e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper||void 0===e.owner)throw new ct(400,"Position lookup requires owner, token0, token1, fee, tickLower, and tickUpper");return this.toSearchParams({token0:Ks(e.token0),token1:Ks(e.token1),fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner})}toSearchParams(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))t.set(n,String(r));return t}normalizePositions(e,t){const n=this.asRecord(e);let r;r=Array.isArray(e)?e:Array.isArray(n.positions)?n.positions:"positionId"in n?[n]:[];const o=[];for(const e of r){if(!ut(e))throw new ct(t,"Invalid position in response",this.asRecord(e));o.push(e)}return o}unwrapEnvelope(e){const t=e.data;if(t.error||void 0===t.data)throw new ct(t.status,t.message??"Trade backend error");return t.data}validateResponse(e){const t=e;if(null==t||"object"!=typeof t)throw new ct(500,"Invalid response format: not an object");if(!("Data"in t)||!("Status"in t))throw new ct(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new ct(e.Status,e.Message??"Gateway error",e.Data)}validateTokenObjects(e,t,n){if("string"==typeof e||"string"==typeof t)throw new ht(`Defi backend ${n} requires TokenClassKey objects, not strings.`,"token","INVALID_TOKEN_FORMAT")}toTokenClassKey(e){if("string"==typeof e)return{collection:e,category:"Unit",type:"none",additionalKey:"none"};const{collection:t,category:n,type:r,additionalKey:o}=e;if("string"!=typeof t||"string"!=typeof n||"string"!=typeof r||"string"!=typeof o)throw new ht("Invalid TokenClassKey object","token","INVALID_TOKEN_FORMAT");return{collection:t,category:n,type:r,additionalKey:o}}asRecord(e){return"object"==typeof e&&null!==e?e:{}}handleError(e,t){return Ct(e,t)}}const iA=10;class sA extends Sr{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new Kv,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.privateKey=e.privateKey,void 0===e.bundlerBaseUrl||null===e.bundlerBaseUrl||""===e.bundlerBaseUrl||void 0===e.dexBackendBaseUrl||null===e.dexBackendBaseUrl||""===e.dexBackendBaseUrl||void 0===e.dexBackendHttp||null===e.dexBackendHttp)throw new ft("GSwapService requires explicit bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.","gswapConfig");try{this.tradeClient=new oA({baseUrl:e.dexBackendBaseUrl,timeout:3e4}),this.dexBackendClient=new rA(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new ft("Failed to initialize GSwapService HTTP clients","httpClients")}}setPricingConcurrency(e){if(e<1)throw Wt("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(Hi(e.amount).isLessThanOrEqualTo(0))throw new yt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new yt("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],i=[3e3,500,1e4];let s;for(const a of i)try{const i=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:a}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),c=Hi(s.currentSqrtPrice),l=Hi(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):Hi(0),d=Hi(s.amount0),h=Hi(s.amount1),g=ns(d),p=ns(h);this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":g,"amount1BN.isNegative()":p});const f=g?d:h;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:g,selectedAmount:f.toFixed(),selectedAmountAbs:f.absoluteValue().toFixed()});const m=f.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact:u.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,m),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:Et(e)?e.message:"Unknown error"})}throw s??new yt("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",yt,e)}}async getSwapQuoteExactOutput(e){try{if(Hi(e.amount).isLessThanOrEqualTo(0))throw new yt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new yt("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],i=[3e3,500,1e4];let s;for(const a of i)try{const i=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:o,fee:a}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),c=Hi(s.currentSqrtPrice),l=Hi(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):Hi(0),d=i.pool.token0,h="string"==typeof d?uk(d).collection:"object"==typeof d&&null!==d&&"tokenName"in d?d.tokenName:String(d),g=uk(n).collection===h?s.amount1:s.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:g,estimatedOutput:e.amount,feeTier:a,priceImpact:u.toFixed(),executionPrice:this.calculateExecutionPrice(g,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:Et(e)?e.message:"Unknown error"})}throw s??new yt("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",yt,e)}}async executeSwap(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("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=zi(e.estimatedOutput,e.slippageTolerance??.01),o=this.getWalletAddress();if(null==o||""===o)throw new ht("Wallet address required for swap execution","walletAddress",dt.REQUIRED);let i;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});i=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:i,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:Tt(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:o,slippageTolerance:e.slippageTolerance??.01,...!ar(i)&&{currentSqrtPrice:i}},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",wt,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return Rs(async()=>{if(!Br(e))throw new kt(Ft("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(kt,{walletAddress:e,page:t,limit:n}))}async getAllUserAssets(e){return Rs(async()=>{if(!Br(e))throw new kt(Ft("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 Sv(async(n,r)=>{const o=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r}),i=[];for(const e of o.token){if("0"===e.quantity){t=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&i.push(n)}return{items:i,page:n,limit:r,total:i.length,totalPages:1,hasNext:!t&&o.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(kt,{walletAddress:e}))}async fetchAvailableDexTokens(e={}){return Rs(async()=>{const{search:t,limit:n=20,page:r=1}=e;this.logger.debug("Fetching available DEX tokens",{search:t,limit:n,page:r});const o=await this.dexBackendClient.fetchTokenList({...!ar(t)&&{search:t},limit:n,page:r}),i=o.token.map(e=>this.transformRawTokenToDexToken(e)),s=r*n<o.count;return{tokens:i,count:o.count,page:r,limit:n,hasMore:s}},"Failed to fetch available DEX tokens",this.logger,this.createGSwapErrorHandler(kt,{...e}))}async fetchAllAvailableDexTokens(e={}){return Rs(async()=>{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=[];let r=1;for(;;){const e=await this.dexBackendClient.fetchTokenList({...!ar(t)&&{search:t},limit:20,page:r}),o=e.token.map(e=>this.transformRawTokenToDexToken(e));if(n.push(...o),o.length<20||20*r>=e.count)break;r+=1}return this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.length}),n},"Failed to fetch all available DEX tokens",this.logger,this.createGSwapErrorHandler(kt,e))}async getPoolInfo(e,t){try{if(null==e||""===e)throw Ut("tokenA","Token A");if(null==t||""===t)throw Ut("tokenB","Token B");this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),o=[500,3e3,1e4];let i=Hi(0),s=0;for(const a of o)try{const e="string"==typeof n?uk(n):n,t="string"==typeof r?uk(r):r,o=await this.tradeClient.getPoolData({token0:e,token1:t,fee:a});null!=o&&(i=i.plus(Hi(o.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:i.toFixed(),feeTiers:o,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new bt(`Failed to fetch pool info: ${Tt(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,r=e=>{if(null==e)return"";if("string"==typeof e)return e;if("object"==typeof e){const t=e;if(null!==t.type&&void 0!==t.type&&"none"!==t.type)return t.type;if(null!==t.collection&&void 0!==t.collection&&""!==t.collection)return t.collection;if(null!==t.symbol&&void 0!==t.symbol&&""!==t.symbol)return t.symbol;if(null!==t.tokenSymbol&&void 0!==t.tokenSymbol&&""!==t.tokenSymbol)return t.tokenSymbol;if(null!==t.name&&void 0!==t.name&&""!==t.name)return t.name}return""},o=r(n.token0),i=r(n.tokenA),s=r(n.token1),a=r(n.tokenB),c=n.token0Symbol??(""!==o?o:""!==i?i:n.tokenSymbol0??""),l=n.token1Symbol??(""!==s?s:""!==a?a:n.tokenSymbol1??""),u=""!==c?this.tokenConverter.normalizeInternalApiResponse(c):"",d=""!==l?this.tokenConverter.normalizeInternalApiResponse(l):"";return{positionId:n.positionId??n.id??"",ownerAddress:null!=t&&""!==t?t:n.ownerAddress??n.owner??"",token0:u,token1:d,feeTier:n.feeTier??n.fee??n.feeAmount??0,tickLower:n.tickLower??n.lowerTick??0,tickUpper:n.tickUpper??n.upperTick??0,liquidity:String(n.liquidity??n.liquidityAmount??"0"),amount0:String(n.amount0??n.amountA??"0"),amount1:String(n.amount1??n.amountB??"0"),feeAmount0:String(n.feeAmount0??n.feesA??"0"),feeAmount1:String(n.feeAmount1??n.feesB??"0"),...null!==n.createdAt&&void 0!==n.createdAt&&{createdAt:new Date(n.createdAt)},...null!==n.updatedAt&&void 0!==n.updatedAt&&{updatedAt:new Date(n.updatedAt)}}}parseTokenFlexible(e){try{return uk(e)}catch(t){if(Et(t)&&Tt(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:Hn(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=null!==e.symbol&&void 0!==e.symbol&&""!==e.symbol?e.symbol:"UNKNOWN";try{const n=null!==e.compositeKey&&void 0!==e.compositeKey&&""!==e.compositeKey?uk(e.compositeKey.replace(/\$/g,"|")):uk(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:n,balance:Wi(null!==e.quantity&&void 0!==e.quantity&&""!==e.quantity?e.quantity:"0")}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:Tt(e)}),null}}async getUserLiquidityPositions(e,t=10,n,r){try{if(null==e||""===e)throw Ut("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:t,bookmark:n});const o=await this.tradeClient.getUserPositions(e,t,n),i=o.positions,s=o.nextBookMark,a=i.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let c;this.logger.debug("Retrieved liquidity positions",{count:a.length,hasNextBookmark:null!=s,nextBookmark:s}),r?.withPrices&&a.length>0&&(c=await this.fetchPositionPrices(a));const l={items:a};return ar(s)||(l.nextBookmark=s),ar(c)||(l.prices=c),l}catch(e){this.handleGSwapError("Failed to fetch user liquidity positions",vt,e)}}async getAllSwapUserLiquidityPositions(e,t){try{if(null==e||""===e)throw Ut("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,iA,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,l;if(!0===Array.isArray(t))n=t,c=void 0,l=!1;else{if(null==t||"object"!=typeof t||!("items"in t)){r&&r.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(n)){r&&r.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){r&&r.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}i.push(...n),a++,r&&r.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:""!==(c??""),format:l?"BookmarkPaginationResult":"legacy-array"});const u=n.length<o;if(l&&(""===c||void 0===c)){r&&r.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){r&&r.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:o,format:l?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&r&&r.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination (bookmark): completed with total items: ${i.length}`,{pageCount:a}),{items:i,total:i.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:iA}),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",vt,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{if(null==e||""===e)throw Ut("ownerAddress","Owner address");if(void 0===t.token0||null===t.token0||""===t.token0)throw Ut("token0","Token 0");if(void 0===t.token1||null===t.token1||""===t.token1)throw Ut("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),o=gS(n),i=gS(r),s=(await this.tradeClient.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 vt("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",vt,e)}}async getLiquidityPositionById(e,t,n,r,o,i,s){try{if(null==e||""===e)throw Ut("ownerAddress","Owner address");if(null==t||""===t)throw Ut("positionId","Position ID");let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:null!=n,hasToken1:null!=r,hasFee:null!=o,hasTickLower:!ar(i),hasTickUpper:!ar(s)});let c=null;const l=5,u=2e3;for(let d=1;d<=l;d++)try{if(null!=n&&""!==n&&null!=r&&""!==r&&!ar(o)&&!ar(i)&&!ar(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.tradeClient.getPositionById(e,n,r,o,i,s,t)).Data,null!=a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position via compound key",{attempt:d,positionId:t});break}throw new vt("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:d,error:Et(e)?e.message:e})}const h=await this.getAllSwapUserLiquidityPositions(e),g=Array.isArray(h)?h:h.items,p=g.find(e=>ps(e.positionId,t));if(p){a=p,this.logger.debug("Found position via user positions scan",{attempt:d,positionId:t,totalPositions:g.length});break}if(c=Xt(t),d<l){this.logger.warn("User positions scan did not find position, retrying",{attempt:d,positionId:t,ownerAddress:e,foundCount:g.length}),await new Promise(e=>setTimeout(e,u));continue}}catch(e){if(d<l){this.logger.warn("Error fetching position, retrying",{attempt:d,positionId:t,error:Tt(e)}),await new Promise(e=>setTimeout(e,u));continue}c=Et(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:null!=a?Object.keys(a):"null",lastError:c?.message}),c??Xt(t);const d=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:d.positionId}),d}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",vt,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.tradeClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(null===r.positions||void 0===r.positions||0===r.positions.length)throw new vt("Position not found: No position exists for this compound key",null,"NOT_FOUND");const o=r.positions[0],i=this.normalizePositionResponse(o,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:i.positionId,token0:i.token0,token1:i.token1}),i}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",vt,e)}}async estimateRemoveLiquidity(e){try{if(void 0===e.token0||null===e.token0||""===e.token0)throw Ut("token0","Token 0");if(void 0===e.token1||null===e.token1||""===e.token1)throw Ut("token1","Token 1");if(void 0===e.liquidity||null===e.liquidity||""===e.liquidity)throw Ut("liquidity","Liquidity amount");if(void 0===e.owner||null===e.owner||""===e.owner)throw Ut("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=gS(t),o=gS(n),i=await this.tradeClient.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",vt,e)}}async addLiquidityByPrice(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("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=uk(t),o=uk(n),i=(await this.tradeClient.getPoolData({token0:r,token1:o,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:i,fee:e.fee});const s=Hi(e.minPrice),a=Hi(e.maxPrice),c=Math.floor(Xi(s)),l=Math.ceil(Xi(a)),u=ls(c,i),d=ls(l,i);this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:u,tickUpper:d,tickSpacing:i});const h=this.getWalletAddress();if(null==h||""===h)throw new ft("GSwapService: No wallet address available - cannot create position","walletAddress");const g="string"==typeof e.token0?uk(e.token0):e.token0,p="string"==typeof e.token1?uk(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${u}-${d}`,walletAddress:h});const f=await this.sendAddLiquidityToBundler({token0:g,token1:p,fee:e.fee,tickLower:u,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:null!==e.amount0Min&&void 0!==e.amount0Min&&""!==e.amount0Min?e.amount0Min:"0",amount1Min:null!==e.amount1Min&&void 0!==e.amount1Min&&""!==e.amount1Min?e.amount1Min:"0",owner:h}),m={transactionId:f};if(null!==m.positionId&&void 0!==m.positionId&&""!==m.positionId&&null!=f&&""!==f){this.logger.debug("Position ID returned directly from backend",{transactionId:f,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(f);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:e.status});const t=this.getWalletAddress();if(null!=t&&""!==t&&null!==m.positionId&&void 0!==m.positionId&&""!==m.positionId)try{const n=await this.getLiquidityPositionById(t,m.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,...i}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...m,...i,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}};return ar(s)||(a.createdAt=s),a}catch(t){return this.logger.debug("Could not fetch full position details",{error:Tt(t)}),{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}}if(null!=f&&""!==f){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:f}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(f);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:f,status:t.status});let r=null;this.logger.debug("Waiting for position indexing after WebSocket confirmation",{token0:e.token0,token1:e.token1,fee:e.fee}),await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(null==t||""===t)throw new ft("No wallet address available","walletAddress");this.logger.debug("Fetching positions",{walletAddress:t});const o=(await this.getUserLiquidityPositions(t,10)).items;if(this.logger.debug("Fetched positions",{count:null!=o?o.length:0}),null!=o&&o.length>0){const t=uk(e.token0).collection.toUpperCase(),i=uk(e.token1).collection.toUpperCase(),s=[];for(const n of o){if(""===(n?.positionId??""))continue;const r=null!==n.token0&&void 0!==n.token0?n.token0.toUpperCase():void 0,o=null!==n.token1&&void 0!==n.token1?n.token1.toUpperCase():void 0;if(null==r||""===r||null==o||""===o){this.logger.debug("Skipping position with empty tokens",{positionId:n.positionId});continue}const a=ms(r,o,t,i),c=n.feeTier===e.fee;this.logger.debug("Checking position",{positionId:n.positionId,tokens:`${r}/${o}`,tokensMatch:a,fee:n.feeTier,feeMatches:c}),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:`${uk(e.token0).collection}/${uk(e.token1).collection}`,expectedFee:e.fee,positionCount:o.length,liquidity:r.liquidity,amount0:r.amount0,amount1:r.amount1})):this.logger.debug("No matching position found",{availablePositions:o.map(e=>({id:e.positionId,token0:e.token0,token1:e.token1,fee:e.feeTier}))})}else this.logger.debug("No positions returned from API")}catch(e){this.logger.debug("Error fetching positions",{error:Tt(e)})}this.logger.debug("Discovery complete",{positionId:null!=n&&""!==n?n:"not found",matchedPositionData:{positionId:r?.positionId,liquidity:r?.liquidity,amount0:r?.amount0,amount1:r?.amount1,feeAmount0:r?.feeAmount0,feeAmount1:r?.feeAmount1,token0:r?.token0,token1:r?.token1,feeTier:r?.feeTier}});let o=r;if(null!=n&&""!==n)try{o=await this.getLiquidityPositionById(h,n),this.logger.debug("Fetched full position details",{positionId:o.positionId,liquidity:o.liquidity,amount0:o.amount0,amount1:o.amount1,feeAmount0:o.feeAmount0,feeAmount1:o.feeAmount1})}catch(e){this.logger.debug("Could not fetch full position details, using discovered data",{error:Tt(e)})}const i=o?{ownerAddress:o.ownerAddress,token0:o.token0,token1:o.token1,feeTier:o.feeTier,tickLower:o.tickLower,tickUpper:o.tickUpper,liquidity:o.liquidity,amount0:o.amount0,amount1:o.amount1,feeAmount0:o.feeAmount0,feeAmount1:o.feeAmount1}:{};return{...m,...i,...null!=n&&""!==n&&{positionId:n},status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(f)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){this.logger.error("Error in addSwapLiquidityByPrice",{error:Tt(e),stack:Et(e)?xt(e)?.split("\n").slice(0,3).join(" | "):void 0}),this.handleGSwapError("Failed to add liquidity by price",vt,e)}}async addSwapLiquidityByTicks(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("GSwapService not initialized with signing capability (privateKey required)","privateKey");const t=this.getWalletAddress();if(null==t||""===t)throw new ft("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?uk(e.token0):e.token0,r="string"==typeof e.token1?uk(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:null!==e.amount0Min&&void 0!==e.amount0Min&&""!==e.amount0Min?e.amount0Min:"0",amount1Min:null!==e.amount1Min&&void 0!==e.amount1Min&&""!==e.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(null!==s.positionId&&void 0!==s.positionId&&""!==s.positionId&&null!=o&&""!==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(null!=t&&""!==t&&null!==s.positionId&&void 0!==s.positionId&&""!==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,l={...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 ar(c)||(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:Tt(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(null!=o&&""!==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",l="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,fee:e.fee});try{const t=this.getWalletAddress();if(null==t||""===t)throw new ft("No wallet address available","walletAddress");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:iA});const n=3,o=5e3,i=3e3;let s=[];for(let c=1;c<=n;c++){const l=1===c?o:i;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:iA});if(s=(await this.getUserLiquidityPositions(t,iA)).items,this.logger.debug("Got positions from API",{count:null!=s?s.length:0}),null!=s&&s.length>0){const t=("string"==typeof e.token0?uk(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?uk(e.token1).collection:e.token1.collection).toUpperCase(),o=[];for(const r of s){if(""===(r?.positionId??""))continue;const i=null!==r.token0&&void 0!==r.token0?r.token0.toUpperCase():void 0,s=null!==r.token1&&void 0!==r.token1?r.token1.toUpperCase():void 0;if(null==i||""===i||null==s||""===s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=ms(i,s,t,n),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:`${uk(e.token0).collection}/${uk(e.token1).collection}`,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:Tt(e)}),this.logger.debug("Error waiting for position indexing",{error:Tt(e)})}this.logger.debug("Position discovery complete",{positionId:null!=r&&""!==r?r:"not found",found:null!=r&&""!==r}),this.logger.debug("Matched position data",{positionId:a?.positionId,liquidity:a?.liquidity,amount0:a?.amount0,amount1:a?.amount1,feeAmount0:a?.feeAmount0,feeAmount1:a?.feeAmount1,token0:a?.token0,token1:a?.token1,feeTier:a?.feeTier});let u=a;if(null!=r&&""!==r)try{this.logger.debug("Fetching full position details",{positionId:r}),u=await this.getLiquidityPositionById(t,r),this.logger.debug("Fetched full position data",{positionId:u.positionId,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:r,error:Tt(e)})}const d=u?{ownerAddress:u.ownerAddress,token0:u.token0,token1:u.token1,feeTier:u.feeTier,tickLower:u.tickLower,tickUpper:u.tickUpper,liquidity:u.liquidity,amount0:u.amount0,amount1:u.amount1,feeAmount0:u.feeAmount0,feeAmount1:u.feeAmount1}:{};return{...s,...d,...null!=r&&""!==r&&{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",vt,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const o=await t;r={status:o.status,transactionId:null!==o.transactionId&&void 0!==o.transactionId&&""!==o.transactionId?o.transactionId:e,timestamp:null!==o.timestamp&&void 0!==o.timestamp&&0!==o.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:Tt(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(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("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=qn(e.liquidity,Number.NaN);if(isNaN(t))throw new ht(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"unknown"}`,"liquidity","INVALID_VALUE");if(0===t)throw new ht(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"unknown"}`,"liquidity","ZERO_VALUE")}catch(e){if(Et(e)&&Tt(e).includes("Cannot remove zero liquidity"))throw e;if(Et(e)&&Tt(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?uk(e.token0):e.token0,n="string"==typeof e.token1?uk(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,null!==e.amount0Min&&void 0!==e.amount0Min&&""!==e.amount0Min?e.amount0Min:"0",null!==e.amount1Min&&void 0!==e.amount1Min&&""!==e.amount1Min?e.amount1Min:"0",null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?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",vt,e)}}async collectPositionFees(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("Private key not available for bundler-direct operations","privateKey");if(null!==e.ownerAddress&&void 0!==e.ownerAddress&&""!==e.ownerAddress&&null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId&&(null===e.token0||void 0===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(null==t)throw Xt(e.positionId);if(null===t.token0||void 0===t.token0||""===t.token0||null===t.token1||void 0===t.token1||""===t.token1)throw new vt("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:null!==e.amount0Max&&void 0!==e.amount0Max&&""!==e.amount0Max?e.amount0Max:null!==e.amount0Requested&&void 0!==e.amount0Requested&&""!==e.amount0Requested?e.amount0Requested:"0",amount1Requested:null!==e.amount1Max&&void 0!==e.amount1Max&&""!==e.amount1Max?e.amount1Max:null!==e.amount1Requested&&void 0!==e.amount1Requested&&""!==e.amount1Requested?e.amount1Requested:"0",positionId:e.positionId})}if(null===e.token0||void 0===e.token0||null===e.token1||void 0===e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw Ut("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?uk(e.token0):e.token0,n="string"==typeof e.token1?uk(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendCollectPositionFeesToBundler(t,n,e.fee,null!==e.amount0Requested&&void 0!==e.amount0Requested&&""!==e.amount0Requested?e.amount0Requested:"0",null!==e.amount1Requested&&void 0!==e.amount1Requested&&""!==e.amount1Requested?e.amount1Requested:"0",e.tickLower,e.tickUpper,null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?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",vt,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),i=uk(r),s=uk(o),a=await this.tradeClient.getPoolData({token0:i,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(Hi(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",bt,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=Hi(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:o.toFixed(),invertedPrice:Qi(o,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",bt,e)}}async calculateOptimalPositionSize(e,t,n,r,o,i,a){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:o});const c=(await this.getPoolData(e,t,n)).tick,l=s.tickToSqrtPrice(i),u=s.tickToSqrtPrice(c),d=s.tickToSqrtPrice(a),h=s.getLiquidityForAmounts(Hi(r),Hi(o),l,u,d),g=s.getAmountsForLiquidity(h,u,l,d),p=g[0],f=g[1],m=Hi(r),y=Hi(o);return{amount0:p.toFixed(),amount1:f.toFixed(),liquidity:h.toFixed(),ratio:cs(p,f).toFixed(),utilizationPercent:{amount0:os(cs(p,m),100).toFixed(2),amount1:os(cs(f,y),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",vt,e)}}async validatePositionParameters(e,t,n,r,o,i,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:o});const l=[500,3e3,1e4];l.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${l.join(", ")}`);const u=this.getTickSpacing(n);let d;r%u!==0&&a.push(`tickLower must be multiple of ${u}`),o%u!==0&&a.push(`tickUpper must be multiple of ${u}`),r>=o&&a.push(`tickLower (${r}) must be less than tickUpper (${o})`);try{d=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const h=Hi(i),g=Hi(s);if(h.isNaN()||g.isNaN())a.push("Amounts must be valid numbers");else try{ss(h,g)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const p=d.tick;(p<r||p>o)&&c.push("Position is out of current price range - will not earn fees until price moves into range");Hi(d.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const f=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:f,tickSpacing:u,currentTick:p,poolLiquidity:d.liquidity}}catch(e){const t=Tt(e);return a.includes(t)||a.push(`Validation failed: ${t}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}calculateTicksForPrice(e,t,n,r,o){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const i=this.getTickSpacing(o),s=Hi(n),a=Hi(r);er(n,r,"priceRange");const c=Math.floor(Xi(s)),l=Math.ceil(Xi(a)),u=ls(c,i),d=ls(l,i),h=Math.pow(1.0001,u),g=Math.pow(1.0001,d),p=Hi(h),f=Hi(g);return{tokenA:e,tokenB:t,feeTier:o,tickLower:u,tickUpper:d,tickSpacing:i,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:p.toFixed(8),actualMaxPrice:f.toFixed(8),priceDeviation:{minPriceDeviation:os(p.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:os(f.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",vt,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),i=Math.pow(1.0001,r);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=Hi(o),c=Hi(i),l={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:r-n};return ar(s)||(l.currentPrice=s),l}catch(e){throw this.handleGSwapError("Failed to calculate price for ticks",vt,e),e}}calculateExecutionPrice(e,t){try{const n=Hi(e);return cs(Hi(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 Ft("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new ht(`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 ht(`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=Yi();return cs(e,t).pow(2)}catch{return Hi(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return Hi(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?uk(e):e,o="string"==typeof t?uk(t):t,i=await this.tradeClient.getSlot0({token0:r,token1:o,fee:n}),s={sqrtPrice:null!==i.sqrtPrice&&void 0!==i.sqrtPrice&&""!==i.sqrtPrice?i.sqrtPrice:"0",tick:null!==i.tick&&void 0!==i.tick&&0!==i.tick?i.tick:0,liquidity:null!==i.liquidity&&void 0!==i.liquidity&&""!==i.liquidity?i.liquidity:"0",grossPoolLiquidity:null!==i.grossPoolLiquidity&&void 0!==i.grossPoolLiquidity&&""!==i.grossPoolLiquidity?i.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",bt,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=Hi(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",bt,t,{token0:e.token0,token1:e.token1})}}_calculateLiquidityFromAmount0(e,t,n){try{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.liquidity0(e,r,o)}catch{return Hi(0)}}_calculateLiquidityFromAmount1(e,t,n){try{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.liquidity1(e,r,o)}catch{return Hi(0)}}_calculateAmount0FromLiquidity(e,t,n){try{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.getAmount0Delta(r,o,e)}catch{return Hi(0)}}_calculateAmount1FromLiquidity(e,t,n){try{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.getAmount1Delta(r,o,e)}catch{return Hi(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(t){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("GSwapService: AddLiquidity requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new ft("GSwapService: Bundler URL not configured","bundlerBaseUrl");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:t.token0?.type??"unknown",token1:t.token1?.type??"unknown",fee:t.fee,tickRange:`${t.tickLower}-${t.tickUpper}`});const r=`galaswap - operation - ${n.v4()}-${Date.now()}-${t.owner}`,o={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:r},i=new e.ethers.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(o),l={...o,prefix:c},u=await i.signTypedData(a,s,l),d={...l,signature:u,types:s,domain:a};this.logger.debug("AddLiquidity DTO signed with manual types",{prefix:d.prefix,tickLower:o.tickLower,tickUpper:o.tickUpper});const h=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),g=nA.createClient(this.bundlerBaseUrl,3e4),p=await g.post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:h}),f=nn(p),m=f?.data??f?.transactionId??f?.id;if(null==m)throw this.logger.error("Bundler response structure",{status:p.status,dataType:typeof f}),new mt("Bundler response does not contain transaction ID. Response type: "+typeof f,void 0,"INVALID_RESPONSE");return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:m}),m}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(t,r,o,i,s,a,c,l,u){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new ft("GSwapService: Bundler URL not configured","bundlerBaseUrl");const d=new e.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${n.v4()}-${Date.now()}-${h}`,p={tickLower:t,tickUpper:r,amount:o,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:l,positionId:u,uniqueKey:g},f={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},b=await d.signTypedData(m,f,w),k={...w,signature:b,types:f,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,h);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:t,tickUpper:r,amount:o,fee:a,positionId:u,transactionId:g});const S=nA.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v}),E=nn(A),T=E?.data??E?.transactionId??E?.id;if(null==T)throw this.logger.error("Bundler response structure",{status:A.status,dataType:typeof E}),new mt("Bundler response does not contain transaction ID. Response type: "+typeof E,void 0,"INVALID_RESPONSE");return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:T}),T}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(t,r,o,i,s,a,c,l){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new ft("GSwapService: Bundler URL not configured","bundlerBaseUrl");const u=new e.ethers.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${n.v4()}-${Date.now()}-${d}`,g={token0:t,token1:r,fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:l,uniqueKey:h},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},w=await u.signTypedData(f,p,y),b={...y,signature:w,types:p,domain:f},k=this.buildLiquidityStringsInstructions(t,r,o,d);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:l,transactionId:h});const v=nA.createClient(this.bundlerBaseUrl,3e4),S=await v.post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k}),A=nn(S),E=A?.data??A?.transactionId??A?.id;if(null==E)throw this.logger.error("Bundler response structure",{status:S.status,dataType:typeof A}),new mt("Bundler response does not contain transaction ID. Response type: "+typeof A,void 0,"INVALID_RESPONSE");return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(t){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new ft("GSwapService: Swap requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new ft("GSwapService: Bundler URL not configured","bundlerBaseUrl");const r=[500,3e3,1e4];if(!r.includes(t.feeTier))throw new ht(`GSwapService: Invalid fee tier ${t.feeTier}. Must be one of: ${r.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let r=t.fromToken,o=t.toToken;"string"==typeof r&&(r=uk(r)),"string"==typeof o&&(o=uk(o));const i=qs(r),s=qs(o),a=i<s?[r,o,i,s]:[o,r,s,i],[c,l,u,d]=a,h=qs("string"==typeof t.fromToken?uk(t.fromToken):t.fromToken),g=h===u,p=`galaswap - operation - ${n.v4()}-${Date.now()}-${t.walletAddress}`;let f;if(void 0===t.currentSqrtPrice||null===t.currentSqrtPrice||""===t.currentSqrtPrice)throw new ht("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",dt.REQUIRED);const m=Hi(t.currentSqrtPrice),y=t.slippageTolerance??.01;if(g){const e=Vi(y);f=m.multipliedBy(e).toString()}else{const e=ji(y);f=m.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:t.currentSqrtPrice,slippageTolerance:100*y+"%",zeroForOne:g,sqrtPriceLimit:f,direction:g?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const w={token0:c,token1:l,fee:t.feeTier,amount:Hi(t.inputAmount).toFixed(),zeroForOne:g,sqrtPriceLimit:f,recipient:t.walletAddress,amountOutMinimum:Hi(t.minOutput).multipliedBy(-1).toFixed(),uniqueKey:p};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:u,orderedToken1String:d,fromTokenStr:h,zeroForOne:g?`TRUE (${u} → ${d})`:`FALSE (${d} → ${u})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(null!==t.slippageTolerance&&void 0!==t.slippageTolerance&&0!==t.slippageTolerance?t.slippageTolerance:.01)+"%",currentSqrtPrice:t.currentSqrtPrice,swapDto:{amount:w.amount,zeroForOne:w.zeroForOne,sqrtPriceLimit:w.sqrtPriceLimit,amountOutMinimum:w.amountOutMinimum}});const b=new e.ethers.Wallet(this.privateKey),k={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},v={name:"ethereum",chainId:1},S=this.calculatePersonalSignPrefix(w),A={...w,prefix:S},E=await b.signTypedData(v,k,A),T={...A,signature:E,types:k,domain:v};this.logger.debug("Swap DTO signed",{prefix:T.prefix,zeroForOne:w.zeroForOne});const I=this.buildLiquidityStringsInstructions(c,l,t.feeTier,t.walletAddress),C=nA.createClient(this.bundlerBaseUrl,3e4),x=await C.post("/bundle",{method:"Swap",signedDto:T,stringsInstructions:I}),N=nn(x),_=N?.data??N?.transactionId??N?.id;if(null==_)throw this.logger.error("Bundler response structure",{status:x.status,dataType:typeof N}),new mt("Bundler response does not contain transaction ID. Response type: "+typeof N,void 0,"INVALID_RESPONSE");return this.logger.debug("Swap transaction sent to bundler",{transactionId:_,inputAmount:t.inputAmount,minOutput:t.minOutput}),_}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const o=Gs(e),i=Gs(t),s=`$pool${o}${i}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${s}`,`$tokenBalance${i}${s}`]}createGSwapErrorHandler(e,t){return(n,r,o)=>{this.handleGSwapError(r,e,n,t)}}handleGSwapError(e,t,n,r){this.logger.error(e,n);const o=this.extractGSwapErrorCode(n),i=n,s=[`${e}: ${i?.message??Tt(n)}`,n],a=t.name;throw r&&("GSwapSwapError"===a&&null!==r.transactionHash&&void 0!==r.transactionHash&&s.push(r.transactionHash),"GSwapPoolError"===a&&(null!==r.tokenA&&void 0!==r.tokenA&&s.push(r.tokenA),null!==r.tokenB&&void 0!==r.tokenB&&s.push(r.tokenB)),"GSwapAssetError"===a&&null!==r.walletAddress&&void 0!==r.walletAddress&&s.push(r.walletAddress)),null!=o&&""!==o&&s.push(o),new t(...s)}extractGSwapErrorCode(e){const t=Nt(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)}`}}function aA(e,t="image",n){const r=new FormData;if("undefined"!=typeof File&&e instanceof File)r.append(t,e);else{if(!Buffer.isBuffer(e))throw Ft("file","a File object (browser) or Buffer (Node.js)");{const o=new Blob([e],{type:"image/png"});r.append(t,o,n)}}return r}class cA extends vr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;vs(t);const r=`${t}.png`;hs(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=aA(n.file,"image",e),o=await on(()=>this.http.request({method:"POST",url:`${y.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof o?o:""}catch(e){if(e instanceof ft)throw e;if(Et(e)&&Tt(e).includes("FormData"))throw qt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const lA={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},uA={PAGINATION:{MAX_LIMIT:In.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:Nn.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:Nn.COMMENTS_V1.MAX_LENGTH}};function dA(e){if(!!(void 0===e.messagesEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl))throw new ht("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",dt.REQUIRED);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Vt("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Vt("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Vt("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Vt("streamLanguage","string");const t=["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"];for(const n of t){const t=e[n];if(null!=t&&"string"!=typeof t)throw Vt(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Vt("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new ht("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",dt.INVALID_FORMAT)}}function hA(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class gA extends vr{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!ar(e.search)&&{search:e.search},...!ar(e.tokenName)&&{tokenName:e.tokenName},...!ar(e.type)&&{type:e.type},...!ar(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!ar(e.language)&&{language:e.language},...!ar(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!ar(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!ar(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,r={pageSize:String(t)};void 0!==n&&(r.cursor=n),ar(e.type)||(r.type=e.type),ar(e.tokenName)||(r.tokenName=e.tokenName),ar(e.search)||(r.search=e.search),ar(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),ar(e.language)||(r.language=e.language),ar(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),ar(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),ar(e.streamStatus)||(r.streamStatus=e.streamStatus);const o=Ki(r),i=nn(await an(()=>this.http.get(y.FETCH_POOLS,o),{errorContext:"Failed to fetch pools"})),s=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(i),a={hasNextPage:i.hasNextPage??!1},c=i.count??i.total;return void 0!==c&&(a.totalCount=c),void 0!==i.nextCursor&&null!==i.nextCursor&&(a.nextCursor=i.nextCursor),void 0!==i.prevCursor&&null!==i.prevCursor&&(a.prevCursor=i.prevCursor),void 0!==i.hasPrevPage&&(a.hasPrevPage=i.hasPrevPage),{items:s,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??Xk.DEFAULT_LIMIT;ir(e?.tokenName)&&vs(e.tokenName);const r=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,o=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,i={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:o}),pageSize:n,...void 0!==t&&{cursor:t}},s=await this.fetchSinglePage(i);return{items:s.items,pageInfo:s.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=Xk.BACKEND_MAX_PAGE_SIZE;for(;;){const o={...e,pageSize:r,...void 0!==n&&{cursor:n}},i=await this.fetchPools(o);if(t.push(...i.items),!i.pageInfo.hasNextPage)break;n=i.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){Ss(e),ir(e.tokenName)&&vs(e.tokenName);try{const t=await this.http.post(y.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===ir(e.symbol)){return!n.symbolAvailable}if(!0===ir(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const o="number"==typeof n.statusCode?n.statusCode:null;if(404===o)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===o&&r.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!Li(e))throw new ht("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(vs(t),null==n||null==r||null==o)throw new ht("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:r,resolution:o};As(i);const s=Ki(i);return{dataPoints:await on(()=>this.http.get(y.CHART,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw Ut("tokenName","Token name");let t;vs(e);try{t=await an(()=>this.http.get(`${y.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(_t(t)&&500===t.response?.status)throw $t(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=nn(t);if(!Array.isArray(n))throw $t("Invalid API response: expected array of holders",t.status);for(const e of n){if(""===e.owner||null===e.owner||void 0===e.owner||"string"!=typeof e.owner)throw $t("Invalid holder data: missing or invalid owner field",t.status);if(""===e.quantity||null===e.quantity||void 0===e.quantity||"string"!=typeof e.quantity)throw $t("Invalid holder data: missing or invalid quantity field",t.status);const n=qn(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw $t(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),Hi(0));return{holders:n.map(e=>{const t=cs(Hi(e.quantity),r,Hi(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||null==e)throw Ut("tokenName","Token name");if(""===t||null==t)throw Ut("userAddress","User address");return vs(e),on(()=>this.http.get(`${y.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(""===e||null==e)throw Ut("tokenName","Token name");vs(e);const t=y.GET_TOKEN_BADGES.replace(":tokenName",e.toLowerCase().trim()),n=await on(()=>this.http.get(t),{errorContext:"Failed to fetch token badges"});return{volumeBadges:n.volumeBadge??[],engagementBadges:n.engagementBadge??[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:r}=e;try{const e=await this.fetchTokenBadges(t);if(null==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(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0].vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}catch{return null}}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");vs(e);try{const t=y.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=nn(await this.http.get(t));if(null!=n?.tokens){const t=Array.isArray(n.tokens)?n.tokens[0]:n.tokens;if(null==t)throw new Error(`Token not found: ${e}`);return t}throw new Error(`Invalid response format when fetching token: ${e}`)}catch(t){const n=String(t);if(n.includes("404")||n.includes("not found"))throw new Error(`Token not found: ${e}`);throw t}}async validateToken(e){if(!(null!==e.tokenName&&void 0!==e.tokenName||null!==e.symbol&&void 0!==e.symbol))throw new Error("At least one of tokenName or symbol is required");if(null!==e.tokenName&&void 0!==e.tokenName&&("string"!=typeof e.tokenName||""===e.tokenName.trim()))throw new Error("tokenName must be a non-empty string");if(null!==e.symbol&&void 0!==e.symbol&&("string"!=typeof e.symbol||""===e.symbol.trim()))throw new Error("symbol must be a non-empty string");null!==e.tokenName&&void 0!==e.tokenName&&vs(e.tokenName);try{const t=await this.http.post(y.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!ir(e))throw Ut("tokenName","Token name");vs(e);const t=y.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=nn(await this.http.get(t));if(!e?.stats)throw new Error("Invalid response: missing stats data");return{success:!0,data:e.stats}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw Ut("tokenName","Token name");vs(e),dA(t);const n=y.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),r={};void 0!==t.messagesEnabled&&(r.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(r.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(r.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(r.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(r.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(r.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(r.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(r.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(r.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(r.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(r.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(r.tiktokUrl=t.tiktokUrl),await this.http.patch(n,r,this.getJwtHeaders())}}const pA={PAGINATION:In,TOKEN_NAME:An,USER_ADDRESS:xn};function fA(e){if(void 0!==e.tokenName){if(!ir(e.tokenName))throw Vt("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>pA.TOKEN_NAME.MAX_LENGTH)throw zt("tokenName",pA.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!ir(e.userAddress))throw Vt("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>pA.USER_ADDRESS.MAX_LENGTH)throw zt("userAddress",pA.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Vt("search","a string",typeof e.search);if(e.search.length>256)throw zt("search",256,e.search.length)}if(cr(0,void 0,pA.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Ft("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!ir(e.startDate))throw Vt("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Ft("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!ir(e.endDate))throw Vt("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Ft("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Yn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Ft("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Yn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Ft("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&er(e.minAmount,e.maxAmount,"amountRange")}class mA extends vr{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Bi(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Mi(t,"userAddress")&&Oi(t,"offset")&&Oi(t,"pageSize")&&Oi(t,"page")&&Oi(t,"limit")}(e))throw new ht("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:r,cursor:o,pageSize:i=Xk.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!ir(t))throw Ut("tokenName","Token name");const l={pageSize:String(Math.min(i,Tn))};void 0!==o&&(l.cursor=o);const u={...l};u.tokenName=t;const d=await this.http.get(y.GET_TRADES,u);if(null==d)throw new ht("No response from trade service","response","NO_RESPONSE");const h=nn(d),g=hA(h,"trades"),p=h?.pageInfo;return{items:g,pageInfo:p??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=ln(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=e.userAddress),null!==e.search&&void 0!==e.search&&e.search.length>0&&(t.search=e.search);const n=void 0!==e.pageSize?Qk(e.pageSize,1,pA.PAGINATION.MAX_LIMIT):pA.PAGINATION.MAX_LIMIT;return void 0!==e.cursor&&(t.cursor=e.cursor),t.pageSize=String(n),null!==e.txnType&&void 0!==e.txnType&&e.txnType.length>0&&(t.txnType=e.txnType),null!==e.startDate&&void 0!==e.startDate&&e.startDate.length>0&&(t.startDate=e.startDate),null!==e.endDate&&void 0!==e.endDate&&e.endDate.length>0&&(t.endDate=e.endDate),void 0!==e.minAmount&&(t.minAmount=String(e.minAmount)),void 0!==e.maxAmount&&(t.maxAmount=String(e.maxAmount)),t}async getTrades(e){fA(e);const t=this.buildTradesQueryParams(e);return on(()=>this.http.get(Oe,t),{errorContext:"Failed to fetch trades"})}}function yA(e){return!!ir(e)&&Cn.PATTERN.test(e)}lr({ALL:"all",DEFI:"DEFI",ASSET:"ASSET",COLLECTION:"COLLECTION",CREATED:"created"});class wA extends vr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!yA(t))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");const n={userAddress:t},r=await this.http.get(y.GET_PROFILE,n);if(null==r)throw new ht("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!ir(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await on(()=>this.http.put(y.UPDATE_PROFILE,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(null==t||""===t)throw new ht("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=aA(e.file,"image",n),o=await on(()=>this.http.request({method:"POST",url:`${y.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof o?o:""}catch(e){if(e instanceof ht||e instanceof ft)throw e;throw new ht(`Profile image upload failed: ${Tt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(y.GET_TOKEN_LIST,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(y.GET_TOKENS_HELD,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:o,status:i}=e??{},s=e?.type??(void 0!==i?"created":"DEFI"),a=this.http.getAddress();if(null==a||""===a)throw new ht("Wallet address not available - wallet not configured","address","NO_WALLET");const c={type:s,address:a,pageSize:n??Xk.DEFAULT_LIMIT};return void 0!==t&&(c.cursor=t),void 0!==r&&(c.search=r),void 0!==o&&(c.tokenName=o),void 0!==i&&(c.status=i),this.fetchTokenList(c)}async getManagedTokens(e={}){const t=Jk({pageSize:e.pageSize??Xk.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},Tn);return on(()=>this.http.get(y.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Jk({pageSize:t.pageSize??Xk.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Tn);Zk(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type="all"===(t.type??"DEFI")?"DEFI":t.type??"DEFI");let o=e;if(e.includes(":address")){const n=t.address??this.http.getAddress();if(0===n.length)throw Ut("address","User address");o=e.replace(":address",n),delete r.address}const i=nn(await an(()=>this.http.get(o,r),{errorContext:n.errorMessage})),s=hA(i,"token"),a={hasNextPage:i.hasNextPage??!1},c=i.count??i.total;void 0!==c&&(a.totalCount=c),void 0!==i.nextCursor&&(a.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(a.prevCursor=i.prevCursor),void 0!==i.hasPrevPage&&(a.hasPrevPage=i.hasPrevPage);const l={tokens:s,pageInfo:a};return void 0!==c&&(l.total=c),l}async fetchUserBalances(e){if(!yA(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");const t=Jk({pageSize:e.pageSize??Xk.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},Tn),n=y.USER_BALANCES.replace(":address",e.address),r=nn(await an(()=>this.http.get(n,t),{errorContext:"Failed to fetch user balances"}));if(!r)throw new ht("Invalid response: missing data","response","NO_DATA");const o={hasNextPage:r.hasNextPage??!1};return void 0!==r.nextCursor&&(o.nextCursor=r.nextCursor),void 0!==r.prevCursor&&(o.prevCursor=r.prevCursor),void 0!==r.hasPrevPage&&(o.hasPrevPage=r.hasPrevPage),void 0!==r.total&&(o.totalCount=r.total),{balances:Array.isArray(r.balances)?r.balances:[],pageInfo:o,total:r.total}}async fetchUserReport(e){if(!yA(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");if(!this.jwtAuth)throw new ft("JWT authentication is required for fetchUserReport. Call sdk.login() first.","jwtAuth");const t=y.USER_REPORT.replace(":address",e.address),n=nn(await an(()=>this.http.get(t,{},this.getJwtHeaders()),{errorContext:"Failed to fetch user report"}));if(!n?.report)throw new ht("Invalid response: missing report data","response","NO_DATA");return{report:n.report}}validateGetTokenListOptions(e){const t=e.pageSize??Xk.DEFAULT_LIMIT;if(t<1||t>Tn)throw new ht(`pageSize must be between 1 and ${Tn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!yA(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=gs(e.search);if(null!==n&&!(ir(r=n)&&r.length>=Ln&&r.length<=Un))throw Ht("search",Ln,Un,n.length,"Search query");var r;const o=gs(e.tokenName);if(null!==o&&!(ir(i=o)&&i.length>=An.MIN_LENGTH&&i.length<=An.MAX_LENGTH))throw Ht("tokenName",An.MIN_LENGTH,An.MAX_LENGTH,o.length,"Token name");var i}validateUpdateProfileData(e){if(!yA(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(ir(t)&&t.length>=Fn.FULL_NAME.MIN_LENGTH&&t.length<=Fn.FULL_NAME.MAX_LENGTH&&Fn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Ht("fullName",Fn.FULL_NAME.MIN_LENGTH,Fn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!yA(e.address))throw Ft("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class bA{constructor(e,t,n=!1){this.http=e,this.poolService=new gA(e,t,n),this.tradeService=new mA(e,n),this.userService=new wA(e,t,n),this.imageService=new cA(e,t,n)}setJwtAuth(e){this.poolService.setJwtAuth(e),this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async 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 vs(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async fetchUserBalances(e){return this.userService.fetchUserBalances(e)}async fetchUserReport(e){return this.userService.fetchUserReport(e)}}class kA extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}validateContent(e,t){if(!ir(e))throw Ut("content","Message content");if(0===e.trim().length)throw Ut("content","Message content");Jn(e,t===lA.CHAT_MESSAGE?Nn.CHAT_MESSAGES_V1.MAX_LENGTH:Nn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!ir(e))throw Ut("id","Message ID");if(e.length<10||e.length>64)throw Ft("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==lA.CHAT_MESSAGE&&e!==lA.COMMENT)throw new ht(`type must be one of: ${Object.values(lA).join(", ")}`,"type","INVALID_VALUE")}async fetchMessages(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName;t&&this.validateMessageType(e.type),n&&this.validateTokenName(e.tokenName,Sn);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Xk.DEFAULT_LIMIT;const o=Jk(r,In.MAX_LIMIT),i={};void 0!==o.pageSize&&(i.pageSize=o.pageSize),void 0!==o.cursor&&(i.cursor=o.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=ln(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(i.search=e.search);const s=await this.http.get(Le.GET_MESSAGES,i),a=this.extractData(s);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Sn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:ln(e.tokenName),content:e.content.trim()},n=await this.http.post(Le.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(Le.UPDATE_MESSAGE,e),r={content:t.content.trim()},o=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(o)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Le.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Sn);const t=await this.http.get(Le.GET_PINNED,{tokenName:ln(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=Le.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Le.UNPIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(Le.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const vA={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},SA=ur(vA),AA={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},EA=ur(AA),TA={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},IA=ur(TA);function CA(e){return SA.includes(e)}function xA(e){return IA.includes(e)}function NA(e){return Bn.PATTERN.test(e)}const _A=pr([{field:"id",type:"number"},{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"role",type:"string"},{field:"inviteCode",type:"string"},{field:"inviteUrl",type:"string"},{field:"status",type:"string"},{field:"createdAt",type:"string"}]),DA=pr([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),PA=pr([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"string"}]);function RA(e){return EA.includes(e)}class BA extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}validateRole(e){if(!ir(e))throw Ut("role","Role");if(!CA(e))throw Ft("role",`one of: ${SA.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!ir(e))throw Ut("inviteCode","Invite code");if(!NA(e))throw Ft("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!RA(e))throw new ht(`Invalid invite scope. Must be one of: ${EA.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??AA.TOKEN;if(t===AA.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new ht("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,vn)}else if(t===AA.ALL_OWNER_TOKENS&&e.tokenName)throw new ht("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",Nn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Z,r={inviteScope:t,role:e.role};t===AA.TOKEN&&null!=e.tokenName&&""!==e.tokenName&&(r.tokenName=ln(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const o=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(o)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,vn),this.validateStatusFilter(e.status,TA);const t=ne,n={...this.buildPaginationParams(e,In.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=ln(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),o=this.extractData(r);return{items:o.invites,pageInfo:o.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(re,{id:String(e)});tn(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(oe,{id:String(e.inviteId)}),n={role:e.role},r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new ht("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",Nn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(ie,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const r=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=ee,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),o=this.extractData(r);return"tokenName"in o&&void 0!==o.tokenName?{token:o}:{blanketAccess:o}}async getModeratedTokens(e){const t=te,n=this.buildPaginationParams(e??{},In.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),o=this.extractData(r);return{items:o.tokens,pageInfo:o.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(se,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}class MA{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++}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=Kn(Math.floor(.5*e.length),0),n=Kn(Math.floor(.95*e.length),0),r=Kn(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 Kn(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=Kn(kn(this.startTime)/1e3,0);return 0===e?0:Kn(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&"function"==typeof process.memoryUsage){const e=Kn(process.memoryUsage().heapUsed/1024/1024,0);this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&"function"==typeof process.memoryUsage?Kn(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?Kn(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:Kn(t.cacheHits/n*100,0)}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:Kn(Wi(s,1),0),maxMB:o,percentUsed:Math.min(100,Kn(Wi(s/o*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.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?Kn(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:Kn(Wi(e,0),0),memoryUsedMB:Kn(Wi(this.getMemoryUsedMB(),1),0),throughputPerSecond:Kn(Wi(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 OA{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!ir(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=Gn(o,-1);return i<0?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(ar(e))return null;const t="number"==typeof e?e:Vn(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`${Wi(Hi(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class LA{constructor(e){this.logger=e??new gn({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(null!=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(null===t)return null;const n=e.Data,r=null==n||"object"!=typeof n||Array.isArray(n)?e:n,o=this.extractToken(r,"token0","fromToken","source"),i=this.extractToken(r,"token1","toToken","destination");if(null===o||null===i)return null;const s=this.extractAmount(r,"amount0","amountIn","inputAmount"),a=this.extractAmount(r,"amount1","amountOut","outputAmount");if(null===s||null===a)return null;const c=this.extractFeeTier(r);if(null===c)return null;const l=this.extractTimestamp(r),u=this.buildPoolKey(o,i,c),d=this.determineDirection(r,o,i),h={transactionId:t,poolKey:u,token0:o,token1:i,amount0:s,amount1:a,feeTier:c,direction:d,timestamp:l,exactInput:this.determineExactInput(r,d)},g=this.extractUser(r);return void 0!==g&&(h.user=g),h}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(ir(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(ir(t))return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(!ar(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(ar(e))return null;const t="number"==typeof e?e:Vn(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(ir(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(ps(r,"zerotoone")||"0to1"===r)return"zeroForOne";if(ps(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 o=this.extractAmount(e,"amount0","amountIn");return null!==o&&qn(o,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,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}`}}const UA=new Map;function FA(e,t){const n=e;return UA.set(n,{createdAt:Date.now(),label:t}),n}function $A(e){const t=e;UA.delete(t)}class qA{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,Hi(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])}}}qA.CACHE=new Map,qA.ZERO=Wn(0),qA.ONE=Wn(1),qA.FEE_PIPS=Wn(1e6),qA.MIN_SQRT_RATIO=Wn("4295128739"),qA.MAX_SQRT_RATIO=new o("1461446703485210103287273052203988822378723970342");const KA={maxIterations:100,enableBigNumberCache:!0,roundingMode:o.ROUND_DOWN,debugLogging:!1};class GA{static calculateSwapDelta(e,t,n={}){const r=Date.now(),o={...KA,...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 i=this.computeSwapLoop(n,e,t,o);o.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length,priceHitLimit:i.priceHitLimit});const s=this.createUpdatedPool(e.pool,i.state,t,o),a=this.calculateFinalAmounts(n,i.state,t);let c;if(void 0!==t.actualSqrtPrice&&""!==t.actualSqrtPrice){const e=Hi(s.sqrtPrice),n=Hi(t.actualSqrtPrice),r=e.minus(n).abs();c=Kn(cs(r,n).times(100).toNumber(),0)}const l=kn(r);o.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length}),i.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:i.stepCount}),i.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:i.stepCount,ticksCrossed:i.ticksCrossed.length});return{updatedPool:s,updatedTicks:i.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:i.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:i.stepCount,priceHitLimit:i.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${Tt(e)}`)}}static initializeSwapState(e,t,n){const{pool:r}=e;if(null===r.sqrtPrice||void 0===r.sqrtPrice||null===r.liquidity||void 0===r.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const o=n.enableBigNumberCache?qA.getCached.bind(qA):e=>Wn(e),i="string"==typeof r.sqrtPrice?r.sqrtPrice:Wi(r.sqrtPrice,0),a="string"==typeof r.liquidity?r.liquidity:Wi(r.liquidity,0),c=o(i),l=o(a),u=r.tick??0,d=s.sqrtPriceToTick(Hi(i)),h=Math.abs(d-u);h>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:u,calculatedTick:d,drift:h,threshold:100});const g=o(t.amountSpecified);as(g,"amountSpecified");const p="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:Wi(r.feeGrowthGlobal1,0),f="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:Wi(r.feeGrowthGlobal0,0),m=t.zeroForOne?o(p):o(f);return{sqrtPrice:c,liquidity:l,tick:u,amountSpecifiedRemaining:g,amountCalculated:qA.ZERO,feeGrowthGlobalX:m,protocolFee:qA.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:i,tickDataMap:a}=t,c=[],l={};let u=0;const d=n.zeroForOne?qA.MIN_SQRT_RATIO:qA.MAX_SQRT_RATIO,h=Hi("0.000001");for(;e.amountSpecifiedRemaining.gt(h)&&!e.sqrtPrice.eq(d)&&u<r.maxIterations;){u++;const[t,h]=this.findNextInitializedTick(a,e.tick,i.tickSpacing,n.zeroForOne);let g;if(r.debugLogging&&this.logger.debug(`Swap step ${u}`,{currentTick:e.tick,tickNext:t,initialized:h,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),h&&t>=-887272&&t<=887272){const e=s.tickToSqrtPrice(t);g=e instanceof o?e:Hi(String(e))}else g=d;const p=n.zeroForOne?Zi(g,d):Ji(g,d),f=this.executeSwapStep(e.sqrtPrice,p,e.liquidity,e.amountSpecifiedRemaining,i.fee,n.exactInput);if(e.sqrtPrice=f.sqrtPriceNext,n.exactInput){const t=f.amountIn.plus(f.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=qA.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=qA.ZERO)),e.amountCalculated=e.amountCalculated.minus(f.amountOut)}else{f.amountOut.lte(0)?e.amountSpecifiedRemaining=qA.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(f.amountOut),e.amountCalculated=e.amountCalculated.plus(f.amountIn.plus(f.feeAmount))}if(e.liquidity.gt(0)){const t=cs(f.feeAmount,e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(g)&&h){const o=a[t.toString()];if(null==o)throw new Error(`Missing tick data for initialized tick ${t}`);const i=n.zeroForOne?Hi(o.liquidityNet).negated():Hi(o.liquidityNet);if(e.liquidity=e.liquidity.plus(i),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);c.push(t),l[t.toString()]=o,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:i.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(g))e.tick=n.zeroForOne?t-1:t;else{const t=s.sqrtPriceToTick(Hi(e.sqrtPrice.toString()));e.tick=t}}if(u>=r.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${r.maxIterations}). Possible infinite loop or very complex swap.`);const g=e.sqrtPrice.eq(d);return{state:e,ticksCrossed:c,priceHitLimit:g,stepCount:u,updatedTicks:l}}static createUpdatedPool(e,t,n,r){const o=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(o.sqrtPrice=Hi(t.sqrtPrice).toFixed(0),o.liquidity=Hi(t.liquidity).toFixed(0),o.tick=t.tick,n.zeroForOne?o.feeGrowthGlobal1=Hi(t.feeGrowthGlobalX).toFixed(0):o.feeGrowthGlobal0=Hi(t.feeGrowthGlobalX).toFixed(0),n.zeroForOne){const n=Hi(e.protocolFeesToken0);o.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=Hi(e.protocolFeesToken1);o.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return o}static calculateFinalAmounts(e,t,n){let r,o,i,s;if(n.exactInput){const e=Hi(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),o=a,i=qA.ZERO,s=qA.ZERO):(r=a,o=e.negated(),i=qA.ZERO,s=qA.ZERO)}else{const e=Hi(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),o=e,i=qA.ZERO,s=qA.ZERO):(r=e,o=a.negated(),i=qA.ZERO,s=qA.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:i=a,{amount0:r,amount1:o,feeAmount0:i,feeAmount1:s}}static findNextInitializedTick(e,t,n,r){const o=Object.keys(e).map(e=>Hn(e,0)).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,i,a){ss(n),as(r,"amountRemaining");const c=[500,3e3,1e4];if(!c.includes(i))throw new Error(`Invalid fee tier: ${i}. Must be one of: ${c.join(", ")}`);const l=s.computeSwapStep(e,t,n,r,i,t.lt(e)),u=l[0],d=l[1],h=l[2],g=l[3],p=o.isBigNumber(u)?u:Hi(String(u)),f=o.isBigNumber(d)?d:Hi(String(d)),m=o.isBigNumber(h)?h:Hi(String(h)),y=o.isBigNumber(g)?g:Hi(String(g));return{sqrtPriceStart:e,tickNext:s.sqrtPriceToTick(p),sqrtPriceNext:p,initialised:!1,amountIn:f,amountOut:m,feeAmount:y}}}GA.logger=new gn({debug:!1,context:"SwapDeltaCalculator"});class HA extends Sr{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,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},l=GA.calculateSwapDelta(i.poolData,c);i.poolData={...i.poolData,pool:l.updatedPool},i.swapsSinceRefetch++,i.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(i.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${i.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.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(""===e)throw Ut("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await Rs(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(0===e.length)throw Ut("poolKeys","Pool keys array");return Rs(async()=>{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},"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=>{null!=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 WA extends Sr{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()};void 0!==e&&e>0&&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(kn(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=kn(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class zA extends Sr{constructor(e,t,n,r={},o){super(!1,o),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 MA,this.config=this.applyDefaults(r),this.eventExtractor=new LA(this.logger),this.cacheManager=new HA(t,this.config,this.metrics,this.logger),this.eventQueue=new WA(this.config,this.metrics,this.logger),this.seenTransactions=new VA(this.maxSeenTransactions),this.reconnectionManager=new JS({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()=>{if(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)try{n.unsubscribe()}catch(e){n.logger.error("Error during unsubscribe cleanup:",e)}}}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.reconnectionManager.getAttempts()};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(null!==this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=FA(setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),"background-warming"),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){null!==this.warmingIntervalHandle&&($A(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.socketReady.catch(()=>{}),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(Et(e)?e:new Error(Tt(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 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}}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(),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=kn(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(Et(e)?e:new Error(Tt(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")}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(void 0!==t.tokenFilter&&""!==t.tokenFilter){if(!OA.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!OA.containsTokenPair(e.poolKey,n,r))return!1}if(void 0!==t.feeTierFilter&&""!==t.feeTierFilter){if(OA.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return void 0===t.userFilter||""===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=kn(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(Et(t)?t:new Error(Tt(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 VA{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}}const jA={COLLECTION_CLAIM_FEE:"10000",TOKEN_CLASS_CREATE_FEE:"1000",DESCRIPTIONS:{COLLECTION_CLAIM:"10,000 GALA to claim a collection name",TOKEN_CLASS_CREATE:"1,000 GALA to create a token class",MINT:"Dynamic fee estimated via DryRun endpoint"}};function XA(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function QA(){return Date.now()+6e4}function YA(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function JA(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function ZA(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class eE extends vr{constructor(e){super(e)}getCollectionClaimFee(){return jA.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return jA.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for mint fee estimation");if(!ZA(e.ownerAddress))throw new Error(`Invalid owner address format: ${e.ownerAddress}`);const t="0";return this.logger.debug("Estimated mint fee:",t),t}catch(e){throw this.logger.error("Failed to estimate mint fee",e),e}}estimateNftOperationFees(e){let t="0";const n={};if(e.claimCollection){const e=jA.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=jA.TOKEN_CLASS_CREATE_FEE,o=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(o))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!YA(e.collectionName))throw new Error(`Invalid collection name format. Must be alphanumeric, 3-50 characters: ${e.collectionName}`);if(!await this.isCollectionAvailable(e.collectionName))throw new Error(`Collection name already claimed: ${e.collectionName}`);const t={collectionName:e.collectionName,expiresAt:QA(),uniqueKey:XA("auth")};this.logger.debug("Built claim DTO",t);return{transactionId:`claim-${Date.now()}`,collection:e.collectionName,authorizedUser:"",status:"pending"}}catch(e){throw this.logger.error("Failed to claim collection",e),e}}async fetchUserCollections(e){try{if(this.logger.debug("Fetching user collections for",e),!ZA(e))throw new Error(`Invalid wallet address format: ${e}`);const t=[];return this.logger.debug(`Found ${t.length} collections for user`),t}catch(e){throw this.logger.error("Failed to fetch user collections",e),e}}async isCollectionAvailable(e){try{if(this.logger.debug("Checking collection availability",e),!YA(e))throw new Error(`Invalid collection name format: ${e}`);const t=!0;return this.logger.debug(`Collection ${e} available:`,t),t}catch(e){throw this.logger.error("Failed to check collection availability",e),e}}async createTokenClass(e){try{if(this.logger.debug("Creating NFT token class",e),null==e.collection||0===e.collection.length||null==e.type||0===e.type.length||null==e.category||0===e.category.length)throw new Error("Missing required parameters: collection, type, category");if(!YA(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);if(void 0!==e.symbol&&(""===(t=e.symbol)||"string"!=typeof t||!/^[a-zA-Z]{1,8}$/.test(t)))throw new Error(`Invalid token symbol: ${e.symbol}`);const n={collection:e.collection,type:e.type,category:e.category,name:e.name,description:e.description,image:e.image,symbol:e.symbol,rarity:e.rarity,maxSupply:void 0!==e.maxSupply?JA(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?JA(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:QA(),uniqueKey:XA("create")};this.logger.debug("Built token class DTO",n);return{transactionId:`create-${Date.now()}`,tokenClass:{collection:e.collection,type:e.type,category:e.category,additionalKey:e.additionalKey??""},status:"pending"}}catch(e){throw this.logger.error("Failed to create token class",e),e}var t}async fetchTokenClasses(e){try{if(this.logger.debug("Fetching token classes",e),!YA(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);const t=[];return this.logger.debug(`Found ${t.length} token classes`),t}catch(e){throw this.logger.error("Failed to fetch token classes",e),e}}async mintNft(e){try{if(this.logger.debug("Minting NFT",e),0===e.collection.length||0===e.type.length||0===e.category.length||0===e.quantity.length)throw new Error("Missing required parameters for minting");const t=parseInt(e.quantity,10);if(t<=0)throw new Error("Quantity must be greater than 0");if(!ZA(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const r={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:QA(),uniqueKey:XA("mint")};this.logger.debug("Built mint DTO",r);const o=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:o,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!ZA(e))throw new Error(`Invalid owner address: ${e}`);const n=[];return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}}class tE extends vr{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(tt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),r=this.extractData(n);return this.logger.debug("Push token registered",{registered:r.registered}),r}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:nt,data:{token:e},headers:t}),r=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:r.unregistered}),r}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(rt,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(ot,e,t),r=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:r.tradesEnabled,streamsEnabled:r.streamsEnabled}),{preferences:r}}}class nE extends vr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(y.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(y.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new ht("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=y.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:r.title}),{oembed:r}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new ht("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=y.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:r}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new ht("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=y.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:r.title}),{oembed:r}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new ht("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=y.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),r=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:r}}}function rE(e){if(!ir(e))throw Ut("address","Address")}const oE={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},iE={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},sE=lr(oE),aE=lr(iE);function cE(e){try{yr(e.description,"description",255)}catch(e){if(e instanceof ht){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(!ir(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{wr(e.expiresAt,"expiresAt")}catch(e){if(e instanceof ht)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(bn(e.expiresAt)){if(wn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function lE(e){if(void 0!==e.status&&!sE(e.status))throw Qt("status",e.status,Object.values(oE),"status");cr(0,void 0,50,e.pageSize,e.cursor)}function uE(e){if(void 0!==e.status&&!aE(e.status))throw Qt("status",e.status,Object.values(iE),"status");cr(0,void 0,50,e.pageSize,e.cursor)}function dE(e){if(!ir(e))throw new Error("Invite code must be a non-empty string");Jn(e,100,"code")}function hE(e){if(!ir(e))throw new Error("Address must be a non-empty string");try{Mr(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function gE(e){try{Zn(e,"id")}catch(e){if(e instanceof ht)throw new Error("Invite ID must be a positive integer");throw e}}function pE(e){if(null==e||"object"!=typeof e)throw new ht("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new ht("Search must be a string");if(0===e.search.length)throw new ht("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new ht("Sort field must be a string");if(0===e.sortBy.length)throw new ht("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new ht('Sort order must be "asc" or "desc"')}function fE(e){if(null==e||"object"!=typeof e)throw new ht("Options are required");if(!ir(e.userAddress))throw new ht("userAddress is required and must be a non-empty string");try{Mr(e.userAddress,"userAddress")}catch{throw new ht("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new ht("description must be a string");if(e.description.length>255)throw new ht("description must be at most 255 characters")}}class mE extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}validateInviteCodeFormat(e){if(!ir(e))throw Ut("inviteCode","Invite code");dE(e)}validateWalletAddressFormat(e){if(!ir(e))throw Ut("address","Address");hE(e)}async createInvite(e={}){cE(e),this.validateOptionalString(e.description,"description","Description",Nn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=ce,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e={}){lE(e),this.validateStatusFilter(e.status,oE);const t=le,n={...this.buildPaginationParams(e,In.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),o=this.extractData(r);return{items:o.invites,pageInfo:o.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(ue,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){gE(e);const t=this.buildEndpoint(he,{id:String(e)});tn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=de,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){uE(e),this.validateStatusFilter(e.status,iE);const t=ge,n={...this.buildPaginationParams(e,In.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),o=this.extractData(r);return{items:o.overseers,pageInfo:o.pageInfo}}async createOverseerDirect(e){fE(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Nn.DESCRIPTION.MAX_LENGTH);const t=pe,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(fe,{address:e});tn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=me,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=ye,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=we,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=be,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=ve,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Se,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&pE(t);const n=Ae,r=this.buildPaginationParams(t,In.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const o=await this.http.get(n,r,this.getDualAuthHeaders()),i=this.extractData(o);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!ir(e))throw Ut("address","User address");hE(e);const t=this.buildEndpoint(Ee,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){rE(e);const t=this.buildEndpoint(Te,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!ir(e))throw Ut("tokenName","Token name")}(e);const t=this.buildEndpoint(Ie,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new ht("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ce,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){rE(e);const t=this.buildEndpoint(xe,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Ne,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function yE(e){const t=[];return 0===Object.keys(e).length&&t.push("At least one field (streamingEnabled, chatEnabled, commentsEnabled, webhooksEnabled, aiModerationEnabled) must be provided"),void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled&&t.push("streamingEnabled must be a boolean"),void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled&&t.push("chatEnabled must be a boolean"),void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled&&t.push("commentsEnabled must be a boolean"),void 0!==e.webhooksEnabled&&"boolean"!=typeof e.webhooksEnabled&&t.push("webhooksEnabled must be a boolean"),void 0!==e.aiModerationEnabled&&"boolean"!=typeof e.aiModerationEnabled&&t.push("aiModerationEnabled must be a boolean"),t}class wE extends vr{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:"success"in e?!e.success:!("data"in e),data:e.data};return void 0!==e.message&&(t.message=e.message),tn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(P);return this.extractData(e)}async updatePlatformConfig(e){const t=yE(e);if(t.length>0)throw new ht(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(R,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(O);return this.extractData(e)}}class bE extends vr{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(Xe),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class kE extends vr{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw Ut("tokenName","Token name");if(!this.tokenResolverService)throw qt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{hr(e)}catch(e){throw qt(Tt(e),"tokenName")}this.logger.debug(`Resolving token name '${e}' to token class key`);try{const t=await this.tokenResolverService.resolveTokenToVault(e);if(null==t)throw qt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=qs(Ev(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(Et(t)&&Tt(t).includes("ConfigurationError"))throw t;throw $t(`Failed to resolve token name '${e}': ${Tt(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw Ut("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Rs(async()=>{let t=e.tokenId;if(null!=e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(null==t)throw qt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return xv}),r=Gv(qs(n(t))),{from:o,to:i,sortOrder:s="DESC"}=e,a=Kn(e.offset,0),c=Kn(e.limit,10),l={token:r,skip:String(a),take:String(c)};o&&(l.from=o.toISOString()),i&&(l.to=i.toISOString());const u=function(e){if(null!=e)return e.toLowerCase()}(s);null!=u&&(l.order=u),this.logger.debug(`Querying price snapshots for token ${r}, offset ${a}, limit ${c}`);const d=await this.http.get("/price-oracle/fetch-price",l);if(null==d)throw $t("No response from price history service",500);const h=this.transformApiResponseToPriceHistory(d);return this.logger.debug(`Found ${h.snapshots.length} price snapshots, total ${h.total}`),h},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e){if(!en(e))throw $t("Invalid API response: missing data wrapper",500);const t=nn(e);if(!t||"object"!=typeof t)throw $t("Invalid API response: data is not an object",500);const n=t,r=n.data;if(!Array.isArray(r))throw $t("Invalid API response: missing or invalid data.data array",500);const o=n.meta;if(null==o||"object"!=typeof o)throw $t("Invalid API response: missing data.meta pagination info",500);const i=o,s=r.map(e=>{if("object"!=typeof e||null===e)throw $t("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:wn(t.createdAt),tokenId:qs({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=Gn(i.currentPage,1),c=Gn(i.totalPages,1);return{snapshots:s,page:a,limit:Gn(i.pageSize,50),total:Gn(i.totalItems,0),totalPages:c,hasNext:a<c,hasPrevious:a>1}}async fetchAllPriceHistory(e){if(null==e)throw Ut("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Rs(async()=>{const t=await Sv((t,n)=>this.fetchPriceHistory({...e,offset:t,limit:n}).then(e=>({items:e.snapshots,page:e.page,limit:e.limit,total:e.total,totalPages:e.totalPages,hasNext:e.hasNext,hasPrevious:e.hasPrevious})),{maxPages:1e4,logger:this.logger,pageSize:50,startPage:0});return function(e,t=e.length,n="items"){const r=e.length;return{offset:0,limit:r,total:t,totalPages:0!==r?Yk(t,r):void 0,hasNext:!1,hasPrevious:!1,[n]:e}}(t.items,t.total,"snapshots")},"Failed to fetch all price history",this.logger)}validateOptions(e){const{from:t,to:n,sortOrder:r}=e;if(dr(e,"tokenName","tokenId",{description:"token identifier"}),t&&!bn(t))throw qt("from must be a valid Date","from");if(n&&!bn(n))throw qt("to must be a valid Date","to");null!=r&&nr(r,"sortOrder"),cr(0,void 0,50,e.pageSize)}}class vE extends tv{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Ue)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!ir(e.content))throw new ht("Content is required");return{success:!0,data:(await this.http.put(Fe,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}vn.MIN_LENGTH,vn.MAX_LENGTH,vn.PATTERN;lr({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function SE(e){return"global"===e||"token"===e}function AE(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.tokenName&&"string"==typeof t.createdAt}function EE(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}const TE=lr({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function IE(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}class CE extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async getChatStatus(e){if(null==e||""===e)throw Ut("tokenName","Token name");return this.validateTokenName(e,vn),Rs(async()=>{const t=this.buildEndpoint($e,{tokenName:e}),n=await this.http.get(t),r=this.extractData(n),o={enabled:r.enabled,tokenName:r.tokenName??ln(e)};return void 0!==r.status&&null!==r.status&&(o.status=r.status),o},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Ut("tokenName","Token name");return this.validateTokenName(e,vn),Rs(async()=>{const t=this.buildEndpoint(Ke,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders()),r=this.extractData(n),o={enabled:r.enabled,tokenName:r.tokenName??ln(e)};return void 0!==r.status&&null!==r.status&&(o.status=r.status),o},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Ut("tokenName","Token name");return this.validateTokenName(e,vn),Rs(async()=>{const t=this.buildEndpoint(qe,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders()),r=this.extractData(n),o={enabled:r.enabled,tokenName:r.tokenName??ln(e)};return void 0!==r.status&&null!==r.status&&(o.status=r.status),o},`Failed to enable chat for token: ${e}`,this.logger)}async setSlowMode(e,t){if(null==e||""===e)throw Ut("tokenName","Token name");if(this.validateTokenName(e,vn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Rs(async()=>{const n=this.buildEndpoint(ze,{tokenName:e}),r=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(r)},`Failed to set slow mode for token: ${e}`,this.logger)}async getGlobalChatStatus(){const e=await this.http.get(Ge);return this.extractData(e)}async disableGlobalChat(){const e=await this.http.post(We,{enabled:!1},this.getAdminHeaders());return this.extractData(e)}async enableGlobalChat(){const e=await this.http.post(He,{enabled:!0},this.getAdminHeaders());return this.extractData(e)}async setGlobalChatEnabled(e){return e?this.enableGlobalChat():this.disableGlobalChat()}async getEngagementStats(e){if(null==e)throw Ut("options","Engagement stats options");return function(e){if(!ir(e.tokenName))throw Ut("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw Ut("tokenName","Token name");if(!vn.PATTERN.test(t))throw Ft("tokenName",`match pattern ${String(vn.PATTERN)}`,"Token name")}(e),Rs(async()=>{const t=this.buildEndpoint(Ve,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),r=this.extractData(n);return{tokenName:ln(e.tokenName),chat:r.chat,comments:r.comments}},"Failed to get engagement stats",this.logger)}}class xE extends Sr{constructor(e=!1){super(e),this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.logger.debug("📡 [Events] Socket cleared from StreamingEventService")}createEmptyRegistry(){return{stream_status:new Set,user_banned:new Set,user_unbanned:new Set,ban_enforcement:new Set,content_flagged:new Set,flag_resolved:new Set,stream_chat_message:new Set,stream_chat_updated:new Set,stream_chat_deleted:new Set,stream_chat_pinned:new Set,stream_chat_unpinned:new Set,chat_status_changed:new Set,viewer_count:new Set,recording_status:new Set,simulcast_status:new Set,download_ready:new Set,recordings_count_updated:new Set,user_typing:new Set,stream_reaction:new Set,content_reaction_added:new Set,content_reaction_removed:new Set,stream_countdown_updated:new Set,stream_language_updated:new Set,stream_control_status_changed:new Set,connection:new Set,authenticated:new Set,token_subscribed:new Set,token_unsubscribed:new Set,room_subscribed:new Set,room_left:new Set}}registerCallback(e,t){const n=this.eventRegistry[e];return n.add(t),()=>{n.delete(t)}}async emitEvent(e,t){const n=this.eventRegistry[e];if(0!==n.size)for(const r of n)try{const e=r(t);e instanceof Promise&&await e}catch(t){this.logger.error(`Error in ${e} callback:`,t instanceof Error?t.message:String(t))}}onStreamStatusChanged(e){return this.registerCallback("stream_status",e)}onUserBanned(e){return this.registerCallback("user_banned",e)}onUserUnbanned(e){return this.registerCallback("user_unbanned",e)}onBanEnforcement(e){return this.registerCallback("ban_enforcement",e)}onContentFlagged(e){return this.registerCallback("content_flagged",e)}onFlagResolved(e){return this.registerCallback("flag_resolved",e)}onStreamChatMessage(e){return this.registerCallback("stream_chat_message",e)}onStreamChatUpdated(e){return this.registerCallback("stream_chat_updated",e)}onStreamChatDeleted(e){return this.registerCallback("stream_chat_deleted",e)}onStreamChatPinned(e){return this.registerCallback("stream_chat_pinned",e)}onStreamChatUnpinned(e){return this.registerCallback("stream_chat_unpinned",e)}onChatStatusChanged(e){return this.registerCallback("chat_status_changed",e)}onViewerCountChanged(e){return this.registerCallback("viewer_count",e)}onRecordingStatusChanged(e){return this.registerCallback("recording_status",e)}onSimulcastStatusChanged(e){return this.registerCallback("simulcast_status",e)}onDownloadReady(e){return this.registerCallback("download_ready",e)}onRecordingsCountUpdated(e){return this.registerCallback("recordings_count_updated",e)}onUserTyping(e){return this.registerCallback("user_typing",e)}onStreamReaction(e){return this.registerCallback("stream_reaction",e)}onContentReactionAdded(e){return this.registerCallback("content_reaction_added",e)}onContentReactionRemoved(e){return this.registerCallback("content_reaction_removed",e)}onStreamCountdownUpdated(e){return this.registerCallback("stream_countdown_updated",e)}onStreamLanguageUpdated(e){return this.registerCallback("stream_language_updated",e)}onStreamControlStatusChanged(e){return this.registerCallback("stream_control_status_changed",e)}onConnection(e){return this.registerCallback("connection",e)}onAuthenticated(e){return this.registerCallback("authenticated",e)}onTokenSubscribed(e){return this.registerCallback("token_subscribed",e)}onTokenUnsubscribed(e){return this.registerCallback("token_unsubscribed",e)}onRoomSubscribed(e){return this.registerCallback("room_subscribed",e)}onRoomLeft(e){return this.registerCallback("room_left",e)}async emitStreamStatusChanged(e){await this.emitEvent("stream_status",e)}async emitUserBanned(e){await this.emitEvent("user_banned",e)}async emitUserUnbanned(e){await this.emitEvent("user_unbanned",e)}async emitBanEnforcement(e){await this.emitEvent("ban_enforcement",e)}async emitContentFlagged(e){await this.emitEvent("content_flagged",e)}async emitFlagResolved(e){await this.emitEvent("flag_resolved",e)}async emitStreamChatMessage(e){await this.emitEvent("stream_chat_message",e)}async emitStreamChatUpdated(e){await this.emitEvent("stream_chat_updated",e)}async emitStreamChatDeleted(e){await this.emitEvent("stream_chat_deleted",e)}async emitStreamChatPinned(e){await this.emitEvent("stream_chat_pinned",e)}async emitStreamChatUnpinned(e){await this.emitEvent("stream_chat_unpinned",e)}async emitChatStatusChanged(e){await this.emitEvent("chat_status_changed",e)}async emitViewerCountChanged(e){await this.emitEvent("viewer_count",e)}async emitRecordingStatusChanged(e){await this.emitEvent("recording_status",e)}async emitSimulcastStatusChanged(e){await this.emitEvent("simulcast_status",e)}async emitDownloadReady(e){await this.emitEvent("download_ready",e)}async emitRecordingsCountUpdated(e){await this.emitEvent("recordings_count_updated",e)}async emitUserTyping(e){await this.emitEvent("user_typing",e)}async emitStreamReaction(e){await this.emitEvent("stream_reaction",e)}async emitContentReactionAdded(e){await this.emitEvent("content_reaction_added",e)}async emitContentReactionRemoved(e){await this.emitEvent("content_reaction_removed",e)}async emitStreamCountdownUpdated(e){await this.emitEvent("stream_countdown_updated",e)}async emitStreamLanguageUpdated(e){await this.emitEvent("stream_language_updated",e)}async emitStreamControlStatusChanged(e){await this.emitEvent("stream_control_status_changed",e)}async emitConnection(e){await this.emitEvent("connection",e)}async emitAuthenticated(e){await this.emitEvent("authenticated",e)}async emitTokenSubscribed(e){await this.emitEvent("token_subscribed",e)}async emitTokenUnsubscribed(e){await this.emitEvent("token_unsubscribed",e)}async emitRoomSubscribed(e){await this.emitEvent("room_subscribed",e)}async emitRoomLeft(e){await this.emitEvent("room_left",e)}}const NE={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},_E={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},DE={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},PE=lr(NE),RE=lr(_E),BE=lr(DE);const ME={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},OE={OWNER:"OWNER",MODERATOR:"MODERATOR"};lr(ME),lr(OE);const LE={...ME,OVERSEER:"OVERSEER"},UE={OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"};function FE(e){if(null==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 $E=lr(LE),qE=lr(UE);function KE(e,t="tokenName"){hr(e,t,vn)}function GE(e){if(KE(e.tokenName),!ir(e.language))throw Ut("language");if(t=e.language,!ir(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new ht('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",dt.INVALID_FORMAT);var t}class HE extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async startStream(e){this.validateTokenName(e,vn);const t=this.buildEndpoint(v,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,vn);const t=this.buildEndpoint(S,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,A,vn)}async enableStream(e){return this.toggleFeature(e,E,vn)}async resetStreamKey(e){this.validateTokenName(e,vn);const t=this.buildEndpoint(T,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,vn);const t=this.buildEndpoint(U,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){KE(e.tokenName),cr(0,void 0,On,e.pageSize)}(e);const t=this.buildEndpoint(I,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,On),r=e.offset;"number"==typeof r&&(n.offset=String(r));const o=await this.http.get(t,n),i=this.extractData(o),s=e,a=i.pageSize??i.limit??e.pageSize??("number"==typeof s.limit?s.limit:20),c="number"==typeof s.offset?s.offset:0,l=Math.floor(c/a)+1;return{recordings:i.recordings,tokenName:ln(e.tokenName),page:i.page??l,limit:a,total:i.total,hasNext:i.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,vn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(C,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,vn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(x,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,vn);const t=this.buildEndpoint(N,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(KE(e.tokenName),!ir(e.platform))throw Ut("platform");if(!BE(e.platform))throw new ht("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",dt.INVALID_VALUE);if(!ir(e.rtmpUrl))throw Ut("rtmpUrl");if(!Mn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new ht("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",dt.INVALID_FORMAT);if(!ir(e.streamKey))throw Ut("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new ht("name must be a string","name",dt.INVALID_TYPE)}(e);const t=this.buildEndpoint(_,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,rtmpUrl:e.rtmpUrl,streamKey:e.streamKey,name:e.name},this.getJwtHeaders());return this.extractData(n)}async removeSimulcastTarget(e,t){this.validateTokenName(e,vn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(D,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(P);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(R,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(B,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(KE(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||ir(e.nextLiveStreamAt)))throw new ht("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",dt.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new ht("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",dt.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(n,{nextLiveStreamAt:t},this.getJwtHeaders())}async clearNextLiveStream(e){this.validateTokenName(e,vn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){GE(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){KE(e.tokenName)}(e);const t=this.buildEndpoint(M,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},r=await this.http.get(t,{},n);return this.extractData(r)}async getAvailableRoles(){const e=await this.http.get(O);return this.extractData(e)}async getTokenAccess(e){!function(e){KE(e.tokenName)}(e);const t=this.buildEndpoint(L,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{};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})}}const WE={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"send_stream_reaction",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"STREAM_STATUS",RECORDING_STATUS:"RECORDING_STATUS",RECORDINGS_COUNT_UPDATED:"RECORDINGS_COUNT_UPDATED",SIMULCAST_STATUS:"SIMULCAST_STATUS",DOWNLOAD_READY:"DOWNLOAD_READY",STREAM_COUNTDOWN_UPDATED:"STREAM_COUNTDOWN_UPDATED",STREAM_LANGUAGE_UPDATED:"STREAM_LANGUAGE_UPDATED",VIEWER_COUNT:"VIEWER_COUNT",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",STREAM_GLOBAL_STATUS:"STREAM_GLOBAL_STATUS",ENGAGEMENT_STATS_UPDATED:"ENGAGEMENT_STATS_UPDATED",CHAT_MESSAGE:"STREAM_CHAT_MESSAGE",CHAT_SENT:"STREAM_CHAT_SENT",CHAT_UPDATED:"STREAM_CHAT_UPDATED",CHAT_DELETED:"STREAM_CHAT_DELETED",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"CHAT_STATUS_CHANGED",CHAT_GLOBAL_STATUS:"STREAM_CHAT_GLOBAL_STATUS",CHAT_AUTHENTICATED:"authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",STREAM_CONTROL_STATUS_CHANGED:"STREAM_CONTROL_STATUS_CHANGED",REACTION:"STREAM_REACTION",CONTENT_REACTION_ADDED:"CONTENT_REACTION_ADDED",CONTENT_REACTION_REMOVED:"CONTENT_REACTION_REMOVED",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"USER_TYPING",CHAT_PINNED:"STREAM_CHAT_PINNED",CHAT_UNPINNED:"STREAM_CHAT_UNPINNED",COMMENT_CREATED:"COMMENT_CREATED",COMMENT_UPDATED:"COMMENT_UPDATED",COMMENT_DELETED:"COMMENT_DELETED",USER_BANNED:"USER_BANNED",USER_UNBANNED:"USER_UNBANNED",BAN_ENFORCEMENT:"BAN_ENFORCEMENT",TOKEN_BANNED:"TOKEN_BANNED",TOKEN_UNBANNED:"TOKEN_UNBANNED",CONTENT_FLAGGED:"CONTENT_FLAGGED",FLAG_RESOLVED:"FLAG_RESOLVED",MODERATOR_INVITE_CREATED:"MODERATOR_INVITE_CREATED",MODERATOR_ADDED:"MODERATOR_ADDED",MODERATOR_REMOVED:"MODERATOR_REMOVED",MODERATOR_ROLE_UPDATED:"MODERATOR_ROLE_UPDATED",OVERSEER_ADDED:"OVERSEER_ADDED",OVERSEER_REMOVED:"OVERSEER_REMOVED",TRADE_EXECUTED:"TRADE_EXECUTED",BALANCE_UPDATED:"BALANCE_UPDATED",STATS_UPDATED:"STATS_UPDATED",POOL_METADATA_UPDATED:"POOL_METADATA_UPDATED",POOL_SOCIAL_LINKS_UPDATED:"POOL_SOCIAL_LINKS_UPDATED",POOL_BADGE_ASSIGNED:"POOL_BADGE_ASSIGNED",HOLDER_COUNT_UPDATED:"HOLDER_COUNT_UPDATED",USER_PROFILE_UPDATED:"USER_PROFILE_UPDATED",API_KEY_CREATED:"API_KEY_CREATED",API_KEY_UPDATED:"API_KEY_UPDATED",API_KEY_REVOKED:"API_KEY_REVOKED",TOKEN_CONFIG_UPDATED:"TOKEN_CONFIG_UPDATED",SITE_CONFIG_CHANGED:"SITE_CONFIG_CHANGED",COMMENTS_GLOBAL_STATUS:"COMMENTS_GLOBAL_STATUS",WEBHOOKS_GLOBAL_STATUS:"WEBHOOKS_GLOBAL_STATUS",SUBSCRIBE_GLOBAL_FEED:"subscribe_global_feed",UNSUBSCRIBE_GLOBAL_FEED:"unsubscribe_global_feed",GLOBAL_FEED_SUBSCRIBED:"global_feed_subscribed",GLOBAL_FEED_UNSUBSCRIBED:"global_feed_unsubscribed"};class zE extends Sr{constructor(e,t=!1){if(super(t),this.socket=null,this.isAuthenticated=!1,this.subscribedRooms=new Map,this.roomCallbacks=new Map,this.pendingSubscriptions=new Map,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=100,this.BUFFER_CLEANUP_MS=3e4,this.globalCallbacks={},this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription=null,""===e.url)throw new ft("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 JS({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:",Tt(e)),!1}}getRoomName(e){return`token:${ln(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let o=this.eventBuffer.get(r);o||(o=[],this.eventBuffer.set(r,o)),o.length>=this.MAX_BUFFER_SIZE&&(o.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),o.push(n);const i=this.eventBufferTimeouts.get(r);i&&clearTimeout(i);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=ln(e),r=[{key:`${WE.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${WE.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${WE.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${WE.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${WE.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${WE.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${WE.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${WE.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${WE.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${WE.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${WE.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${WE.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${WE.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${WE.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${WE.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${WE.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${WE.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${WE.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${WE.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${WE.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${WE.COMMENT_CREATED}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of r){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const r of n)try{t?.(r)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const r=this.eventBufferTimeouts.get(e);r&&(clearTimeout(r),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(WE.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(WE.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStreamStatus&&this.globalFeedCallbacks.onStreamStatus(e)}),this.socket.on(WE.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=ln(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const r=this.roomCallbacks.get(t);r?.onStreamSubscribed&&r.onStreamSubscribed(e)}),this.socket.on(WE.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(ln(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(WE.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(WE.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onViewerCount&&this.globalFeedCallbacks.onViewerCount(e)}),this.socket.on(WE.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(WE.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(WE.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(WE.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(WE.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(WE.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(WE.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(WE.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(WE.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(WE.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(WE.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(WE.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(WE.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(ln(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(WE.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(WE.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(WE.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(WE.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(WE.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(WE.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(ln(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(WE.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(WE.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(WE.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(WE.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(WE.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(WE.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(WE.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(WE.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(WE.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(WE.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(WE.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(WE.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(WE.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(WE.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(WE.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(WE.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(WE.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(WE.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(WE.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(WE.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(WE.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(WE.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(WE.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(WE.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(WE.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(WE.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(WE.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(WE.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(WE.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(WE.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(WE.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(WE.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(WE.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(WE.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(WE.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(WE.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(WE.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(WE.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onStatsUpdated&&t.onStatsUpdated(e),this.globalCallbacks.onStatsUpdated&&this.globalCallbacks.onStatsUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onStatsUpdated&&this.globalFeedCallbacks.onStatsUpdated(e)}),this.socket.on(WE.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(WE.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(ln(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(WE.GLOBAL_FEED_SUBSCRIBED,e=>{if(this.logger.debug("📡 [Global Feed Subscribed]"),this.isGlobalFeedSubscribed=!0,this.pendingGlobalFeedSubscription){const{resolve:t,timeoutId:n}=this.pendingGlobalFeedSubscription;clearTimeout(n),this.pendingGlobalFeedSubscription=null,t(e)}this.globalFeedCallbacks.onGlobalFeedSubscribed&&this.globalFeedCallbacks.onGlobalFeedSubscribed(e)}),this.socket.on(WE.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(WE.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(WE.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(WE.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(WE.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(WE.WEBHOOKS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Webhooks Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onWebhooksGlobalStatus&&this.globalFeedCallbacks.onWebhooksGlobalStatus(e)}))}resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(WE.SUBSCRIBE,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}if(this.isGlobalFeedSubscribed)try{this.logger.debug("📡 Re-subscribing to global feed after reconnect"),this.socket?.emit(WE.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{Rs(async()=>{if(!this.isSocketIOAvailable)throw new ft('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};return""!==this.config.authToken&&(n.token=this.config.authToken),this.socket=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: ${String(this.socket?.id)}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")}),Promise.resolve(void 0)},"Stream WebSocket connection setup",this.logger,e=>{throw t(e),e})})}authenticate(e){if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw Ut("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(WE.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw Ut("tokenName","Token name");if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=ln(e);return this.subscribedRooms.has(n)?(this.logger.debug(`📡 Already subscribed to ${n}, updating callbacks`),this.roomCallbacks.set(n,t),this.processBufferedEvents(n,t),{tokenName:n,room:this.getRoomName(e)}):new Promise((r,o)=>{const i=setTimeout(()=>{this.pendingSubscriptions.delete(n),o(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:r,reject:o,timeoutId:i}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(WE.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=ln(e);if(!this.subscribedRooms.has(t))return void this.logger.debug(`📡 Not subscribed to ${t}, skipping unsubscribe`);this.logger.debug(`📡 Unsubscribing from stream: ${t}`),this.socket?.connected&&this.socket.emit(WE.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 Ut("tokenName","Token name");if(""===t)throw Ut("content","Message content");if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new ht("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=ln(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(WE.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw Ut("tokenName","Token name");if(""===t)throw Ut("emoji");if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new ht("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=ln(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(WE.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){if(""===e)throw Ut("tokenName","Token name");if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new ht("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=ln(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(WE.TYPING_START,{tokenName:t})}sendTypingStop(e){if(""===e)throw Ut("tokenName","Token name");if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new ht("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=ln(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(WE.TYPING_STOP,{tokenName:t})}subscribeTokenBanned(e,t){const n=ln(e),r={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onTokenBanned:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeTokenUnbanned(e,t){const n=ln(e),r={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onTokenUnbanned:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeModeratorInviteCreated(e,t){const n=ln(e),r={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorInviteCreated:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeModeratorAdded(e,t){const n=ln(e),r={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorAdded:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeModeratorRemoved(e,t){const n=ln(e),r={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorRemoved:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeModeratorRoleUpdated(e,t){const n=ln(e),r={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorRoleUpdated:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeOverseerAdded(e){return this.globalCallbacks.onOverseerAdded=e,()=>{delete this.globalCallbacks.onOverseerAdded}}subscribeOverseerRemoved(e){return this.globalCallbacks.onOverseerRemoved=e,()=>{delete this.globalCallbacks.onOverseerRemoved}}subscribeTradeExecuted(e,t){const n=ln(e),r={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onTradeExecuted:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribePoolMetadataUpdated(e,t){const n=ln(e),r={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onPoolMetadataUpdated:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribePoolSocialLinksUpdated(e,t){const n=ln(e),r={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onPoolSocialLinksUpdated:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribePoolBadgeAssigned(e,t){const n=ln(e),r={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onPoolBadgeAssigned:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeHolderCountUpdated(e,t){const n=ln(e),r={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onHolderCountUpdated:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeCommentCreated(e,t){const n=ln(e),r={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...r}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onCommentCreated:t,...r}=e;this.roomCallbacks.set(n,r)}}}subscribeUserProfileUpdated(e){return this.globalCallbacks.onUserProfileUpdated=e,()=>{delete this.globalCallbacks.onUserProfileUpdated}}subscribeApiKeyCreated(e){return this.globalCallbacks.onApiKeyCreated=e,()=>{delete this.globalCallbacks.onApiKeyCreated}}subscribeApiKeyUpdated(e){return this.globalCallbacks.onApiKeyUpdated=e,()=>{delete this.globalCallbacks.onApiKeyUpdated}}subscribeApiKeyRevoked(e){return this.globalCallbacks.onApiKeyRevoked=e,()=>{delete this.globalCallbacks.onApiKeyRevoked}}subscribeStatsUpdated(e){return this.globalCallbacks.onStatsUpdated=e,()=>{delete this.globalCallbacks.onStatsUpdated}}subscribeEngagementStatsUpdated(e){return this.globalCallbacks.onEngagementStatsUpdated=e,()=>{delete this.globalCallbacks.onEngagementStatsUpdated}}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}async subscribeToGlobalFeed(e){if(!this.socket?.connected)throw new ht("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");return this.isGlobalFeedSubscribed?(this.logger.debug("📡 Already subscribed to global feed, updating callbacks"),e&&(this.globalFeedCallbacks=e),{room:"global:feed"}):new Promise((t,n)=>{const r=setTimeout(()=>{this.pendingGlobalFeedSubscription=null,n(new Error(`Global feed subscription timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingGlobalFeedSubscription={resolve:t,reject:n,timeoutId:r},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(WE.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(WE.UNSUBSCRIBE_GLOBAL_FEED),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks={},this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription=null)):this.logger.debug("📡 Not subscribed to global feed, skipping unsubscribe")}isSubscribedToGlobalFeed(){return this.isGlobalFeedSubscribed}setGlobalFeedCallbacks(e){this.globalFeedCallbacks=e,this.logger.debug("📡 Updated global feed callbacks")}getSocket(){return this.socket}disconnect(){if(this.socket){this.logger.debug("🔌 Disconnecting from Stream WebSocket");try{for(const[e,t]of this.pendingSubscriptions){try{clearTimeout(t.timeoutId),t.reject(new Error("WebSocket disconnected"))}catch(t){this.logger.error(`Error cleaning up pending subscription for ${e}:`,t)}this.pendingSubscriptions.delete(e)}}catch(e){this.logger.error("Error clearing pending subscriptions:",e)}try{this.subscribedRooms.clear(),this.roomCallbacks.clear()}catch(e){this.logger.error("Error clearing room tracking:",e)}try{for(const e of this.eventBufferTimeouts.values())clearTimeout(e);this.eventBuffer.clear(),this.eventBufferTimeouts.clear()}catch(e){this.logger.error("Error clearing event buffers:",e)}this.globalCallbacks={};try{this.globalFeedCallbacks={},this.isGlobalFeedSubscribed=!1,this.pendingGlobalFeedSubscription&&(clearTimeout(this.pendingGlobalFeedSubscription.timeoutId),this.pendingGlobalFeedSubscription.reject(new Error("WebSocket disconnected")),this.pendingGlobalFeedSubscription=null)}catch(e){this.logger.error("Error clearing global feed state:",e)}try{this.socket.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}this.socket=null,this.isAuthenticated=!1,this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}}}function VE(e){return null==e||""===e||"string"==typeof e&&(!mr(e)&&e.length<=Nn.BAN_REASON.MAX_LENGTH)}function jE(e){if(hr(e.tokenName,"tokenName",vn),!VE(e.reason))throw new ht(`reason must be at most ${Nn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function XE(e){hr(e.tokenName,"tokenName",vn)}function QE(e){cr(0,void 0,En,e.pageSize)}function YE(e){hr(e.tokenName,"tokenName",vn)}class JE extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async banToken(e){jE(e);const t=_e,n={tokenName:ln(e.tokenName)};if(void 0!==e.reason)try{tr(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const r=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(r),tokenName:ln(e.tokenName)}}async unbanToken(e){XE(e);const t=this.buildEndpoint(Re,{tokenName:e.tokenName});return tn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:ln(e.tokenName)}}async listTokenBans(e={}){QE(e);const t=De,n=this.buildPaginationParams(e,En);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),o=this.extractData(r);return{items:o.bans,pageInfo:o.pageInfo}}async getTokenBan(e){YE(e);const t=this.buildEndpoint(Pe,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:ln(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class ZE extends Sr{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map,this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}async resolveTokenToVault(e){if(!ir(e))throw Ut("tokenName","Token name");const t=ln(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;try{const n=await this.poolService.resolveTokenNameToVault(e);if(null!==n&&""!==n){const e=this.parseVaultAddressToTokenClassKey(n);this.setCacheEntry(t,{vaultAddress:n,tokenClassKey:e,cachedAt:Date.now()})}return n}catch{return null}}async resolveTokenClassKey(e){if(!ir(e))throw Ut("tokenName","Token name");const t=ln(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const r=await this.poolService.resolveTokenNameToVault(e);if(null===r||""===r)throw Lt(e);const o=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:o,cachedAt:Date.now()}),o}get(e){const t=this.getCacheEntry(ln(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=ZE.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=ln(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:ZE.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(ln(e));return t?.tokenClassKey??null}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}preWarmWithTokenClassKey(e){for(const{tokenName:t,vaultAddress:n,tokenClassKey:r}of e){const e=ln(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Ev(e)}catch(e){if(e instanceof ht)throw Ft("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}ZE.MAX_CACHE_SIZE=1e4;class eT extends vr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return on(()=>this.http.get(Qe),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return on(()=>this.http.get(Ye,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return on(()=>this.http.get(Je,{tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method}),{errorContext:`Failed to get trade quote for ${e.tokenName}`})}async getPremintQuote(e){return on(()=>this.http.get(Ze,{amount:e}),{errorContext:"Failed to get premint quote"})}}class tT extends tv{constructor(e,t,n,r=!1,o){super(e,t,n,r,o)}async emitTradeExecuted(e,t){this.validateTokenName(e,Sn);const n={action:"trade_executed",tokenName:e,payload:t};await this.emitEvent(n)}async emitBalanceUpdated(e,t,n){this.validateRequiredString(e,"userAddress","User Address"),this.validateTokenName(t,Sn);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Sn);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Sn);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Sn);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Sn);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Sn);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Sn);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,Sn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Sn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Sn);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Sn);const r={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitUserProfileUpdated(e,t){this.validateRequiredString(e,"userAddress","User Address");const n={action:"user_profile_updated",userAddress:e,payload:t};await this.emitEvent(n)}async emitSiteConfigChanged(e){const t={action:"site_config_changed",payload:e,broadcast:!0};await this.emitEvent(t)}async emitFeatureStatus(e){const t={action:"feature_status",payload:e,broadcast:!0};await this.emitEvent(t)}async emitEvent(e){this.validateRequiredString(e.action,"action","Event Action");const t=this.buildEndpoint("/v1/websocket",{});await this.http.post(t,e,this.getDualAuthHeaders())}async getConnectedClients(e){const t=this.buildEndpoint("/v1/connected-clients",{}),n={};void 0!==e?.room&&""!==e.room&&(n.room=e.room),void 0!==e?.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.userAddress&&(n.userAddress=e.userAddress),void 0!==e?.userAddresses&&(n.userAddresses=e.userAddresses),void 0!==e?.authenticated&&(n.authenticated=e.authenticated),void 0!==e?.isOverseer&&(n.isOverseer=e.isOverseer),void 0!==e?.minConnectionSeconds&&(n.minConnectionSeconds=e.minConnectionSeconds),void 0!==e?.offset&&(n.offset=e.offset),void 0!==e?.limit&&(n.limit=e.limit);const r=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(r)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new ft("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.includes(e)),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,Sn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const r=await this.getConnectedClients(n);return{clients:r.clients,count:r.summary.totalConnected,authenticatedCount:r.summary.authenticatedCount}}async getOnlineOverseers(){const e=await this.getConnectedClients({isOverseer:!0});return{clients:e.clients,count:e.summary.totalConnected}}async emitRecordingStatus(e,t){this.validateTokenName(e,Sn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Sn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Sn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}var nT,rT;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(nT||(nT={})),exports.SDKTransactionStatus=void 0,(rT=exports.SDKTransactionStatus||(exports.SDKTransactionStatus={})).PENDING="pending",rT.PROCESSING="processing",rT.COMPLETED="completed",rT.FAILED="failed",rT.TIMEOUT="timeout";const oT={[nT.PROCESSED]:exports.SDKTransactionStatus.COMPLETED,[nT.COMPLETED]:exports.SDKTransactionStatus.COMPLETED,[nT.SUCCESS]:exports.SDKTransactionStatus.COMPLETED,[nT.FAILED]:exports.SDKTransactionStatus.FAILED,[nT.ERROR]:exports.SDKTransactionStatus.FAILED,[nT.PROCESSING]:exports.SDKTransactionStatus.PROCESSING,[nT.PENDING]:exports.SDKTransactionStatus.PENDING};class iT{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,o={value:t};r>0&&(o.expiresAt=Date.now()+r),this.cache.set(e,o)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function sT(e,t,n,r={}){const{logger:o,cacheNullish:i=!1,keyGenerator:s}=r,a=s?s(e):String(e),c=n.get(a);if(void 0!==c)return o&&o.debug(`Cache hit for key: ${a}`),c;o&&o.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),o&&o.debug(`Cached result for key: ${a}`)):i&&(n.set(a,l),o&&o.debug(`Cached nullish result for key: ${a}`)),l}class aT extends Sr{constructor(e,t=!1){super(t),this.socket=null,this.listeners=new Map,this.timeouts=new Map,this.hasOnAnyListener=!1,this.MAX_BUFFER_SIZE=1e3,this.config={reconnectAttempts:5,reconnectDelay:2e3,timeout:3e5,...e},this.debug=t,this.reconnectionManager=new JS({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new iT(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),aT.instances.add(this)}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)=>{Rs(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",Tt(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;"string"==typeof r&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${r}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{throw this.logger.error("Socket.IO connection failed:",e),t(e),e}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const r=this.config.timeout??3e5,o=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),o={transactionId:e,status:exports.SDKTransactionStatus.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(o),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,o),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:exports.SDKTransactionStatus.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,o=r?.data,i=r?.status??r?.Status??o?.status??o?.Status;let s=r?.message??r?.Message??o?.message??o?.Message??r?.error??o?.error;ir(s)||(s=i===nT.FAILED||i===nT.ERROR?"Transaction failed - check transaction details":i===nT.COMPLETED||i===nT.PROCESSED||i===nT.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const a=r?.blockHash??o?.blockHash,c=r?.gasUsed??o?.gasUsed,l=r?.Data??o?.Data,u={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${u.status}`),this.logger.debug(`📡 Final message: "${String(s)}"`),n(u),u.status===exports.SDKTransactionStatus.COMPLETED||u.status===exports.SDKTransactionStatus.FAILED){this.listeners.delete(e);const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.socket?.off(e),this.logger.debug(`📡 Cleaned up listener for ${e} (${u.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===exports.SDKTransactionStatus.COMPLETED?t(e):e.status!==exports.SDKTransactionStatus.FAILED&&e.status!==exports.SDKTransactionStatus.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return oT[t]??exports.SDKTransactionStatus.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected")),aT.instances.delete(this)}static cleanupAll(e=!1){for(const e of aT.instances)e.disconnect();aT.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}aT.instances=new Set;class cT extends vr{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new ht("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},r=await this.http.get(et.GET_LEADERBOARD,n),o=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:o.count}),{leaderboard:o}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new ht("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=et.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),o=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:o.length}),{snapshots:o}}}class lT extends Ar{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return un(e)}hasItems(){return this.cache.size>0}getAllItems(){return Array.from(this.cache.values())}setAll(e){this.cache.clear();for(const t of e){const e=this.extractKey(t),n=this.normalizeKey(e);this.cache.set(n,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Cached ${e.length} items`)}merge(e){for(const t of e){const e=this.extractKey(t),n=this.normalizeKey(e);this.cache.set(n,t)}this.lastFetchedAt=Date.now(),this.logger.debug(`Merged ${e.length} items (total: ${this.cache.size})`)}getFetchTimestamp(){return this.lastFetchedAt}clear(){super.clear(),this.lastFetchedAt=null}getByKey(e){const t=this.normalizeKey(e);return this.cache.get(t)}hasKey(e){const t=this.normalizeKey(e);return this.cache.has(t)}buildBaseStats(){return{totalItems:this.cache.size,isPopulated:this.cache.size>0,lastFetchedAt:this.lastFetchedAt}}}class uT extends lT{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 dT extends Nv{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new uT(t)}buildApiParams(e){return{wrappable:!0}}transformApiResponse(e){return e.map(e=>{const t={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,wrapCounterpart:e.wrap,swappable:e.swappable,verified:e.verified};return void 0!==e.channel&&""!==e.channel&&(t.channel=e.channel),void 0!==e.trending&&(t.trending=e.trending),void 0!==e.image&&""!==e.image&&(t.image=e.image),void 0!==e.description&&""!==e.description&&(t.description=e.description),void 0!==e.currentPrices&&(t.currentPrices=e.currentPrices),t})}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=this.getDefaultLimit()}=e;return this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${Math.min(n,this.getMaxLimit())})`),Rs(async()=>{const e=(await this.executePaginatedRequest(t,n)).items;try{0===t?this.cache.setAll(e):this.cache.merge(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}},"Failed to fetch wrappable tokens",this.logger)}async fetchAllWrappableTokens(){return Rs(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:r,itemTypeName:o="items"}=e;if(t.has()){const e=t.getAll();return r&&r.debug(`Returning ${e.length} cached ${o}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${o} (no cache)`);const i=await n();try{t.setAll(i)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:i,fetchedAt:Date.now(),itemCount:i.length}}({cache:this.cache,fetchFn:()=>this.autoPaginateFetch(),logger:this.logger,itemTypeName:"wrappable tokens"});return{tokens:e.items,fetchedAt:e.fetchedAt,tokenCount:e.itemCount}},"Failed to fetch wrappable tokens",this.logger)}async getWrappableToken(e){const t=Cv(e),n=this.cache.getByTokenId(t);return n||(await sT("wrappable:all",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger}),this.cache.getByTokenId(t))}async getWrapCounterpart(e){const t=await this.getWrappableToken(e);if(t)return this.getWrappableToken(t.wrapCounterpart)}async isTokenWrappable(e){const t=Cv(e);await sT("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),r=void 0!==n,o={isWrappable:r,tokenId:t};return r&&(o.wrapCounterpart=n.wrapCounterpart),o}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class hT extends Sr{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 ht(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new ht(`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 ht(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:!0})}async unwrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new ht(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new ht(`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 ht(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:!1})}async estimateWrapFee(e,t){if("string"==typeof e&&0===e.length)throw Ut("tokenId","Token identifier");if(0===t.length)throw Ut("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new ht(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new ht(`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("string"==typeof e&&0===e.length)throw Ut("tokenId","Token identifier");if(0===t.length)throw Ut("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new ht(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new ht(`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}}getWrapStatus(e){if(0===e.length)throw Ut("transactionId");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||void 0===this.walletAddress||0===this.walletAddress.length)throw new ht("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-${Ob()}`,l=zb,u={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};return this.logger.debug(`[WrapService] ${i?"Wrap":"Unwrap"} message (pre-signing)`,{amount:r,uniqueKey:c,sourceChannel:a.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:r,message:u,routing:a,isWrap:i,senderAddress:s,typedDataTypes:l})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:o,routing:i,isWrap:s,typedDataTypes:a}=e;try{const e=await this.wallet.signTypedData(Ub,a,o),c=`Ethereum Signed Message:\n${Bb({domain:Ub,message:o,primaryType:"GalaTransaction",types:a}).length}`,l={...o,signature:e,prefix:c,types:a,domain:Ub};this.logger.debug(`[WrapService] ${s?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:r,channel:i.sourceChannel});const u=await this.galaConnectClient.requestBridgeOut(l);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:u.Status,hasData:"Data"in u}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(u)){const e=`Status=${u.Status}`,o="string"==typeof u.Message&&u.Message.length>0?`: ${u.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:s?"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}(u)){const e=u.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const o={bridgeFromChannel:i.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:o.bridgeFromChannel});const a=await this.galaConnectClient.bridgeTokenOut(o);return this.logger.debug("[WrapService] BridgeTokenOut response",{status:a.Status,hash:a.Hash}),1!==a.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(a.Status)}`}:{success:!0,transactionId:a.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:s?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof u})`}}catch(e){const o=Tt(e);return this.logger.error(`[WrapService] ${s?"Wrap":"Unwrap"} operation failed:`,o),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:i.sourceChannel,toChannel:s?"asset":n.channel??"music",error:o}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:Ws.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Ws.MUSIC,authType:"automatic"}}requireWallet(){if(void 0===this.walletAddress||0===this.walletAddress.length)throw new ht("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:qs(e)}}const gT=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function pT(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>pT(e,t+1));if(e instanceof Map){const n={};for(const[r,o]of e.entries()){const e=String(r);n[e]=gT.has(e.toLowerCase())?"[REDACTED]":pT(o,t+1)}return n}if("object"==typeof e){const n={};for(const[r,o]of Object.entries(e))n[r]=gT.has(r.toLowerCase())?"[REDACTED]":pT(o,t+1);return n}return e}class fT{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new gn({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??"https://lpad-backend-dev1.defi.gala.com",r=t.timeout??6e4;this.axios=tA(n,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return Rs(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Ki(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};e.data instanceof FormData&&(void 0!==t.headers&&"Content-Type"in t.headers&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload")),e.headers&&this.logger.debug("Custom headers provided:",Object.keys(t.headers??{}));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":pT(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:pT(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:pT(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 Rs(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}async signWithGalaChain(e,n,r=t.SigningType.SIGN_TYPED_DATA){const o=this.auth.getPrivateKey(),i={};Object.entries(n).forEach(([e,t])=>{void 0!==t&&(i[e]=t)});const s=new t.SigningClient(o);return await s.sign(e,i,r)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,r={message:n?.message??Tt(e),...n&&Boolean(n.error)&&{error:n.error},statusCode:t.response.status,...n&&Boolean(n.details)&&{details:n.details},...n&&Boolean(n.timestamp)&&{timestamp:n.timestamp},...n&&Boolean(n.path)&&{path:n.path}};t.launchpadError=r,this.logger.error("Backend error:",r)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class mT extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class yT extends Error{constructor(e,t,n){super(`Transaction ${e} failed with status: ${t}${void 0!==n?` - ${n}`:""}`),this.transactionId=e,this.status=t,this.name="TransactionFailedError"}}function wT(e,t){if(ar(e))throw new mT(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new mT(`Invalid WebSocket response received for transaction ${t}: expected object, got ${typeof e}`);if(!Object.prototype.hasOwnProperty.call(e,"status")&&!Object.prototype.hasOwnProperty.call(e,"Status"))throw new mT(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function bT(e,t,n,r){wT(e,t);const o=e,i=o.data??{};if(!function(e){if(ar(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new mT(`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 kT=4001,vT=4100,ST=4900,AT=4901;class ET{constructor(e){if(this.providerType="external",this.connectedAddress=null,this.accountsChangedHandler=null,this.disconnectHandler=null,null==e)throw new Os("EIP-1193 provider is required",_s.INVALID_CONFIG);this.provider=e,this.setupEventListeners()}setupEventListeners(){"function"==typeof this.provider.on&&(this.accountsChangedHandler=t=>{0===t.length?this.connectedAddress=null:this.connectedAddress=e.getAddress(t[0])},this.provider.on("accountsChanged",this.accountsChangedHandler),this.disconnectHandler=()=>{this.connectedAddress=null},this.provider.on("disconnect",this.disconnectHandler))}removeEventListeners(){"function"==typeof this.provider.removeListener&&(this.accountsChangedHandler&&(this.provider.removeListener("accountsChanged",this.accountsChangedHandler),this.accountsChangedHandler=null),this.disconnectHandler&&(this.provider.removeListener("disconnect",this.disconnectHandler),this.disconnectHandler=null))}handleProviderError(e,t){const n=e;if(n.code===kT)throw new Os(`User rejected ${t}`,_s.USER_REJECTED,e instanceof Error?e:void 0);if(n.code===vT)throw new Os("Wallet is not authorized",_s.NOT_CONNECTED,e instanceof Error?e:void 0);if(n.code===ST||n.code===AT)throw this.connectedAddress=null,new Os("Wallet disconnected",_s.NOT_CONNECTED,e instanceof Error?e:void 0);throw new Os(n.message??`${t} failed`,t.includes("sign")?_s.SIGNING_FAILED:_s.UNKNOWN,e instanceof Error?e:void 0)}ensureConnected(){if(!this.connectedAddress)throw new Os("Wallet is not connected. Call connect() first.",_s.NOT_CONNECTED)}async connect(){try{const t=await this.provider.request({method:"eth_requestAccounts"});if(null==t||0===t.length)throw new Os("No accounts returned from wallet",_s.CONNECTION_FAILED);return this.connectedAddress=e.getAddress(t[0]),this.connectedAddress}catch(e){if(e instanceof Os)throw e;return this.handleProviderError(e,"connect")}}async disconnect(){this.connectedAddress=null,this.removeEventListeners();try{await this.provider.request({method:"wallet_revokePermissions",params:[{eth_accounts:{}}]})}catch{}}isConnected(){return null!==this.connectedAddress}async signMessage(e){this.ensureConnected();try{const t=`0x${Buffer.from(e,"utf8").toString("hex")}`;return await this.provider.request({method:"personal_sign",params:[t,this.connectedAddress]})}catch(e){if(e instanceof Os)throw e;return this.handleProviderError(e,"sign message")}}async signTypedData(e,t,n){this.ensureConnected();try{const r={types:{EIP712Domain:this.getEIP712DomainType(e),...t},primaryType:Object.keys(t)[0],domain:this.serializeDomain(e),message:n};return await this.provider.request({method:"eth_signTypedData_v4",params:[this.connectedAddress,JSON.stringify(r)]})}catch(e){if(e instanceof Os)throw e;return this.handleProviderError(e,"sign typed data")}}getEIP712DomainType(e){const t=[];return void 0!==e.name&&t.push({name:"name",type:"string"}),void 0!==e.version&&t.push({name:"version",type:"string"}),void 0!==e.chainId&&t.push({name:"chainId",type:"uint256"}),void 0!==e.verifyingContract&&t.push({name:"verifyingContract",type:"address"}),void 0!==e.salt&&t.push({name:"salt",type:"bytes32"}),t}serializeDomain(e){const t={};return void 0!==e.name&&(t.name=e.name),void 0!==e.version&&(t.version=e.version),void 0!==e.chainId&&(t.chainId="bigint"==typeof e.chainId||"number"==typeof e.chainId?`0x${e.chainId.toString(16)}`:e.chainId),void 0!==e.verifyingContract&&(t.verifyingContract=e.verifyingContract),void 0!==e.salt&&(t.salt=e.salt),t}async getAddress(){return this.ensureConnected(),this.connectedAddress}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){throw new Os("Private key is not accessible with external wallet providers. Use PrivateKeyProvider if you need private key access for @gala-chain operations.",_s.PRIVATE_KEY_NOT_ACCESSIBLE)}getProvider(){return this.provider}}function TT(e){return"privateKey"===e.providerType}function IT(e){if(e&&TT(e))return e.getWallet()}function CT(e){return"object"==typeof e&&null!==e&&"request"in e&&"function"==typeof e.request}class xT{constructor(e){this.logger=e??new gn({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(null!=e&&!ir(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(null===t||""===t)return null;const n=e.Data,r=null==n||"object"!=typeof n||Array.isArray(n)?e:n,o=this.extractPositionId(r),i=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(null===o||""===o||null===i||""===i||null===s||null===a||""===a||null===c)return null;const l=this.extractPoolAlias(r),u=this.extractUserBalanceDelta(r),d=this.extractTimestamp(r),h=u?.token0Balance?.collection,g=u?.token1Balance?.collection,p={transactionId:t,positionId:o,poolHash:i,poolFee:c,amounts:s,userAddress:a};return void 0!==h&&(p.token0=h),void 0!==g&&(p.token1=g),void 0!==d&&(p.timestamp=d),void 0!==l&&(p.poolAlias=l),void 0!==u&&(p.userBalanceDelta=u),p}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(ir(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(ir(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","pool"];for(const n of t){const t=e[n];if(ir(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(ir(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(ir(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(ir(t)){const e=qn(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(ir(t)){const e=new Date(t).getTime();if(isFinite(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(null==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(null==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 ir(n)&&ir(r)&&ir(o)&&ir(i)&&ir(s)&&ir(a)?{collection:n,category:r,type:o,additionalKey:i,quantity:s,owner:a}:void 0}}class NT{constructor(e){let t,n;e.walletProvider?(t=e.walletProvider,n=IT(e.walletProvider)):e.wallet&&(n=e.wallet,t=Ls.fromWallet(e.wallet)),this.wallet=n;let r=null,o="PROD";if(void 0!==e.env?(o=e.env,r=$s(e.env)):e.baseUrl?.includes("dev")||e.baseUrl?.includes("qa")||e.baseUrl?.includes("test")||e.baseUrl?.includes("stage")?(o="STAGE",r=$s("STAGE")):(o="PROD",r=$s("PROD")),this.environment=o,this.config={baseUrl:r.launchpadBaseUrl,galaChainBaseUrl:r.galaChainBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,gdexWebSocketUrl:r.gdexWebSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new gn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?NT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?NT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??NT.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency??5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new Us({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Ps,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new fT(this.auth,this.config),this.sessionAuth=new Ms(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new fT(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new fT(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new fT(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new fT(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=tA(this.config.galaChainBaseUrl,this.config.timeout??3e4),this.cache=new Er(e.debug??!1),this.launchpadService=new bA(this.http,this.jwtAuth),this.tokenResolverService=new ZE(this.launchpadService.poolService),this.launchpadAPI=new Is(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new YS(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new fS(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new zv(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new aT({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new kE(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService),this.dexQuoteService=new pS(this.dexBackendHttp,this.config.dexBackendBaseUrl,e.debug??!1,e.dexQuoteNetworkTimeout??3e4),this.gswapService=new sA({privateKey:n?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,bundlerBaseUrl:this.config.bundleBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new hS(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug??!1),this.nftCollectionService=new eE(this.galaChainHttp),this.tradingQuotesService=new eT(this.http,e.debug??!1)}createOverrideSdk(t){if(!ir(t))throw qt("Invalid privateKey: must be a non-empty string","privateKey");if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw qt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new e.Wallet(t),r={...this.config,wallet:n};return new NT(r)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Ut("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new ht("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?IT(e):void 0}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,streamAdminApiKey:n,userApiKey:r,accessToken:o,headers:i,...s}=this.config;return{...s,...void 0!==n&&{streamAdminApiKey:"[REDACTED]"},...void 0!==r&&{userApiKey:"[REDACTED]"},...void 0!==o&&{accessToken:"[REDACTED]"},...void 0!==i&&{headers:Object.fromEntries(Object.keys(i).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:cn.GAS_FEE}}getVersion(){return jk}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw qt("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 getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),r=Math.min(t,100);return n.holders.slice(0,r).map((e,t)=>({...e,rank:t+1}))}async getHolderCount(e){const t=await this.fetchTokenDistribution(e);return{count:t.totalHolders,totalBalance:t.totalSupply}}async getHolderRank(e,t){const n=await this.fetchTokenDistribution(e),r=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());return-1===r?null:{rank:r+1,balance:n.holders[r].balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),r=t?.minBalance??0,o=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),s=new Map;return n.holders.forEach((e,t)=>{s.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=r&&t<=o}).map(e=>({...e,rank:s.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:r}=dr(e,"tokenName","tokenId",{description:"token identifier"});if(r&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const o=n;try{return await this.dexService.fetchTokenPrice({tokenId:o})}catch(e){const t=function(e){if(_t(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=ln((await this.fetchTokenDetails(o)).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: ${Tt(t)}`),e}}throw e}}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(null==t)throw new Error(Mt(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 Ur}),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 Vk({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:e?.ethereumPrivateKey??t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(),environment:this.environment,...void 0!==this.config.ethereumRpcUrl&&""!==this.config.ethereumRpcUrl?{ethereumRpcUrl:this.config.ethereumRpcUrl}:{},...void 0!==this.config.solanaRpcUrl&&""!==this.config.solanaRpcUrl?{solanaRpcUrl:this.config.solanaRpcUrl}:{}})}return this._bridgeService}getBridgeableTokenService(){return this._bridgeableTokenService??(this._bridgeableTokenService=new Rv(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new dT(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(null===this._galaConnectClient||void 0===this._galaConnectClient){const e=this.getAddress();if(void 0===this.config.dexApiBaseUrl||""===this.config.dexApiBaseUrl)throw new Error("DEX API base URL is required for GalaConnectClient. Check SDK configuration.");this._galaConnectClient=new Ik({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.galaChainBaseUrl&&""!==this.config.galaChainBaseUrl?{galachainBaseUrl:this.config.galaChainBaseUrl}:{},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new hT({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new HE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new CE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new vv(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new JE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new nv(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new cT(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new nE(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new bE(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new tE(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new Vv(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new hv(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new BA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new lS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new mE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new tT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new dS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}getMessagesService(){return this._messagesService??(this._messagesService=new kA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new vE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new wE(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new yS(this.http,this.config.events)),this._eventsBatcherService}getStreamWebSocketService(){if(null===this._streamWebSocketService||void 0===this._streamWebSocketService){if(void 0===this.config.streamWebSocketUrl||""===this.config.streamWebSocketUrl)throw new Error('Stream WebSocket URL is required for real-time streaming features.\n\nConfigure SDK:\n const sdk = createLaunchpadSDK({\n wallet: yourWallet,\n streamWebSocketUrl: "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 zE({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new eA({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new xE(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getEngagementStats(e){if(null===gs(e.tokenName))throw Ut("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){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return{tokenName:e,pinnedMessage:n.message?{messageId:n.message.id,content:n.message.content,userAddress:n.message.userAddress,pinnedBy:""!==n.message.pinnedBy?n.message.pinnedBy:n.message.userAddress,pinnedAt:""!==n.message.pinnedAt?n.message.pinnedAt:n.message.createdAt}:null}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);const r=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:r.message?{messageId:r.message.id,content:r.message.content,userAddress:r.message.userAddress,pinnedBy:""!==r.message.pinnedBy?r.message.pinnedBy:r.message.userAddress,pinnedAt:""!==r.message.pinnedAt?r.message.pinnedAt:r.message.createdAt}:null}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.id),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.id}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t={type:"COMMENT"};void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize);const n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t={type:"CHAT_MESSAGE"};void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize);const n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getStreamWebSocketService(),t=await this.ensureValidToken();e.authenticate(t)}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onRecordingsCountUpdated(e){return this.getStreamingEventService().onRecordingsCountUpdated(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEngagementStatsUpdated(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return Promise.resolve({tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return xv}),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(void 0!==e.tokenName&&""!==e.tokenName){const t=dn(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const r=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none",instance:"0"},e.withExpired??!1)}}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const r=t.collection??"Token",o={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:r,category:"Unit",tokenId:qs(o)}}throw Ut("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),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==o&&(l.privateKey=o),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Kt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>bT(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.sell(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Kt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>bT(t,n,"sell",e))}async getBundlerTransactionResult(e){return this.bundleService.getBundlerTransactionResult(e)}async launchToken(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.launchToken(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{wT(n,t);const r=n.data??{};if(!function(e){if(ar(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new mT(`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(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==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(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchUserBalances(e){return this.launchpadService.fetchUserBalances(e)}async fetchUserReport(e){return this.launchpadService.fetchUserReport(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(w,void 0,{"x-wallet-address":e})}async fetchReferrals(e){let t;if(void 0!==e?.address&&""!==e.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return Ur}),r=n(e.address);if(void 0===r)throw new ht(`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(b,o,{"x-wallet-address":t});if(!Array.isArray(i))throw new pt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:r,hasMore:i.length===r}}async fetchAllReferrals(e){const t=await Sv((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(void 0!==e?.address&&""!==e.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return Ur}),r=n(e.address);if(void 0===r)throw new ht(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get(k,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new pt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.updateProfile(r)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.uploadProfileImage(r)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n=t(e?.address)??this.getAddress(),r={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),this.launchpadService.fetchTokensHeld(r)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n=t(e?.address)??this.getAddress(),r={type:void 0!==e?.status?"created":"DEFI",address:n,pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(r.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(r.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(r.search=e.search),void 0!==e?.status&&(r.status=e.status),this.launchpadService.fetchTokenList(r)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferGala(r)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.transferToken(r)}return this.validateWallet(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async convertTokenNameToTokenClassKey(e){return this.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ur});return{...e,lockAuthority:t(e.lockAuthority)}}return e})),n={...e,tokens:t};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...r}=n;return e.lockTokens(r)}return this.validateWallet(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.unlockTokens(r)}return this.validateWallet(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.burnTokens(r)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{Yn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw qt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw qt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw qt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw qt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.galaChainBaseUrl&&""!==this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw qt(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw qt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw qt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=qn("string"==typeof e||"number"==typeof e?e:String(e),NT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${NT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),NT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=qn("string"==typeof e||"number"==typeof e?e:String(e),NT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${String(e)}, using default: ${NT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),NT.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 yT(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof mT)throw t;throw new mT(`Failed to transform WebSocket response for transaction ${e}`,Et(t)?t:new Error(Tt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof yT||t instanceof mT)throw t;throw new mT(`WebSocket confirmation failed for transaction ${e}`,Et(t)?t:new Error(Tt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return bI});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(void 0!==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);void 0!==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 l=0;const u=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.items.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),void 0!==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){l++;const t=Tt(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(a){const e=Math.min(Math.max(l-1,0),2),t=r*Math.pow(2,e);c=setTimeout(()=>{u()},t)}}};return u(),()=>{a=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);null!=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 l=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==o&&""!==o&&t.creatorAddress!==o||e(t))})}catch(e){c++;const t=Tt(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(s){const e=Math.min(Math.max(c-1,0),2),t=r*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;let t;if("string"==typeof e||"number"==typeof e)t=e;else{if("boolean"!=typeof e)return null;t=e?"1":"0"}const n=Vn(t,Number.NaN);return Number.isNaN(n)?null:1===n||1e4===n?1e4:.3===n||3e3===n?3e3:.05===n||500===n?500:!Number.isInteger(n)||500!==n&&3e3!==n&&1e4!==n?null:n}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(null!==n[e]&&void 0!==n[e]){const t=n[e];return"string"==typeof t?t:"number"==typeof t||"boolean"==typeof t?String(t):"object"==typeof t&&null!==t&&"toString"in t?t.toString():""}return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();return OA.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"),o=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return""===n||""===r||null===o?null:`${n}/${r}/${o}`}parsePoolPairString(e){const t=OA.parsePoolKey(e);if(!t)return null;const n=hk(t.token0)?dk(t.token0).collection:t.token0,r=hk(t.token1)?dk(t.token1).collection:t.token1,o=t.feeTier.toString();return""===n||""===r||""===o?null:{token0:n,token1:r,fee:o,poolPair:e}}serializeBalanceToken(e){if(null==e||"object"!=typeof e)return"";const t=e,n=t.collection??t.token??"",r=t.category??"",o=t.type??"",i=t.additionalKey??"none";return[""!==n?n:"",""!==r?r:"none",""!==o?o:"none",""!==i?i:"none"].join("|")}buildPoolPairFromBalances(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.userBalanceDelta??t.balanceDelta??t.delta;if(null==n||"object"!=typeof 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?null:`${s}/${a}/${c}`}extractPoolDataFromPayload(e){if("string"==typeof e){const t=this.looksLikePoolPair(e);return null!=t?this.parsePoolPairString(t):null}if("object"!=typeof e||null===e)return null;const t=e,n=this.looksLikePoolPair(t.poolPair);if(null!=n)return this.parsePoolPairString(n);const r=this.buildPoolPairFromBalances(t);if(null!==r)return this.parsePoolPairString(r);const o=this.buildPoolPairFromObject(t);if(null!==o)return this.parsePoolPairString(o);if(void 0!==t.pool&&null!==t.pool&&"object"==typeof t.pool){const e=this.extractPoolDataFromPayload(t.pool);if(null!==e)return e}return null}matchesPoolFilter(e,t){if(void 0!==t?.tokenFilter&&""!==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 void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw qt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");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(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:""!==r.tokenName?r.tokenName:"",symbol:""!==r.symbol?r.symbol:"",creatorAddress:""!==r.creatorAddress?r.creatorAddress:"",description:""!==r.description?r.description:"",image:""!==r.image?r.image:"",vaultAddress:""!==r.vaultAddress?r.vaultAddress:"",tokenStringKey:""!==r.tokenStringKey?r.tokenStringKey:"",preBuyQuantity:""!==r.initialBuyQuantity?r.initialBuyQuantity:"0",websiteUrl:""!==r.websiteUrl?r.websiteUrl:"",telegramUrl:""!==r.telegramUrl?r.telegramUrl:"",twitterUrl:""!==r.twitterUrl?r.twitterUrl:"",instagramUrl:""!==r.instagramUrl?r.instagramUrl:"",facebookUrl:""!==r.facebookUrl?r.facebookUrl:"",redditUrl:""!==r.redditUrl?r.redditUrl:"",tiktokUrl:""!==r.tiktokUrl?r.tiktokUrl:"",isFinalized:!1!==r.isFinalized&&null!==r.isFinalized&&void 0!==r.isFinalized&&r.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Tt(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: ${Tt(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<NT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),NT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=NT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${NT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*NT.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(null!=n){const e=this.parsePoolPairString(n);null===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"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw qt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");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: ${Tt(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: ${Tt(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<NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),NT.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS*NT.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"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw qt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=null,r=null,o=null,i=!1;const s=async e=>{const t=OA.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 zA(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: ${Tt(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"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw qt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const o=new Set,i=new xT(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: ${Tt(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${Tt(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${Tt(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: ${Tt(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<NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>o(),NT.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS*NT.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(void 0!==t.positionId&&""!==t.positionId&&e.positionId!==t.positionId)return!1;if(void 0!==t.poolHash&&""!==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(void 0!==t.userFilter&&""!==t.userFilter&&e.userAddress!==t.userFilter)return!1;if(void 0!==t.tokenFilter&&""!==t.tokenFilter){const n=void 0!==e.token0&&""!==e.token0&&fs(e.token0,t.tokenFilter),r=void 0!==e.token1&&""!==e.token1&&fs(e.token1,t.tokenFilter);if(!n&&!r)return!1}if(void 0!==t.pairTokens){const[n,r]=t.pairTokens,o=e.token0??"",i=e.token1??"",s=fs(o,n)&&fs(i,r),a=fs(o,r)&&fs(i,n);if(!s&&!a)return!1}if(void 0!==t.minAmount&&""!==t.minAmount){const n=qn(t.minAmount),r=qn(e.amounts[0]),o=qn(e.amounts[1]);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);return function(e,t=3e3){if(mn(e))return t;if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const n=String(e).trim();if(n.endsWith("%")){const e=qn(n.replace("%",""));return Math.floor(1e4*e)}const r=parseFloat(n);return isNaN(r)?t:r<100?Math.floor(1e4*r):Math.floor(r)}(e)}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.disconnect(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new gn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),aT.cleanupAll(e),t.debug("Global cleanup completed")}}NT.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,NT.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,NT.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=cn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,NT.DEFAULT_CALCULATE_AMOUNT_MODE=at.LOCAL,NT.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,NT.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,NT.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,NT.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class _T{static generateWallet(){try{const t=e.Wallet.createRandom();if(null==t.mnemonic?.phrase||""===t.mnemonic.phrase)throw Ut("mnemonic","Mnemonic phrase");const n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:t.mnemonic.phrase,wallet:new e.Wallet(t.privateKey)}}catch(t){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const t=`test-wallet-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(t).toString("hex").padStart(64,"1").slice(0,64),r=new e.Wallet(n),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 t}}static fromPrivateKey(t){const n=new e.Wallet(t),r=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(t,n=0){try{const r=e.Mnemonic.fromPhrase(t),o=e.HDNodeWallet.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),i=new e.Wallet(o.privateKey),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:t,wallet:i}}catch(r){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const r=`test-mnemonic-index-${n}-${t}`,o="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),i=new e.Wallet(o),s=this.toGalaAddress(i.address);return{privateKey:i.privateKey,address:i.address,galaAddress:s,mnemonic:t,wallet:i}}throw r}}static toGalaAddress(t){const n=_r(t);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Ft("address","a valid Ethereum address (40 hex characters)");return`eth|${e.getAddress(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return Pr(e)}catch(t){const n=Tt(t);if(n.includes("required")||!e?.startsWith("eth|"))throw Ut("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Ft("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=_r(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===Lr(e)}static generateMultipleWallets(e=1){Yn(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: ${null!=e.mnemonic&&""!==e.mnemonic?e.mnemonic:"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function DT(e){if(void 0===e)return _T.generateWallet();const t=e.trim();if(!ir(t))throw Ft("input","a non-empty string");if(function(e){const t=_r(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return _T.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 _T.fromMnemonic(t);throw Ft("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}_T.testCounter=0;let PT=null;async function RT(){if(!1===PT)return null;try{const e=await import("@gala-chain/connect");return PT=!0,e}catch{return PT=!1,null}}class BT{constructor(e){if(this.providerType="external",this.connectedAddress=null,!e)throw new Os("@gala-chain/connect client is required",_s.INVALID_CONFIG);if("function"!=typeof e.signMessage)throw new Os("Invalid @gala-chain/connect client: signMessage method is required",_s.INVALID_CONFIG);this.client=e}static async createBrowserClient(e){const t=await RT();if(null==t)throw new Os("Failed to create BrowserConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",_s.PROVIDER_NOT_AVAILABLE);const{BrowserConnectClient:n}=t,r=n,o=e?new r(e):new r;return new BT(o)}static async createTrustWalletClient(){const e=await RT();if(null==e)throw new Os("Failed to create TrustWalletConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",_s.PROVIDER_NOT_AVAILABLE);const{TrustWalletConnectClient:t}=e,n=new t;return new BT(n)}static async isAvailable(){return null!==await RT()}ensureConnected(){if(null===this.connectedAddress||void 0===this.connectedAddress)throw new Os("Wallet is not connected. Call connect() first.",_s.NOT_CONNECTED)}async connect(){try{if("function"==typeof this.client.connect){const t=await this.client.connect();if(null!=t&&t.length>0)return this.connectedAddress=e.getAddress(t),this.connectedAddress}if("function"==typeof this.client.getAccount){const t=await this.client.getAccount();if(null!=t&&t.length>0)return this.connectedAddress=e.getAddress(t),this.connectedAddress}throw new Os("Failed to connect: no account returned",_s.CONNECTION_FAILED)}catch(e){if(e instanceof Os)throw e;const t=e instanceof Error?e.message:String(e);if(t.length>0&&(t.includes("rejected")||t.includes("denied")))throw new Os("User rejected connection",_s.USER_REJECTED,e instanceof Error?e:void 0);throw new Os("Failed to connect to wallet",_s.CONNECTION_FAILED,e instanceof Error?e:void 0)}}async disconnect(){"function"==typeof this.client.disconnect&&await this.client.disconnect(),this.connectedAddress=null}isConnected(){return null!==this.connectedAddress}async signMessage(e){this.ensureConnected();try{return await this.client.signMessage(e)}catch(e){const t=e instanceof Error?e.message:String(e);if(t.includes("rejected")||t.includes("denied"))throw new Os("User rejected signing",_s.USER_REJECTED,e instanceof Error?e:void 0);throw new Os("Failed to sign message",_s.SIGNING_FAILED,e instanceof Error?e:void 0)}}async signTypedData(e,t,n){throw new Os("signTypedData is not supported by GalaChainConnectProvider. Use ExternalWalletProvider with the underlying EIP-1193 provider instead.",_s.SIGNING_FAILED)}async getAddress(){return this.ensureConnected(),this.connectedAddress}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){throw new Os("Private key is not accessible with @gala-chain/connect. Use PrivateKeyProvider if you need private key access.",_s.PRIVATE_KEY_NOT_ACCESSIBLE)}getClient(){return this.client}}const MT={METAMASK:"io.metamask",METAMASK_FLASK:"io.metamask.flask",COINBASE:"com.coinbase.wallet",TRUST_WALLET:"com.trustwallet.app",PHANTOM:"app.phantom",RAINBOW:"me.rainbow",OKX:"com.okex.wallet",RABBY:"io.rabby",BRAVE:"com.brave.wallet",FRAME:"sh.frame",LEDGER:"com.ledger",ZERION:"io.zerion.wallet",GALA:"com.gala.wallet"},OT={[MT.METAMASK]:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4=",[MT.GALA]:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAYAAACoYAD2AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAjWSURBVHgBzZkLVI1ZG8f/pZKjq0uK0LglIiMKU5EuBkMxUgmjL6GFSZJ7QpJx+Ujpk1Eat3KJySXjTnIpVJRPhnTSxWVaSveL1Zlnv3WshnM67wlrzX+t3T5nv3vv99d+9/O8z36OAj5DIpGoM1W2VPSp6FJp03ipmkoRlVwq9xUUFDLwGVKCnCKwAVRNqa2rc8vOLeiRkpqpcO/hY7woeI3yikrUva9DG1VV6HXqiJHDv0Uvg66oqa0VqigrX6dxUQScCDmlwLcjwfWjKuhJdq5jVMwpxMRfQP7LN7zGttPWxARbC3i4OsDCzOQuNQUS7GnwlExIgmtH1ea0zCfugdsjFeMvJLI2tFSmA/sieMV82Fqa/UFfvQhWKGuMggzAYfX19dHBYdGGm8MPoKy8El9Knm4OWO83L6+DtmaAkpLSPrQEkgDH5eQVnnTxWqVyN/3/+Brqrq+H+H1bMdCo13pa0QDIA0mAM4R5hbu/d/MW/Pn8Bb6mdHXa42hEMCyGmqwh0EDwgSRAq5wXBZfsXBcqP88tAF+1VlGBj6crvunWGf5bIvCm6C3vsZoaarh6NByDjA0XEWgImoMkwG7FpWXJ5uPddZ/l5IGPVJSV4OJgj83+P0OnvTbXVkp7d2NIFGJPXSTX9IrXPHqdOiDp5J66b7p1sSDQlKbXFD/qG7g1/ABvQAd7K9w6HYXoHQHQUBNg0679WBTwXzKwcmxatQDX4nbT6k4D3VTmXC9fF2G230Zl+niEFksgsRNdmJKS9kik0MVMZrGY5Cm6k5ohEiv8t+MiA3OHD9cFPa1EO6OOiIpLSrnrtH1EP3mvFSnqm8ucOzg0mg1Z15RNoQlkhtXkucZJKelS/1vTAQ0+zsZyKPf9wvVk+ARsR1a2UGJ/Zr0L3Z3gPdsVrVopIutZLhas3oIrSXel3oM99swrMSXamhp96An8xdoUGwFtL95Ilgqor6eDvVtWIyUhGrZWZriZ8gAWjp4YO91bKiBTbv5LLAnciX6jpuJg3Dn07dUdl2LDcO5gCHM7Esewx74r+rgWffxJ3Cbekx6795+QejMbSzOMthzC7a3id6XYfzwBd1IzwVdPaY/P9F6LQXZuSLhyC+aD+2PqBFu0UlSU2P8AzV9ZWe0j/q5Aq6hWU1NbqNnXWr227v0nA9b4eNBq5eL2vQz8/B9nLJ7bYAhXb9/H4rXb8eDRU8irbl100ZE8wQLaCu4+6yX2uUIuadQIU0u6VxL7V4bEJVyWCMjE/F5seBBUVVvDb8NO9Bw+CcfOXIb1cFOknT+IqG3+0OnQDnxl0LUzAhbPRsrZfRg5bLDUfldu3WPVGPaHQdqkZjyRNfcHCxPSPnOetxL2rgvwPDcfs5x/QOr5/dyKqwkawkmHMSNxM34vlnrN+OB+BAJVrg/r6+48QaZbOnnuGqsMxZCmj58KIa8u3biL/tYumLN0I9oS3FrfOXhw6RAST+zBycjN5AmM0Fm3A1RUlOHqaM+tOutTXV0Lv8AQFL76q9n5CxquW4gh2wnz+b0VPlZ48DKU09vFmGBD9saiE72HKV7kjMPQ6kfEJVzlgA+FBaJrZx3s+DUG/aydsS3isMy5S96VoaysQo9sRoNF5uqv3hShJWL79XD4BpwjqMXrdmDPod+51bv/IAthQX5wHDsKAtrL56/dwdKgUGQ8fibX/BVV1VBXbytgK6laVlGFlmj2kiCcuZSEsaNH4PH1o7SKg5jrQPatE5g2aQz+JK8wxXMZ50/lBWSqe88ZszKDrNGiKKQlYlHSxFm+8F3XELj062NAlq4NbS0NRB89A8tJc3CiwQBapDb0FEhVDLLYQF8Xn6N7Dz8Nip8J81FR2bInxMSsX0NdjS1lKYMU9unRDf82ddHtyMLADIKtZZDJvb8wZDFZJjOWz5FJv96s4hw4g7xm/d1QmYO6UpDBR4l30tBjmCPu01lcmvR0OkBdrW2z84y35Vxkihgyy9LMJL9jey2JndneYjofE4oNy7zQjoyiObFVfFdWLvFaa3Lsc6Y74tG1WIIUUOAh+fzE9uOIISwHgSMcJHvmVI54uEyUOCAoZB/3GnxR+BorF85C+oWDcJ5oB3ll0r83kn7/Fbs3rUB9vQgrN4WDDnoS+7LMx0Cj3snEVchBNraHzXT6oUbaI2ABhdFIJ2ym4wGLXmKYA6eYsGd3fciSloY6Qjcswd2z0RhMQfOZi0noNWIyNoX9JjXJ4DXjR1ZtFX/nIFkWgQLS05PpDSFNNTV1WB68C8Y2rkhMTsOYUcOQTJFMgK+n1MP7NMcxeJoUh/mznOj0WAwb5/mY6O6LktIyqfcZYNQTThNs2YaOF7c1PT50p/2Ubmg5RavobQlkaabTODpKLCAjaM/dlK1YSGQsd5wYQFH39oBFGG0xFNU1NVj1y/8QceAkKquqZc57+3QkzL81HksL94e47UNoTI252praa3fSo+Gj/ccSYD5+FrbuPsgBimU9whQ3KBJigJeTUtDXaiq274nhBei/yIMBHm4K+A/IRoW6TLQ7tWTedPARy6ot3RAKE9tpeNj4btZQb8tZ92SPpbBzWcj73M0C4DU+s4X08RNrkpTBYA7xhrf/tj6h+45CHhn27M7lKCsoyGhu332sQcZ9kBgXUazWVmBKq5gDWZCNoAaUTUugk54RiwG/puzo9Bm5zb+MTqRsH96U1Ke5rBrzL/E7I48MXkFWXVVdgy+txXPdsHG5F8sC2xOg1BOdrPwke734ZQvzV09fuAbJaY/wJdRFVwcRvyzHOJvvLtPXaQTYbMqYVzqaYCdQ2UFZ3h6U7QVlfdESMec/d8Yk+M51e01gLCcZzmcc75x5I+wMquanZz4xjz52FiyhzwIJ5uglSYlSKz0IzMJ8ENwoUrccNjhLSVHxAF0KI8BS8JRckE1gzamyp/J94auiITl5BSpvS0rJsqu4Xx8E9OsDi9D19TrVUyovh+KFOOp7nsptgpM7Em4R5EfArdDwOw5L7rAsATvcFVMRskJQsr24DP0NVvGaoREi2pYAAAAASUVORK5CYII="};function LT(){return"undefined"!=typeof window&&"function"==typeof window.dispatchEvent}function UT(){if(!LT())return null;return window.ethereum??null}async function FT(e=500){const t=[],n=new Map;return LT()?new Promise(r=>{const o=new Set,i=e=>{const r=e,{info:i,provider:s}=r.detail;if(o.has(i.uuid))return;o.add(i.uuid);const a={id:i.rdns||i.uuid,name:i.name,rdns:i.rdns||i.uuid,icon:i.icon??OT[i.rdns||""]??"",provider:s,isInjected:!1};t.push(a),n.set(a.id,a)};window.addEventListener("eip6963:announceProvider",i),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{if(window.removeEventListener("eip6963:announceProvider",i),0===t.length){const e=UT();if(e){const r=window;let o="Browser Wallet",i="injected";r.ethereum?.isMetaMask?(o="MetaMask",i=MT.METAMASK):r.ethereum?.isCoinbaseWallet?(o="Coinbase Wallet",i=MT.COINBASE):r.ethereum?.isTrust&&(o="Trust Wallet",i=MT.TRUST_WALLET);const s={id:i,name:o,rdns:i,icon:OT[i]??"",provider:e,isInjected:!0};t.push(s),n.set(s.id,s)}}const e=window;if(e.gala?.request&&!n.has(MT.GALA)){const r={id:MT.GALA,name:"Gala Wallet",rdns:MT.GALA,icon:OT[MT.GALA]??"",provider:e.gala,isInjected:!0};t.push(r),n.set(r.id,r)}r({wallets:t,byId:n,hasWallets:t.length>0,primary:t[0]})},e)}):{wallets:t,byId:n,hasWallets:!1}}async function $T(e,t){return(await FT(t)).byId.get(e)??null}function qT(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 KT(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function GT(e){if(null==e||"object"!=typeof e)return 0;const t=e;if("number"==typeof t.status)return t.status;if("number"==typeof t.statusCode)return t.statusCode;if("number"==typeof t.code)return t.code;const n=t.response;return n&&"number"==typeof n.status?n.status:0}function HT(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function WT(e){if(void 0!==e&&e.length>0&&!/^[a-z0-9]+$/.test(e.toLowerCase()))throw new Error(`Invalid asset extension format: "${e}". Must contain only alphanumeric characters.`)}function zT(e,t){return`${e.replace(/\/$/,"")}${t}`}const VT={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},jT=Fi({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),XT=Fi({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});class QT{static fastValidation(e,t,n,r=QT.DEFAULT_CONFIG){const o=Date.now();let i=!0;try{const s=Hi(e.sqrtPrice),a=Hi(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}),i=!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}),i=!1);const c=Hi(e.liquidity),l=Hi(t.liquidity);if(!es(c)){const e=cs(l.minus(c).abs(),c);e.gt(r.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:l.toString(),changePct:Wi(e.times(100),2)})}const u=Hi(e.feeGrowthGlobal0),d=Hi(t.feeGrowthGlobal0),h=Hi(e.feeGrowthGlobal1),g=Hi(t.feeGrowthGlobal1);n.zeroForOne?g.lt(h)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:h.toString(),updatedFeeGrowth1:g.toString()}),i=!1):d.lt(u)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:u.toString(),updatedFeeGrowth0:d.toString()}),i=!1);const p=Hi(e.protocolFeesToken0),f=Hi(t.protocolFeesToken0),m=Hi(e.protocolFeesToken1),y=Hi(t.protocolFeesToken1);f.lt(p)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:p.toString(),updatedProtocolFees0:f.toString()}),i=!1),y.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:y.toString()}),i=!1);const w=kn(o);return this.logger.debug("Fast validation completed",{passed:i,elapsedMs:w}),i}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=QT.DEFAULT_CONFIG){const r=Date.now(),o=[];let i=0;try{if(void 0!==t.actualSqrtPrice){const r=Hi(e.sqrtPrice),s=Hi(t.actualSqrtPrice),a=this.calculateDriftPercentage(r,s);i=a,a>100*n.maxDriftThreshold&&o.push(`Price drift detected: ${Wi(a,4)}% (threshold: ${Wi(100*n.maxDriftThreshold,4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const a=Hi(e.sqrtPrice),c=cs(a,Yi()),l=s.sqrtPriceToTick(c),u=e.tick??0,d=Math.abs(l-u);d>n.maxTickDrift&&o.push(`Tick/price mismatch: tick=${u}, calculated=${l}, drift=${d}`);const h=Hi(e.feeGrowthGlobal0),g=Hi(e.feeGrowthGlobal1),p=Hi(e.liquidity);try{ss(h,g,p)}catch(e){o.push(e.message)}const f=0===o.length,m=!f||i>100*n.maxDriftThreshold,y=kn(r);return this.logger.debug("Moderate validation completed",{isValid:f,shouldRefetch:m,driftPercentage:i,errorCount:o.length,elapsedMs:y}),this.buildValidationResult(f,i,m,o)}catch(e){return this.logger.error("Moderate validation exception",e),this.buildValidationResult(!1,0,!0,[`Exception during validation: ${Tt(e)}`])}}static async fullValidation(e,t,n){const r=Date.now(),o=[];let i=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=Hi(t.pool.sqrtPrice),c=Hi(s.pool.sqrtPrice),l=this.calculateDriftPercentage(a,c);i=Math.max(i,l),l>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&o.push(`Price drift: ${l.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const u=Hi(t.pool.liquidity),d=Hi(s.pool.liquidity),h=this.calculateDriftPercentage(u,d);i=Math.max(i,h),h>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&o.push(`Liquidity drift: ${h.toFixed(4)}% (cached: ${u.toString()}, fresh: ${d.toString()})`);const g=Object.keys(t.tickDataMap).length,p=Object.keys(s.tickDataMap).length;if(p>0){const e=Math.abs(p-g)/p;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&o.push(`Tick data incomplete: cached has ${g} ticks, fresh has ${p} ticks (${(100*e).toFixed(2)}% difference)`)}const f=0===o.length,m=!f,y=kn(r);return this.logger.debug("Full validation completed",{poolKey:e,isValid:f,shouldRefetch:m,maxDriftPercentage:i,priceDrift:l,liquidityDrift:h,cachedTickCount:g,freshTickCount:p,errorCount:o.length,elapsedMs:y}),this.buildValidationResult(f,i,m,o)}catch(t){return this.logger.error("Full validation exception",{poolKey:e,error:t}),this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${Tt(t)}`])}}static calculateDriftPercentage(e,t){if(es(t))return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return cs(t.minus(e).abs(),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}}QT.logger=new gn({debug:!1,context:"PoolStateValidator"}),QT.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class YT extends Sr{static calculatePoolStateHash(e){return Lb(`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick??0}`)}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=QT.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:YT.calculatePoolStateHash(this.pool)};if(!QT.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new ht("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(null==e)throw Ut("swapEvent","Swap event");if(!e.transactionId)throw Ut("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 mt(`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=GA.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(!QT.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new ht("Swap validation failed","swapResult","VALIDATION_FAILED");if(null!=e.actualAmount0&&null!=e.actualAmount1&&null!=e.actualSqrtPrice){const t=Hi(e.actualAmount0),n=Hi(e.actualAmount1),o=r.amount0.minus(t).abs(),i=r.amount1.minus(n).abs(),s=cs(o,t.abs(),Hi(0)).times(100).toNumber(),a=cs(i,n.abs(),Hi(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=YT.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=YT.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=Tt(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:Hi(0),amount1:Hi(0),feeAmount0:Hi(0),feeAmount1:Hi(0),ticksCrossed:[],metadata:{calculationTimeMs:kn(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:YT.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}var JT,ZT,eI,tI,nI,rI;exports.AnalysisStatus=void 0,(JT=exports.AnalysisStatus||(exports.AnalysisStatus={})).PENDING="PENDING",JT.PROCESSING="PROCESSING",JT.COMPLETED="COMPLETED",JT.FAILED="FAILED",exports.AnalysisType=void 0,(ZT=exports.AnalysisType||(exports.AnalysisType={})).TEXT="TEXT",ZT.IMAGE="IMAGE",ZT.VIDEO="VIDEO",exports.AIRecommendation=void 0,(eI=exports.AIRecommendation||(exports.AIRecommendation={})).NO_ACTION="NO_ACTION",eI.REVIEW_REQUIRED="REVIEW_REQUIRED",eI.DELETE_CONTENT="DELETE_CONTENT",eI.BAN_USER="BAN_USER",eI.DELETE_AND_BAN="DELETE_AND_BAN",exports.AnalysisCategory=void 0,(tI=exports.AnalysisCategory||(exports.AnalysisCategory={})).VIOLENCE="VIOLENCE",tI.HATE_SPEECH="HATE_SPEECH",tI.SEXUAL_CONTENT="SEXUAL_CONTENT",tI.HARASSMENT="HARASSMENT",tI.SPAM="SPAM",tI.SCAM="SCAM",tI.SELF_HARM="SELF_HARM",tI.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",tI.MISINFORMATION="MISINFORMATION",tI.COPYRIGHT="COPYRIGHT",tI.SAFE="SAFE",exports.AnalysisTier=void 0,(nI=exports.AnalysisTier||(exports.AnalysisTier={})).QUICK="QUICK",nI.DETAILED="DETAILED",exports.AIModerationMode=void 0,(rI=exports.AIModerationMode||(exports.AIModerationMode={})).DISABLED="DISABLED",rI.ADVISORY="ADVISORY";const oI={[exports.AnalysisStatus.PENDING]:"Pending",[exports.AnalysisStatus.PROCESSING]:"Processing",[exports.AnalysisStatus.COMPLETED]:"Completed",[exports.AnalysisStatus.FAILED]:"Failed"},iI={[exports.AIRecommendation.NO_ACTION]:"No Action Needed",[exports.AIRecommendation.REVIEW_REQUIRED]:"Human Review Required",[exports.AIRecommendation.DELETE_CONTENT]:"Delete Content",[exports.AIRecommendation.BAN_USER]:"Ban User",[exports.AIRecommendation.DELETE_AND_BAN]:"Delete & Ban"},sI={[exports.AnalysisCategory.VIOLENCE]:"Violence",[exports.AnalysisCategory.HATE_SPEECH]:"Hate Speech",[exports.AnalysisCategory.SEXUAL_CONTENT]:"Sexual Content",[exports.AnalysisCategory.HARASSMENT]:"Harassment",[exports.AnalysisCategory.SPAM]:"Spam",[exports.AnalysisCategory.SCAM]:"Scam",[exports.AnalysisCategory.SELF_HARM]:"Self Harm",[exports.AnalysisCategory.ILLEGAL_ACTIVITY]:"Illegal Activity",[exports.AnalysisCategory.MISINFORMATION]:"Misinformation",[exports.AnalysisCategory.COPYRIGHT]:"Copyright",[exports.AnalysisCategory.SAFE]:"Safe"},aI={[exports.AnalysisTier.QUICK]:"Quick Scan",[exports.AnalysisTier.DETAILED]:"Detailed Scan"},cI={[exports.AnalysisType.TEXT]:"Text",[exports.AnalysisType.IMAGE]:"Image",[exports.AnalysisType.VIDEO]:"Video"},lI={[exports.AIModerationMode.DISABLED]:"Disabled",[exports.AIModerationMode.ADVISORY]:"Advisory"},uI=lr(exports.AnalysisStatus),dI=lr(exports.AnalysisType),hI=lr(exports.AIRecommendation),gI=lr(exports.AnalysisCategory),pI=lr(exports.AnalysisTier),fI=lr(exports.AIModerationMode),mI=pr([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:uI},{field:"analysisType",type:"string",validator:dI},{field:"provider",type:"string"}]),yI=pr([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:fI},{field:"provider",type:"string"}]);function wI(e){return null!==e.analysisTier}var bI=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const r=qn(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=qn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});exports.ACCESS_SOURCE=UE,exports.ACTIVE_USER_TYPE=gv,exports.AI_MODE_LABELS=lI,exports.AI_RECOMMENDATION_LABELS=iI,exports.ALL_PERMISSIONS=sv,exports.ANALYSIS_CATEGORY_LABELS=sI,exports.ANALYSIS_STATUS_LABELS=oI,exports.ANALYSIS_TIER_LABELS=aI,exports.ANALYSIS_TYPE_LABELS=cI,exports.API_KEY_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.API_KEY_ROLE=rv,exports.API_KEY_ROLES=ov,exports.API_KEY_ROLE_HIERARCHY=dv,exports.AddressFormatter=xr,exports.AgentConfig=class{static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress??process.env.WALLET_ADDRESS,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??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{}},i=new NT(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 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??{},...void 0!==n&&""!==n?{galaChainAddress:n}:{}},o=new NT(r);return Promise.resolve({sdk:o,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,void 0!==t?.quantity&&""!==t.quantity){const e=qn(t.quantity,0);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: ${Tt(e)}`)}try{const t=await e.fetchPools({type:"recent",pageSize:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||r.push("Pool listing not accessible - some features may be limited")}catch(e){r.push(`Pool access test failed: ${Tt(e)}`)}return{ready:0===n.length&&o.connectionHealthy,sdk:e,wallet:t??_T.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);break;case"general":break;default:throw new Error(`Unexpected useCase: ${String(t)}`)}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(void 0===e||""===e){const e=process.env.PRIVATE_KEY;return void 0!==e&&""!==e?_T.fromPrivateKey(e):_T.generateWallet()}return"generate"===e?_T.generateWallet():_T.fromPrivateKey(e)}static getDefaultBaseUrl(e){return"production"===e?"https://lpad-backend-prod1.defi.gala.com":"https://lpad-backend-dev1.defi.gala.com"}static getDefaultTimeout(e){switch(e){case"production":default:return 3e4;case"development":return 45e3;case"testing":return 6e4}}static getEnvironmentDefaults(e){const t={};if("production"===e)t.bundleBaseUrl="https://bundle-backend-prod1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-prod-chain-platform-eks.prod.galachain.com";else t.bundleBaseUrl="https://bundle-backend-dev1.defi.gala.com",t.galaChainBaseUrl="https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com";return t}},exports.AuthError=Ds,exports.BAN_DURATIONS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},exports.BRIDGE_CONTRACT_ABI=ra,exports.BRIDGE_TOKEN_METADATA=ta,exports.BaseBridgeStrategy=xk,exports.BridgeRateLimiter=Zb,exports.BurnError=KS,exports.CALCULATION_MODES=at,exports.CHAIN_IDS=Hs,exports.COMPOSITE_POOL_FETCH_CONCURRENCY=5,exports.CONTENT_REACTION_TYPES=uS,exports.CONTENT_TYPE_LABELS=tS,exports.CROSS_RATE_TYPED_DATA_TYPES=Hb,exports.ChartService=class extends vr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw Ut("options","Chart options");const{tokenName:t,from:n,to:r,resolution:o}=e;if(null==t||""===t)throw Ut("tokenName","Token name");if(null==n)throw Ut("from","Start timestamp");if(null==r)throw Ut("to","End timestamp");if(null==o)throw Ut("resolution","Data resolution interval");vs(t);const i=173e6;if("number"!=typeof n||n<i)throw new ht("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<i)throw new ht("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof o||o<1)throw new ht("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:s}=await Promise.resolve().then(function(){return Gi}),a=s({tokenName:t,from:n,to:r,resolution:o}),c=await an(()=>this.http.get(y.CHART,a),{errorContext:"Failed to fetch chart data"}),l=nn(c);if(null==l||"object"!=typeof l)throw $t("Invalid API response: missing or invalid data",c.status??500);const u=l,d=u.data;if(!Array.isArray(d))throw $t("Invalid API response: expected data array",c.status??500);const h={dataPoints:d.map(e=>{if("object"!=typeof e||null===e)throw $t("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,o=t.closePrice??t.value,i=t.lowPrice??t.value,s=t.highPrice??t.value,a=t.volume??"0";return{startTime:"number"==typeof n?n:Number(n),openPrice:String(r),closePrice:String(o),lowPrice:String(i),highPrice:String(s),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(h.isPreviousData=u.isPreviousData),h}},exports.ConfigurationError=ft,exports.DEFAULT_ETHEREUM_BRIDGE_CONTRACT=zs,exports.DEFAULT_ETHEREUM_RPC_URL="https://ethereum.publicnode.com",exports.DEFAULT_ETHEREUM_TOKENS=Zs,exports.DEFAULT_EVENTS_CONFIG=mS,exports.DEFAULT_POLL_INTERVAL_MS=15e3,exports.DEFAULT_POLL_TIMEOUT_MS=27e5,exports.DEFAULT_PRICING_CONCURRENCY=5,exports.DEFAULT_RATE_LIMIT_RPS=12,exports.DEFAULT_SOLANA_BRIDGE_PROGRAM="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",exports.DEFAULT_SOLANA_RPC_URL="https://api.mainnet-beta.solana.com",exports.DEFAULT_SOLANA_TOKENS=ea,exports.DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS=5,exports.DexPoolNotFoundError=At,exports.DexQuoteError=St,exports.ERC20_ABI=na,exports.ERROR_CODES=dt,exports.ETHEREUM_BRIDGE_CONTRACT_SEPOLIA=Vs,exports.ETHEREUM_TOKENS_PROD=Xs,exports.ETHEREUM_TOKENS_STAGE=Qs,exports.EVENT_TYPES={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"},exports.EXTENDED_STREAM_ROLE=LE,exports.EthereumBridgeStrategy=Nk,exports.EventBufferWithAutoCleanup=class{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}},exports.EventsBatcherService=yS,exports.ExternalWalletProvider=ET,exports.FLAG_ACTION_LABELS=eS,exports.FLAG_DETAILS_MAX_LENGTH=500,exports.FLAG_REASON_LABELS=Jv,exports.FLAG_STATUS_LABELS=Zv,exports.FileValidationError=ds,exports.GALACHAIN_CHANNELS=Ws,exports.GALACONNECT_PRODUCTION_URL=js,exports.GALA_BRIDGE_TYPED_DATA_DOMAIN=Ub,exports.GALA_DECIMALS=8,exports.GALA_TOKEN_CLASS_KEY={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},exports.GSwapAssetError=kt,exports.GSwapAssetService=class extends Sr{constructor(e){super(e.debugMode??!1),e.dexBackendHttp?this.dexBackendHttp=e.dexBackendHttp:this.dexBackendHttp=tA(e.dexBackendBaseUrl,3e4)}parseTokenFlexible(e){try{return uk(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=null!=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=nn(await this.dexBackendHttp.get("/api/tokens/balances",{params:{wallet:e,limit:t,page:n}})),o=r?.data??{},i=Array.isArray(o?.tokens)?o.tokens:[],s="number"==typeof o?.count?o.count:i.length;return{assets:i.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 kt(`Failed to fetch user assets: ${Tt(t)}`,t,e)}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets",{walletAddress:e});return(await Sv(async(t,n)=>{const r=await this.getUserAssets(e,n,t);return{items:r.assets,page:t,limit:n,total:r.count,totalPages:Yk(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 kt(`Failed to fetch all user assets: ${Tt(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 o={limit:n,page:r};null!=t&&t.length>0&&(o.search=t);const i=nn(await this.dexBackendHttp.get("/api/tokens",{params:o})),s=i?.data??{},a=Array.isArray(s?.tokens)?s.tokens:[],c="number"==typeof s?.count?s.count:a.length,l=a.map(e=>this.transformRawTokenToDexToken(e));return{tokens:l,count:c,page:r,limit:n,hasMore:r*n<c}}catch(e){throw this.logger.error("Failed to fetch available DEX tokens",e),new kt(`Failed to fetch available DEX tokens: ${Tt(e)}`,e)}}async fetchAllAvailableDexTokens(e={}){try{this.logger.debug("Fetching all available DEX tokens",e);const t=[];let n=1;for(;;){const r=await this.fetchAvailableDexTokens({...e,limit:100,page:n});if(t.push(...r.tokens),!r.hasMore)break;n+=1}return t}catch(e){throw this.logger.error("Failed to fetch all available DEX tokens",e),new kt(`Failed to fetch all available DEX tokens: ${Tt(e)}`,e)}}},exports.GSwapLiquidityMutationService=class extends Sr{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.webSocketService=e.webSocketService,this.calculationService=e.calculationService,this.tokenConverter=new Kv,""!==e.bundlerBaseUrl&&(this.bundlerClient=nA.createClient(e.bundlerBaseUrl,3e4))}getBundlerClient(){if(""===this.bundlerBaseUrl)throw new ft("Bundler URL not configured","bundlerBaseUrl");return this.bundlerClient??(this.bundlerClient=nA.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 o=Gs(e),i=Gs(t),s=`$pool${o}${i}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${s}`,`$tokenBalance${i}${s}`]}async monitorBundlerTransaction(e,t,n){return{...{transactionId:e,liquidity:"0",amount0:"0",amount1:"0",status:"pending"},wait:async(r=12e4)=>Rs(async()=>{const o=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${e} timed out after ${r}ms`)),r)});await Promise.race([t,o]),this.logger.debug(`${n} confirmed`,{transactionId:e})},`${n} failed or timed out`,this.logger,(t,r,o)=>{throw o?.error(`GSwapLiquidityMutationService: ${r}`,{error:Tt(t),operationType:n,transactionId:e}),t})}}async sendAddLiquidityToBundler(t){if(void 0===this.privateKey)throw new ft("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===this.bundlerBaseUrl)throw new ft("Bundler URL not configured","bundlerBaseUrl");return Rs(async()=>{const r=`galaswap - operation - ${n.v4()}-${Date.now()}-${t.owner}`,o={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:r},i=new e.ethers.Wallet(this.privateKey),s={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},a={name:"ethereum",chainId:1},c=this.calculatePersonalSignPrefix(o),l={...o,prefix:c},u=await i.signTypedData(a,s,l),d={...l,signature:u,types:s,domain:a},h=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),g=nn(await this.getBundlerClient().post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:h})),p="string"==typeof g?.data?g.data:g?.data?.transactionId??g?.data?.id??g?.transactionId??g?.id;if(void 0===p)throw new mt("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return p},"Failed to send AddLiquidity to bundler",this.logger)}async sendRemoveLiquidityToBundler(t,r,o,i,s,a,c,l,u){if(void 0===this.privateKey)throw new ft("RemoveLiquidity requires wallet (full-access mode)","privateKey");return Rs(async()=>{const d=new e.ethers.Wallet(this.privateKey),h=await d.getAddress(),g=`galaswap - operation - ${n.v4()}-${Date.now()}-${h}`,p={tickLower:t,tickUpper:r,amount:o,token0:i,token1:s,fee:a,amount0Min:c,amount1Min:l,positionId:u,uniqueKey:g},f={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},y=this.calculatePersonalSignPrefix(p),w={...p,prefix:y},b=await d.signTypedData(m,f,w),k={...w,signature:b,types:f,domain:m},v=this.buildLiquidityStringsInstructions(i,s,a,h),S=nn(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(void 0===A)throw new mt("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return A},"Failed to send RemoveLiquidity to bundler",this.logger)}async sendCollectPositionFeesToBundler(t,r,o,i,s,a,c,l){if(void 0===this.privateKey)throw new ft("CollectPositionFees requires wallet (full-access mode)","privateKey");return Rs(async()=>{const u=new e.ethers.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${n.v4()}-${Date.now()}-${d}`,g={token0:t,token1:r,fee:o,amount0Requested:i,amount1Requested:s,tickLower:a,tickUpper:c,positionId:l,uniqueKey:h},p={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},w=await u.signTypedData(f,p,y),b={...y,signature:w,types:p,domain:f},k=this.buildLiquidityStringsInstructions(t,r,o,d),v=nn(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(void 0===S)throw new mt("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(void 0===this.privateKey)throw new ft("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===e.token0)throw Ut("token0","Token 0");if(""===e.token1)throw Ut("token1","Token 1");if(""===e.minPrice)throw Ut("minPrice","Minimum price");if(""===e.maxPrice)throw Ut("maxPrice","Maximum price");if(""===e.amount0Desired)throw Ut("amount0Desired","Desired amount 0");if(""===e.amount1Desired)throw Ut("amount1Desired","Desired amount 1");return Rs(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=uk(t),o=uk(n),i=(await this.gatewayClient.getPoolData({token0:r,token1:o,fee:e.fee})).tickSpacing,s=Hi(e.minPrice),a=Hi(e.maxPrice),c=Math.floor(Xi(s)),l=Math.ceil(Xi(a)),u=ls(c,i),d=ls(l,i),h=this.getWalletAddress();if(void 0===h)throw new ft("Wallet address not available","walletAddress");const g=await this.sendAddLiquidityToBundler({token0:r,token1:o,fee:e.fee,tickLower:u,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min??"0",amount1Min:e.amount1Min??"0",owner:h}),p=this.webSocketService.waitForTransaction(g);return this.monitorBundlerTransaction(g,p,"addLiquidityByPrice")},"Failed to add liquidity by price",this.logger,(e,t,n)=>{throw n?.error(t,{error:Tt(e)}),new vt(`${t}: ${Tt(e)}`,e,"ADD_FAILED")})}async addSwapLiquidityByTicks(e){if(void 0===this.privateKey)throw new ft("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===e.token0)throw Ut("token0","Token 0");if(""===e.token1)throw Ut("token1","Token 1");if(""===e.amount0Desired)throw Ut("amount0Desired","Desired amount 0");if(""===e.amount1Desired)throw Ut("amount1Desired","Desired amount 1");return Rs(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=uk(t),o=uk(n),i=this.getWalletAddress();if(void 0===i)throw new ft("Wallet address not available","walletAddress");const s=await this.sendAddLiquidityToBundler({token0:r,token1:o,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min??"0",amount1Min:e.amount1Min??"0",owner:i}),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:Tt(e)}),new vt(`${t}: ${Tt(e)}`,e,"ADD_FAILED")})}async removeLiquidity(e){if(void 0===this.privateKey)throw new ft("RemoveLiquidity requires wallet (full-access mode)","privateKey");if("string"==typeof e.token0&&""===e.token0||"string"!=typeof e.token0&&void 0===e.token0)throw Ut("token0","Token 0");if("string"==typeof e.token1&&""===e.token1||"string"!=typeof e.token1&&void 0===e.token1)throw Ut("token1","Token 1");if(""===e.liquidity)throw Ut("liquidity","Liquidity amount");return Rs(async()=>{this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=Hi(e.liquidity);try{ss(t)}catch(t){const n=`Invalid liquidity value: "${e.liquidity}". Must be a valid number.`;throw this.logger.error(n,{error:Tt(t)}),new ht(n,"liquidity","INVALID_VALUE")}if(es(t))throw new ht("Cannot remove zero liquidity from position.","liquidity","ZERO_VALUE");const n="string"==typeof e.token0?uk(e.token0):e.token0,r="string"==typeof e.token1?uk(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,n,r,e.fee,e.amount0Min??"0",e.amount1Min??"0",e.positionId??""),i=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,i,"removeLiquidity")},"Failed to remove liquidity",this.logger,(e,t,n)=>{throw n?.error(t,{error:Tt(e)}),new vt(`${t}: ${Tt(e)}`,e,"REMOVE_FAILED")})}async collectPositionFees(e){if(void 0===this.privateKey)throw new ft("CollectPositionFees requires wallet (full-access mode)","privateKey");if(void 0===e.positionId)throw Ut("positionId","Position ID");return Rs(async()=>{if(void 0!==e.ownerAddress&&void 0!==e.positionId&&("string"==typeof e.token0?""===e.token0:void 0===e.token0))throw new ht("collectPositionFees requires direct parameters: token0, token1, fee, tickLower, tickUpper. Use GSwapService.collectPositionFees() for automatic position lookup.","parameters",dt.REQUIRED);const t="string"==typeof e.token0?""===e.token0:void 0===e.token0,n="string"==typeof e.token1?""===e.token1:void 0===e.token1;if(t||n||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw new ht("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required","parameters",dt.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 r="string"==typeof e.token0?uk(e.token0):e.token0,o="string"==typeof e.token1?uk(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendCollectPositionFeesToBundler(r,o,e.fee,e.amount0Requested??"0",e.amount1Requested??"0",e.tickLower,e.tickUpper,e.positionId??""),s=this.webSocketService.waitForTransaction(i);return this.monitorBundlerTransaction(i,s,"collectPositionFees")},"Failed to collect position fees",this.logger,(e,t,n)=>{throw n?.error(t,{error:Tt(e)}),new vt(`${t}: ${Tt(e)}`,e,"COLLECT_FAILED")})}},exports.GSwapLiquidityQueryService=class extends Sr{constructor(e){super(e.debugMode??!1),this.gatewayClient=e.gatewayClient,this.calculationService=e.calculationService,this.tokenConverter=new Kv}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}parseTokenFlexible(e){try{return uk(e)}catch{return{collection:e,category:"Unit",type:"none",additionalKey:"none"}}}extractTokenSymbol(e){return null==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;Array.isArray(n.positions)&&n.positions.length>0&&(r=n.positions[0]);const o=r.positionId??r.id??n.positionId??n.id??"",i=this.extractTokenSymbol(r.token0),s=this.extractTokenSymbol(r.token1),a=r.feeTier??r.fee??r.feeAmount??3e3,c=r.tickLower??r.lowerTick??0,l=r.tickUpper??r.upperTick??0,u=r.liquidity?.toString()??r.liquidityAmount?.toString()??"0",d=r.amount0?.toString()??r.amountA?.toString()??"0",h=r.amount1?.toString()??r.amountB?.toString()??"0",g=r.feeAmount0?.toString()??r.feesA?.toString()??r.tokensOwed0?.toString()??"0",p=r.feeAmount1?.toString()??r.feesB?.toString()??r.tokensOwed1?.toString()??"0";return{positionId:o,ownerAddress:t,token0:i,token1:s,feeTier:Hn(a,3e3),tickLower:Hn(c,0),tickUpper:Hn(l,0),liquidity:u,amount0:d,amount1:h,feeAmount0:g,feeAmount1:p}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.calculationService.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),o=gS(n),i=gS(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 vt("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:Tt(e)}),new vt(`Failed to fetch liquidity position: ${Tt(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(!Array.isArray(r.positions)||0===r.positions.length)throw new vt("Position not found: API returned no position data",null,"NOT_FOUND");const o=r.positions[0];return this.normalizePositionResponse(o,e.owner)}catch(e){throw this.logger.error("Failed to fetch swap position via compound key",{error:Tt(e)}),new vt(`Failed to fetch swap position: ${Tt(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=gS(t),o=gS(n);return await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:o,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:Tt(e)}),new vt(`Failed to estimate liquidity removal: ${Tt(e)}`,e,"ESTIMATE_FAILED")}}},exports.GSwapPoolCalculationService=class{constructor(e){this.logger=e?.logger}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw new ht(`Invalid fee tier: ${e}. Valid values are 500, 3000, or 10000.`,"feeTier",dt.INVALID_FEE_TIER)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new ht(`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 ht(`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 Bs(()=>{const t=Yi();return cs(e,t).pow(2)},"calculatePriceFromSqrtPriceX96 failed",this.logger)}calculatePriceFromSqrtPriceDecimal(e){return Bs(()=>e.pow(2),"calculatePriceFromSqrtPriceDecimal failed",this.logger)}calculateLiquidityFromAmount0(e,t,n){return Bs(()=>{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.liquidity0(e,r,o)},"calculateLiquidityFromAmount0 failed",this.logger)}calculateLiquidityFromAmount1(e,t,n){return Bs(()=>{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.liquidity1(e,r,o)},"calculateLiquidityFromAmount1 failed",this.logger)}calculateAmount0FromLiquidity(e,t,n){return Bs(()=>{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.getAmount0Delta(r,o,e)},"calculateAmount0FromLiquidity failed",this.logger)}calculateAmount1FromLiquidity(e,t,n){return Bs(()=>{const r=s.tickToSqrtPrice(t),o=s.tickToSqrtPrice(n);return s.getAmount1Delta(r,o,e)},"calculateAmount1FromLiquidity failed",this.logger)}calculateOptimalPositionSize(e,t,n,r,o){if(""===t)throw Ut("desiredAmount0","Desired amount 0");if(""===n)throw Ut("desiredAmount1","Desired amount 1");const i=s.tickToSqrtPrice(r),a=s.tickToSqrtPrice(e),c=s.tickToSqrtPrice(o),l=s.getLiquidityForAmounts(Hi(t),Hi(n),i,a,c),u=s.getAmountsForLiquidity(l,a,i,c),d=u[0],h=u[1],g=Hi(t),p=Hi(n);es(Hi(h))&&this.logger?.warn("GSwapPoolCalculationService: Calculated amount1 is zero - position may be heavily skewed to amount0",{desiredAmount0:t,desiredAmount1:n,currentTick:r,tickUpper:o});const f=cs(d,h,Hi(0));return{amount0:Wi(d),amount1:Wi(h),liquidity:Wi(l),ratio:Wi(f),utilizationPercent:{amount0:Wi(os(cs(d,g),100),2),amount1:Wi(os(cs(h,p),100),2)}}}validatePositionParameters(e,t,n,r,o,i,s){if(""===r)throw Ut("amount0","Amount 0");if(""===o)throw Ut("amount1","Amount 1");const a=[],c=[],l=[500,3e3,1e4];let u;l.includes(e)||a.push(`Invalid fee tier: ${e}. Must be one of: ${l.join(", ")}`);try{u=Bs(()=>this.getTickSpacing(e),"validatePositionParameters tick spacing lookup",this.logger),void 0!==u&&(t%u!==0&&a.push(`tickLower must be multiple of ${u}`),n%u!==0&&a.push(`tickUpper must be multiple of ${u}`))}catch{}t>=n&&a.push(`tickLower (${t}) must be less than tickUpper (${n})`);const d=Hi(r),h=Hi(o);if(d.isNaN()||h.isNaN())a.push("Amounts must be valid numbers");else try{Bs(()=>ss(d,h),"validatePositionParameters amounts validation",this.logger)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}if(void 0!==i&&(i<t||i>n)&&c.push("Position is out of current price range - will not earn fees until price moves into range"),void 0!==s){Hi(s).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance")}const g=0===a.length?35e4:0,p={valid:0===a.length,errors:a,warnings:c,gasEstimate:g};return void 0!==u&&(p.tickSpacing=u),void 0!==i&&(p.currentTick=i),void 0!==s&&(p.poolLiquidity=s),p}calculateTicksForPrice(e,t,n){if(""===e)throw Ut("minPrice","Minimum price");if(""===t)throw Ut("maxPrice","Maximum price");const r=this.getTickSpacing(n),o=Hi(e),i=Hi(t);er(e,t,"priceRange");const s=Kn(Math.floor(Xi(o)),0),a=Kn(Math.ceil(Xi(i)),0),c=Kn(ls(s,r),0),l=Kn(ls(a,r),0),u=Kn(Math.pow(1.0001,c),0===c?1:NaN),d=Kn(Math.pow(1.0001,l),0===l?1:NaN),h=Hi(u),g=Hi(d);return{tickLower:c,tickUpper:l,tickSpacing:r,requestedMinPrice:e,requestedMaxPrice:t,actualMinPrice:h.toFixed(8),actualMaxPrice:g.toFixed(8),priceDeviation:{minPriceDeviation:os(cs(h.minus(o),o),100).toFixed(4),maxPriceDeviation:os(cs(g.minus(i),i),100).toFixed(4)}}}calculatePriceForTicks(e,t){const n=Kn(Math.pow(1.0001,e),1),r=Kn(Math.pow(1.0001,t),1),o=Hi(n),i=Hi(r);return{tickLower:e,tickUpper:t,minPrice:o.toFixed(8),maxPrice:i.toFixed(8),priceRange:`${o.toFixed(4)} - ${i.toFixed(4)}`,tickSpread:Kn(t-e,0)}}calculateExecutionPrice(e,t){if(null==e||"string"==typeof e&&""===e)throw Ut("inputAmount","Input amount");if(null==t||"string"==typeof t&&""===t)throw Ut("outputAmount","Output amount");return Bs(()=>{const n=Hi(e);return Wi(cs(Hi(t),n,Hi("0")))},"calculateExecutionPrice failed",this.logger)}},exports.GSwapPoolError=bt,exports.GSwapPoolQueryService=class extends Sr{constructor(e){super(e.debugMode??!1),this.tradeClient=e.tradeClient,this.calculationService=e.calculationService,this.tokenConverter=new Kv}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:o}=this.convertTokenPair(e,t),i=uk(r),s=uk(o),a=await this.tradeClient.getPoolData({token0:i,token1:s,fee:n}),c=this.calculationService.calculatePriceFromSqrtPriceX96(Hi(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 bt(`Failed to get pool data: ${Tt(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),o=[500,3e3,1e4];let i=Hi(0),s=0;for(const a of o)try{const e=uk(n),t=uk(r),o=await this.tradeClient.getPoolData({token0:e,token1:t,fee:a});null!=o&&(i=i.plus(Hi(o.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:i.toFixed(),feeTiers:o,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new bt(`Failed to fetch pool info: ${Tt(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?uk(e):e,o="string"==typeof t?uk(t):t,i=await this.tradeClient.getSlot0({token0:r,token1:o,fee:n}),s={sqrtPrice:""!==i.sqrtPrice?i.sqrtPrice:"0",tick:0!==i.tick?i.tick:0,liquidity:""!==i.liquidity?i.liquidity:"0",grossPoolLiquidity:i.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 bt(`Failed to fetch pool slot0 data: ${Tt(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),o=Hi(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:o.toFixed(),invertedPrice:Qi(o,!0),tick:r.tick,liquidity:r.liquidity}}catch(n){throw this.logger.error("Failed to calculate spot price",n),new bt(`Failed to calculate spot price: ${Tt(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=Hi(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 bt(`Failed to fetch position current price: ${Tt(e)}`,e)}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}},exports.GSwapQuoteError=yt,exports.GSwapSwapError=wt,exports.GSwapSwapService=class extends Sr{constructor(e){super(e.debugMode??!1),this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.webSocketService=e.webSocketService,this.dexQuoteService=e.dexQuoteService,this.tokenConverter=new Kv}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=Hi(e),r=Hi(t);return Wi(cs(r,n,Hi("0")))}catch(n){return this.logger.warn("Failed to calculate execution price",{inputAmount:e,outputAmount:t,error:Tt(n)}),"0"}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildSwapStringsInstructions(e,t,n,r){const o=Gs(e),i=Gs(t),s=`$pool${o}${i}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${s}`,`$tokenBalance${i}${s}`]}async sendSwapToBundler(t){return Rs(async()=>{if("string"!=typeof this.privateKey||0===this.privateKey.length)throw new ft("Swap requires wallet (full-access mode)","privateKey");if("string"!=typeof this.bundlerBaseUrl||0===this.bundlerBaseUrl.length)throw new ft("Bundler URL not configured","bundlerBaseUrl");const r=[500,3e3,1e4];if(!r.includes(t.feeTier))throw new ht(`Invalid fee tier ${t.feeTier}. Must be one of: ${r.join(", ")}`,"feeTier","INVALID_FEE_TIER");this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let o=t.fromToken,i=t.toToken;"string"==typeof o&&(o=uk(o)),"string"==typeof i&&(i=uk(i));const s=qs(o),a=qs(i),c=s<a?[o,i,s,a]:[i,o,a,s],[l,u,d,h]=c,g=qs("string"==typeof t.fromToken?uk(t.fromToken):t.fromToken),p=g===d,f=`galaswap - operation - ${n.v4()}-${Date.now()}-${t.walletAddress}`;let m;if("string"!=typeof t.currentSqrtPrice||0===t.currentSqrtPrice.length)throw Ut("currentSqrtPrice","Current sqrt price");const y=Hi(t.currentSqrtPrice),w=t.slippageTolerance??.01;if(p){const e=Vi(w);m=Wi(y.multipliedBy(e))}else{const e=ji(w);m=Wi(y.multipliedBy(e))}const b={token0:l,token1:u,fee:t.feeTier,amount:Wi(Hi(t.inputAmount)),zeroForOne:p,sqrtPriceLimit:m,recipient:t.walletAddress,amountOutMinimum:Wi(Hi(t.minOutput).multipliedBy(-1)),uniqueKey:f};this.logger.info("SWAP DTO DETAILS",{orderedToken0String:d,orderedToken1String:h,fromTokenStr:g,zeroForOne:p?`TRUE (${d} -> ${h})`:`FALSE (${h} -> ${d})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(t.slippageTolerance??.01)+"%"});const k=new e.ethers.Wallet(this.privateKey),v={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(b),E={...b,prefix:A},T=await k.signTypedData(S,v,E),I={...E,signature:T,types:v,domain:S},C=this.buildSwapStringsInstructions(l,u,t.feeTier,t.walletAddress),x=nA.createClient(this.bundlerBaseUrl,3e4),N=nn(await x.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:C})),_=N?.data??N?.transactionId??N?.id;if("string"!=typeof _||0===_.length)throw new mt("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return _},"Failed to send Swap to bundler",this.logger)}async getSwapQuoteExactInput(e){return Rs(async()=>{if(Hi(e.amount).isLessThanOrEqualTo(0))throw new yt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new yt("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,o]=t<n?[t,n]:[n,t],i=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of i)try{return await Rs(async()=>{const i=await a.fetchCompositePoolData({token0:r,token1:o,fee:c}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),l=Hi(s.currentSqrtPrice),u=Hi(s.newSqrtPrice),d=l.gt(u)?cs(l.minus(u),l,"0"):Hi(0),h=Hi(s.amount0),g=Hi(s.amount1);if(!ns(h)&&!ns(g))throw new yt("Unexpected quote result: neither amount is negative (no output from pool)",{amount0:s.amount0,amount1:s.amount1,fromToken:e.fromToken,toToken:e.toToken});const p=(ns(h)?h:g).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:p,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,p),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}},`Quote calculation for fee tier ${c}`,this.logger)}catch(e){s=e,this.logger.debug("Fee tier failed, trying next",{feeTier:c,error:Tt(e)})}throw s??new yt("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact input quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new yt(`${n}: ${Tt(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async getSwapQuoteExactOutput(e){return Rs(async()=>{if(Hi(e.amount).isLessThanOrEqualTo(0))throw new yt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new yt("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,o]=t<n?[t,n]:[n,t],i=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of i)try{return await Rs(async()=>{const i=await a.fetchCompositePoolData({token0:r,token1:o,fee:c}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:i,fromToken:t,toToken:n,amount:e.amount}),l=Hi(s.currentSqrtPrice),u=Hi(s.newSqrtPrice),d=l.gt(u)?cs(l.minus(u),l,"0"):Hi(0),h=Hi(s.amount0),g=Hi(s.amount1),p=(ts(h)?h:ts(g)?g:h).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:p,estimatedOutput:e.amount,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(p,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}},`Quote calculation for fee tier ${c}`,this.logger)}catch(e){s=e,this.logger.debug("Fee tier failed, trying next",{feeTier:c,error:Tt(e)})}throw s??new yt("No available fee tiers for quote",{feeTiers:i,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact output quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new yt(`${n}: ${Tt(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async executeSwap(e){return Rs(async()=>{if("string"!=typeof this.privateKey||0===this.privateKey.length)throw new ft("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,o=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount}),i=zi(e.estimatedOutput,r).toFixed();await this.ensureWebSocketConnected();const s=this.getWalletAddress();if("string"!=typeof s||0===s.length)throw new ft("Wallet address not available","walletAddress");const a=await this.sendSwapToBundler({fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:i,feeTier:e.feeTier,walletAddress:s,currentSqrtPrice:o.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 Rs(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:Tt(e)}),e})}}},"Failed to execute swap",this.logger,(e,t,n)=>{throw n?.error(t,e),new wt(`${t}: ${Tt(e)}`,e)})}},exports.GalaChainConnectProvider=BT,exports.GalaConnectClient=Ik,exports.GalaConnectHttpError=bk,exports.GdexStreamError=ZS,exports.GdexStreamService=eA,exports.GlobalAndRoomCallbackDispatcher=class{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${e}`)}const n=this.roomCallbacks.get(e);if(n)for(const r of n)try{r(t)}catch(t){this.logger?.error(`Error in room callback for ${e}: ${t}`)}}clear(){this.globalCallbacks=[],this.roomCallbacks.clear()}clearRoom(e){this.roomCallbacks.delete(e)}},exports.HOLDER_DELTA_TYPES=VT,exports.IMAGE_EXTENSIONS=go,exports.INVITE_STATUS=TA,exports.INVITE_STATUSES=IA,exports.JWT_CONSTANTS=Cs,exports.KNOWN_WALLET_RDNS=MT,exports.LAUNCHPAD_TOKEN_DECIMALS=18,exports.LEGACY_TYPED_DATA_TYPES=Gb,exports.LaunchpadSDK=NT,exports.ListenerCleanupManager=class{constructor(e){this.listeners=[],this.logger=e}register(e,t){this.listeners.push({id:e,cleanup:t})}async cleanup(){const e=[];for(let t=this.listeners.length-1;t>=0;t--){const{id:n,cleanup:r}=this.listeners[t];try{await r()}catch(t){const r=t instanceof Error?t:new Error(String(t));e.push(r),this.logger?.error(`Cleanup error for listener ${n}:`,r)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}},exports.LockError=_S,exports.MAX_BURN_BATCH_SIZE=50,exports.MAX_CONCURRENT_POOL_FETCHES=5,exports.MAX_LOCK_BATCH_SIZE=100,exports.MAX_UNLOCK_BATCH_SIZE=100,exports.MESSAGES_CONSTRAINTS=uA,exports.MESSAGE_TYPES=lA,exports.MODERATOR_ROLE=vA,exports.MODERATOR_ROLES=SA,exports.NFT_FEES=jA,exports.NetworkError=pt,exports.NftCollectionService=eE,exports.OEmbedService=nE,exports.OVERSEER_INVITE_STATUS=oE,exports.OVERSEER_STATUS=iE,exports.PAGINATION_DEFAULTS=Xk,exports.PERMISSION=iv,exports.POOL_FETCH_CONFIG={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20},exports.POOL_TYPES={RECENT:"recent",POPULAR:"popular"},exports.PayloadWalkerWithDeduplication=class{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,o=0)=>{if(o>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const i=this.extractor(e);if(null!==i){const e=this.dedupeKeyFn(i);this.seen.has(e)||(this.seen.add(e),t.push(i))}for(const t of Object.values(e))r(t,o+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}},exports.PendingSubscriptionTracker=class{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}},exports.PlatformStatsService=bE,exports.PoolStateManager=YT,exports.PrivateKeyProvider=Ls,exports.QUERY_FIELD_NAMES={PAGE:"page",LIMIT:"limit",TOKEN_NAME:"tokenName",VAULT_ADDRESS:"vaultAddress",USER_ADDRESS:"userAddress",TRADE_TYPE:"tradeType",POOL_TYPE:"type",SEARCH:"search",SORT_ORDER:"sortOrder",START_DATE:"startDate",END_DATE:"endDate"},exports.REACTION_EMOJI_MAP={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"},exports.RECORDING_STATUS=_E,exports.ROLE_SOURCE=OE,exports.RoomSubscriptionManager=class{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}},exports.SDK_VERSION=jk,exports.SIMULATE_EVENT_TYPE={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"},exports.SIMULCAST_PLATFORM=DE,exports.SIMULCAST_STATUS={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},exports.SOLANA_COMPUTE={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},exports.SOLANA_DISCRIMINATORS=oa,exports.STREAM_EVENTS=WE,exports.STREAM_PERMISSION={MANAGE_COMMENTS:"MANAGE_COMMENTS",MANAGE_CHAT:"MANAGE_CHAT",BAN_USERS:"BAN_USERS",UNBAN_USERS:"UNBAN_USERS",MANAGE_SIMULCAST:"MANAGE_SIMULCAST",GET_STREAM_KEY:"GET_STREAM_KEY",STOP_STREAM:"STOP_STREAM",RESET_STREAM_KEY:"RESET_STREAM_KEY",START_STREAM:"START_STREAM",DELETE_RECORDINGS:"DELETE_RECORDINGS",MANAGE_STREAM_SETTINGS:"MANAGE_STREAM_SETTINGS"},exports.STREAM_ROLE=ME,exports.STREAM_STATUS=NE,exports.SelectiveEventForwarding=class{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}},exports.SolanaBridgeStrategy=Hk,exports.StreamWebSocketService=zE,exports.StreamingEventService=xE,exports.TIME_CONSTANTS={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6},exports.TRADES_QUERY_CONSTRAINTS=pA,exports.TRADING_TYPES=st,exports.TokenMetadataService=class extends Sr{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}resolveTokenMetadata(e){const t=this.getCacheKey(e),n=this.cache[t];if(null!=n&&!this.isCacheExpired(n.timestamp))return this.logger.debug(`Using cached metadata for token: ${t}`),n.data;const r=this.extractMetadata(e);return this.cache[t]={data:r,timestamp:Date.now()},r}getTokenSymbol(e){return this.resolveTokenMetadata(e).symbol}getTokenDecimals(e){return this.resolveTokenMetadata(e).decimals}clearCache(e){null!=e&&""!==e?(delete this.cache[e],this.logger.debug(`Cleared cache for token: ${e}`)):(this.cache={},this.logger.debug("Cleared all token metadata cache"))}getCacheStats(){const e=Object.keys(this.cache);return{size:e.length,entries:e}}getCacheKey(e){if("string"==typeof e)return ln(e);const t=e;return ln(`${t.type??t.symbol??"unknown"}|${t.additionalKey??"none"}`)}extractMetadata(e){let t,n,r="Token",o="Unit",i="none";if("string"==typeof e)if(hk(e)){const s=dk(e);"Token"===s.collection&&""!==s.type?(r=s.collection,o=""!==s.category?s.category:"Unit",t=s.type,i=""!==s.additionalKey?s.additionalKey:"none",n=t):(t=s.collection,n=t,o=""!==s.category?s.category:"Unit",i=""!==s.additionalKey?s.additionalKey:"none")}else t=e,n=e;else{const s=e;t=s.type??"unknown",r=s.collection??"Token",o=s.category??"Unit",i=s.additionalKey??"none";const a=s.symbol??("Token"===r?t:r);n=""!==a?a:"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 kn(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}},exports.TokenRestrictedError=gt,exports.TradingQuotesService=eT,exports.TransactionError=mt,exports.TransactionFailedError=yT,exports.TypingIndicatorDebouncer=class{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const o=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,o)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}},exports.ValidationError=ht,exports.WebSocketError=mT,exports.WebSocketTimeoutError=class extends mT{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}},exports.WeeklyChallengeService=cT,exports.addCursorToPagination=function(e,t){return void 0===t?e:{...e,cursor:t}},exports.addressFormatSchema=Wr,exports.aggregateMultipleApiSources=async function(e,t,n){const r=n?.logger,o=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const i=e.map(async(t,n)=>{try{const i=await o(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),i}catch(o){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Tt(o)}`)}}),s=(await Promise.allSettled(i)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${s.filter(e=>void 0!==e).length} successful results`),t(s)},exports.amountMethodSchema=No,exports.amountTypeSchema=xo,exports.assertValidWalletAddress=Mr,exports.bidirectionalTokenMatch=ms,exports.browserFileSchema=fo,exports.bufferFileSchema=mo,exports.buildConcurrentBatchRequests=async function(e,t,n,r){const o=r?.logger,i=new Array(e.length);let s=0,a=0;o?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return i[c]=r,s++,o?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,o?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Tt(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){"rejected"===r[e].status&&o?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){o?.error(`Batch processing error at index ${r}: ${Tt(e)}`)}}return o?.debug(`Batch complete: ${s} succeeded, ${a} failed`),i},exports.buildQueryParametersWithValidation=function(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(sr(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 o=encodeURIComponent(n),i=encodeURIComponent(e);t.push(`${o}=${i}`)}return t.length>0?`?${t.join("&")}`:""},exports.buildSafePaginationOptions=KT,exports.buyTokensDataSchema=Ko,exports.calculateLinearFeeInterpolation=function(e,t,n){const r="number"==typeof e?new o(e):e;if(r.isLessThan(0)||r.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${r.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const i=n-t;return new o(t).plus(new o(i).multipliedBy(r))},exports.calculatePreMintDataSchema=Xo,exports.calculateScaledFeeAmount=function(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return Hi(e).multipliedBy(t).integerValue(o.ROUND_DOWN)},exports.calculateTotalPages=Yk,exports.capitalize=Ot,exports.caseInsensitiveTokenComparison=ps,exports.checkPoolOptionsSchema=Co,exports.commonValidators=fr,exports.compareAmounts=function(e,t){const n=Hi(e),r=Hi(t);return n.comparedTo(r)},exports.conditionalSpreadBuilder=function(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n},exports.conditionalTrimAndValidateString=gs,exports.createLaunchpadSDK=function(t){ar(t)&&(t={});const{wallet:n,env:r,config:o={},...i}=t,s={...i,...o},{wallet:a,env:c,config:l,...u}=s;let d;if(ar(n)){d=DT().wallet}else if("string"==typeof n){d=DT(n).wallet}else{if(!(n instanceof e.Wallet))throw qt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");d=n}const h={wallet:d,...void 0!==r?{env:r}:{},debug:!1,timeout:3e4,...u};return new NT(h)},exports.createLimitSchema=eo,exports.createOptionsValidator=function(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:o,type:i,validator:s}=t,a=r[e];if(o){if(ar(a)){n.push(`${e} is required`);continue}if("string"===i){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!ar(a))if(void 0===i||typeof a===i){if(void 0!==s){const e=s(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${i}`)}return n}},exports.createPaginatedResultSchema=function(e){return r.z.object({data:r.z.array(e),page:r.z.number().int().min(1),limit:r.z.number().int().min(1),total:r.z.number().int().min(0),totalPages:r.z.number().int().min(0),hasNext:r.z.boolean(),hasPrevious:r.z.boolean()})},exports.createPaginationQuery=function(e,t=Xk.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Vt("offset","a non-negative integer",e);return Zn(t,"limit"),{offset:e,limit:t}},exports.createPoolStateManager=function(e,t){return new YT(e,t)},exports.createProviderFromEip1193=function(e){return new ET(e)},exports.createProviderFromWallet=function(e){return Ls.fromWallet(e)},exports.createSolanaWallet=function(){const e=Zw.generate();return{privateKey:Kk.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}},exports.createTradeDataSchema=qo,exports.createWallet=DT,exports.createWalletProvider=function(e){if(null!=e.privateKey&&e.privateKey.length>0)return new Ls(e.privateKey);if(null!=e.eip1193Provider)return new ET(e.eip1193Provider);throw new Os("Invalid wallet provider config: must provide either privateKey or eip1193Provider",_s.INVALID_CONFIG)},exports.decimalRoundingUp=function(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=Hi(e),r=new o(10).pow(t);return n.multipliedBy(r).integerValue(o.ROUND_UP).dividedBy(r)},exports.deduplicateByKey=function(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const o=t(e);r.set(o,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 o=t(e);return r.get(o)===n})},exports.detectWallets=FT,exports.ensureConnected=async function(e){return e.isConnected()?e.getAddress():e.connect()},exports.errorMessageCaseNormalization=function(e){return e.toLowerCase()},exports.ethereumAddressSchema=zr,exports.extractFieldWithFallbackPath=function(e,t,n=null){if(null==e||"object"!=typeof e)return n;const r=e;for(const e of t){const t=e.split(".");let n=r;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(ir(n))return n;if(null!=n&&""!==n)return n}return n},exports.extractPaginationMetadata=function(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=Hn(String(n.page??n.Page??n.current??1),t.page),o=Hn(String(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),i=n.data,s=i?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof s?.totalItems?s.totalItems:"number"==typeof i?.count?i.count:Hn(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:o,totalCount:a,hasMore:c}},exports.fetchGalaBalanceOptionsSchema=ei,exports.fetchPoolDetailsDataSchema=Qo,exports.fetchTokenBalanceOptionsSchema=oi,exports.fileSizeSchema=oo,exports.fileUploadSchema=po,exports.filenameSchema=io,exports.filterByFeeTier=function(e,t){return e.filter(e=>e.feeTier===t)},exports.filterByLiquidity=function(e){return e.filter(e=>ts(e.liquidity))},exports.filterByMinLiquidity=function(e,t){const n=Hi(t);return e.filter(e=>Hi(e.liquidity).isGreaterThanOrEqualTo(n))},exports.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})},exports.filterByToken=function(e,t){return e.filter(e=>ps(e.token0,t)||ps(e.token1,t))},exports.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})},exports.flexibleAddressSchema=Vr,exports.flexibleFileSchema=yo,exports.formatGalaForDTO=Xn,exports.formatLaunchpadTokenForDTO=Qn,exports.formatTokenAmount=function(e,t=6){const n=Hi(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!es(n))return n.toExponential(2);const r=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(r).replace(/\.?0+$/,"")},exports.formatTokenDescriptor=function(e){return qs(e)},exports.fromBackendAddressFormat=Pr,exports.fromBaseUnits=yk,exports.fullNameSchema=Hr,exports.generateUniqueKey=vS,exports.getAmountOptionsSchema=jo,exports.getEnv=function(e,t){return process.env[e]??t},exports.getEnvOrThrow=function(e,t){const n=process.env[e];if(mn(n)||!pn(n)){throw Ut(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n},exports.getEthereumAddressFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw Ft("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e.getAddress(e.computeAddress(t))},exports.getEthereumBridgeContractByEnvironment=Js,exports.getEthereumTokenConfig=function(e){const t=dn(e);return Zs.find(e=>dn(e.symbol)===t||dn(e.symbol)===`G${t}`)},exports.getEthereumTokensByEnvironment=Ys,exports.getGalaBridgeTypedDataTypes=Wb,exports.getInjectedEip1193Provider=function(){if("undefined"==typeof window)return null;const e=window.ethereum;return CT(e)?e:null},exports.getIntervalRegistryStats=function(){const e=Array.from(UA.entries()).map(([e,t])=>({id:e,...t}));return{size:UA.size,entries:e}},exports.getLaunchTokenDataValidationErrors=Pi,exports.getNftFeeAsNumber=function(e){return parseFloat(jA[e])},exports.getPublicKeyFromPrivateKey=function(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw Ft("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const n=new e.SigningKey(t);return{publicKey:n.publicKey,compressedPublicKey:n.compressedPublicKey}},exports.getRecordingAnimatedUrl=function(e,t,n,r="gif"){const o=HT(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return WT(r),zT(n,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(i)}/assets/animated.${r.toLowerCase()}`)},exports.getRecordingAssetUrl=function(e,t,n,r,o){const i=HT(e),s=t.trim(),a=n.trim().toLowerCase();if(0===s.length)throw new Error("Recording ID cannot be empty");if(0===a.length)throw new Error("Asset type cannot be empty");WT(o);const c=void 0!==o&&o.length>0?`.${o.toLowerCase()}`:"";return zT(r,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(s)}/assets/${encodeURIComponent(a)}${c}`)},exports.getRecordingPosterUrl=function(e,t,n){const r=HT(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return zT(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(o)}/assets/poster.jpg`)},exports.getRecordingStoryboardUrl=function(e,t,n,r="vtt"){const o=HT(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return WT(r),zT(n,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(i)}/assets/storyboard.${r.toLowerCase()}`)},exports.getRecordingStreamUrl=function(e,t,n){const r=HT(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");return zT(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(o)}/assets/stream.m3u8`)},exports.getRecordingThumbnailUrl=function(e,t,n,r="jpg"){const o=HT(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return WT(r),zT(n,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(i)}/assets/thumbnail.${r.toLowerCase()}`)},exports.getSolanaTokenConfig=function(e){const t=dn(e);return ea.find(e=>dn(e.symbol)===t||dn(e.symbol)===`G${t}`)},exports.getStaticTokenMetadata=function(e){const t=dn(e),n=ta[t];if(void 0!==n)return n;if(!t.startsWith("G")){const e=ta[`G${t}`];if(void 0!==e)return e}},exports.getTieredModerationSavings=function(e,t){if(!wI(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))},exports.getTokenAnimatedUrl=function(e,t,n="gif"){const r=HT(e);return WT(n),zT(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)},exports.getTokenAssetUrl=function(e,t,n,r){const o=HT(e),i=t.trim().toLowerCase();if(0===i.length)throw new Error("Asset type cannot be empty");WT(r);const s=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return zT(n,`/v1/tokens/${encodeURIComponent(o)}/assets/${encodeURIComponent(i)}${s}`)},exports.getTokenImageUrl=function(e,t){const n=HT(e);return zT(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)},exports.getTokenLiveStreamUrl=function(e,t){const n=HT(e);return zT(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)},exports.getTokenPosterUrl=function(e,t){const n=HT(e);return zT(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)},exports.getTokenStoryboardUrl=function(e,t,n="vtt"){const r=HT(e);return WT(n),zT(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)},exports.getTokenThumbnailUrl=function(e,t,n="jpg"){const r=HT(e);return WT(n),zT(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)},exports.getTradeOptionsSchema=Ho,exports.getWalletByRdns=$T,exports.graduateTokenOptionsSchema=Do,exports.graphDataOptionsSchema=_o,exports.groupByFeeTier=function(e){return qT(e,e=>e.feeTier)},exports.groupByKey=qT,exports.groupByPoolKey=function(e){return qT(e,e=>`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`)},exports.groupByTokenPair=function(e){return qT(e,e=>`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`)},exports.hasAnyWallet=function(){return null!==UT()},exports.hasMorePages=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Vt("offset","a non-negative integer",e);if(e<0)throw Ht("offset",0,1/0,e);return e+t<n},exports.hexStringExtractionAndNormalization=function(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(ys(e))return ws(e)}return null}return ys(e)?ws(e):null},exports.imageExtensionSchema=wo,exports.imageFilenameSchema=bo,exports.imageMimeTypeSchema=so,exports.imageUploadOptionsSchema=To,exports.isAIModerationData=mI,exports.isAIModerationMode=fI,exports.isAIModerationSettings=yI,exports.isAIRecommendation=hI,exports.isAccessSource=qE,exports.isActiveUserType=pv,exports.isAnalysisCategory=gI,exports.isAnalysisStatus=uI,exports.isAnalysisTier=pI,exports.isAnalysisType=dI,exports.isBanData=fv,exports.isBanEnforcementEvent=wv,exports.isBurnTokenEntry=FS,exports.isBurnTokensData=$S,exports.isChatDisabledReason=SE,exports.isChatMessageItem=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt&&"number"==typeof t.flagCount&&"object"==typeof t.reactions},exports.isChatStatusResponse=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||SE(t.reason))},exports.isClaimableInvite=function(e){if(e.status!==oE.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(wn(e.expiresAt)<=new Date)return!1}return!0},exports.isContentType=nS,exports.isEip1193Provider=CT,exports.isEmptyValue=sr,exports.isExtendedStreamRole=$E,exports.isExternalProvider=function(e){return"external"===e.providerType},exports.isFlagAction=iS,exports.isFlagData=sS,exports.isFlagReason=rS,exports.isFlagStatus=oS,exports.isHolderDelta=jT,exports.isHolderDeltaType=function(e){return"string"==typeof e&&(e===VT.NEW_HOLDER||e===VT.EXITED_HOLDER||e===VT.BALANCE_CHANGED)},exports.isLockTokenEntry=ES,exports.isLockTokensData=IS,exports.isMessage=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===lA.CHAT_MESSAGE||t.type===lA.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt},exports.isMessageType=function(e){return e===lA.CHAT_MESSAGE||e===lA.COMMENT},exports.isModeratedToken=DA,exports.isModerationTiered=wI,exports.isModeratorInvite=_A,exports.isNonEmptyString=ir,exports.isOverseerInviteStatus=sE,exports.isOverseerStatus=aE,exports.isPinnedMessage=EE,exports.isPrivateKeyProvider=TT,exports.isPublicInviteInfo=PA,exports.isReactionErrorCode=TE,exports.isRecordingStatus=RE,exports.isSimulcastPlatform=BE,exports.isStreamChatDeletedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt},exports.isStreamChatErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamChatMessage=AE,exports.isStreamChatMessageEvent=function(e){return AE(e)},exports.isStreamChatPinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&EE(t.pinnedMessage)},exports.isStreamChatUnpinnedEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId},exports.isStreamReactionErrorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message},exports.isStreamReactionEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime},exports.isStreamStatus=PE,exports.isStreamStatusEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&PE(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive},exports.isStreamingEvent=function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","recordings_count_updated","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)},exports.isTokenAccessPermissions=FE,exports.isTokenAccessResult=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.hasAccess&&(null===t.role||$E(t.role))&&FE(t.permissions)&&(null===t.accessSource||qE(t.accessSource))&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer},exports.isTokenBanData=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)},exports.isTypingIndicatorEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(IE)},exports.isTypingUser=IE,exports.isUnlockTokenEntry=TS,exports.isUnlockTokensData=CS,exports.isUserBannedEvent=mv,exports.isUserHoldingData=XT,exports.isUserUnbannedEvent=yv,exports.isValidAddress=Br,exports.isValidApiKeyRole=av,exports.isValidBanDuration=kv,exports.isValidBanReason=bv,exports.isValidChatContent=function(e){return!!ir(e)&&(e.length>=Nn.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Nn.CHAT_MESSAGE.MAX_LENGTH)},exports.isValidChatTokenName=function(e){return!!ir(e)&&vn.PATTERN.test(e)},exports.isValidGalaChainChannel=function(e){return Object.values(Ws).includes(e)},exports.isValidInviteCode=NA,exports.isValidInviteStatus=xA,exports.isValidLaunchTokenData=function(e){return fi(e).success},exports.isValidModeratorRole=CA,exports.isValidTokenBanReason=VE,exports.isValidTokenName=function(e,t=vn){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)},exports.isViewerCountEvent=function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount},exports.isWalletAvailable=async function(e,t){return null!==await $T(e,t)},exports.isoDateStringSchema=ao,exports.launchTokenDataSchema=Eo,exports.loadEnvWithFallback=function(){const e=m.join(process.cwd(),"..","..",".env");f.existsSync(e)&&p.config({path:e});const t=m.join(process.cwd(),".env");f.existsSync(t)&&p.config({path:t})},exports.mergeSafePaginationOptions=function(e,t){return KT({...e,...t})},exports.nonNegativeDecimalStringSchema=Qr,exports.normalizeAddressInput=Rr,exports.normalizeDataWithMapping=function(e,t){return e.map(e=>{const n={};for(const[r,o]of Object.entries(t)){const t=o(e);void 0!==t&&(n[r]=t)}return n})},exports.normalizeErrorMessage=fs,exports.normalizeLimit=Qk,exports.normalizeTokenKey=un,exports.normalizeTokenName=ln,exports.normalizeTokenSymbol=dn,exports.optionalUrlSchema=Jr,exports.pageNumberSchema=Zr,exports.paginationResultMetaSchema=Uo,exports.parseHttpErrorResponse=function(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let o,i=t.errorMessage;"string"==typeof n.message?i=n.message:"string"==typeof n.error?i=n.error:e instanceof Error?i=e.message:"string"==typeof e&&(i=e);const s=n.response;if(s){const e=s.data;if("object"==typeof e&&null!==e){o=e;const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error)}}const a={statusCode:r,errorMessage:i,raw:e};return null!=o&&(a.errorData=o),a},exports.percentileIndexCalculation=function(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)},exports.poolFetchTypeSchema=Io,exports.poolPaginationSchema=Mo,exports.positiveDecimalStringSchema=Xr,exports.priceTickRangeMapping=function(e,t,n=60){const r=Hi(e),i=Hi(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(Xi(r)),a=Math.ceil(Xi(i)),c=Math.floor(s/n)*n,l=Math.ceil(a/n)*n;return{minTick:c,maxTick:l,actualMinPrice:new o(1.0001).pow(c),actualMaxPrice:new o(1.0001).pow(l)}},exports.privateKeySchema=lo,exports.providerToWallet=IT,exports.registerInterval=FA,exports.requireNonNegative=ss,exports.requirePositive=is,exports.requirePositiveWithContext=as,exports.retryableHttpRequest=async function(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,o=t?.retryableStatus??[429,503,504];let i,s=0;for(;s<=n;)try{return await e()}catch(e){i=e,s++;const t=GT(e),a=o.includes(t);if(s>n||!a)throw e;const c=r*Math.pow(2,s-1);await new Promise(e=>setTimeout(e,c))}throw i},exports.reverseBondingCurveConfigSchema=Ao,exports.reverseBondingCurveConfigurationSchema=Yo,exports.roleHasSufficientPermission=function(e,t){return e===rv.MANAGER?t!==rv.OWNER:e===rv.OWNER||e===t},exports.roundTickBoundaries=function(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}},exports.roundTickToSpacing=function(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t},exports.safeDivideWithMinimum=function(e,t,n,r="0"){const o=Hi(t);if(es(o))return Hi(r);const i=Hi(e).dividedBy(o);if(null!=n){const e=Hi(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(i.isLessThan(e))return e}return i},exports.searchQuerySchema=Gr,exports.sellTokensDataSchema=Go,exports.sortByLiquidity=function(e,t="desc"){return[...e].sort((e,n)=>{const r=Hi(e.liquidity),o=Hi(n.liquidity);return"desc"===t?o.minus(r).toNumber():r.minus(o).toNumber()})},exports.standardLimitSchema=to,exports.standardPaginationSchema=Po,exports.stripHexPrefix=Ir,exports.subscribeToWalletChanges=function(e){if(!LT())return()=>{};let t=!0,n={wallets:[],byId:new Map,hasWallets:!1};const r=r=>{if(!t)return;const o=r,{info:i,provider:s}=o.detail,a=i.rdns||i.uuid;if(n.byId.has(a))return;const c={id:a,name:i.name,rdns:a,icon:i.icon??"",provider:s,isInjected:!1},l=[...n.wallets,c],u=new Map(n.byId);u.set(c.id,c),n={wallets:l,byId:u,hasWallets:!0,primary:l[0]},e(n)};return window.addEventListener("eip6963:announceProvider",r),FT().then(r=>{t&&(n=r,e(r))}),()=>{t=!1,window.removeEventListener("eip6963:announceProvider",r)}},exports.timestampSchema=co,exports.toBackendAddressFormat=Dr,exports.toBackendAddressFromEthers=Or,exports.toBaseUnits=mk,exports.tokenCategorySchema=vo,exports.tokenCollectionSchema=So,exports.tokenDescriptionSchema=qr,exports.tokenHoldSchema=ri,exports.tokenListOptionsSchema=Zo,exports.tokenNameSchema=Fr,exports.tokenSymbolSchema=$r,exports.tokenUrlsSchema=ko,exports.tradeCalculationMethodSchema=Vo,exports.tradeCalculationTypeSchema=zo,exports.tradeLimitSchema=ro,exports.tradeListParamsSchema=Wo,exports.tradePaginationSchema=Bo,exports.tradePaginationWithFiltersSchema=Lo,exports.tradeTypeBackendSchema=$o,exports.tradeTypeSchema=Fo,exports.transactionIdSchema=uo,exports.transformRawApiTokenToDomainModel=function(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(ir(t.name)?t.name:void 0)??(ir(t.tokenName)?t.tokenName:void 0)??"";if(!ir(n))throw new Error("Token name is required and must be a non-empty string");const r=(ir(t.symbol)?t.symbol:void 0)??(ir(t.tokenSymbol)?t.tokenSymbol:void 0)??(ir(t.collection)?t.collection:void 0)??"";if(!ir(r))throw new Error("Token symbol is required and must be a non-empty string");let o=8;"number"==typeof t.decimals&&t.decimals>=0&&(o=Math.floor(t.decimals));const i={name:n,symbol:r,decimals:o};return ir(t.address)&&(i.address=t.address),"boolean"==typeof t.verified&&(i.verified=t.verified),i},exports.trimmedLengthValidation=function(e){return null==e||"string"!=typeof e||0===e.trim().length},exports.uniqueKeySchema=ho,exports.unregisterAllIntervals=function(){const e=UA.size;return UA.clear(),e},exports.unregisterInterval=$A,exports.updateProfileDataSchema=ti,exports.uploadProfileImageOptionsSchema=ni,exports.urlSchema=Yr,exports.userLimitSchema=no,exports.userPaginationSchema=Ro,exports.userTokenNameSchema=Kr,exports.userTokenTypeSchema=Jo,exports.userTokensPaginationSchema=Oo,exports.validateAddress=li,exports.validateAmountString=di,exports.validateBanTokenOptions=jE,exports.validateBuyTokensData=Ti,exports.validateCalculatePreMintData=_i,exports.validateChatMessageId=function(e){if(!ir(e))throw Ut("id","Message ID");if(!_n.CHAT_MESSAGE.PATTERN.test(e))throw new ht("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",dt.INVALID_FORMAT)},exports.validateCheckPoolOptions=wi,exports.validateConstrainedEnumVariant=function(e,t,n){if(!t.includes(e))throw new ht(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")},exports.validateCreateApiKeyOptions=cv,exports.validateCreateChatMessageOptions=function(e){if(!ir(e.tokenName))throw Ut("tokenName");if(e.tokenName.length>An.MAX_LENGTH)throw new ht(`tokenName must be at most ${An.MAX_LENGTH} characters`,"tokenName",dt.TOO_LONG);if(!ir(e.content))throw Ut("content");if(0===e.content.trim().length)throw new ht("content cannot be empty","content",dt.REQUIRED);if(e.content.length>Nn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new ht(`content must be at most ${Nn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",dt.TOO_LONG)},exports.validateCreateCommentOptions=function(e){if(!ir(e.tokenName))throw Ut("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=Sn;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw Ft("tokenName",`${t}-${n} alphanumeric characters`,"Token name");if(!ir(e.content))throw Ut("content");if(0===e.content.trim().length)throw Zt("content","Content");if(e.content.length>Nn.COMMENTS_V1.MAX_LENGTH)throw Jt("content",Nn.COMMENTS_V1.MAX_LENGTH,e.content.length)},exports.validateCreateMessageOptions=function(e){if(void 0===e.type||null===e.type)throw Ut("type");if(e.type!==lA.CHAT_MESSAGE&&e.type!==lA.COMMENT)throw new ht(`type must be one of: ${Object.values(lA).join(", ")}`,"type",dt.INVALID_VALUE);if(!ir(e.tokenName))throw Ut("tokenName");if(e.tokenName.length>An.MAX_LENGTH)throw new ht(`tokenName must be at most ${An.MAX_LENGTH} characters`,"tokenName",dt.TOO_LONG);if(!ir(e.content))throw Ut("content");if(0===e.content.trim().length)throw Zt("content","Content");const t=e.type===lA.CHAT_MESSAGE?uA.CONTENT.CHAT_MAX_LENGTH:uA.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw Jt("content",t,e.content.length)},exports.validateCreateModeratorInviteOptions=function(e){const t=[],n=e.inviteScope??AA.TOKEN;return void 0===e.inviteScope||RA(e.inviteScope)||Rt(t,()=>{throw Qt("inviteScope",e.inviteScope,EA,"Invite scope")}),n===AA.TOKEN?Rt(t,()=>{hr(e.tokenName??"","tokenName",vn)}):n===AA.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),CA(e.role)||Rt(t,()=>{throw Qt("role",e.role,SA,"Role")}),void 0!==e.description&&""!==e.description&&Rt(t,()=>{Jn(e.description,Nn.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||bn(e.expiresAt)||Rt(t,()=>{throw function(e,t="a valid date",n){const r=Ot(e,n);return new ht(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t},exports.validateCreateOverseerDirectOptions=fE,exports.validateCreateOverseerInviteOptions=cE,exports.validateCreateTradeData=Ei,exports.validateDecimalRangeStrict=function(e,t,n,r){const o="string"==typeof e?parseFloat(e):e;if(!isFinite(o))throw new ht(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(o<t||o>n)throw Ht(r,t,n,o,r)},exports.validateFeePortionConstraints=rr,exports.validateFetchGalaBalanceOptions=ki,exports.validateFetchMessagesOptions=function(e){const t=void 0!==e.type,n=void 0!==e.tokenName&&""!==e.tokenName,r=void 0!==e.userAddress&&""!==e.userAddress;if(!t&&!n&&!r)throw Yt(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==lA.CHAT_MESSAGE&&e.type!==lA.COMMENT)throw new ht(`type must be one of: ${Object.values(lA).join(", ")}`,"type",dt.INVALID_VALUE);if(n){if(!ir(e.tokenName))throw Vt("tokenName","string");if(e.tokenName.length>An.MAX_LENGTH)throw new ht(`tokenName must be at most ${An.MAX_LENGTH} characters`,"tokenName",dt.TOO_LONG)}if(r){if(!ir(e.userAddress))throw Vt("userAddress","string");if(e.userAddress.length>xn.MAX_LENGTH)throw new ht(`userAddress must be at most ${xn.MAX_LENGTH} characters`,"userAddress",dt.TOO_LONG)}void 0!==e.pageSize&&cr(0,void 0,In.MAX_LIMIT,e.pageSize)},exports.validateFetchPoolDetailsData=Di,exports.validateFetchTokenBalanceOptions=Ai,exports.validateFullName=hi,exports.validateGetAmountOptions=Ni,exports.validateGetChatMessagesOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new ht("At least one of tokenName or userAddress is required","options",dt.REQUIRED);if(void 0!==e.tokenName){if(!ir(e.tokenName))throw Vt("tokenName","string");if(e.tokenName.length>An.MAX_LENGTH)throw new ht(`tokenName must be at most ${An.MAX_LENGTH} characters`,"tokenName",dt.TOO_LONG)}if(void 0!==e.userAddress){if(!ir(e.userAddress))throw Vt("userAddress","string");if(e.userAddress.length>xn.MAX_LENGTH)throw new ht(`userAddress must be at most ${xn.MAX_LENGTH} characters`,"userAddress",dt.TOO_LONG)}void 0!==e.pageSize&&cr(0,void 0,In.MAX_LIMIT,e.pageSize)},exports.validateGetCommentsOptions=function(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw Yt(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=Sn;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw Ft("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}cr(0,void 0,In.MAX_LIMIT,e.pageSize,e.cursor)},exports.validateGetTokenBanOptions=YE,exports.validateGetTradeOptions=Ci,exports.validateGetTradesOptions=fA,exports.validateImageUploadOptions=yi,exports.validateInviteCode=function(e){const t=[];return ir(e)?NA(e)||t.push("Invalid invite code format"):t.push(Ut("inviteCode","Invite code").message),t},exports.validateLaunchTokenData=Ri,exports.validateListApiKeysOptions=uv,exports.validateListModeratorInvitesOptions=function(e){const t=[];return Rt(t,()=>{hr(e.tokenName??"","tokenName",vn)}),void 0===e.status||xA(e.status)||Rt(t,()=>{throw Qt("status",e.status,IA,"Status")}),Rt(t,()=>{cr(0,void 0,En,e.pageSize)}),t},exports.validateListOverseerInvitesOptions=lE,exports.validateListOverseersOptions=uE,exports.validateListTokenBansOptions=QE,exports.validateListUsersOptions=pE,exports.validateMessageId=function(e){if(!ir(e))throw Ut("id","Message ID");const t=_n.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new ht("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",dt.INVALID_FORMAT)},exports.validateMinMaxRelationship=function(e,t,n,r){const o="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(o))throw new ht(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(i))throw new ht(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(o>i)throw new ht(`${n} (${o}) must be less than or equal to ${r} (${i})`,n,"INVALID_RANGE")},exports.validateOptionalTokenName=function(e,t="tokenName",n=vn){if(null==e)return;if("string"!=typeof e)throw Vt(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new ht(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,dt.INVALID_FORMAT)},exports.validateOverseerInviteCode=dE,exports.validateOverseerInviteId=gE,exports.validateOverseerWalletAddress=hE,exports.validatePaginationParams=function(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Vt("offset","a non-negative integer",e);Zn(t,"limit")},exports.validateSearchQuery=gi,exports.validateSellTokensData=Ii,exports.validateSortOrderDirection=nr,exports.validateTokenDescription=ci,exports.validateTokenListOptions=bi,exports.validateTokenName=gr,exports.validateTokenSymbol=ai,exports.validateTokenUrls=mi,exports.validateTradeListParams=xi,exports.validateUnbanTokenOptions=XE,exports.validateUpdateApiKeyOptions=lv,exports.validateUpdateChatMessageOptions=function(e){if(!ir(e.content))throw Ut("content");if(0===e.content.trim().length)throw new ht("content cannot be empty","content",dt.REQUIRED);if(e.content.length>Nn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new ht(`content must be at most ${Nn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",dt.TOO_LONG)},exports.validateUpdateCommentOptions=function(e){if(!ir(e.content))throw Ut("content");if(0===e.content.trim().length)throw Zt("content","Content");if(e.content.length>Nn.COMMENTS_V1.MAX_LENGTH)throw Jt("content",Nn.COMMENTS_V1.MAX_LENGTH,e.content.length)},exports.validateUpdateMessageOptions=function(e){if(!ir(e.content))throw Ut("content");if(0===e.content.trim().length)throw Zt("content","Content");const t=Math.max(uA.CONTENT.CHAT_MAX_LENGTH,uA.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw Jt("content",t,e.content.length)},exports.validateUpdatePlatformConfigOptions=yE,exports.validateUpdateProfileData=vi,exports.validateUpdateTokenConfigOptions=dA,exports.validateUploadProfileImageOptions=Si,exports.validateUserTokenName=pi,exports.validateVaultAddress=ui,exports.vaultAddressSchema=jr,exports.walletToProvider=function(e){if(e)return Ls.fromWallet(e)},exports.wasModerationEscalated=function(e){return!0===e.escalatedFromQuick};