@gala-chain/launchpad-sdk 5.0.4-beta.6 → 5.0.4-beta.60

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 (1775) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/EXAMPLES.md +99 -0
  3. package/README.md +163 -49
  4. package/README.md.bak +3174 -0
  5. package/dist/LaunchpadSDK.d.ts +10615 -0
  6. package/dist/LaunchpadSDK.d.ts.map +1 -0
  7. package/dist/ai-docs.json +5081 -1052
  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 +49 -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 +776 -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/logger.d.ts +52 -0
  721. package/dist/examples/utils/logger.d.ts.map +1 -0
  722. package/dist/examples/utils/pool-helpers.d.ts +226 -0
  723. package/dist/examples/utils/pool-helpers.d.ts.map +1 -0
  724. package/dist/examples/utils/punchlist.d.ts +104 -0
  725. package/dist/examples/utils/punchlist.d.ts.map +1 -0
  726. package/dist/examples/utils/sdk-setup.d.ts +423 -0
  727. package/dist/examples/utils/sdk-setup.d.ts.map +1 -0
  728. package/dist/examples/utils/suppress-logging.d.ts +11 -0
  729. package/dist/examples/utils/suppress-logging.d.ts.map +1 -0
  730. package/dist/examples/utils/token-naming.d.ts +117 -0
  731. package/dist/examples/utils/token-naming.d.ts.map +1 -0
  732. package/dist/examples/utils/trade-helpers.d.ts +195 -0
  733. package/dist/examples/utils/trade-helpers.d.ts.map +1 -0
  734. package/dist/examples/utils/transaction-helpers.d.ts +92 -0
  735. package/dist/examples/utils/transaction-helpers.d.ts.map +1 -0
  736. package/dist/examples/wallet/wallet-initialization-complete.d.ts +31 -0
  737. package/dist/examples/wallet/wallet-initialization-complete.d.ts.map +1 -0
  738. package/dist/examples/wallet/wallet-key-rotation.d.ts +28 -0
  739. package/dist/examples/wallet/wallet-key-rotation.d.ts.map +1 -0
  740. package/dist/examples/wallet/wallet-recovery-patterns.d.ts +29 -0
  741. package/dist/examples/wallet/wallet-recovery-patterns.d.ts.map +1 -0
  742. package/dist/examples/wallet/wallet-signature-operations.d.ts +28 -0
  743. package/dist/examples/wallet/wallet-signature-operations.d.ts.map +1 -0
  744. package/dist/examples/wallet-tracking/wallet-balance-monitoring.d.ts +21 -0
  745. package/dist/examples/wallet-tracking/wallet-balance-monitoring.d.ts.map +1 -0
  746. package/dist/examples/wallet-tracking/wallet-portfolio-alerts.d.ts +21 -0
  747. package/dist/examples/wallet-tracking/wallet-portfolio-alerts.d.ts.map +1 -0
  748. package/dist/examples/wallet-tracking/wallet-transaction-tracking.d.ts +21 -0
  749. package/dist/examples/wallet-tracking/wallet-transaction-tracking.d.ts.map +1 -0
  750. package/dist/examples/websocket/websocket-chat-advanced.d.ts +26 -0
  751. package/dist/examples/websocket/websocket-chat-advanced.d.ts.map +1 -0
  752. package/dist/examples/websocket/websocket-chat-events-detailed.d.ts +28 -0
  753. package/dist/examples/websocket/websocket-chat-events-detailed.d.ts.map +1 -0
  754. package/dist/examples/websocket/websocket-chat-events.d.ts +26 -0
  755. package/dist/examples/websocket/websocket-chat-events.d.ts.map +1 -0
  756. package/dist/examples/websocket/websocket-combined-events.d.ts +28 -0
  757. package/dist/examples/websocket/websocket-combined-events.d.ts.map +1 -0
  758. package/dist/examples/websocket/websocket-comprehensive.d.ts +25 -0
  759. package/dist/examples/websocket/websocket-comprehensive.d.ts.map +1 -0
  760. package/dist/examples/websocket/websocket-connected-clients.d.ts +30 -0
  761. package/dist/examples/websocket/websocket-connected-clients.d.ts.map +1 -0
  762. package/dist/examples/websocket/websocket-connection-management.d.ts +28 -0
  763. package/dist/examples/websocket/websocket-connection-management.d.ts.map +1 -0
  764. package/dist/examples/websocket/websocket-content-events.d.ts +28 -0
  765. package/dist/examples/websocket/websocket-content-events.d.ts.map +1 -0
  766. package/dist/examples/websocket/websocket-core-events.d.ts +27 -0
  767. package/dist/examples/websocket/websocket-core-events.d.ts.map +1 -0
  768. package/dist/examples/websocket/websocket-dex-events.d.ts +40 -0
  769. package/dist/examples/websocket/websocket-dex-events.d.ts.map +1 -0
  770. package/dist/examples/websocket/websocket-dex-pools.d.ts +23 -0
  771. package/dist/examples/websocket/websocket-dex-pools.d.ts.map +1 -0
  772. package/dist/examples/websocket/websocket-download-recording.d.ts +26 -0
  773. package/dist/examples/websocket/websocket-download-recording.d.ts.map +1 -0
  774. package/dist/examples/websocket/websocket-interactions.d.ts +25 -0
  775. package/dist/examples/websocket/websocket-interactions.d.ts.map +1 -0
  776. package/dist/examples/websocket/websocket-moderation-events.d.ts +26 -0
  777. package/dist/examples/websocket/websocket-moderation-events.d.ts.map +1 -0
  778. package/dist/examples/websocket/websocket-recording-events.d.ts +24 -0
  779. package/dist/examples/websocket/websocket-recording-events.d.ts.map +1 -0
  780. package/dist/examples/websocket/websocket-room-events.d.ts +27 -0
  781. package/dist/examples/websocket/websocket-room-events.d.ts.map +1 -0
  782. package/dist/examples/websocket/websocket-room-management.d.ts +27 -0
  783. package/dist/examples/websocket/websocket-room-management.d.ts.map +1 -0
  784. package/dist/examples/websocket/websocket-simulcast-events.d.ts +26 -0
  785. package/dist/examples/websocket/websocket-simulcast-events.d.ts.map +1 -0
  786. package/dist/examples/websocket/websocket-stream-auth.d.ts +23 -0
  787. package/dist/examples/websocket/websocket-stream-auth.d.ts.map +1 -0
  788. package/dist/examples/websocket/websocket-stream-countdown.d.ts +38 -0
  789. package/dist/examples/websocket/websocket-stream-countdown.d.ts.map +1 -0
  790. package/dist/examples/websocket/websocket-stream-events.d.ts +26 -0
  791. package/dist/examples/websocket/websocket-stream-events.d.ts.map +1 -0
  792. package/dist/examples/websocket/websocket-stream-status.d.ts +39 -0
  793. package/dist/examples/websocket/websocket-stream-status.d.ts.map +1 -0
  794. package/dist/examples/websocket/websocket-subscription-management.d.ts +27 -0
  795. package/dist/examples/websocket/websocket-subscription-management.d.ts.map +1 -0
  796. package/dist/examples/websocket/websocket-token-creation-events.d.ts +22 -0
  797. package/dist/examples/websocket/websocket-token-creation-events.d.ts.map +1 -0
  798. package/dist/examples/websocket/websocket-token-events.d.ts +24 -0
  799. package/dist/examples/websocket/websocket-token-events.d.ts.map +1 -0
  800. package/dist/examples/websocket/websocket-token-subscription.d.ts +26 -0
  801. package/dist/examples/websocket/websocket-token-subscription.d.ts.map +1 -0
  802. package/dist/examples/websocket/websocket-token-viewers.d.ts +29 -0
  803. package/dist/examples/websocket/websocket-token-viewers.d.ts.map +1 -0
  804. package/dist/examples/websocket/websocket-unsubscribe.d.ts +25 -0
  805. package/dist/examples/websocket/websocket-unsubscribe.d.ts.map +1 -0
  806. package/dist/examples/websocket/websocket-user-events.d.ts +40 -0
  807. package/dist/examples/websocket/websocket-user-events.d.ts.map +1 -0
  808. package/dist/examples/websocket/websocket-user-presence.d.ts +29 -0
  809. package/dist/examples/websocket/websocket-user-presence.d.ts.map +1 -0
  810. package/dist/examples/websocket/websocket-viewer-analytics.d.ts +38 -0
  811. package/dist/examples/websocket/websocket-viewer-analytics.d.ts.map +1 -0
  812. package/dist/examples/wrap/wrap-status-tracking.d.ts +19 -0
  813. package/dist/examples/wrap/wrap-status-tracking.d.ts.map +1 -0
  814. package/dist/examples/wrap/wrap-token-discovery.d.ts +20 -0
  815. package/dist/examples/wrap/wrap-token-discovery.d.ts.map +1 -0
  816. package/dist/helpers/sdk.d.ts +87 -0
  817. package/dist/helpers/sdk.d.ts.map +1 -0
  818. package/dist/helpers/wallet.d.ts +151 -0
  819. package/dist/helpers/wallet.d.ts.map +1 -0
  820. package/dist/index.browser.d.ts +147 -0
  821. package/dist/index.browser.d.ts.map +1 -0
  822. package/dist/index.browser.esm.js +1 -0
  823. package/dist/index.cjs +1 -0
  824. package/dist/index.d.ts +6 -115
  825. package/dist/index.d.ts.map +1 -1
  826. package/dist/index.esm.js +1 -1
  827. package/dist/index.js +1 -1
  828. package/dist/index.node.d.ts +13 -0
  829. package/dist/index.node.d.ts.map +1 -0
  830. package/dist/polyfills/file-global.d.ts +12 -0
  831. package/dist/polyfills/file-global.d.ts.map +1 -0
  832. package/dist/react/WalletContext.d.ts +60 -0
  833. package/dist/react/WalletContext.d.ts.map +1 -0
  834. package/dist/react/index.d.ts +65 -0
  835. package/dist/react/index.d.ts.map +1 -0
  836. package/dist/react/types.d.ts +76 -0
  837. package/dist/react/types.d.ts.map +1 -0
  838. package/dist/react/useWallet.d.ts +123 -0
  839. package/dist/react/useWallet.d.ts.map +1 -0
  840. package/dist/react/useWalletConnection.d.ts +89 -0
  841. package/dist/react/useWalletConnection.d.ts.map +1 -0
  842. package/dist/react/useWalletDetection.d.ts +81 -0
  843. package/dist/react/useWalletDetection.d.ts.map +1 -0
  844. package/dist/react.cjs +1 -0
  845. package/dist/react.esm.js +1 -0
  846. package/dist/schemas/files.d.ts +83 -0
  847. package/dist/schemas/files.d.ts.map +1 -0
  848. package/dist/schemas/index.d.ts +83 -0
  849. package/dist/schemas/index.d.ts.map +1 -0
  850. package/dist/schemas/launchpad.d.ts +135 -0
  851. package/dist/schemas/launchpad.d.ts.map +1 -0
  852. package/dist/schemas/pagination.d.ts +107 -0
  853. package/dist/schemas/pagination.d.ts.map +1 -0
  854. package/dist/schemas/primitives.d.ts +142 -0
  855. package/dist/schemas/primitives.d.ts.map +1 -0
  856. package/dist/schemas/trade.d.ts +140 -0
  857. package/dist/schemas/trade.d.ts.map +1 -0
  858. package/dist/schemas/user.d.ts +99 -0
  859. package/dist/schemas/user.d.ts.map +1 -0
  860. package/dist/schemas/validators.d.ts +332 -0
  861. package/dist/schemas/validators.d.ts.map +1 -0
  862. package/dist/scripts/derive-public-key-from-private-key.d.ts +8 -0
  863. package/dist/scripts/derive-public-key-from-private-key.d.ts.map +1 -0
  864. package/dist/scripts/eslint-fixer.d.ts +7 -0
  865. package/dist/scripts/eslint-fixer.d.ts.map +1 -0
  866. package/dist/scripts/final-fixer.d.ts +7 -0
  867. package/dist/scripts/final-fixer.d.ts.map +1 -0
  868. package/dist/scripts/fix-all-remaining-boolean.d.ts +7 -0
  869. package/dist/scripts/fix-all-remaining-boolean.d.ts.map +1 -0
  870. package/dist/scripts/fix-boolean-expressions-advanced.d.ts +7 -0
  871. package/dist/scripts/fix-boolean-expressions-advanced.d.ts.map +1 -0
  872. package/dist/scripts/fix-boolean-expressions-ast.d.ts +9 -0
  873. package/dist/scripts/fix-boolean-expressions-ast.d.ts.map +1 -0
  874. package/dist/scripts/fix-boolean-expressions-auto.d.ts +7 -0
  875. package/dist/scripts/fix-boolean-expressions-auto.d.ts.map +1 -0
  876. package/dist/scripts/fix-final-aggressive.d.ts +6 -0
  877. package/dist/scripts/fix-final-aggressive.d.ts.map +1 -0
  878. package/dist/scripts/fix-final-boolean.d.ts +7 -0
  879. package/dist/scripts/fix-final-boolean.d.ts.map +1 -0
  880. package/dist/scripts/fix-remaining-boolean.d.ts +7 -0
  881. package/dist/scripts/fix-remaining-boolean.d.ts.map +1 -0
  882. package/dist/scripts/fix-strict-boolean-comprehensive.d.ts +3 -0
  883. package/dist/scripts/fix-strict-boolean-comprehensive.d.ts.map +1 -0
  884. package/dist/scripts/fix-strict-boolean-expressions.d.ts +2 -0
  885. package/dist/scripts/fix-strict-boolean-expressions.d.ts.map +1 -0
  886. package/dist/scripts/fix-strict-boolean-final.d.ts +13 -0
  887. package/dist/scripts/fix-strict-boolean-final.d.ts.map +1 -0
  888. package/dist/scripts/fixer-aggressive.d.ts +7 -0
  889. package/dist/scripts/fixer-aggressive.d.ts.map +1 -0
  890. package/dist/scripts/fixer-conservative.d.ts +7 -0
  891. package/dist/scripts/fixer-conservative.d.ts.map +1 -0
  892. package/dist/scripts/fixer-direct.d.ts +7 -0
  893. package/dist/scripts/fixer-direct.d.ts.map +1 -0
  894. package/dist/scripts/generate-demo-registry.d.ts +14 -0
  895. package/dist/scripts/generate-demo-registry.d.ts.map +1 -0
  896. package/dist/scripts/inject-version.d.ts +8 -0
  897. package/dist/scripts/inject-version.d.ts.map +1 -0
  898. package/dist/scripts/strict-boolean-fixer.d.ts +9 -0
  899. package/dist/scripts/strict-boolean-fixer.d.ts.map +1 -0
  900. package/dist/scripts/validate-demo-registry.d.ts +17 -0
  901. package/dist/scripts/validate-demo-registry.d.ts.map +1 -0
  902. package/dist/services/AIModerationService.d.ts +217 -0
  903. package/dist/services/AIModerationService.d.ts.map +1 -0
  904. package/dist/services/AbstractCacheService.d.ts +227 -0
  905. package/dist/services/AbstractCacheService.d.ts.map +1 -0
  906. package/dist/services/AbstractTokenFetchService.d.ts +150 -0
  907. package/dist/services/AbstractTokenFetchService.d.ts.map +1 -0
  908. package/dist/services/ApiKeyService.d.ts +211 -0
  909. package/dist/services/ApiKeyService.d.ts.map +1 -0
  910. package/dist/services/BanService.d.ts +312 -0
  911. package/dist/services/BanService.d.ts.map +1 -0
  912. package/dist/services/BaseService.d.ts +116 -0
  913. package/dist/services/BaseService.d.ts.map +1 -0
  914. package/dist/services/BatchedCacheService.d.ts +133 -0
  915. package/dist/services/BatchedCacheService.d.ts.map +1 -0
  916. package/dist/services/BridgeableTokenCache.d.ts +120 -0
  917. package/dist/services/BridgeableTokenCache.d.ts.map +1 -0
  918. package/dist/services/BridgeableTokenService.d.ts +218 -0
  919. package/dist/services/BridgeableTokenService.d.ts.map +1 -0
  920. package/dist/services/BundleService.d.ts +245 -0
  921. package/dist/services/BundleService.d.ts.map +1 -0
  922. package/dist/services/BundlerClientFactory.d.ts +32 -0
  923. package/dist/services/BundlerClientFactory.d.ts.map +1 -0
  924. package/dist/services/ChartService.d.ts +106 -0
  925. package/dist/services/ChartService.d.ts.map +1 -0
  926. package/dist/services/ContentFlagService.d.ts +218 -0
  927. package/dist/services/ContentFlagService.d.ts.map +1 -0
  928. package/dist/services/ContentReactionService.d.ts +175 -0
  929. package/dist/services/ContentReactionService.d.ts.map +1 -0
  930. package/dist/services/DexBackendClient.d.ts +225 -0
  931. package/dist/services/DexBackendClient.d.ts.map +1 -0
  932. package/dist/services/DexPoolService.d.ts +137 -0
  933. package/dist/services/DexPoolService.d.ts.map +1 -0
  934. package/dist/services/DexQuoteService.d.ts +446 -0
  935. package/dist/services/DexQuoteService.d.ts.map +1 -0
  936. package/dist/services/DexService.d.ts +433 -0
  937. package/dist/services/DexService.d.ts.map +1 -0
  938. package/dist/services/EventsBatcherService.d.ts +111 -0
  939. package/dist/services/EventsBatcherService.d.ts.map +1 -0
  940. package/dist/services/GSwapAssetService.d.ts +96 -0
  941. package/dist/services/GSwapAssetService.d.ts.map +1 -0
  942. package/dist/services/GSwapLiquidityMutationService.d.ts +138 -0
  943. package/dist/services/GSwapLiquidityMutationService.d.ts.map +1 -0
  944. package/dist/services/GSwapLiquidityQueryService.d.ts +75 -0
  945. package/dist/services/GSwapLiquidityQueryService.d.ts.map +1 -0
  946. package/dist/services/GSwapPoolCalculationService.d.ts +187 -0
  947. package/dist/services/GSwapPoolCalculationService.d.ts.map +1 -0
  948. package/dist/services/GSwapPoolQueryService.d.ts +115 -0
  949. package/dist/services/GSwapPoolQueryService.d.ts.map +1 -0
  950. package/dist/services/GSwapService.d.ts +1207 -0
  951. package/dist/services/GSwapService.d.ts.map +1 -0
  952. package/dist/services/GSwapSwapService.d.ts +68 -0
  953. package/dist/services/GSwapSwapService.d.ts.map +1 -0
  954. package/dist/services/GalaChainBalanceService.d.ts +155 -0
  955. package/dist/services/GalaChainBalanceService.d.ts.map +1 -0
  956. package/dist/services/GalaChainGatewayClient.d.ts +227 -0
  957. package/dist/services/GalaChainGatewayClient.d.ts.map +1 -0
  958. package/dist/services/GalaChainLockService.d.ts +144 -0
  959. package/dist/services/GalaChainLockService.d.ts.map +1 -0
  960. package/dist/services/GalaChainService.d.ts +399 -0
  961. package/dist/services/GalaChainService.d.ts.map +1 -0
  962. package/dist/services/GalaChainTokenService.d.ts +108 -0
  963. package/dist/services/GalaChainTokenService.d.ts.map +1 -0
  964. package/dist/services/GalaChainTransferService.d.ts +205 -0
  965. package/dist/services/GalaChainTransferService.d.ts.map +1 -0
  966. package/dist/services/HolderService.d.ts +181 -0
  967. package/dist/services/HolderService.d.ts.map +1 -0
  968. package/dist/services/ImageService.d.ts +173 -0
  969. package/dist/services/ImageService.d.ts.map +1 -0
  970. package/dist/services/LaunchpadService.d.ts +343 -0
  971. package/dist/services/LaunchpadService.d.ts.map +1 -0
  972. package/dist/services/MessagesService.d.ts +251 -0
  973. package/dist/services/MessagesService.d.ts.map +1 -0
  974. package/dist/services/ModeratorService.d.ts +311 -0
  975. package/dist/services/ModeratorService.d.ts.map +1 -0
  976. package/dist/services/MultiPoolStateManager.d.ts +289 -0
  977. package/dist/services/MultiPoolStateManager.d.ts.map +1 -0
  978. package/dist/services/NetworkKeyedCacheService.d.ts +185 -0
  979. package/dist/services/NetworkKeyedCacheService.d.ts.map +1 -0
  980. package/dist/services/NftCollectionService.d.ts +121 -0
  981. package/dist/services/NftCollectionService.d.ts.map +1 -0
  982. package/dist/services/OEmbedService.d.ts +152 -0
  983. package/dist/services/OEmbedService.d.ts.map +1 -0
  984. package/dist/services/OverseerService.d.ts +524 -0
  985. package/dist/services/OverseerService.d.ts.map +1 -0
  986. package/dist/services/PlatformConfigService.d.ts +149 -0
  987. package/dist/services/PlatformConfigService.d.ts.map +1 -0
  988. package/dist/services/PlatformStatsService.d.ts +72 -0
  989. package/dist/services/PlatformStatsService.d.ts.map +1 -0
  990. package/dist/services/PoolCacheManager.d.ts +258 -0
  991. package/dist/services/PoolCacheManager.d.ts.map +1 -0
  992. package/dist/services/PoolService.d.ts +316 -0
  993. package/dist/services/PoolService.d.ts.map +1 -0
  994. package/dist/services/PoolStateManager.d.ts +176 -0
  995. package/dist/services/PoolStateManager.d.ts.map +1 -0
  996. package/dist/services/PriceHistoryService.d.ts +207 -0
  997. package/dist/services/PriceHistoryService.d.ts.map +1 -0
  998. package/dist/services/RestrictedNamesService.d.ts +80 -0
  999. package/dist/services/RestrictedNamesService.d.ts.map +1 -0
  1000. package/dist/services/SignatureService.d.ts +113 -0
  1001. package/dist/services/SignatureService.d.ts.map +1 -0
  1002. package/dist/services/StreamChatService.d.ts +259 -0
  1003. package/dist/services/StreamChatService.d.ts.map +1 -0
  1004. package/dist/services/StreamTokenServiceBase.d.ts +404 -0
  1005. package/dist/services/StreamTokenServiceBase.d.ts.map +1 -0
  1006. package/dist/services/StreamWebSocketService.d.ts +586 -0
  1007. package/dist/services/StreamWebSocketService.d.ts.map +1 -0
  1008. package/dist/services/StreamingEventService.d.ts +441 -0
  1009. package/dist/services/StreamingEventService.d.ts.map +1 -0
  1010. package/dist/services/StreamingService.d.ts +573 -0
  1011. package/dist/services/StreamingService.d.ts.map +1 -0
  1012. package/dist/services/SwapEventQueue.d.ts +192 -0
  1013. package/dist/services/SwapEventQueue.d.ts.map +1 -0
  1014. package/dist/services/TokenBanService.d.ts +217 -0
  1015. package/dist/services/TokenBanService.d.ts.map +1 -0
  1016. package/dist/services/TokenClassKeyService.d.ts +162 -0
  1017. package/dist/services/TokenClassKeyService.d.ts.map +1 -0
  1018. package/dist/services/TokenMetadataCache.d.ts +310 -0
  1019. package/dist/services/TokenMetadataCache.d.ts.map +1 -0
  1020. package/dist/services/TokenMetadataService.d.ts +509 -0
  1021. package/dist/services/TokenMetadataService.d.ts.map +1 -0
  1022. package/dist/services/TokenResolverService.d.ts +329 -0
  1023. package/dist/services/TokenResolverService.d.ts.map +1 -0
  1024. package/dist/services/TradeService.d.ts +286 -0
  1025. package/dist/services/TradeService.d.ts.map +1 -0
  1026. package/dist/services/TradingQuotesService.d.ts +162 -0
  1027. package/dist/services/TradingQuotesService.d.ts.map +1 -0
  1028. package/dist/services/UserService.d.ts +352 -0
  1029. package/dist/services/UserService.d.ts.map +1 -0
  1030. package/dist/services/WebSocketAdminService.d.ts +587 -0
  1031. package/dist/services/WebSocketAdminService.d.ts.map +1 -0
  1032. package/dist/services/WebSocketService.d.ts +189 -0
  1033. package/dist/services/WebSocketService.d.ts.map +1 -0
  1034. package/dist/services/WeeklyChallengeService.d.ts +114 -0
  1035. package/dist/services/WeeklyChallengeService.d.ts.map +1 -0
  1036. package/dist/services/WrapService.d.ts +172 -0
  1037. package/dist/services/WrapService.d.ts.map +1 -0
  1038. package/dist/services/WrappableTokenCache.d.ts +100 -0
  1039. package/dist/services/WrappableTokenCache.d.ts.map +1 -0
  1040. package/dist/services/WrappableTokenService.d.ts +130 -0
  1041. package/dist/services/WrappableTokenService.d.ts.map +1 -0
  1042. package/dist/services/__mocks__/logger.mock.d.ts +24 -0
  1043. package/dist/services/__mocks__/logger.mock.d.ts.map +1 -0
  1044. package/dist/services/shared/cache-helpers.d.ts +188 -0
  1045. package/dist/services/shared/cache-helpers.d.ts.map +1 -0
  1046. package/dist/services/shared/http-helpers.d.ts +146 -0
  1047. package/dist/services/shared/http-helpers.d.ts.map +1 -0
  1048. package/dist/services/shared/pagination-helpers.d.ts +167 -0
  1049. package/dist/services/shared/pagination-helpers.d.ts.map +1 -0
  1050. package/dist/services/shared/service-validators.d.ts +137 -0
  1051. package/dist/services/shared/service-validators.d.ts.map +1 -0
  1052. package/dist/services/shared/websocket-helpers.d.ts +158 -0
  1053. package/dist/services/shared/websocket-helpers.d.ts.map +1 -0
  1054. package/dist/setup.d.ts +8 -0
  1055. package/dist/setup.d.ts.map +1 -0
  1056. package/dist/src/LaunchpadSDK.d.ts +2192 -404
  1057. package/dist/src/LaunchpadSDK.d.ts.map +1 -1
  1058. package/dist/src/api/LaunchpadAPI.d.ts +15 -8
  1059. package/dist/src/api/LaunchpadAPI.d.ts.map +1 -1
  1060. package/dist/src/api/dto/BondingCurveDTOs.d.ts.map +1 -1
  1061. package/dist/src/api/dto/BurnTokensDto.d.ts +1 -1
  1062. package/dist/src/api/dto/BurnTokensDto.d.ts.map +1 -1
  1063. package/dist/src/api/dto/LockTokenDto.d.ts +1 -1
  1064. package/dist/src/api/dto/LockTokenDto.d.ts.map +1 -1
  1065. package/dist/src/api/dto/TransferTokenDto.d.ts +1 -1
  1066. package/dist/src/api/dto/TransferTokenDto.d.ts.map +1 -1
  1067. package/dist/src/api/dto/UnlockTokenDto.d.ts +1 -1
  1068. package/dist/src/api/dto/UnlockTokenDto.d.ts.map +1 -1
  1069. package/dist/src/auth/JwtAuth.d.ts +43 -5
  1070. package/dist/src/auth/JwtAuth.d.ts.map +1 -1
  1071. package/dist/src/auth/SessionAuthService.d.ts +11 -6
  1072. package/dist/src/auth/SessionAuthService.d.ts.map +1 -1
  1073. package/dist/src/auth/SignatureAuth.d.ts +64 -3
  1074. package/dist/src/auth/SignatureAuth.d.ts.map +1 -1
  1075. package/dist/src/auth/storage.d.ts +66 -0
  1076. package/dist/src/auth/storage.d.ts.map +1 -0
  1077. package/dist/src/auth/types.d.ts +11 -2
  1078. package/dist/src/auth/types.d.ts.map +1 -1
  1079. package/dist/src/bridge/BridgeService.d.ts +1 -1
  1080. package/dist/src/bridge/BridgeService.d.ts.map +1 -1
  1081. package/dist/src/bridge/GalaConnectClient.d.ts +1 -1
  1082. package/dist/src/bridge/GalaConnectClient.d.ts.map +1 -1
  1083. package/dist/src/bridge/constants/tokens.d.ts +1 -1
  1084. package/dist/src/bridge/constants/tokens.d.ts.map +1 -1
  1085. package/dist/src/bridge/index.d.ts +10 -10
  1086. package/dist/src/bridge/index.d.ts.map +1 -1
  1087. package/dist/src/bridge/strategies/BridgeStrategy.d.ts.map +1 -1
  1088. package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts +1 -1
  1089. package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -1
  1090. package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts +1 -1
  1091. package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts.map +1 -1
  1092. package/dist/src/bridge/utils/addressValidation.d.ts.map +1 -1
  1093. package/dist/src/bridge/utils/balanceHelpers.d.ts +1 -1
  1094. package/dist/src/bridge/utils/balanceHelpers.d.ts.map +1 -1
  1095. package/dist/src/bridge/utils/bridgeErrors.d.ts.map +1 -1
  1096. package/dist/src/bridge/utils/bridgeOutHelpers.d.ts +1 -1
  1097. package/dist/src/bridge/utils/bridgeOutHelpers.d.ts.map +1 -1
  1098. package/dist/src/bridge/utils/bridgePayload.d.ts +2 -11
  1099. package/dist/src/bridge/utils/bridgePayload.d.ts.map +1 -1
  1100. package/dist/src/bridge/utils/bridgeStatusParser.d.ts.map +1 -1
  1101. package/dist/src/bridge/utils/eip712Helpers.d.ts.map +1 -1
  1102. package/dist/src/bridge/utils/index.d.ts +9 -9
  1103. package/dist/src/bridge/utils/index.d.ts.map +1 -1
  1104. package/dist/src/bridge/utils/tokenIdUtils.d.ts +1 -1
  1105. package/dist/src/bridge/utils/tokenIdUtils.d.ts.map +1 -1
  1106. package/dist/src/bridge/utils/tokenMetadataResolver.d.ts +1 -1
  1107. package/dist/src/bridge/utils/tokenMetadataResolver.d.ts.map +1 -1
  1108. package/dist/src/config/environments.d.ts +1 -1
  1109. package/dist/src/config/environments.d.ts.map +1 -1
  1110. package/dist/src/constants/endpoints.d.ts +522 -260
  1111. package/dist/src/constants/endpoints.d.ts.map +1 -1
  1112. package/dist/src/constants/events.d.ts +53 -0
  1113. package/dist/src/constants/events.d.ts.map +1 -0
  1114. package/dist/src/constants/pagination.d.ts +23 -13
  1115. package/dist/src/constants/pagination.d.ts.map +1 -1
  1116. package/dist/src/constants/version.generated.d.ts +1 -1
  1117. package/dist/src/constants/version.generated.d.ts.map +1 -1
  1118. package/dist/src/helpers/sdk.d.ts.map +1 -1
  1119. package/dist/src/helpers/wallet.d.ts.map +1 -1
  1120. package/dist/src/index.browser.d.ts +147 -0
  1121. package/dist/src/index.browser.d.ts.map +1 -0
  1122. package/dist/src/index.d.ts +6 -115
  1123. package/dist/src/index.d.ts.map +1 -1
  1124. package/dist/src/index.node.d.ts +13 -0
  1125. package/dist/src/index.node.d.ts.map +1 -0
  1126. package/dist/src/react/WalletContext.d.ts +60 -0
  1127. package/dist/src/react/WalletContext.d.ts.map +1 -0
  1128. package/dist/src/react/index.d.ts +65 -0
  1129. package/dist/src/react/index.d.ts.map +1 -0
  1130. package/dist/src/react/types.d.ts +76 -0
  1131. package/dist/src/react/types.d.ts.map +1 -0
  1132. package/dist/src/react/useWallet.d.ts +123 -0
  1133. package/dist/src/react/useWallet.d.ts.map +1 -0
  1134. package/dist/src/react/useWalletConnection.d.ts +89 -0
  1135. package/dist/src/react/useWalletConnection.d.ts.map +1 -0
  1136. package/dist/src/react/useWalletDetection.d.ts +81 -0
  1137. package/dist/src/react/useWalletDetection.d.ts.map +1 -0
  1138. package/dist/src/schemas/files.d.ts.map +1 -1
  1139. package/dist/src/schemas/index.d.ts +4 -3
  1140. package/dist/src/schemas/index.d.ts.map +1 -1
  1141. package/dist/src/schemas/launchpad.d.ts +1 -0
  1142. package/dist/src/schemas/launchpad.d.ts.map +1 -1
  1143. package/dist/src/schemas/pagination.d.ts +16 -19
  1144. package/dist/src/schemas/pagination.d.ts.map +1 -1
  1145. package/dist/src/schemas/primitives.d.ts +1 -1
  1146. package/dist/src/schemas/primitives.d.ts.map +1 -1
  1147. package/dist/src/schemas/trade.d.ts +2 -2
  1148. package/dist/src/schemas/trade.d.ts.map +1 -1
  1149. package/dist/src/schemas/user.d.ts +2 -2
  1150. package/dist/src/schemas/user.d.ts.map +1 -1
  1151. package/dist/src/schemas/validators.d.ts +6 -5
  1152. package/dist/src/schemas/validators.d.ts.map +1 -1
  1153. package/dist/src/services/AIModerationService.d.ts +217 -0
  1154. package/dist/src/services/AIModerationService.d.ts.map +1 -0
  1155. package/dist/src/services/AbstractTokenFetchService.d.ts +1 -1
  1156. package/dist/src/services/AbstractTokenFetchService.d.ts.map +1 -1
  1157. package/dist/src/services/ApiKeyService.d.ts +14 -9
  1158. package/dist/src/services/ApiKeyService.d.ts.map +1 -1
  1159. package/dist/src/services/BanService.d.ts +132 -16
  1160. package/dist/src/services/BanService.d.ts.map +1 -1
  1161. package/dist/src/services/BaseService.d.ts +1 -1
  1162. package/dist/src/services/BaseService.d.ts.map +1 -1
  1163. package/dist/src/services/BatchedCacheService.d.ts.map +1 -1
  1164. package/dist/src/services/BridgeableTokenCache.d.ts +1 -1
  1165. package/dist/src/services/BridgeableTokenCache.d.ts.map +1 -1
  1166. package/dist/src/services/BridgeableTokenService.d.ts +4 -4
  1167. package/dist/src/services/BridgeableTokenService.d.ts.map +1 -1
  1168. package/dist/src/services/BundleService.d.ts +5 -5
  1169. package/dist/src/services/BundleService.d.ts.map +1 -1
  1170. package/dist/src/services/BundlerClientFactory.d.ts.map +1 -1
  1171. package/dist/src/services/ChartService.d.ts +106 -0
  1172. package/dist/src/services/ChartService.d.ts.map +1 -0
  1173. package/dist/src/services/ContentFlagService.d.ts +13 -7
  1174. package/dist/src/services/ContentFlagService.d.ts.map +1 -1
  1175. package/dist/src/services/ContentReactionService.d.ts +3 -3
  1176. package/dist/src/services/ContentReactionService.d.ts.map +1 -1
  1177. package/dist/src/services/DexBackendClient.d.ts +1 -1
  1178. package/dist/src/services/DexBackendClient.d.ts.map +1 -1
  1179. package/dist/src/services/DexPoolService.d.ts +9 -11
  1180. package/dist/src/services/DexPoolService.d.ts.map +1 -1
  1181. package/dist/src/services/DexQuoteService.d.ts +5 -6
  1182. package/dist/src/services/DexQuoteService.d.ts.map +1 -1
  1183. package/dist/src/services/DexService.d.ts +6 -6
  1184. package/dist/src/services/DexService.d.ts.map +1 -1
  1185. package/dist/src/services/EventsBatcherService.d.ts +111 -0
  1186. package/dist/src/services/EventsBatcherService.d.ts.map +1 -0
  1187. package/dist/src/services/GSwapAssetService.d.ts +18 -2
  1188. package/dist/src/services/GSwapAssetService.d.ts.map +1 -1
  1189. package/dist/src/services/GSwapLiquidityMutationService.d.ts +4 -6
  1190. package/dist/src/services/GSwapLiquidityMutationService.d.ts.map +1 -1
  1191. package/dist/src/services/GSwapLiquidityQueryService.d.ts +2 -14
  1192. package/dist/src/services/GSwapLiquidityQueryService.d.ts.map +1 -1
  1193. package/dist/src/services/GSwapPoolCalculationService.d.ts +0 -13
  1194. package/dist/src/services/GSwapPoolCalculationService.d.ts.map +1 -1
  1195. package/dist/src/services/GSwapPoolQueryService.d.ts +2 -3
  1196. package/dist/src/services/GSwapPoolQueryService.d.ts.map +1 -1
  1197. package/dist/src/services/GSwapService.d.ts +11 -11
  1198. package/dist/src/services/GSwapService.d.ts.map +1 -1
  1199. package/dist/src/services/GSwapSwapService.d.ts +2 -2
  1200. package/dist/src/services/GSwapSwapService.d.ts.map +1 -1
  1201. package/dist/src/services/GalaChainBalanceService.d.ts +2 -2
  1202. package/dist/src/services/GalaChainBalanceService.d.ts.map +1 -1
  1203. package/dist/src/services/GalaChainGatewayClient.d.ts +3 -3
  1204. package/dist/src/services/GalaChainGatewayClient.d.ts.map +1 -1
  1205. package/dist/src/services/GalaChainLockService.d.ts +3 -3
  1206. package/dist/src/services/GalaChainLockService.d.ts.map +1 -1
  1207. package/dist/src/services/GalaChainService.d.ts +10 -13
  1208. package/dist/src/services/GalaChainService.d.ts.map +1 -1
  1209. package/dist/src/services/GalaChainTokenService.d.ts +3 -3
  1210. package/dist/src/services/GalaChainTokenService.d.ts.map +1 -1
  1211. package/dist/src/services/GalaChainTransferService.d.ts +4 -4
  1212. package/dist/src/services/GalaChainTransferService.d.ts.map +1 -1
  1213. package/dist/src/services/HolderService.d.ts +181 -0
  1214. package/dist/src/services/HolderService.d.ts.map +1 -0
  1215. package/dist/src/services/ImageService.d.ts +2 -15
  1216. package/dist/src/services/ImageService.d.ts.map +1 -1
  1217. package/dist/src/services/LaunchpadService.d.ts +67 -24
  1218. package/dist/src/services/LaunchpadService.d.ts.map +1 -1
  1219. package/dist/src/services/MessagesService.d.ts +251 -0
  1220. package/dist/src/services/MessagesService.d.ts.map +1 -0
  1221. package/dist/src/services/ModeratorService.d.ts +58 -22
  1222. package/dist/src/services/ModeratorService.d.ts.map +1 -1
  1223. package/dist/src/services/MultiPoolStateManager.d.ts +17 -10
  1224. package/dist/src/services/MultiPoolStateManager.d.ts.map +1 -1
  1225. package/dist/src/services/NetworkKeyedCacheService.d.ts.map +1 -1
  1226. package/dist/src/services/NftCollectionService.d.ts +3 -5
  1227. package/dist/src/services/NftCollectionService.d.ts.map +1 -1
  1228. package/dist/src/services/OEmbedService.d.ts +152 -0
  1229. package/dist/src/services/OEmbedService.d.ts.map +1 -0
  1230. package/dist/src/services/OverseerService.d.ts +230 -35
  1231. package/dist/src/services/OverseerService.d.ts.map +1 -1
  1232. package/dist/src/services/PlatformConfigService.d.ts +149 -0
  1233. package/dist/src/services/PlatformConfigService.d.ts.map +1 -0
  1234. package/dist/src/services/PlatformStatsService.d.ts +72 -0
  1235. package/dist/src/services/PlatformStatsService.d.ts.map +1 -0
  1236. package/dist/src/services/PoolCacheManager.d.ts +3 -10
  1237. package/dist/src/services/PoolCacheManager.d.ts.map +1 -1
  1238. package/dist/src/services/PoolService.d.ts +108 -25
  1239. package/dist/src/services/PoolService.d.ts.map +1 -1
  1240. package/dist/src/services/PoolStateManager.d.ts +2 -2
  1241. package/dist/src/services/PoolStateManager.d.ts.map +1 -1
  1242. package/dist/src/services/PriceHistoryService.d.ts +11 -12
  1243. package/dist/src/services/PriceHistoryService.d.ts.map +1 -1
  1244. package/dist/src/services/RestrictedNamesService.d.ts +80 -0
  1245. package/dist/src/services/RestrictedNamesService.d.ts.map +1 -0
  1246. package/dist/src/services/SignatureService.d.ts.map +1 -1
  1247. package/dist/src/services/StreamChatService.d.ts +68 -187
  1248. package/dist/src/services/StreamChatService.d.ts.map +1 -1
  1249. package/dist/src/services/StreamTokenServiceBase.d.ts +45 -12
  1250. package/dist/src/services/StreamTokenServiceBase.d.ts.map +1 -1
  1251. package/dist/src/services/StreamWebSocketService.d.ts +335 -17
  1252. package/dist/src/services/StreamWebSocketService.d.ts.map +1 -1
  1253. package/dist/src/services/StreamingEventService.d.ts +16 -6
  1254. package/dist/src/services/StreamingEventService.d.ts.map +1 -1
  1255. package/dist/src/services/StreamingService.d.ts +66 -40
  1256. package/dist/src/services/StreamingService.d.ts.map +1 -1
  1257. package/dist/src/services/SwapEventQueue.d.ts +1 -1
  1258. package/dist/src/services/SwapEventQueue.d.ts.map +1 -1
  1259. package/dist/src/services/TokenBanService.d.ts +18 -16
  1260. package/dist/src/services/TokenBanService.d.ts.map +1 -1
  1261. package/dist/src/services/TokenClassKeyService.d.ts.map +1 -1
  1262. package/dist/src/services/TokenMetadataCache.d.ts.map +1 -1
  1263. package/dist/src/services/TokenMetadataService.d.ts +4 -4
  1264. package/dist/src/services/TokenMetadataService.d.ts.map +1 -1
  1265. package/dist/src/services/TokenResolverService.d.ts +197 -24
  1266. package/dist/src/services/TokenResolverService.d.ts.map +1 -1
  1267. package/dist/src/services/TradeService.d.ts +19 -19
  1268. package/dist/src/services/TradeService.d.ts.map +1 -1
  1269. package/dist/src/services/TradingQuotesService.d.ts +162 -0
  1270. package/dist/src/services/TradingQuotesService.d.ts.map +1 -0
  1271. package/dist/src/services/UserService.d.ts +83 -23
  1272. package/dist/src/services/UserService.d.ts.map +1 -1
  1273. package/dist/src/services/WebSocketAdminService.d.ts +587 -0
  1274. package/dist/src/services/WebSocketAdminService.d.ts.map +1 -0
  1275. package/dist/src/services/WebSocketService.d.ts +7 -1
  1276. package/dist/src/services/WebSocketService.d.ts.map +1 -1
  1277. package/dist/src/services/WeeklyChallengeService.d.ts +114 -0
  1278. package/dist/src/services/WeeklyChallengeService.d.ts.map +1 -0
  1279. package/dist/src/services/WrapService.d.ts +5 -5
  1280. package/dist/src/services/WrapService.d.ts.map +1 -1
  1281. package/dist/src/services/WrappableTokenService.d.ts +3 -3
  1282. package/dist/src/services/WrappableTokenService.d.ts.map +1 -1
  1283. package/dist/src/services/__mocks__/logger.mock.d.ts +14 -7
  1284. package/dist/src/services/__mocks__/logger.mock.d.ts.map +1 -1
  1285. package/dist/src/services/shared/cache-helpers.d.ts.map +1 -1
  1286. package/dist/src/services/shared/http-helpers.d.ts.map +1 -1
  1287. package/dist/src/services/shared/pagination-helpers.d.ts +19 -19
  1288. package/dist/src/services/shared/pagination-helpers.d.ts.map +1 -1
  1289. package/dist/src/services/shared/service-validators.d.ts +1 -1
  1290. package/dist/src/services/shared/service-validators.d.ts.map +1 -1
  1291. package/dist/src/setup.d.ts +2 -2
  1292. package/dist/src/types/ai-moderation.dto.d.ts +294 -0
  1293. package/dist/src/types/ai-moderation.dto.d.ts.map +1 -0
  1294. package/dist/src/types/api-key.dto.d.ts +82 -9
  1295. package/dist/src/types/api-key.dto.d.ts.map +1 -1
  1296. package/dist/src/types/ban.dto.d.ts +174 -3
  1297. package/dist/src/types/ban.dto.d.ts.map +1 -1
  1298. package/dist/src/types/cache-management.dto.d.ts +44 -0
  1299. package/dist/src/types/cache-management.dto.d.ts.map +1 -0
  1300. package/dist/src/types/chat-messages.dto.d.ts +7 -7
  1301. package/dist/src/types/chat-messages.dto.d.ts.map +1 -1
  1302. package/dist/src/types/comment.dto.d.ts +3 -7
  1303. package/dist/src/types/comment.dto.d.ts.map +1 -1
  1304. package/dist/src/types/comments.dto.d.ts +9 -9
  1305. package/dist/src/types/comments.dto.d.ts.map +1 -1
  1306. package/dist/src/types/common.d.ts +115 -27
  1307. package/dist/src/types/common.d.ts.map +1 -1
  1308. package/dist/src/types/composite-pool.dto.d.ts +4 -4
  1309. package/dist/src/types/composite-pool.dto.d.ts.map +1 -1
  1310. package/dist/src/types/constraints.d.ts +6 -2
  1311. package/dist/src/types/constraints.d.ts.map +1 -1
  1312. package/dist/src/types/content-flag.dto.d.ts +43 -4
  1313. package/dist/src/types/content-flag.dto.d.ts.map +1 -1
  1314. package/dist/src/types/content-reactions.dto.d.ts +4 -4
  1315. package/dist/src/types/content-reactions.dto.d.ts.map +1 -1
  1316. package/dist/src/types/dex-pool.dto.d.ts +20 -7
  1317. package/dist/src/types/dex-pool.dto.d.ts.map +1 -1
  1318. package/dist/src/types/dto.d.ts +5 -1
  1319. package/dist/src/types/dto.d.ts.map +1 -1
  1320. package/dist/src/types/engagement-stats.dto.d.ts +62 -0
  1321. package/dist/src/types/engagement-stats.dto.d.ts.map +1 -0
  1322. package/dist/src/types/events.dto.d.ts +80 -0
  1323. package/dist/src/types/events.dto.d.ts.map +1 -0
  1324. package/dist/src/types/global-feed.dto.d.ts +203 -0
  1325. package/dist/src/types/global-feed.dto.d.ts.map +1 -0
  1326. package/dist/src/types/gswap-responses.types.d.ts +14 -14
  1327. package/dist/src/types/gswap-responses.types.d.ts.map +1 -1
  1328. package/dist/src/types/gswap.dto.d.ts +12 -5
  1329. package/dist/src/types/gswap.dto.d.ts.map +1 -1
  1330. package/dist/src/types/holder.types.d.ts +106 -0
  1331. package/dist/src/types/holder.types.d.ts.map +1 -0
  1332. package/dist/src/types/launchpad.dto.d.ts +154 -77
  1333. package/dist/src/types/launchpad.dto.d.ts.map +1 -1
  1334. package/dist/src/types/launchpad.validation.d.ts.map +1 -1
  1335. package/dist/src/types/lock.dto.d.ts +1 -1
  1336. package/dist/src/types/lock.dto.d.ts.map +1 -1
  1337. package/dist/src/types/messages.dto.d.ts +386 -0
  1338. package/dist/src/types/messages.dto.d.ts.map +1 -0
  1339. package/dist/src/types/moderator.dto.d.ts +38 -5
  1340. package/dist/src/types/moderator.dto.d.ts.map +1 -1
  1341. package/dist/src/types/oembed.dto.d.ts +160 -0
  1342. package/dist/src/types/oembed.dto.d.ts.map +1 -0
  1343. package/dist/src/types/options.dto.d.ts +9 -1
  1344. package/dist/src/types/options.dto.d.ts.map +1 -1
  1345. package/dist/src/types/overseer.dto.d.ts +152 -35
  1346. package/dist/src/types/overseer.dto.d.ts.map +1 -1
  1347. package/dist/src/types/platform-config.dto.d.ts +89 -0
  1348. package/dist/src/types/platform-config.dto.d.ts.map +1 -0
  1349. package/dist/src/types/platform-stats.dto.d.ts +40 -0
  1350. package/dist/src/types/platform-stats.dto.d.ts.map +1 -0
  1351. package/dist/src/types/pool-state-delta.dto.d.ts.map +1 -1
  1352. package/dist/src/types/pool.dto.d.ts +6 -1
  1353. package/dist/src/types/pool.dto.d.ts.map +1 -1
  1354. package/dist/src/types/priceHistory.dto.d.ts +6 -2
  1355. package/dist/src/types/priceHistory.dto.d.ts.map +1 -1
  1356. package/dist/src/types/restricted-names.dto.d.ts +50 -0
  1357. package/dist/src/types/restricted-names.dto.d.ts.map +1 -0
  1358. package/dist/src/types/session-auth.dto.d.ts +9 -1
  1359. package/dist/src/types/session-auth.dto.d.ts.map +1 -1
  1360. package/dist/src/types/stream-chat.dto.d.ts +4 -9
  1361. package/dist/src/types/stream-chat.dto.d.ts.map +1 -1
  1362. package/dist/src/types/streaming-events.dto.d.ts +20 -1
  1363. package/dist/src/types/streaming-events.dto.d.ts.map +1 -1
  1364. package/dist/src/types/streaming.dto.d.ts +64 -20
  1365. package/dist/src/types/streaming.dto.d.ts.map +1 -1
  1366. package/dist/src/types/token-ban.dto.d.ts +7 -8
  1367. package/dist/src/types/token-ban.dto.d.ts.map +1 -1
  1368. package/dist/src/types/token-config.dto.d.ts +117 -0
  1369. package/dist/src/types/token-config.dto.d.ts.map +1 -0
  1370. package/dist/src/types/token.types.d.ts +336 -0
  1371. package/dist/src/types/token.types.d.ts.map +1 -0
  1372. package/dist/src/types/trade.dto.d.ts +5 -1
  1373. package/dist/src/types/trade.dto.d.ts.map +1 -1
  1374. package/dist/src/types/trades-query.dto.d.ts +8 -2
  1375. package/dist/src/types/trades-query.dto.d.ts.map +1 -1
  1376. package/dist/src/types/transfer.dto.d.ts.map +1 -1
  1377. package/dist/src/types/user.dto.d.ts +218 -48
  1378. package/dist/src/types/user.dto.d.ts.map +1 -1
  1379. package/dist/src/types/websocket-admin.dto.d.ts +390 -0
  1380. package/dist/src/types/websocket-admin.dto.d.ts.map +1 -0
  1381. package/dist/src/types/websocket-events.dto.d.ts +472 -0
  1382. package/dist/src/types/websocket-events.dto.d.ts.map +1 -0
  1383. package/dist/src/types/weekly-challenge.dto.d.ts +130 -0
  1384. package/dist/src/types/weekly-challenge.dto.d.ts.map +1 -0
  1385. package/dist/src/types/wrappable-token.dto.d.ts +1 -1
  1386. package/dist/src/types/wrappable-token.dto.d.ts.map +1 -1
  1387. package/dist/src/utils/LiquidityEventExtractor.d.ts +7 -0
  1388. package/dist/src/utils/LiquidityEventExtractor.d.ts.map +1 -1
  1389. package/dist/src/utils/Logger.d.ts.map +1 -1
  1390. package/dist/src/utils/MonitoringMetrics.d.ts +0 -1
  1391. package/dist/src/utils/MonitoringMetrics.d.ts.map +1 -1
  1392. package/dist/src/utils/SignatureHelper.d.ts.map +1 -1
  1393. package/dist/src/utils/SwapEventExtractor.d.ts.map +1 -1
  1394. package/dist/src/utils/adapters.d.ts +1 -1
  1395. package/dist/src/utils/adapters.d.ts.map +1 -1
  1396. package/dist/src/utils/address-formatter.d.ts +7 -6
  1397. package/dist/src/utils/address-formatter.d.ts.map +1 -1
  1398. package/dist/src/utils/agent-config.d.ts.map +1 -1
  1399. package/dist/src/utils/amount-validator.d.ts.map +1 -1
  1400. package/dist/src/utils/api-patterns.d.ts +1 -1
  1401. package/dist/src/utils/api-patterns.d.ts.map +1 -1
  1402. package/dist/src/utils/assetUrls.d.ts +450 -0
  1403. package/dist/src/utils/assetUrls.d.ts.map +1 -0
  1404. package/dist/src/utils/auto-pagination.d.ts +89 -0
  1405. package/dist/src/utils/auto-pagination.d.ts.map +1 -1
  1406. package/dist/src/utils/bignumber-helpers.d.ts.map +1 -1
  1407. package/dist/src/utils/bignumber-pool-cache.d.ts.map +1 -1
  1408. package/dist/src/utils/composite-pool-converter.d.ts +4 -4
  1409. package/dist/src/utils/composite-pool-converter.d.ts.map +1 -1
  1410. package/dist/src/utils/crypto-compat.d.ts +40 -0
  1411. package/dist/src/utils/crypto-compat.d.ts.map +1 -0
  1412. package/dist/src/utils/delimiter-parser.d.ts +1 -1
  1413. package/dist/src/utils/delimiter-parser.d.ts.map +1 -1
  1414. package/dist/src/utils/error-factories.d.ts +1 -1
  1415. package/dist/src/utils/error-factories.d.ts.map +1 -1
  1416. package/dist/src/utils/error-handling-patterns.d.ts +1 -1
  1417. package/dist/src/utils/error-handling-patterns.d.ts.map +1 -1
  1418. package/dist/src/utils/error-patterns.d.ts.map +1 -1
  1419. package/dist/src/utils/error-utils.d.ts +1 -1
  1420. package/dist/src/utils/error-utils.d.ts.map +1 -1
  1421. package/dist/src/utils/errors.d.ts +2 -2
  1422. package/dist/src/utils/errors.d.ts.map +1 -1
  1423. package/dist/src/utils/http.d.ts +2 -2
  1424. package/dist/src/utils/http.d.ts.map +1 -1
  1425. package/dist/src/utils/load-env.d.ts.map +1 -1
  1426. package/dist/src/utils/multipart.d.ts.map +1 -1
  1427. package/dist/src/utils/nft-helpers.d.ts.map +1 -1
  1428. package/dist/src/utils/numeric-patterns.d.ts.map +1 -1
  1429. package/dist/src/utils/numeric-wrappers.d.ts +3 -0
  1430. package/dist/src/utils/numeric-wrappers.d.ts.map +1 -1
  1431. package/dist/src/utils/pagination-validation.d.ts +88 -0
  1432. package/dist/src/utils/pagination-validation.d.ts.map +1 -0
  1433. package/dist/src/utils/pool-state-validator.d.ts +1 -1
  1434. package/dist/src/utils/pool-state-validator.d.ts.map +1 -1
  1435. package/dist/src/utils/primitives.d.ts +76 -0
  1436. package/dist/src/utils/primitives.d.ts.map +1 -0
  1437. package/dist/src/utils/query-params.d.ts +6 -6
  1438. package/dist/src/utils/query-params.d.ts.map +1 -1
  1439. package/dist/src/utils/response-handlers.d.ts.map +1 -1
  1440. package/dist/src/utils/response-normalizers.d.ts.map +1 -1
  1441. package/dist/src/utils/safe-parsers.d.ts.map +1 -1
  1442. package/dist/src/utils/service-validators.d.ts.map +1 -1
  1443. package/dist/src/utils/slippage-utils.d.ts.map +1 -1
  1444. package/dist/src/utils/string-patterns.d.ts +3 -3
  1445. package/dist/src/utils/string-patterns.d.ts.map +1 -1
  1446. package/dist/src/utils/swap-delta-calculator.d.ts +2 -2
  1447. package/dist/src/utils/swap-delta-calculator.d.ts.map +1 -1
  1448. package/dist/src/utils/tick-crossing-handler.d.ts.map +1 -1
  1449. package/dist/src/utils/token-format-converter.d.ts +1 -1
  1450. package/dist/src/utils/token-format-converter.d.ts.map +1 -1
  1451. package/dist/src/utils/token-stringification.d.ts.map +1 -1
  1452. package/dist/src/utils/tokenNormalizer.d.ts +1 -1
  1453. package/dist/src/utils/tokenNormalizer.d.ts.map +1 -1
  1454. package/dist/src/utils/trade-transformers.d.ts +1 -1
  1455. package/dist/src/utils/trade-transformers.d.ts.map +1 -1
  1456. package/dist/src/utils/validation-helpers.d.ts +5 -97
  1457. package/dist/src/utils/validation-helpers.d.ts.map +1 -1
  1458. package/dist/src/utils/validation-patterns.d.ts.map +1 -1
  1459. package/dist/src/utils/validation.d.ts +1 -1
  1460. package/dist/src/utils/validation.d.ts.map +1 -1
  1461. package/dist/src/utils/wallet.d.ts.map +1 -1
  1462. package/dist/src/utils/websocket-patterns.d.ts +1 -2
  1463. package/dist/src/utils/websocket-patterns.d.ts.map +1 -1
  1464. package/dist/src/utils/websocket-validators.d.ts +1 -1
  1465. package/dist/src/utils/websocket-validators.d.ts.map +1 -1
  1466. package/dist/src/wallet/ExternalWalletProvider.d.ts +109 -0
  1467. package/dist/src/wallet/ExternalWalletProvider.d.ts.map +1 -0
  1468. package/dist/src/wallet/GalaChainConnectProvider.d.ts +125 -0
  1469. package/dist/src/wallet/GalaChainConnectProvider.d.ts.map +1 -0
  1470. package/dist/src/wallet/GalaWalletProvider.d.ts +139 -0
  1471. package/dist/src/wallet/GalaWalletProvider.d.ts.map +1 -0
  1472. package/dist/src/wallet/PrivateKeyProvider.d.ts +90 -0
  1473. package/dist/src/wallet/PrivateKeyProvider.d.ts.map +1 -0
  1474. package/dist/src/wallet/detection.d.ts +107 -0
  1475. package/dist/src/wallet/detection.d.ts.map +1 -0
  1476. package/dist/src/wallet/index.d.ts +52 -0
  1477. package/dist/src/wallet/index.d.ts.map +1 -0
  1478. package/dist/src/wallet/types.d.ts +267 -0
  1479. package/dist/src/wallet/types.d.ts.map +1 -0
  1480. package/dist/src/wallet/utils.d.ts +117 -0
  1481. package/dist/src/wallet/utils.d.ts.map +1 -0
  1482. package/dist/test-constants.d.ts +29 -0
  1483. package/dist/test-constants.d.ts.map +1 -0
  1484. package/dist/types/ai-moderation.dto.d.ts +294 -0
  1485. package/dist/types/ai-moderation.dto.d.ts.map +1 -0
  1486. package/dist/types/api-key.dto.d.ts +373 -0
  1487. package/dist/types/api-key.dto.d.ts.map +1 -0
  1488. package/dist/types/backend-responses.d.ts +235 -0
  1489. package/dist/types/backend-responses.d.ts.map +1 -0
  1490. package/dist/types/ban.dto.d.ts +577 -0
  1491. package/dist/types/ban.dto.d.ts.map +1 -0
  1492. package/dist/types/burn.dto.d.ts +170 -0
  1493. package/dist/types/burn.dto.d.ts.map +1 -0
  1494. package/dist/types/cache-management.dto.d.ts +44 -0
  1495. package/dist/types/cache-management.dto.d.ts.map +1 -0
  1496. package/dist/types/chat-messages.dto.d.ts +193 -0
  1497. package/dist/types/chat-messages.dto.d.ts.map +1 -0
  1498. package/dist/types/comment.dto.d.ts +176 -0
  1499. package/dist/types/comment.dto.d.ts.map +1 -0
  1500. package/dist/types/comments.dto.d.ts +198 -0
  1501. package/dist/types/comments.dto.d.ts.map +1 -0
  1502. package/dist/types/common.d.ts +602 -0
  1503. package/dist/types/common.d.ts.map +1 -0
  1504. package/dist/types/composite-pool.dto.d.ts +103 -0
  1505. package/dist/types/composite-pool.dto.d.ts.map +1 -0
  1506. package/dist/types/constraints.d.ts +378 -0
  1507. package/dist/types/constraints.d.ts.map +1 -0
  1508. package/dist/types/content-flag.dto.d.ts +337 -0
  1509. package/dist/types/content-flag.dto.d.ts.map +1 -0
  1510. package/dist/types/content-reactions.dto.d.ts +132 -0
  1511. package/dist/types/content-reactions.dto.d.ts.map +1 -0
  1512. package/dist/types/dex-pool.dto.d.ts +214 -0
  1513. package/dist/types/dex-pool.dto.d.ts.map +1 -0
  1514. package/dist/types/dto.d.ts +183 -0
  1515. package/dist/types/dto.d.ts.map +1 -0
  1516. package/dist/types/engagement-stats.dto.d.ts +62 -0
  1517. package/dist/types/engagement-stats.dto.d.ts.map +1 -0
  1518. package/dist/types/events.dto.d.ts +80 -0
  1519. package/dist/types/events.dto.d.ts.map +1 -0
  1520. package/dist/types/galachain-api.types.d.ts +297 -0
  1521. package/dist/types/galachain-api.types.d.ts.map +1 -0
  1522. package/dist/types/global-feed.dto.d.ts +203 -0
  1523. package/dist/types/global-feed.dto.d.ts.map +1 -0
  1524. package/dist/types/gswap-responses.types.d.ts +369 -0
  1525. package/dist/types/gswap-responses.types.d.ts.map +1 -0
  1526. package/dist/types/gswap.dto.d.ts +448 -0
  1527. package/dist/types/gswap.dto.d.ts.map +1 -0
  1528. package/dist/types/holder.types.d.ts +106 -0
  1529. package/dist/types/holder.types.d.ts.map +1 -0
  1530. package/dist/types/launchpad.dto.d.ts +1264 -0
  1531. package/dist/types/launchpad.dto.d.ts.map +1 -0
  1532. package/dist/types/launchpad.validation.d.ts +43 -0
  1533. package/dist/types/launchpad.validation.d.ts.map +1 -0
  1534. package/dist/types/liquidity-monitor.dto.d.ts +177 -0
  1535. package/dist/types/liquidity-monitor.dto.d.ts.map +1 -0
  1536. package/dist/types/lock.dto.d.ts +261 -0
  1537. package/dist/types/lock.dto.d.ts.map +1 -0
  1538. package/dist/types/messages.dto.d.ts +386 -0
  1539. package/dist/types/messages.dto.d.ts.map +1 -0
  1540. package/dist/types/moderator.dto.d.ts +607 -0
  1541. package/dist/types/moderator.dto.d.ts.map +1 -0
  1542. package/dist/types/nft.dto.d.ts +155 -0
  1543. package/dist/types/nft.dto.d.ts.map +1 -0
  1544. package/dist/types/oembed.dto.d.ts +160 -0
  1545. package/dist/types/oembed.dto.d.ts.map +1 -0
  1546. package/dist/types/options.dto.d.ts +485 -0
  1547. package/dist/types/options.dto.d.ts.map +1 -0
  1548. package/dist/types/overseer.dto.d.ts +530 -0
  1549. package/dist/types/overseer.dto.d.ts.map +1 -0
  1550. package/dist/types/platform-config.dto.d.ts +89 -0
  1551. package/dist/types/platform-config.dto.d.ts.map +1 -0
  1552. package/dist/types/platform-stats.dto.d.ts +40 -0
  1553. package/dist/types/platform-stats.dto.d.ts.map +1 -0
  1554. package/dist/types/pool-state-delta.dto.d.ts +246 -0
  1555. package/dist/types/pool-state-delta.dto.d.ts.map +1 -0
  1556. package/dist/types/pool.dto.d.ts +111 -0
  1557. package/dist/types/pool.dto.d.ts.map +1 -0
  1558. package/dist/types/priceHistory.dto.d.ts +165 -0
  1559. package/dist/types/priceHistory.dto.d.ts.map +1 -0
  1560. package/dist/types/restricted-names.dto.d.ts +50 -0
  1561. package/dist/types/restricted-names.dto.d.ts.map +1 -0
  1562. package/dist/types/result.types.d.ts +104 -0
  1563. package/dist/types/result.types.d.ts.map +1 -0
  1564. package/dist/types/session-auth.dto.d.ts +99 -0
  1565. package/dist/types/session-auth.dto.d.ts.map +1 -0
  1566. package/dist/types/stream-chat.dto.d.ts +810 -0
  1567. package/dist/types/stream-chat.dto.d.ts.map +1 -0
  1568. package/dist/types/streaming-events.dto.d.ts +605 -0
  1569. package/dist/types/streaming-events.dto.d.ts.map +1 -0
  1570. package/dist/types/streaming.dto.d.ts +1178 -0
  1571. package/dist/types/streaming.dto.d.ts.map +1 -0
  1572. package/dist/types/swap-monitor.dto.d.ts +256 -0
  1573. package/dist/types/swap-monitor.dto.d.ts.map +1 -0
  1574. package/dist/types/token-ban.dto.d.ts +194 -0
  1575. package/dist/types/token-ban.dto.d.ts.map +1 -0
  1576. package/dist/types/token-config.dto.d.ts +117 -0
  1577. package/dist/types/token-config.dto.d.ts.map +1 -0
  1578. package/dist/types/token.types.d.ts +336 -0
  1579. package/dist/types/token.types.d.ts.map +1 -0
  1580. package/dist/types/trade.dto.d.ts +457 -0
  1581. package/dist/types/trade.dto.d.ts.map +1 -0
  1582. package/dist/types/trades-query.dto.d.ts +133 -0
  1583. package/dist/types/trades-query.dto.d.ts.map +1 -0
  1584. package/dist/types/transfer.dto.d.ts +156 -0
  1585. package/dist/types/transfer.dto.d.ts.map +1 -0
  1586. package/dist/types/user.dto.d.ts +880 -0
  1587. package/dist/types/user.dto.d.ts.map +1 -0
  1588. package/dist/types/websocket-admin.dto.d.ts +390 -0
  1589. package/dist/types/websocket-admin.dto.d.ts.map +1 -0
  1590. package/dist/types/websocket-data.types.d.ts +35 -0
  1591. package/dist/types/websocket-data.types.d.ts.map +1 -0
  1592. package/dist/types/websocket-events.dto.d.ts +472 -0
  1593. package/dist/types/websocket-events.dto.d.ts.map +1 -0
  1594. package/dist/types/websocket.types.d.ts +118 -0
  1595. package/dist/types/websocket.types.d.ts.map +1 -0
  1596. package/dist/types/weekly-challenge.dto.d.ts +130 -0
  1597. package/dist/types/weekly-challenge.dto.d.ts.map +1 -0
  1598. package/dist/types/wrappable-token.dto.d.ts +305 -0
  1599. package/dist/types/wrappable-token.dto.d.ts.map +1 -0
  1600. package/dist/utils/LiquidityEventExtractor.d.ts +106 -0
  1601. package/dist/utils/LiquidityEventExtractor.d.ts.map +1 -0
  1602. package/dist/utils/Logger.d.ts +136 -0
  1603. package/dist/utils/Logger.d.ts.map +1 -0
  1604. package/dist/utils/MonitoringMetrics.d.ts +151 -0
  1605. package/dist/utils/MonitoringMetrics.d.ts.map +1 -0
  1606. package/dist/utils/PoolKeyNormalizer.d.ts +135 -0
  1607. package/dist/utils/PoolKeyNormalizer.d.ts.map +1 -0
  1608. package/dist/utils/ReconnectionManager.d.ts +142 -0
  1609. package/dist/utils/ReconnectionManager.d.ts.map +1 -0
  1610. package/dist/utils/SignatureHelper.d.ts +140 -0
  1611. package/dist/utils/SignatureHelper.d.ts.map +1 -0
  1612. package/dist/utils/SwapEventExtractor.d.ts +152 -0
  1613. package/dist/utils/SwapEventExtractor.d.ts.map +1 -0
  1614. package/dist/utils/adapters.d.ts +111 -0
  1615. package/dist/utils/adapters.d.ts.map +1 -0
  1616. package/dist/utils/address-formatter.d.ts +318 -0
  1617. package/dist/utils/address-formatter.d.ts.map +1 -0
  1618. package/dist/utils/agent-config.d.ts +288 -0
  1619. package/dist/utils/agent-config.d.ts.map +1 -0
  1620. package/dist/utils/amount-validator.d.ts +268 -0
  1621. package/dist/utils/amount-validator.d.ts.map +1 -0
  1622. package/dist/utils/api-patterns.d.ts +347 -0
  1623. package/dist/utils/api-patterns.d.ts.map +1 -0
  1624. package/dist/utils/array-helpers.d.ts +115 -0
  1625. package/dist/utils/array-helpers.d.ts.map +1 -0
  1626. package/dist/utils/assetUrls.d.ts +450 -0
  1627. package/dist/utils/assetUrls.d.ts.map +1 -0
  1628. package/dist/utils/async-patterns.d.ts +272 -0
  1629. package/dist/utils/async-patterns.d.ts.map +1 -0
  1630. package/dist/utils/auto-pagination.d.ts +549 -0
  1631. package/dist/utils/auto-pagination.d.ts.map +1 -0
  1632. package/dist/utils/bignumber-helpers.d.ts +446 -0
  1633. package/dist/utils/bignumber-helpers.d.ts.map +1 -0
  1634. package/dist/utils/bignumber-pool-cache.d.ts +169 -0
  1635. package/dist/utils/bignumber-pool-cache.d.ts.map +1 -0
  1636. package/dist/utils/bondingCurveCalculations.d.ts +144 -0
  1637. package/dist/utils/bondingCurveCalculations.d.ts.map +1 -0
  1638. package/dist/utils/cacheWarmingHelpers.d.ts +110 -0
  1639. package/dist/utils/cacheWarmingHelpers.d.ts.map +1 -0
  1640. package/dist/utils/composite-pool-converter.d.ts +121 -0
  1641. package/dist/utils/composite-pool-converter.d.ts.map +1 -0
  1642. package/dist/utils/crypto-compat.d.ts +40 -0
  1643. package/dist/utils/crypto-compat.d.ts.map +1 -0
  1644. package/dist/utils/data-transform-patterns.d.ts +393 -0
  1645. package/dist/utils/data-transform-patterns.d.ts.map +1 -0
  1646. package/dist/utils/date-utils.d.ts +205 -0
  1647. package/dist/utils/date-utils.d.ts.map +1 -0
  1648. package/dist/utils/delimiter-parser.d.ts +139 -0
  1649. package/dist/utils/delimiter-parser.d.ts.map +1 -0
  1650. package/dist/utils/error-factories.d.ts +701 -0
  1651. package/dist/utils/error-factories.d.ts.map +1 -0
  1652. package/dist/utils/error-handling-patterns.d.ts +390 -0
  1653. package/dist/utils/error-handling-patterns.d.ts.map +1 -0
  1654. package/dist/utils/error-patterns.d.ts +360 -0
  1655. package/dist/utils/error-patterns.d.ts.map +1 -0
  1656. package/dist/utils/error-utils.d.ts +458 -0
  1657. package/dist/utils/error-utils.d.ts.map +1 -0
  1658. package/dist/utils/error-wrapper.d.ts +208 -0
  1659. package/dist/utils/error-wrapper.d.ts.map +1 -0
  1660. package/dist/utils/errors.d.ts +548 -0
  1661. package/dist/utils/errors.d.ts.map +1 -0
  1662. package/dist/utils/http-factory.d.ts +36 -0
  1663. package/dist/utils/http-factory.d.ts.map +1 -0
  1664. package/dist/utils/http.d.ts +97 -0
  1665. package/dist/utils/http.d.ts.map +1 -0
  1666. package/dist/utils/load-env.d.ts +31 -0
  1667. package/dist/utils/load-env.d.ts.map +1 -0
  1668. package/dist/utils/multipart-helpers.d.ts +38 -0
  1669. package/dist/utils/multipart-helpers.d.ts.map +1 -0
  1670. package/dist/utils/multipart.d.ts +63 -0
  1671. package/dist/utils/multipart.d.ts.map +1 -0
  1672. package/dist/utils/nft-helpers.d.ts +62 -0
  1673. package/dist/utils/nft-helpers.d.ts.map +1 -0
  1674. package/dist/utils/numeric-patterns.d.ts +289 -0
  1675. package/dist/utils/numeric-patterns.d.ts.map +1 -0
  1676. package/dist/utils/numeric-wrappers.d.ts +149 -0
  1677. package/dist/utils/numeric-wrappers.d.ts.map +1 -0
  1678. package/dist/utils/object-extractors.d.ts +115 -0
  1679. package/dist/utils/object-extractors.d.ts.map +1 -0
  1680. package/dist/utils/object-patterns.d.ts +81 -0
  1681. package/dist/utils/object-patterns.d.ts.map +1 -0
  1682. package/dist/utils/pagination-helpers.d.ts +161 -0
  1683. package/dist/utils/pagination-helpers.d.ts.map +1 -0
  1684. package/dist/utils/pagination-validation.d.ts +88 -0
  1685. package/dist/utils/pagination-validation.d.ts.map +1 -0
  1686. package/dist/utils/pool-pair-parser.d.ts +57 -0
  1687. package/dist/utils/pool-pair-parser.d.ts.map +1 -0
  1688. package/dist/utils/pool-state-validator.d.ts +207 -0
  1689. package/dist/utils/pool-state-validator.d.ts.map +1 -0
  1690. package/dist/utils/position-filters.d.ts +252 -0
  1691. package/dist/utils/position-filters.d.ts.map +1 -0
  1692. package/dist/utils/primitives.d.ts +76 -0
  1693. package/dist/utils/primitives.d.ts.map +1 -0
  1694. package/dist/utils/query-params.d.ts +89 -0
  1695. package/dist/utils/query-params.d.ts.map +1 -0
  1696. package/dist/utils/response-handlers.d.ts +225 -0
  1697. package/dist/utils/response-handlers.d.ts.map +1 -0
  1698. package/dist/utils/response-helpers.d.ts +28 -0
  1699. package/dist/utils/response-helpers.d.ts.map +1 -0
  1700. package/dist/utils/response-normalizers.d.ts +115 -0
  1701. package/dist/utils/response-normalizers.d.ts.map +1 -0
  1702. package/dist/utils/safe-parsers.d.ts +487 -0
  1703. package/dist/utils/safe-parsers.d.ts.map +1 -0
  1704. package/dist/utils/service-validators.d.ts +268 -0
  1705. package/dist/utils/service-validators.d.ts.map +1 -0
  1706. package/dist/utils/slippage-utils.d.ts +70 -0
  1707. package/dist/utils/slippage-utils.d.ts.map +1 -0
  1708. package/dist/utils/string-patterns.d.ts +404 -0
  1709. package/dist/utils/string-patterns.d.ts.map +1 -0
  1710. package/dist/utils/string-transforms.d.ts +89 -0
  1711. package/dist/utils/string-transforms.d.ts.map +1 -0
  1712. package/dist/utils/string-utils.d.ts +108 -0
  1713. package/dist/utils/string-utils.d.ts.map +1 -0
  1714. package/dist/utils/swap-delta-calculator.d.ts +231 -0
  1715. package/dist/utils/swap-delta-calculator.d.ts.map +1 -0
  1716. package/dist/utils/tick-crossing-handler.d.ts +250 -0
  1717. package/dist/utils/tick-crossing-handler.d.ts.map +1 -0
  1718. package/dist/utils/token-format-converter.d.ts +175 -0
  1719. package/dist/utils/token-format-converter.d.ts.map +1 -0
  1720. package/dist/utils/token-parser.d.ts +235 -0
  1721. package/dist/utils/token-parser.d.ts.map +1 -0
  1722. package/dist/utils/token-stringification.d.ts +168 -0
  1723. package/dist/utils/token-stringification.d.ts.map +1 -0
  1724. package/dist/utils/tokenNameNormalizer.d.ts +96 -0
  1725. package/dist/utils/tokenNameNormalizer.d.ts.map +1 -0
  1726. package/dist/utils/tokenNormalizer.d.ts +167 -0
  1727. package/dist/utils/tokenNormalizer.d.ts.map +1 -0
  1728. package/dist/utils/trade-transformers.d.ts +28 -0
  1729. package/dist/utils/trade-transformers.d.ts.map +1 -0
  1730. package/dist/utils/transfer-validation.d.ts +58 -0
  1731. package/dist/utils/transfer-validation.d.ts.map +1 -0
  1732. package/dist/utils/type-guard-factory.d.ts +260 -0
  1733. package/dist/utils/type-guard-factory.d.ts.map +1 -0
  1734. package/dist/utils/unique-key-generator.d.ts +148 -0
  1735. package/dist/utils/unique-key-generator.d.ts.map +1 -0
  1736. package/dist/utils/validation-helpers.d.ts +1074 -0
  1737. package/dist/utils/validation-helpers.d.ts.map +1 -0
  1738. package/dist/utils/validation-patterns.d.ts +768 -0
  1739. package/dist/utils/validation-patterns.d.ts.map +1 -0
  1740. package/dist/utils/validation.d.ts +140 -0
  1741. package/dist/utils/validation.d.ts.map +1 -0
  1742. package/dist/utils/wallet.d.ts +185 -0
  1743. package/dist/utils/wallet.d.ts.map +1 -0
  1744. package/dist/utils/websocket-errors.d.ts +30 -0
  1745. package/dist/utils/websocket-errors.d.ts.map +1 -0
  1746. package/dist/utils/websocket-patterns.d.ts +680 -0
  1747. package/dist/utils/websocket-patterns.d.ts.map +1 -0
  1748. package/dist/utils/websocket-validators.d.ts +30 -0
  1749. package/dist/utils/websocket-validators.d.ts.map +1 -0
  1750. package/dist/wallet/ExternalWalletProvider.d.ts +109 -0
  1751. package/dist/wallet/ExternalWalletProvider.d.ts.map +1 -0
  1752. package/dist/wallet/GalaChainConnectProvider.d.ts +125 -0
  1753. package/dist/wallet/GalaChainConnectProvider.d.ts.map +1 -0
  1754. package/dist/wallet/GalaWalletProvider.d.ts +139 -0
  1755. package/dist/wallet/GalaWalletProvider.d.ts.map +1 -0
  1756. package/dist/wallet/PrivateKeyProvider.d.ts +90 -0
  1757. package/dist/wallet/PrivateKeyProvider.d.ts.map +1 -0
  1758. package/dist/wallet/detection.d.ts +107 -0
  1759. package/dist/wallet/detection.d.ts.map +1 -0
  1760. package/dist/wallet/index.d.ts +52 -0
  1761. package/dist/wallet/index.d.ts.map +1 -0
  1762. package/dist/wallet/types.d.ts +267 -0
  1763. package/dist/wallet/types.d.ts.map +1 -0
  1764. package/dist/wallet/utils.d.ts +117 -0
  1765. package/dist/wallet/utils.d.ts.map +1 -0
  1766. package/dist/wallet.cjs +1 -0
  1767. package/dist/wallet.esm.js +1 -0
  1768. package/package.json +131 -33
  1769. package/dist/index.cjs.js +0 -1
  1770. package/dist/src/services/ChatMessagesService.d.ts +0 -152
  1771. package/dist/src/services/ChatMessagesService.d.ts.map +0 -1
  1772. package/dist/src/services/CommentService.d.ts +0 -119
  1773. package/dist/src/services/CommentService.d.ts.map +0 -1
  1774. package/dist/src/services/CommentsService.d.ts +0 -155
  1775. package/dist/src/services/CommentsService.d.ts.map +0 -1
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{ethers as e,getAddress as t,isAddress as n,JsonRpcProvider as i,Wallet as r,Contract as o,Signature as s,keccak256 as a,toUtf8Bytes as c,Mnemonic as l,HDNodeWallet as u,SigningKey as d,computeAddress as h}from"ethers";import g from"axios";import{SigningType as f,SigningClient as p,ChainCallDTO as m,calculatePersonalSignPrefix as y}from"@gala-chain/connect";import{z as w}from"zod";import k from"bignumber.js";import b,{v4 as v}from"uuid";import{TokenClassKey as S,TokenBalance as A}from"@gala-chain/api";import{io as T}from"socket.io-client";import{tickToSqrtPrice as E,getLiquidityForAmounts as I,getAmountsForLiquidity as C,liquidity0 as N,liquidity1 as x,getAmount0Delta as _,getAmount1Delta as B,Pool as P,TickData as D,CompositePoolDto as R,GetCompositePoolDto as M,QuoteExactAmountDto as L,quoteExactAmount as F,sqrtPriceToTick as U,computeSwapStep as O}from"@gala-chain/dex";import*as $ from"node:crypto";import q from"node:crypto";import*as K from"path";import*as G from"fs";import*as W from"dotenv";import H from"crypto";if("undefined"==typeof File){const{File:e}=require("web-file-polyfill");global.File=e}function z(e,t=3e4){return g.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}var j;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(j||(j={}));class V extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}function X(e){return e instanceof Error}function Q(e){return X(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 J(e){return X(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Z(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 Y(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function ee(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 i=n.Status;if("number"!=typeof i)throw new Error(`${t}: Response Status must be a number, got ${typeof i}`);if(1!==i)throw new Error(`${t}: Response status indicates failure (Status: ${i})`);return n}function te(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function ne(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 ie={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 re extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class oe extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class se extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class ae extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class ce extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class le extends Error{constructor(e,t,n,i){super(e),this.originalError=t,this.transactionHash=n,this.code=i,this.name="GSwapSwapError"}}class ue extends Error{constructor(e,t,n,i,r){super(e),this.originalError=t,this.tokenA=n,this.tokenB=i,this.code=r,this.name="GSwapPoolError"}}class de extends Error{constructor(e,t,n,i){super(e),this.originalError=t,this.walletAddress=n,this.code=i,this.name="GSwapAssetError"}}class he extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class ge extends re{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class fe extends re{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function pe(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function me(e,t){return new re(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function ye(e,t){const n=pe(e,t);return new re(`${n} is required`,e,"REQUIRED")}function we(e,t,n){const i=pe(e,n);return new re(`${i} must be ${t}`,e,"INVALID_FORMAT")}function ke(e,t,n){return new oe(e,t,n)}function be(e,t){return new se(e,t)}function ve(e,t,n){return new ae(e,t,n)}function Se(e,t,n,i){n&&n.error(`${t}:`,e);const r=Y(e)?e.response?.status:void 0;return ke(`${t}: ${Q(e)}`,r,X(e)?e:void 0)}function Ae(e,t,n,i,r){const o=pe(e,r);return new re(`${o} must be between ${t} and ${n}${void 0!==i?`, received: ${i}`:""}`,e,"OUT_OF_RANGE")}function Te(e,t,n,i){const r=pe(e,i);return new re(`${r} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Ee(e,t,n,i){const r=pe(e,i);return new re(`${r} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Ie(e,t,n,i){const r=pe(e,i),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new re(`${r} must be ${t}${o}`,e,"INVALID_TYPE")}function Ce(e,t,n){const i=pe(e,n);return new re(`${i} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Ne(e){return new re(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function xe(e,t,n,i){const r=pe(e,i);return new re(`Invalid ${r}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function _e(e,t,n,i){const r=pe(e,i);return new re(`${r} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function Be(e,t){const n=pe(e,t);return new re(`${n} cannot be empty`,e,"EMPTY_STRING")}function Pe(e,t,n,i){if("number"!=typeof e)throw Ie(i,"a number",e,i);if(e<t||e>n)throw Ae(i,t,n,e)}function De(e,t,n){if("string"!=typeof e)throw Ie(n,"a string",e,n);if(e.length>t)throw Ee(n,t,e.length)}function Re(e,t){if("number"!=typeof e)throw Ie(t,"a number",e,t);if(!Number.isInteger(e))throw Ie(t,"an integer",e,t);if(e<=0)throw Te(t,1,e,t)}function Me(e,t,n="range"){const i="number"==typeof e?e:Number(e),r="number"==typeof t?t:Number(t);if(isNaN(i)||isNaN(r))throw Ie(n,"numeric values",void 0,n);if(i>r)throw new re(`Minimum value (${i}) must be less than or equal to maximum value (${r}) for ${n}`,n,ie.INVALID_RANGE)}function Le(e,t,n=!1){if("string"!=typeof e)throw Ie(t,"a string",e,t);if(!n&&0===e.trim().length)throw ye(t,`${t} (non-empty string)`)}function Fe(e,t){if("ASC"!==e&&"DESC"!==e)throw new re(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function Ue(e,t,n,i){const r="string"==typeof e?parseFloat(e):e;if(!isFinite(r))throw new re(`${i} must be a valid finite number between ${t} and ${n}`,i,"INVALID_NUMBER");if(r<t||r>n)throw Ae(i,t,n,r,i)}function Oe(e,t,n){const i="string"==typeof e?parseFloat(e):e,r="string"==typeof t?parseFloat(t):t;if(!isFinite(i))throw new re(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(r))throw new re(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(i<.1)throw new re(`${n} minFee must be >= 0.1, received ${i}`,n,"INVALID_FEE_MINIMUM");if(r>.5)throw new re(`${n} maxFee must be <= 0.5, received ${r}`,n,"INVALID_FEE_MAXIMUM");if(i>r)throw new re(`${n} minFee (${i}) must be <= maxFee (${r})`,n,"INVALID_FEE_RANGE")}function $e(e,t,n,i){const r="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new re(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new re(`${i} must be a valid finite number`,i,"INVALID_MAX_VALUE");if(r>o)throw new re(`${n} (${r}) must be less than or equal to ${i} (${o})`,n,"INVALID_RANGE")}function qe(e,t,n){if(!t.includes(e))throw new re(`${n} must be one of [${t.join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const Ke={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},Ge={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},We={MIN_LENGTH:1,MAX_LENGTH:50},He=100,ze=20,je={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},Ve=100,Xe={PATTERN:/^eth\|[0-9a-fA-F]{40}$/},Qe={MAX_LENGTH:100},Je={COMMENT:{MAX_LENGTH:1e3},COMMENTS_V1:{MAX_LENGTH:2e3},CHAT_MESSAGE:{MIN_LENGTH:1,MAX_LENGTH:500,PATTERN:/^[\s\S]{1,500}$/},CHAT_MESSAGES_V1:{MAX_LENGTH:500},BAN_REASON:{MAX_LENGTH:500},DESCRIPTION:{MAX_LENGTH:255},TOKEN_DESCRIPTION:{MIN_LENGTH:1,MAX_LENGTH:500},FLAG_DETAILS:{MAX_LENGTH:1e3},CONTENT_ID:{MAX_LENGTH:100}},Ze={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})$/}},Ye=60,et=31536e3,tt={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},nt={PATTERN:/^[a-fA-F0-9]{64}$/},it={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},rt=50,ot=1,st=100,at={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function ct(e,t){if(Ct(e))return t;try{return JSON.parse(e)}catch{return t}}function lt(e,t=0){if(Ct(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 ut(e,t,n){if(Nt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const i=Number(e);return isNaN(i)?t:i}function dt(e,t=0){if(Ct(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 ht(e,t,n){if(Nt(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 i=parseInt(String(e),10);return isNaN(i)?t:i}function gt(e,t="0"){if(Ct(e))return new k(t);if(k.isBigNumber(e))return e.isNaN()?new k(t):e;try{const n=new k(e);return n.isNaN()||!n.isFinite()?new k(t):n}catch{return new k(t)}}function ft(e,t){if(Nt(e)||""===e)throw ye(t);if(k.isBigNumber(e)){if(e.isNaN())throw Ce(t,"NaN");return e}try{const n=new k(e);if(n.isNaN())throw Ce(t,e);if(!n.isFinite())throw Ce(t,e);return n}catch(n){if(n instanceof re)throw n;throw Ce(t,e)}}function pt(e,t=0){if(Nt(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return lt(String(e).replace("%","").trim(),t)}function mt(e,t=18){const n=lt(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function yt(e){return mt(e,8)}function wt(e){return mt(e,18)}var kt;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(kt||(kt={}));class bt{constructor(e){this.levelPriority={[kt.DEBUG]:0,[kt.INFO]:1,[kt.WARN]:2,[kt.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?kt.DEBUG:kt.INFO)}debug(e,t){this.log(kt.DEBUG,e,t)}info(e,t){this.log(kt.INFO,e,t)}warn(e,t){this.log(kt.WARN,e,t)}error(e,t){this.log(kt.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===kt.DEBUG&&!this.debugEnabled)return;const i=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==n?X(n)?r(`${i} ${t}`,n.message,J(n)??""):r(`${i} ${t}`,n):r(`${i} ${t}`)}getConsoleMethod(e){switch(e){case kt.DEBUG:return console.debug;case kt.INFO:return console.info;case kt.WARN:return console.warn;case kt.ERROR:return console.error;default:return console.log}}child(e){return new bt({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[kt.DEBUG]>=this.levelPriority[this.minLevel]}}const vt=new bt({debug:!1,context:"DateUtils"});function St(e,t){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(vt.warn(`Invalid date string received: "${e}". Using fallback.`),t??new Date):n}catch(t){return vt.warn(`Date parsing error for "${e}":`,t),new Date}}function At(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 Tt(e){return Date.now()-e}const Et={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/};function It(e){return"string"==typeof e&&e.trim().length>0}function Ct(e){return null==e||""===e}function Nt(e){return null==e}function xt(e,t,n=100){if(void 0!==e&&function(e,t){if("number"!=typeof e)throw Ie(t,"a number",e,t);if(!Number.isInteger(e))throw Ie(t,"an integer",e,t);if(e<0)throw Te(t,0,e,t)}(e,"offset"),void 0!==t&&(Re(t,"limit"),t>n))throw new re(`limit must be at most ${n}`,"limit",ie.TOO_LARGE)}function _t(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Bt(e){return Object.values(e)}function Pt(e,t,n,i={}){const{description:r="parameter",treatEmptyAsNull:o=!0}=i,s=e[t],a=e[n],c=null!=s&&(!o||""!==s),l=null!=a&&(!o||""!==a);if(!c&&!l)throw be(`Either ${t} or ${n} must be provided (${r})`,n);if(c&&l)throw be(`Cannot provide both ${t} and ${n}. Provide exactly one (${r}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function Dt(e,t="tokenName",n=Ke){if(!It(e))throw ye(t);const i=e.trim();if(0===i.length)throw ye(t);if(i.length<n.MIN_LENGTH)throw Ae(t,n.MIN_LENGTH,n.MAX_LENGTH,i.length,`${t} length`);if(i.length>n.MAX_LENGTH)throw Ae(t,n.MIN_LENGTH,n.MAX_LENGTH,i.length,`${t} length`);if(!n.PATTERN.test(i))throw new re(`${t} must contain only alphanumeric characters`,t,ie.INVALID_FORMAT)}function Rt(e,t="tokenName",n=Ke){if(null==e)return;if("string"!=typeof e)throw Ie(t,"a string",e);const i=e.trim();if(0!==i.length&&!n.PATTERN.test(i))throw new re(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,ie.INVALID_FORMAT)}function Mt(e,t=Ke){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function Lt(e,t="tokenName",n=Ke){if(null==e)throw ye(t,t);if("string"!=typeof e)throw Ie(t,"a string",e);const i=e.trim();if(0===i.length)throw ye(t,t);if(!n.PATTERN.test(i))throw new re(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,ie.INVALID_FORMAT)}function Ft(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:i,nullable:r=!1,optional:o=!1,validator:s}of e){const e=n[t];if((!o||void 0!==e)&&(!r||null!==e)){if(typeof e!==i)return!1;if(s&&!s(e))return!1}}return!0}}const Ut={requiredString:e=>t=>Nt(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(!Ct(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(!Nt(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=>Nt(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(!Nt(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Nt(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Nt(t))return"string"!=typeof t?`${e} must be a string`:At(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Nt(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return Et.ETH_ADDRESS.test(n)||Et.BACKEND_ADDRESS.test(n)||Et.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function Ot(e){return t=>{const n=[],i=t;for(const t of e){const{field:e,required:r,type:o,validator:s}=t,a=i[e];if(r){if(Nt(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Nt(a))if(void 0===o||typeof a===o){if(void 0!==s){const e=s(a,i);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${o}`)}return n}}function $t(e){return""===e||0===e.trim().length}function qt(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}const Kt={ETHEREUM:Et.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Et.BACKEND_ADDRESS,CLIENT:Et.CLIENT_ADDRESS};class Gt{toBackendFormat(e){if(!It(e))throw new re("Address is required and must be a string","address","REQUIRED");const t=qt(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw new re(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t.toLowerCase()}`}toEthereumFormat(e){if(!It(e))throw new re("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 re(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],i=void 0!==n&&""!==n?6:4;return`0x${e.substring(i)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("eth|")){if(!Kt.BACKEND.test(e))throw new re(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!It(e)&&(!!Kt.ETHEREUM.test(e)||(!!Kt.ETHEREUM_NO_PREFIX.test(e)||(!!Kt.BACKEND.test(e)||!!Kt.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new re(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return It(e)?Kt.ETHEREUM.test(e)||Kt.ETHEREUM_NO_PREFIX.test(e)?"ethereum":Kt.BACKEND.test(e)?"backend":Kt.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 qt(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new re(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Wt=new Gt,Ht=qt;function zt(e){return Wt.toBackendFormat(e)}function jt(e){return Wt.toEthereumFormat(e)}function Vt(e){return Wt.normalizeInput(e)}function Xt(e){return Wt.isValid(e)}function Qt(e,t="address"){Wt.assertValid(e,t)}function Jt(e){const t="string"==typeof e?e:e.address;return Wt.toBackendFormat(t)}function Zt(e){return Wt.detectFormat(e)}var Yt=Object.freeze({__proto__:null,AddressFormatter:Gt,assertValidWalletAddress:Qt,detectFormat:Zt,fromBackendAddressFormat:jt,isValidAddress:Xt,normalizeAddressInput:Vt,stripHexPrefix:Ht,toBackendAddressFormat:zt,toBackendAddressFromEthers:Jt});class en{constructor(e){if(this.wallet=e.wallet,this.messagePrefix=e.messagePrefix??"Create a GalaChain Wallet",void 0!==e.messagePrefix)try{Le(e.messagePrefix,"messagePrefix",!1)}catch{throw new V(j.SIGNATURE_FAILED,"Message prefix cannot be empty")}}hasWallet(){return void 0!==this.wallet}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new V(j.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if(""===e.address||void 0===e.address||"string"!=typeof e.address)throw new V(j.INVALID_ADDRESS,"Wallet address is not available")}this.wallet=e}async generateSignature(){this.validateWallet();try{const e=Date.now(),t=`${this.messagePrefix} ${e}`,n=await this.wallet.signMessage(t);return{message:t,signature:n,address:this.formatAddress(this.wallet.address),timestamp:e}}catch(e){if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,"Failed to generate signature for authentication",X(e)?e:new Error(Q(e)))}}getAddress(){return this.validateWallet(),this.formatAddress(this.wallet.address)}getEthereumAddress(){return this.validateWallet(),this.wallet.address}getPrivateKey(){if(this.validateWallet(),""===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new V(j.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}formatAddress(e){try{return zt(e)}catch{throw new V(j.INVALID_ADDRESS,`Invalid Ethereum address format: ${e}`)}}async signMessage(e){this.validateWallet();try{return{message:e,signature:await this.wallet.signMessage(e),address:this.wallet.address,timestamp:Date.now()}}catch(e){if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,Q(e),X(e)?e:new Error(Q(e)))}}async generateAuthHeaders(e,t){this.validateWallet();try{const n=Date.now(),i=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,r=await this.wallet.signMessage(i);return{"x-signature":r,"x-address":this.formatAddress(this.wallet.address),"x-message":i,"x-timestamp":n.toString()}}catch(e){if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,"Failed to generate authentication headers",X(e)?e:new Error(Q(e)))}}async signTypedData(e,t,n){this.validateWallet();try{return await this.wallet.signTypedData(e,t,n)}catch(e){if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,"Failed to sign typed data",X(e)?e:new Error(Q(e)))}}async generateCustomSignature(e){if(!It(e))throw new V(j.SIGNATURE_FAILED,"Custom message must be a non-empty string");this.validateWallet();try{const t=await this.wallet.signMessage(e);return{message:e,signature:t,address:this.formatAddress(this.wallet.address),timestamp:Date.now()}}catch(e){if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,"Failed to generate custom message signature",X(e)?e:new Error(Q(e)))}}validateWallet(){if(null===this.wallet||void 0===this.wallet)throw new V(j.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(""===this.wallet.address||void 0===this.wallet.address)throw new V(j.WALLET_NOT_CONNECTED,"Wallet address is not available");if((""===this.wallet.privateKey||void 0===this.wallet.privateKey)&&"function"!=typeof this.wallet.signMessage)throw new V(j.WALLET_NOT_CONNECTED,"Wallet must have a private key for signing messages")}}const tn={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class nn{constructor(e=tn.REFRESH_THRESHOLD_MS){this.tokenState=null,this.refreshThresholdMs=e}setToken(e,t){if(!It(e))throw new V(j.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new V(j.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!isFinite(t))throw new V(j.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new V(j.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");const n=Date.now();this.tokenState={token:e.trim(),issuedAt:n,expiresAt:n+1e3*t}}getToken(){return this.tokenState?.token??null}hasToken(){return null!==this.tokenState}isExpired(){return!this.tokenState||Date.now()>=this.tokenState.expiresAt}shouldRefresh(e){if(!this.tokenState)return!1;const t=e??this.refreshThresholdMs,n=this.tokenState.expiresAt-Date.now();return n>0&&n<=t}getTimeUntilExpiry(){if(!this.tokenState)return 0;const e=this.tokenState.expiresAt-Date.now();return Math.max(0,e)}getExpiresAt(){return this.tokenState?.expiresAt??null}getAuthorizationHeader(){const e=this.getToken();return null===e||""===e?null:`${tn.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new V(j.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[tn.AUTH_HEADER]:e}}clear(){this.tokenState=null}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}const rn="/launchpad/upload-image",on="/launchpad/fetch-pool",sn="/launchpad/check-pool",an="/launchpad/get-graph-data",cn="/holders",ln="/launchpad/get-badge/",un="/launchpad/socials",dn="/trade/",hn="/user/profile",gn="/user/profile",fn="/user/token-list",pn="/user/token-hold",mn="/v1/user/managed-tokens",yn="/v1/users/referrals/url",wn="/v1/users/referrals",kn="/v1/users/referrals/summary",bn="/v1/registered",vn="/live/:tokenName/start",Sn="/live/:tokenName/stop",An="/live/:tokenName",Tn="/live/:tokenName/disable",En="/live/:tokenName/enable",In="/live/:tokenName/reset-key",Cn="/live/:tokenName/recordings",Nn="/live/:tokenName/recordings/:assetId/download",xn="/live/:tokenName/recordings/:assetId",_n="/live/:tokenName/simulcast",Bn="/live/:tokenName/simulcast",Pn="/live/:tokenName/simulcast/:targetId",Dn="/live/global/streaming/status",Rn="/live/global/streaming/disable",Mn="/live/global/streaming/enable",Ln="/live/:tokenName/stream/countdown",Fn="/live/:tokenName/stream/countdown",Un="/live/:tokenName/stream/language",On="/live/:tokenName/role",$n="/live/roles",qn="/live/:tokenName/access",Kn="/live/:tokenName/chat",Gn="/live/:tokenName/chat",Wn="/live/:tokenName/chat/:messageId",Hn="/live/:tokenName/chat/status",zn="/live/:tokenName/chat/disable",jn="/live/:tokenName/chat/enable",Vn="/live/:tokenName/chat/pinned",Xn="/live/:tokenName/chat/pin",Qn="/live/:tokenName/chat/pin",Jn="/live/chat/global/status",Zn="/live/chat/global/disable",Yn="/live/chat/global/enable",ei="/live/:tokenName/engagement/stats",ti="/auth/login",ni="/auth/refresh",ii="/auth/session",ri="/live/:tokenName/bans",oi="/live/:tokenName/bans",si="/live/:tokenName/bans/:userAddress",ai="/live/:tokenName/bans/:userAddress",ci="/live/:tokenName/active-users",li={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},ui="/v1/moderators/invites",di="/v1/moderators/invites/claim",hi="/v1/moderators/tokens",gi="/v1/moderators/invites",fi="/v1/moderators/invites/:id",pi="/v1/moderators/invites/:id/role",mi="/v1/moderators/invites/code/:code",yi={CREATE:"/v1/flags",LIST_GLOBAL:"/v1/flags/global",LIST:"/v1/flags/:tokenName",DISMISS:"/v1/flags/:id/dismiss",ACTION:"/v1/flags/:id/action"},wi="/v1/overseer/invites",ki="/v1/overseer/invites",bi="/v1/overseer/invites/code/:code",vi="/v1/overseer/invites/claim",Si="/v1/overseer/invites/:id",Ai="/v1/overseer",Ti="/v1/overseer/:address",Ei="/v1/overseer/me",Ii="/v1/overseer/summary",Ci="/v1/overseer/users",Ni="/v1/overseer/users/:address",xi="/v1/overseer/token-bans",_i="/v1/overseer/token-bans",Bi="/v1/overseer/token-bans/:tokenName",Pi="/v1/overseer/token-bans/:tokenName",Di="/token/comment",Ri="/token/comment",Mi="/token/comment/:commentId",Li="/reactions",Fi="/reactions/:messageId/:reactionType",Ui="/v1/trades",Oi="/v1/chat-messages",$i="/v1/chat-messages",qi="/v1/chat-messages/:id",Ki="/v1/chat-messages/:id",Gi="/v1/comments",Wi="/v1/comments",Hi="/v1/comments/:id",zi="/v1/comments/:id";function ji(e){return null!=e&&"object"==typeof e&&"data"in e}function Vi(e,t,n=!1){const i=!0===e.error,r=n&&(null===e.data||void 0===e.data);if(i||r){const n=e?.statusCode??e.status??void 0;throw ke(e?.message??t,n)}}function Xi(e){if(ji(e))return e.data}function Qi(e,t="No data found in response"){if(!ji(e))throw ke(t);const n=e.data;if(null==n)throw ke(t);return n}async function Ji(e,t,n,i){try{return await e()}catch(e){throw i?(i(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Se(e,t,n))}}function Zi(e,t,n,i){try{return e()}catch(e){throw i?(i(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Se(e,t,n))}}class Yi{constructor(e,t,n,i=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new bt({debug:i,context:"SessionAuthService"})}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new V(j.WALLET_NOT_CONNECTED,"Wallet is required for login. Configure privateKey in SDK.");this.loginPromise=this.performLogin();try{return await this.loginPromise}finally{this.loginPromise=null}}async performLogin(){return Ji(async()=>{const e=Date.now(),t=`${tn.LOGIN_MESSAGE_PREFIX}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),i=this.signatureAuth.getAddress();Qt(i,"address");const r={address:i,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:i,message:t});const o=await this.http.post(ti,r),s=this.extractLoginData(o);return this.jwtAuth.setToken(s.accessToken,s.expiresIn),this.logger.debug("Login successful",{address:s.address,expiresIn:s.expiresIn}),s},"SessionAuthService.performLogin",this.logger,(e,t,n)=>{if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,`Login failed: ${Q(e)}`,X(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(!this.jwtAuth.hasToken())throw new V(j.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performRefresh(){return Ji(async()=>{this.logger.debug("Refreshing JWT token");const e=await this.http.post(ni,{},this.jwtAuth.getJwtHeaders()),t=this.extractLoginData(e);return this.jwtAuth.setToken(t.accessToken,t.expiresIn),this.logger.debug("Token refreshed successfully",{address:t.address,expiresIn:t.expiresIn}),t},"SessionAuthService.performRefresh",this.logger,(e,t,n)=>{if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,`Token refresh failed: ${Q(e)}`,X(e)?e:void 0)})}logout(){this.logger.debug("Logging out"),this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new V(j.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Ji(async()=>{const e=await this.http.get(ii,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(e,t,n)=>{if(e instanceof V)throw e;throw new V(j.SIGNATURE_FAILED,`Failed to get session: ${Q(e)}`,X(e)?e:void 0)})}getAccessToken(){return this.jwtAuth.getToken()}isAuthenticated(){return this.jwtAuth.isValid()}shouldRefresh(e){return this.jwtAuth.shouldRefresh(e)}async ensureValidToken(e){if(!this.jwtAuth.hasToken())throw new V(j.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){this.logger.debug("Token expired - attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new V(j.SIGNATURE_FAILED,""!==Q(e)?Q(e):"Authentication failed");const t=Qi(e,"No data in authentication response"),{accessToken:n,expiresIn:i,address:r}=t;if(!It(n))throw new V(j.SIGNATURE_FAILED,"Invalid access token in response");if(0===i||null==i||"number"!=typeof i)throw new V(j.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:i,address:r}}extractSessionData(e){if(e.error)throw new V(j.SIGNATURE_FAILED,""!==Q(e)?Q(e):"Failed to get session");return Qi(e,"No data in session response")}}function er(e){if(Nt(e)||"object"!=typeof e)return{};const t={};for(const[n,i]of Object.entries(e))Nt(i)||(It(i)?t[n]=i:"number"==typeof i||"boolean"==typeof i?t[n]=i.toString():Array.isArray(i)?t[n]=i.join(","):t[n]="object"==typeof i?JSON.stringify(i):String(i));return t}class tr{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new bt({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??"https://lpad-backend-dev1.defi.gala.com",i=t.timeout??3e4;this.axios=z(n,i),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return Ji(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:er(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout}};e.headers&&this.logger.debug("Custom headers provided:",e.headers),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"));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":e.data;this.logger.debug("Request:",{method:e.method,url:e.url,fullUrl:`${this.axios.defaults.baseURL}${e.url}`,baseURL:this.axios.defaults.baseURL,params:t.params,data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const i=await this.axios.request(t);return this.logger.debug("Response:",{status:i.status,data:i.data}),i.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 Ji(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}async signWithGalaChain(e,t,n=f.SIGN_TYPED_DATA){const i=this.auth.getPrivateKey(),r=new p(i);return await r.sign(e,t,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.auth.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request headers being sent:",e.headers),e},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n={message:t.response.data?.message??Q(e),...Boolean(t.response.data?.error)&&{error:t.response.data.error},statusCode:t.response.status,...Boolean(t.response.data?.details)&&{details:t.response.data.details},...Boolean(t.response.data?.timestamp)&&{timestamp:t.response.data.timestamp},...Boolean(t.response.data?.path)&&{path:t.response.data.path}};t.launchpadError=n,this.logger.error("Backend error:",n)}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")}}const nr="Token name is required and must be a string",ir=e=>`Could not find vault address for token: ${e}`,rr=5,or=5,sr=w.string("Token name is required").min(3,"Token name must be at least 3 characters").max(20,"Token name must be at most 20 characters").regex(/^[a-zA-Z0-9]{3,20}$/,"Token name can only contain letters and numbers"),ar=w.string("Token symbol is required").min(1,"Token symbol must be at least 1 character").max(8,"Token symbol must be at most 8 characters").regex(/^[A-Z]{1,8}$/,"Token symbol must be uppercase letters only"),cr=w.string("Token description is required").min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),lr=w.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),ur=w.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),dr=w.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"),hr=w.string().regex(Et.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),gr=w.string().regex(Et.ETH_ADDRESS,"Invalid Ethereum address format"),fr=w.string().refine(e=>Et.BACKEND_ADDRESS.test(e)||Et.ETH_ADDRESS.test(e),"Address must be either eth|[40-hex-chars] or 0x[40-hex-chars] format").transform(e=>(new Gt).normalizeInput(e)??e),pr=w.string().refine(e=>Et.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),mr=w.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>lt(e,0)>0,"Amount must be greater than zero"),yr=w.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>lt(e,0)>=0,"Amount must be zero or greater"),wr=w.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),kr=w.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),br=w.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 vr(e=100){return w.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 Sr=vr(100),Ar=vr(20),Tr=vr(20),Er=w.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"),Ir=w.string().max(255,"Filename must be at most 255 characters"),Cr=w.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),Nr=w.string().datetime("Must be a valid ISO 8601 date string"),xr=w.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),_r=w.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Br=w.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"),Pr=w.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Dr=w.object({websiteUrl:kr,telegramUrl:kr,twitterUrl:kr,instagramUrl:kr,facebookUrl:kr,redditUrl:kr,tiktokUrl:kr}).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"),Rr=w.string().min(1,"Token category must not be empty").default("Unit"),Mr=w.string().min(1,"Token collection must not be empty").default("Token"),Lr=w.object({minFeePortion:w.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>lt(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>lt(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:w.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>lt(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>lt(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>lt(e.maxFeePortion,0)>=lt(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Fr=w.object({tokenName:sr,tokenSymbol:ar,tokenDescription:cr,tokenImage:w.union([w.instanceof(File),w.instanceof(Buffer),w.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:yr.default("0"),websiteUrl:kr,telegramUrl:kr,twitterUrl:kr,instagramUrl:kr,facebookUrl:kr,redditUrl:kr,tiktokUrl:kr,tokenCategory:Rr,tokenCollection:Mr,reverseBondingCurveConfiguration:Lr.optional(),privateKey:_r.optional()}),Ur=w.object({file:w.union([w.instanceof(File),w.instanceof(Buffer)]),tokenName:sr}),Or=w.enum(["RECENT","POPULAR"]),$r=w.object({tokenName:sr.optional(),symbol:ar.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),qr=w.enum(["NATIVE","MEME"]),Kr=w.enum(["IN","OUT"]),Gr=w.object({from:w.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:w.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:w.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:sr}),Wr=w.object({tokenName:sr,slippageToleranceFactor:w.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:w.number().min(0).max(1).optional(),privateKey:_r.optional()}),Hr=[".png",".jpg",".jpeg",".gif",".webp",".svg"],zr=w.object({file:w.union([w.instanceof(File),w.instanceof(Buffer)]),name:Ir,size:Er,type:Cr}),jr=w.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"),Vr=w.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Xr=w.union([jr,Vr]),Qr=w.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Jr=Ir.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Hr.includes(t)},`Filename must end with one of: ${Hr.join(", ")}`),Zr=w.object({page:br,limit:Sr}),Yr=w.object({page:br,limit:Ar}),eo=w.object({page:br,limit:Tr}),to=Zr.extend({type:w.enum(["RECENT","POPULAR"]).optional(),tokenName:w.string().min(1).max(50).optional(),search:w.string().min(1).max(100).optional()}),no=Yr.extend({tokenName:w.string().min(1).max(50).optional(),search:w.string().min(1).max(100).optional()}),io=eo.extend({tradeType:w.enum(["BUY","SELL"]).optional(),tokenName:w.string().min(1).max(50).optional(),userAddress:w.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:w.string().datetime().optional(),endDate:w.string().datetime().optional(),sortOrder:w.enum(["ASC","DESC"]).default("DESC")}),ro=w.object({page:w.number().int().min(1),limit:w.number().int().min(1),total:w.number().int().min(0),totalPages:w.number().int().min(0),hasNext:w.boolean(),hasPrevious:w.boolean()});function oo(e){return w.object({data:w.array(e),page:w.number().int().min(1),limit:w.number().int().min(1),total:w.number().int().min(0),totalPages:w.number().int().min(0),hasNext:w.boolean(),hasPrevious:w.boolean()})}const so=w.enum(["all","DEFI","ASSET"]),ao=Yr.extend({type:so.optional(),address:fr.optional(),search:ur.optional(),tokenName:lr.optional()}),co=w.object({address:fr.optional(),refresh:w.boolean().optional()}),lo=w.object({profileImage:w.string(),fullName:dr,address:fr,privateKey:_r.optional()}),uo=w.object({file:w.union([w.instanceof(File),w.instanceof(Buffer)]),address:fr.optional(),privateKey:_r.optional()}),ho=w.object({created:w.number(),createdBy:w.string(),expires:w.number(),instanceId:w.string(),lockAuthority:w.string(),name:w.string(),quantity:w.string(),vestingPeriodStart:w.number()}),go=w.object({address:fr,tokenId:w.union([w.string(),w.object({collection:w.string(),category:w.string(),type:w.string(),additionalKey:w.string()}),w.object({collection:w.string(),category:w.string(),type:w.string(),additionalKey:w.string(),instance:w.string()})]).optional(),tokenName:lr.optional(),withExpired:w.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required"),fo=w.enum(["buy","sell"]),po=w.enum(["BUY","SELL"]),mo=w.object({tradeType:fo,tokenAmount:mr,vaultAddress:pr,userAddress:fr,slippageTolerance:mr.optional(),deadline:w.number().int().positive().optional()}),yo=w.object({tokenSymbol:ar,nativeTokenQuantity:mr,expectedToken:mr,maxAcceptableReverseBondingCurveFee:yr.default("0").optional()}),wo=w.object({tokenSymbol:ar,tokenQuantity:mr,expectedNativeToken:mr,maxAcceptableReverseBondingCurveFee:yr.default("0").optional()}),ko=eo.extend({tokenName:lr.optional()}),bo=w.object({page:w.number().int().min(1).max(1e3).default(1).optional(),limit:w.number().int().min(1).max(20).default(10).optional()}),vo=w.enum(["NATIVE","MEME"]),So=w.enum(["IN","OUT"]),Ao=w.object({type:vo,method:So,vaultAddress:pr,amount:mr}),To=w.object({nativeTokenQuantity:mr}),Eo=w.object({vaultAddress:pr}),Io=w.object({minFeePortion:mr,maxFeePortion:mr});function Co(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 No=Co(sr),xo=Co(ar),_o=Co(cr),Bo=Co(fr),Po=Co(pr),Do=Co(mr),Ro=Co(dr),Mo=Co(ur),Lo=Co(lr),Fo=Co(Fr),Uo=Co(Dr),Oo=Co(Ur),$o=Co($r),qo=Co(ao),Ko=Co(co),Go=Co(lo),Wo=Co(uo),Ho=Co(go),zo=Co(mo),jo=Co(yo),Vo=Co(wo),Xo=Co(ko),Qo=Co(bo),Jo=Co(Ao),Zo=Co(To),Yo=Co(Eo);function es(e,t="0"){return gt(e,t)}function ts(e,t){return void 0!==t?es(e).toFixed(t):es(e).toFixed()}function ns(e,t=.01){const n=es(e),i=new k(1).minus(t);return n.multipliedBy(i)}function is(e=.01){return new k(1).minus(e)}function rs(e=.01){return new k(1).plus(e)}function os(e){const t=es(e),n=Math.log(1.0001),i=t.toNumber();return Math.log(i)/n}function ss(e,t=!1){const n=es(e),i=new k(1).dividedBy(n);return t?i.toFixed():i}function as(){return new k(2).pow(96)}function cs(e,t){return k.min(es(e),es(t))}function ls(e,t){return k.max(es(e),es(t))}function us(e){return es(e).isZero()}function ds(e){return es(e).isGreaterThan(0)}function hs(e){return es(e).isLessThan(0)}function gs(e,t){return es(e).isLessThan(es(t))}function fs(e,t){return es(e).multipliedBy(t).dividedBy(100)}function ps(...e){e.forEach(e=>{if(e.isNaN())throw Ce("value","NaN");if(!e.isFinite())throw Ee("value","finite");if(e.isLessThanOrEqualTo(0))throw Te("value","0",e.toString())})}function ms(...e){e.forEach(e=>{if(e.isNaN())throw Ce("value","NaN");if(!e.isFinite())throw Ee("value","finite");if(e.isLessThan(0))throw Te("value","0",e.toString())})}function ys(e,t,n){if(e.isNaN())throw Ce(t,"NaN");if(!e.isFinite())throw Ee(t,"finite");if(e.isLessThanOrEqualTo(0))throw Te(t,"0",e.toString())}function ws(e,t,n="0"){const i=es(t);return us(i)?es(n):es(e).dividedBy(i)}function ks(e,t){return Math.floor(e/t)*t}class bs{validate(e,t={}){const{allowZero:n=!0,minimum:i,maximum:r,maxDecimals:o=bs.MAX_DECIMAL_PLACES,fieldName:s="amount"}=t;if(!It(e))throw new re(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new re(`${s} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,s,"INVALID_NUMERIC_STRING");const a=lt(e,NaN);if(isNaN(a))throw new re(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new re(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new re(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new re(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=es(e),l=c.decimalPlaces()??0;if(l>o)throw new re(`${s} cannot exceed ${o} decimal places. Received: ${l} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==i&&gs(c,i))throw new re(`${s} must be at least ${i}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==r&&(u=r,es(c).isGreaterThan(es(u))))throw new re(`${s} cannot exceed ${r}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return es(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 ts(e,t)}clampAmount(e,t,n){const i=es(e),r=es(t),o=es(n);return function(e,t,n){const i=es(e),r=es(t),o=es(n);return i.isGreaterThanOrEqualTo(r)&&i.isLessThanOrEqualTo(o)}(i,r,o)?ts(i):gs(i,r)?ts(r):ts(o)}}function vs(e,t){throw new re(e.join("; "),t,"VALIDATION_ERROR")}function Ss(e){const t=No(e);!t.success&&t.errors&&vs(t.errors,"tokenName")}function As(e){const t=$o(e);!t.success&&t.errors&&vs(t.errors,"options")}function Ts(e){const t=Gr.safeParse(e);var n;t.success||vs((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){Is.validate(e,{fieldName:t,allowZero:n})}bs.MAX_DECIMAL_PLACES=18,bs.MIN_POSITIVE="0.00000000000000001";const Is=new bs;const Cs={DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20,SAFETY_MAX_PAGES:100},Ns={MAX_CONCURRENT_FETCHES:5,BACKEND_PAGE_SIZE:20};function xs(e,t=Cs.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Ie("offset","a non-negative integer",e);return Re(t,"limit"),{offset:e,limit:t}}function _s(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw Ie("offset","a non-negative integer",e);Re(t,"limit")}function Bs(e,t=1,n=Cs.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Ps(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Ie("total","a non-negative integer",e);if(e<0)throw Ae("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Ie("limit","a non-negative integer",t);if(t<0)throw Ae("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Ds(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw Ie("offset","a non-negative integer",e);if(e<0)throw Ae("offset",0,1/0,e);return e+t<n}function Rs(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function Ms(e,t){const n=e,i=ht(String(n.page),t.page),r=ht(String(n.limit),t.limit),o=n.data,s=o?.meta,a=ht(String(o?.count),0),c=ht(String(s?.totalItems),a),l=ht(String(n.total),c);return{page:i,limit:r,total:l,totalPages:Ps(l,r)}}async function Ls(e,t={}){const{maxPages:n=1e4,logger:i,pageSize:r=20,concurrency:o=1,startPage:s=1}=t,a=[];let c=s;const l=s+n-1;let u=!0,d=0;if(o<=1)for(;u&&c<=l;){i&&i.debug(`Auto-pagination: fetching page ${c} with limit ${r}`);const t=await e(c,r);if(null==t||!Array.isArray(t.items)){i&&i.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),d=t.total,i&&i.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){i&&i.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}u=t.hasNext,c++}else for(i&&i.debug(`Auto-pagination: using concurrent mode with concurrency=${o}`);u&&c<=l;){const t=[];for(let e=0;e<o&&c+e<=l;e++)t.push(c+e);i&&i.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,r).catch(e=>{const n=e,o=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===o||404===o)return i&&i.debug(`Auto-pagination: page ${t} returned ${o} (end of pagination)`,{statusCode:o}),{items:[],total:0,totalPages:0,page:t,limit:r,hasNext:!1,hasPrevious:!1};throw e})),s=await Promise.all(n);for(const e of s){if(null==e||!Array.isArray(e.items)){i&&i.warn("Auto-pagination: received invalid result structure in batch, stopping"),u=!1;break}if(0===e.items.length){i&&i.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,i&&i.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&i&&i.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),i&&i.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${d}`),{items:a,total:d}}async function Fs(e,t={}){const{errorContext:n="Operation failed",logger:i,debugLogEnabled:r=!1}=t;r&&i&&i.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new re(`${n}: No response from server`,"response","NO_RESPONSE");if(Vi(t,n,!0),r&&i&&i.debug(`${n}: completed successfully`),void 0===t.data)throw new re(`${n}: No data returned from API`,"data","NO_DATA");return t.data}catch(e){throw i&&i.error(n,{error:e}),e}}async function Us(e,t={}){const{errorContext:n="Operation failed",logger:i,debugLogEnabled:r=!1}=t;r&&i&&i.debug(`${n}: starting operation`);try{const t=await e();return r&&i&&i.debug(`${n}: completed successfully`),t}catch(e){throw i&&i.error(n,{error:e}),e}}async function Os(e,t={}){const{errorContext:n="Operation failed",logger:i,debugLogEnabled:r=!1}=t;r&&i&&i.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new re(`${n}: No response from server`,"response","NO_RESPONSE");return Vi(t,n,!0),r&&i&&i.debug(`${n}: completed successfully`),t}catch(e){throw i&&i.error(n,{error:e}),e}}const $s=5;function qs(e){return e.trim().toLowerCase()}function Ks(e){return e.trim().toUpperCase()}function Gs(e){return e.trim().toUpperCase()}function Ws(e,t,n){if(!Nt(e)){if("string"!=typeof e)throw Ie(t,"a string",e,t);if(e.length>n)throw new re(`${t} must be at most ${n} characters`,t,ie.TOO_LARGE)}}function Hs(e,t){Re(e,t)}function zs(e,t){if(Nt(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 Ie(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new re(`${t} must be a valid date`,t,ie.INVALID_FORMAT)}function js(e,t,n){try{Re(e,t)}catch{throw function(e,t,n,i="OPERATION_FAILED"){return new re(`${e} failed: ${t}`,n,i)}(n,"must be a positive integer",t)}}function Vs(e,t,n="status"){void 0!==e&&function(e,t,n){const i=Object.values(t);if(!i.includes(e))throw new re(`${n} must be one of: ${i.join(", ")}`,n,ie.INVALID_FORMAT)}(e,t,n)}class Xs{constructor(e,t=!1,n){this.http=e,this.logger=new bt({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 se("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=J(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){js(e,t,n)}}class Qs{constructor(e=!1,t){this.logger=t||new bt({debug:e,context:this.constructor.name})}}function Js(e,t){return"string"==typeof e[t]}function Zs(e,t){return void 0===e[t]||"string"==typeof e[t]}function Ys(e,t){return void 0===e[t]||"number"==typeof e[t]}function ea(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Js(t,"tokenName")&&Ys(t,"from")&&Ys(t,"to")&&Ys(t,"resolution")}class ta extends Xs{constructor(e,t=!1){super(e,t)}buildPoolFilters(e){return{...!Nt(e.search)&&{search:e.search},...!Nt(e.tokenName)&&{tokenName:e.tokenName},...!Nt(e.type)&&{type:e.type},...!Nt(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Nt(e.language)&&{language:e.language},...!Nt(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Nt(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Nt(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.limit,20),n=e.offset,i={offset:String(n),limit:String(t)};Nt(e.type)||(i.type=e.type),Nt(e.tokenName)||(i.tokenName=e.tokenName),Nt(e.search)||(i.search=e.search),Nt(e.hasUpcomingShows)||(i.hasUpcomingShows=e.hasUpcomingShows.toString()),Nt(e.language)||(i.language=e.language),Nt(e.recentlyStreamed)||(i.recentlyStreamed=e.recentlyStreamed.toString()),Nt(e.hasRecordings)||(i.hasRecordings=e.hasRecordings.toString()),Nt(e.streamStatus)||(i.streamStatus=e.streamStatus);const r=er(i),o=Xi(await Os(()=>this.http.get(on,r),{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}(o),a=o.count??o.total??0;return{items:s,meta:{offset:n,limit:t,total:a,totalPages:Ps(a,t)}}}async fetchPageForAutoPaginate(e,t,n){const i=await this.fetchSinglePage({...e,offset:t,limit:n}),r=i.items.length===n&&Ds(t,n,i.meta.total);return{items:i.items,page:Math.floor(t/n),limit:n,total:i.meta.total,totalPages:i.meta.totalPages??0,hasNext:r,hasPrevious:t>0}}async fetchPools(e={}){const t=e.offset??0,n=e.limit??Cs.DEFAULT_LIMIT;0!==n&&xt(t,n),It(e.tokenName)&&Ss(e.tokenName);const i=void 0!==e.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,r=void 0!==e.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,o=this.buildPoolFilters({search:e.search,tokenName:e.tokenName,type:i,hasUpcomingShows:e.hasUpcomingShows,language:e.language,recentlyStreamed:e.recentlyStreamed,hasRecordings:e.hasRecordings,streamStatus:r});if(n>0&&n<=20){const e=await this.fetchSinglePage({...o,offset:t,limit:n});return{items:e.items,meta:{offset:e.meta.offset,limit:e.meta.limit,total:e.meta.total,...void 0!==e.meta.totalPages&&{totalPages:e.meta.totalPages}}}}if(0===n){const e=Cs.BACKEND_MAX_PAGE_SIZE,t=await Ls((e,t)=>this.fetchPageForAutoPaginate(o,e,t),{pageSize:e,concurrency:5,startPage:0,logger:this.logger});return{items:t.items,meta:{offset:0,limit:t.items.length,total:t.total>0?t.total:t.items.length,totalPages:1}}}const s=Cs.BACKEND_MAX_PAGE_SIZE,a=Ps(n,s),c=Math.floor(t/s)+1,l=await Ls((e,t)=>this.fetchPageForAutoPaginate(o,e,t),{startPage:c,maxPages:a,pageSize:s,concurrency:5,logger:this.logger}),u=l.items.slice(0,n),d=Ps(l.total,s);return{items:u,meta:{offset:c,limit:n,total:l.total,totalPages:d}}}async fetchAllPools(e){return this.fetchPools({...e,limit:0})}async checkPool(e){As(e),It(e.tokenName)&&Ss(e.tokenName);const t=er(e),n=await Fs(()=>this.http.get(sn,t),{errorContext:"Failed to check pool"});return It(e.symbol)?n?.isSymbolExist??!1:It(e.tokenName)?n?.isNameExist??!1:n?.exists??!1}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!ea(e))throw new re("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:i,resolution:r}=e;if(Ss(t),null==n||null==i||null==r)throw new re("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:i,resolution:r};Ts(o);const s=er(o);return{dataPoints:await Fs(()=>this.http.get(an,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw ye("tokenName","Token name");let t;Ss(e);try{t=await Os(()=>this.http.get(`${cn}/${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Y(t)&&500===t.response?.status)throw ke(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=Xi(t);if(!Array.isArray(n))throw ke("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 ke("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 ke("Invalid holder data: missing or invalid quantity field",t.status);const n=lt(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw ke(`Invalid holder quantity: "${e.quantity}"`,t.status)}const i=n.reduce((e,t)=>e.plus(t.quantity),es(0));return{holders:n.map(e=>{const t=ws(es(e.quantity),i,es(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:i.toFixed(),totalHolders:n.length,lastUpdated:new Date}}async fetchUserHolderContext(e,t){if(""===e||null==e)throw ye("tokenName","Token name");if(""===t||null==t)throw ye("userAddress","User address");return Ss(e),Fs(()=>this.http.get(`${cn}/${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(""===e||null==e)throw ye("tokenName","Token name");Ss(e);const t=await Fs(()=>this.http.get(ln,{tokenName:e}),{errorContext:"Failed to fetch token badges"});return{volumeBadges:t.volumeBadge??[],engagementBadges:t.engagementBadge??[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:i}=e;try{const e=await this.fetchTokenBadges(t);if(null==e)return!1;const r=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===i);return r?.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}}}function na(e,t,n){return function(e,t={}){const{stringifyFields:n=[],optionalFields:i=[],fieldMappings:r={}}=t,o={};for(const[t,s]of Object.entries(e)){const e=t;if(i.includes(e)){if(void 0===s)continue;if("string"==typeof s&&!It(s))continue}const a=r[e],c=a?String(a):t;n.includes(e)?o[c]=String(s):o[c]=s}return er(o)}({tokenName:e,page:Math.floor(t/n)+1,limit:n},{stringifyFields:["page","limit"]})}const ia={PAGINATION:je,TOKEN_NAME:We,USER_ADDRESS:Qe};function ra(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new re("At least one of tokenName or userAddress is required","options","MISSING_FILTER");if(void 0!==e.tokenName){if(!It(e.tokenName))throw Ie("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>ia.TOKEN_NAME.MAX_LENGTH)throw Ee("tokenName",ia.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!It(e.userAddress))throw Ie("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>ia.USER_ADDRESS.MAX_LENGTH)throw Ee("userAddress",ia.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(xt(e.offset,e.limit,ia.PAGINATION.MAX_LIMIT),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw we("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!It(e.startDate))throw Ie("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw we("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!It(e.endDate))throw Ie("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw we("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Pe(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw we("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Pe(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw we("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&Me(e.minAmount,e.maxAmount,"amountRange")}class oa extends Xs{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 Js(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Zs(t,"userAddress")&&Ys(t,"page")&&Ys(t,"limit")}(e))throw new re("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, offset?: number, limit?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:i,offset:r=0,limit:o=Cs.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!It(t))throw ye("tokenName","Token name");xt(r,o,ze);const l=na(t,r,o),u=await this.http.get(dn,l);if(null==u)throw new re("No response from trade service","response","NO_RESPONSE");const d=Xi(u),h=Rs(d,"trades"),g=d?.meta,f=Math.floor(r/o)+1;let p=0,m=0;if(null!=g)p=null!==g.total&&void 0!==g.total?parseInt(String(g.total),10):0,m=null!==g.totalPages&&void 0!==g.totalPages?parseInt(String(g.totalPages),10):0;else{const e=Ms(u,{page:f,limit:o});p=e.total,m=e.totalPages}return{items:h,meta:{offset:r,limit:o,total:p,totalPages:m}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=qs(e.tokenName)),null!==e.userAddress&&void 0!==e.userAddress&&e.userAddress.length>0&&(t.userAddress=e.userAddress);const n=void 0!==e.limit?Bs(e.limit,1,ia.PAGINATION.MAX_LIMIT):ia.PAGINATION.MAX_LIMIT,i=e.offset??0,r=Math.floor(i/n)+1;return t.page=String(r),t.limit=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){ra(e);const t=this.buildTradesQueryParams(e);return Fs(()=>this.http.get(Ui,t),{errorContext:"Failed to fetch trades"})}}function sa(e,t){const n={},i=void 0!==e.limit?Math.min(e.limit,t):t;if(void 0!==e.offset){const t=Math.floor(e.offset/i)+1;n.page=String(t)}else void 0!==e.page&&e.page>0&&(n.page=String(e.page));return void 0!==e.limit&&(n.limit=String(i)),n}function aa(e,t,n){for(const i of n){const n=t[i];null!=n&&""!==n&&(e[i]=String(n))}return e}function ca(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const i=e.trim();return i.length<n?null:i}function la(e,t){return e.toLowerCase()===t.toLowerCase()}function ua(e){return e.toLowerCase()}function da(e,t){return e.toLowerCase().includes(t.toLowerCase())}function ha(e,t,n,i){return e===n&&t===i||e===i&&t===n}function ga(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(pa(e))return ma(e)}return null}return pa(e)?ma(e):null}function fa(e){return null==e||"string"!=typeof e||0===e.trim().length}function pa(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 ma(e){return e.startsWith("0x")?e.slice(2):e}function ya(e,t="image",n){const i=new FormData;if("undefined"!=typeof File&&e instanceof File)i.append(t,e);else{if(!Buffer.isBuffer(e))throw we("file","a File object (browser) or Buffer (Node.js)");{const r=new Blob([e],{type:"image/png"});i.append(t,r,n)}}return i}function wa(e){return!!It(e)&&Xe.PATTERN.test(e)}_t({ALL:"all",DEFI:"DEFI",ASSET:"ASSET"});class ka extends Xs{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!wa(t))throw we("address","eth|[40-hex-chars]","Address");const n={userAddress:t},i=await this.http.get(hn,n);if(null==i)throw new re("No response from user service","response","NO_RESPONSE");return i}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!It(t))try{const n=await this.fetchProfile(e.address);t=n?.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName,userAddress:e.address};await Fs(()=>this.http.put(gn,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(""===t||null==t)throw new re("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,i=ya(e.file,"image",n),r=await Fs(()=>this.http.request({method:"POST",url:`${rn}?tokenName=${encodeURIComponent(t)}`,data:i,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof re||e instanceof se)throw e;throw new re(`Profile image upload failed: ${Q(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(fn,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(pn,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e={}){const{offset:t=0,limit:n=Cs.DEFAULT_LIMIT,search:i,tokenName:r}=e,o=this.http.getAddress();if(""===o||null==o)throw new re("Wallet address not available - wallet not configured","address","NO_WALLET");const s={type:"DEFI",address:o,offset:t,limit:n};return void 0!==i&&(s.search=i),void 0!==r&&(s.tokenName=r),this.fetchTokenList(s)}async getManagedTokens(e={}){const t=e.offset??0,n=Bs(e.limit);xt(t,n,ze);const i={};void 0!==t&&(i.offset=t),void 0!==n&&(i.limit=n);const r=sa(i,ze);return Fs(()=>this.http.get(mn,{...r,...this.getJwtHeaders()}),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const i={};void 0!==t.offset&&(i.offset=t.offset),void 0!==t.limit&&(i.limit=t.limit);const r=sa(i,ze);aa(r,t,["address","search","tokenName"]),n.includeType&&(r.type="all"===t.type||null===t.type||void 0===t.type?"DEFI":t.type);const o=await Os(()=>this.http.get(e,r),{errorContext:n.errorMessage}),s=Rs(Xi(o),"token"),a=Ms(o,{page:t.offset??0,limit:t.limit??Cs.DEFAULT_LIMIT}),c=(l=a.page,u=a.totalPages,{hasNext:l<u,hasPrevious:l>1});var l,u;return{tokens:s,...a,...c}}validateGetTokenListOptions(e){if(xt(e.offset??0,e.limit,ze),void 0!==e.address&&!wa(e.address))throw we("address","eth|[40-hex-chars]","Address");const t=ca(e.search);if(null!==t&&!(It(n=t)&&n.length>=ot&&n.length<=st))throw Ae("search",ot,st,t.length,"Search query");var n;const i=ca(e.tokenName);if(null!==i&&!(It(r=i)&&r.length>=We.MIN_LENGTH&&r.length<=We.MAX_LENGTH))throw Ae("tokenName",We.MIN_LENGTH,We.MAX_LENGTH,i.length,"Token name");var r}validateUpdateProfileData(e){if(!wa(e.address))throw we("address","eth|[40-hex-chars]","Address");if(!(It(t=e.fullName)&&t.length>=at.FULL_NAME.MIN_LENGTH&&t.length<=at.FULL_NAME.MAX_LENGTH&&at.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Ae("fullName",at.FULL_NAME.MIN_LENGTH,at.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(null!==e.address&&void 0!==e.address&&!wa(e.address))throw we("address","eth|[40-hex-chars]","Address")}}class ba extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function va(e,t,n){if(null==e)throw new ba("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=jr.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new ba(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new ba("Filename is required when uploading Buffer objects",t,n);const i=Vr.safeParse(e);if(!i.success){const e=i.error.issues.map(e=>e.message).join("; ");throw new ba(e,t,n)}try{De(t,255,"filename")}catch(e){throw new ba(e.message,t,n)}const r=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!r.includes(n))throw new ba(`Invalid file type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,t,n);const o=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(o))throw new ba(`File extension "${o}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new ba(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new ba("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Sa extends Xs{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ss(t);const i=`${t}.png`;va(n.file,i,"image/png");try{const e=`${n.tokenName??t}.png`,i=ya(n.file,"image",e),r=await Fs(()=>this.http.request({method:"POST",url:`${rn}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:i,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof se)throw e;if(X(e)&&Q(e).includes("FormData"))throw be("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async updateTokenSocials(e){if(!It(e.tokenName))throw ye("tokenName","Token name");if(Ss(e.tokenName),!this.jwtAuth)throw be("JWT authentication required for updating token social links. Initialize SDK with a wallet or provide JWT token.","JWT_AUTH_REQUIRED");const t=un,n=Xi(await this.http.put(t,e,this.getJwtHeaders()));if(!n)throw new Error("Failed to update token social links: no data returned");return n}}class Aa{constructor(e,t,n=!1){this.http=e,this.poolService=new ta(e,n),this.tradeService=new oa(e,n),this.userService=new ka(e,t,n),this.imageService=new Sa(e,t,n)}setJwtAuth(e){this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async updateTokenSocials(e){return this.imageService.updateTokenSocials(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async getTrades(e){return this.tradeService.getTrades(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}async getManagedTokens(e={}){return this.userService.getManagedTokens(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Ss(e)}}function Ta(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 Ea(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,i]of Object.entries(e)){if(!Ta(n[t],i))return!1}return!0}}_t({BUY:"buy",SELL:"sell"});const Ia=Ea({vaultAddress:"string"}),Ca=Ea({nativeTokenQuantity:"string"});function Na(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function xa(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function _a(e){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function Ba(e,t,n){const i=void 0!==n?` (${n})`:"";try{if(!It(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[i,r,o,...s]=n;if(""===i||""===r||""===o)throw new Error("Collection, category, and type must be non-empty");const a=s.join(t);if(""===a)throw new Error("AdditionalKey must be non-empty");return{collection:i,category:r,type:o,additionalKey:a}}catch(n){const r=e?.split?.(t)??[];throw new re(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${r.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${r.map(e=>`"${e}"`).join(", ")}]. Error: ${Q(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function Pa(e){if("object"==typeof e&&null!==e)return function(e){if(null===e||"object"!=typeof e)throw new re("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:i,additionalKey:r}=e;if(!It(t))throw new re("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!It(n))throw new re("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!It(i))throw new re("Token.type must be a non-empty string, got "+typeof i,"token.type","MISSING_OR_INVALID_TYPE");if(!It(r))throw new re("Token.additionalKey must be a non-empty string, got "+typeof r,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:i,additionalKey:r}}(e);if(null==e)throw new re(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new re("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(Ra(e))return Da(e);if(Ma(e))return function(e){return function(e,t,n){const i=` (${n})`;try{if(!It(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 i=n[n.length-1],r=n[n.length-2],o=n[n.length-3],s=n.slice(0,n.length-3).join(t);if(""===s||""===o||""===r||""===i)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:s,category:o,type:r,additionalKey:i}}catch(n){const r=e?.split?.(t)??[];throw new re(`Invalid dollar-delimited token: "${e}" (${r.length} parts)${i}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${r.map(e=>`"${e}"`).join(", ")}]. Error: ${Q(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new re(`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 Da(e){return Ba(e,"|","pipe-delimited token")}function Ra(e){return It(e)&&e.includes("|")}function Ma(e){return"string"==typeof e&&e.includes("$")}function La(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,i=t.category,r=t.type,o=t.additionalKey;return"string"==typeof n&&"string"==typeof i&&"string"==typeof r&&"string"==typeof o&&n.length>0&&i.length>0&&r.length>0&&o.length>0}function Fa(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>k(e).plus(t.quantity).toString(),"0")}function Ua(e,t){if(0===(e?.length??0))return[];if(t)return e;const n=Date.now();return e.filter(e=>0===e.expires||e.expires>n)}class Oa extends Xs{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Ma(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`,i=await this.http.post(n,e);if(null==i)return null;try{ee(i,"Fetch balances")}catch{return null}if(0===(i.Data?.length??0))return null;const r=i.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!r||"0"===r.quantity)return null;const o=Na(r),s={quantity:r.quantity,collection:r.collection,category:r.category,tokenId:o};if((r.inUseHolds?.length??0)>0){const e=Ua(r.inUseHolds??[],t);e.length>0&&(s.inUseHolds=e,s.inUseQuantity=Fa(e))}if((r.lockedHolds?.length??0)>0){const e=Ua(r.lockedHolds??[],t);e.length>0&&(s.lockedHolds=e,s.lockedQuantity=Fa(e))}return void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=function(e,t="0",n="0"){return k(e).minus(t).minus(n).toString()}(s.quantity,s.lockedQuantity,s.inUseQuantity)),s}catch(e){throw ke(`Failed to fetch token balance from GalaChain: ${Q(e)}`,void 0,X(e)?e:void 0)}}}function $a(e){if("string"==typeof e){if(!Ra(e))throw new re(`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=Da(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...Da(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(!La(e))throw new re("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!La(e))throw new re("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new re(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function qa(e){return function(e){try{if(!It(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 i=n.split("$");if(i.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${i.length}`);const[r,o,s,...a]=i;if(""===r||""===o||""===s)throw new Error("Collection, category, and type must be non-empty");const c=a.slice(0,-1),l=c.length>0?c.join("$"):a[0];if(""===l||void 0===l)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:o,type:s,additionalKey:l}}catch(t){throw new re(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Q(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function Ka(e){return{...qa(e),instance:"0"}}function Ga(e){return qa(e).type}function Wa(e){return Na($a(e))}var Ha=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Ga,isTokenClassKeyStrict:La,normalizeToTokenInstanceKey:$a,normalizeTokenIdToString:Wa,parseVaultAddressToTokenClassKey:qa,parseVaultAddressToTokenInstance:Ka});class za extends Xs{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?$a(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw ye("publicAxios","Public Axios instance");const i=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(ee(i,"Failed to fetch token class from GalaChain"),null===i.Data||void 0===i.Data||0===i.Data.length)throw ke(`Token not found on GalaChain: ${Na(t)}`,404);return i.Data[0]}catch(e){if(e instanceof re)throw e;if(Y(e)&&404===e.response?.status)throw ke("Token not found on GalaChain",404,X(e)?e:void 0);if(X(e)&&"Error"===e.name&&Q(e).includes("status indicates failure"))throw ke(Q(e),400,X(e)?e:void 0);const t=Q(e);if(t.includes("Token not found"))throw e;throw ke(`Failed to fetch token class from GalaChain: ${t}`,void 0,X(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw ye("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw ye("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(ee(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw ke("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof re)throw e;if(Y(e)&&404===e.response?.status)throw ke("Token supply data not found on GalaChain",404,X(e)?e:void 0);if(X(e)&&"Error"===e.name&&Q(e).includes("status indicates failure"))throw ke(Q(e),400,X(e)?e:void 0);const t=Q(e);if(t.includes("Token not found"))throw e;throw ke(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,X(e)?e:void 0)}}}class ja{toLaunchpadFormat(e){if(null==e)throw new re('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(Ra(e))return e;throw new re(`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 Na({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=Ba(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return""===e?"":Ra(e)?e:`${e}|Unit|none|none`}normalize(e){return"string"==typeof e&&Ra(e)?e:this.toLaunchpadFormat(e)}}function Va(e){if(!It(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function Xa(e){return Ba(e,"$","dollar-delimited token")}function Qa(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class Ja extends m{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&&null!==e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,void 0!==e.signedPayload.prefix&&null!==e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,i,r){let o;if("string"==typeof i){o={...Xa(i),instance:"0"}}else o={collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey,instance:"0"};return new Ja({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:o}],...void 0!==r?.expires&&{expires:r.expires},...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??Qa()})}static forGALA(e,t,n,i){return new Ja({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey??Qa()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return xa(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 Za extends m{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,i){let r;if("string"==typeof n){r={...Xa(n),instance:"0"}}else r={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new Za({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:r}],...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey??Qa()})}static forGALA(e,t,n){return new Za({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==n?.name&&{name:n.name},uniqueKey:n?.uniqueKey??Qa()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return xa(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Ya{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"}]},i={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(i.expires=e.expires),void 0!==e.name&&(i.name=e.name);return{signature:await this.wallet.signTypedData(t,n,i),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"}]},i={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};return{signature:await this.wallet.signTypedData(t,n,i),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"}]},i={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(i.name=e.name);return{signature:await this.wallet.signTypedData(t,n,i),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){return(new Gt).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new Gt).toEthereumFormat(e)}catch{try{return jt(e)}catch{return e}}}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...Xa(e),instance:"0"}}}function ec(e){if(null==e||"object"!=typeof e)return!1;const t=e;return It(t.amount)&&(void 0!==t.tokenId||It(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 tc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return It(t.amount)&&(void 0!==t.tokenId||It(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function nc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(ec)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function ic(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(tc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const rc=100,oc=100;var sc,ac;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(sc||(sc={}));class cc 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"}(ac||(ac={}));class lc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}const uc=100,dc=100;class hc extends Xs{constructor(e,t,n,i=!1){super(e,i),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new Ya(t):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new cc("Wallet required for token lock operations",sc.WALLET_REQUIRED);return Ji(async()=>{const t=zt(this.wallet.address),n=[],i=[];let r=t;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(r=zt(o.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(void 0!==o.tokenId)e=$a(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(void 0===o.tokenName)throw new cc("Must provide either tokenId or tokenName for token identification",sc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),i.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount,lockAuthority:void 0!==o.lockAuthority?zt(o.lockAuthority):r})}const c=new Ja({lockAuthority:r,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??Qa()}),l=await this.signatureHelper.signLockToken(c.toSigningPayload()),u=new Ja({...c.toSigningPayload(),signedPayload:l});this.logger.debug("[DEBUG] Full Lock Request Payload:",JSON.stringify(u,null,2));const d=await this.http.post("/api/asset/token-contract/LockTokens",u);try{ee(d,"Token lock failed")}catch(e){const t=te(d);throw new cc(`${Q(e)}${t}`,sc.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token lock response:",JSON.stringify(d,null,2)),this.extractLockResult(d,i)},"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 cc("Wallet required for token unlock operations",sc.WALLET_REQUIRED);return Ji(async()=>{const t=zt(this.wallet.address),n=[],i=[],r=e.tokens.find(e=>void 0!==e.name);for(const r of e.tokens){let e;if(void 0!==r.tokenId)e=$a(r.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",r.tokenId);else{if(void 0===r.tokenName)throw new cc("Must provide either tokenId or tokenName for token identification",sc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(r.tokenName)}n.push({owner:t,quantity:r.amount,tokenInstanceKey:e}),i.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:r.amount})}const o=new Za({tokenInstances:n,...void 0!==r?.name&&{name:r.name},uniqueKey:e.uniqueKey??Qa()}),s=await this.signatureHelper.signUnlockToken(o.toSigningPayload()),a=new Za({...o.toSigningPayload(),signedPayload:s});this.logger.debug("[DEBUG] Full Unlock Request Payload:",JSON.stringify(a,null,2));const c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);try{ee(c,"Token unlock failed")}catch(e){const t=te(c);throw new cc(`${Q(e)}${t}`,sc.NETWORK_ERROR)}return this.logger.debug("[DEBUG] Token unlock response:",JSON.stringify(c,null,2)),this.extractUnlockResult(c,i)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateLockTokensData(e){if(!nc(e))throw new cc("Invalid lock data: missing required fields",sc.VALIDATION_ERROR);if(e.tokens.length>uc)throw new cc(`Batch size exceeds maximum limit of ${uc} tokens per lock operation`,sc.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new cc("Must provide either tokenId or tokenName for token identification",sc.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{Lt(t.tokenName,"tokenName")}catch{throw new cc("Invalid token name format",sc.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=es(t.amount);try{ps(e)}catch{throw new cc(we("lockAmount","a positive number","Lock amount").message,sc.INVALID_AMOUNT,{amount:t.amount})}if(void 0!==t.lockAuthority&&!Xt(t.lockAuthority))throw new cc("Invalid lock authority address format",sc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Re(t.expires,"expires")}catch{throw new cc(we("expires","a positive integer (epoch milliseconds)","Expires").message,sc.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!ic(e))throw new cc("Invalid unlock data: missing required fields",sc.VALIDATION_ERROR);if(e.tokens.length>dc)throw new cc(`Batch size exceeds maximum limit of ${dc} tokens per unlock operation`,sc.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new cc("Must provide either tokenId or tokenName for token identification",sc.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{Lt(t.tokenName,"tokenName")}catch{throw new cc("Invalid token name format",sc.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=es(t.amount);try{ps(e)}catch{throw new cc(we("unlockAmount","a positive number","Unlock amount").message,sc.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 cc)return e;let i=t,r=sc.NETWORK_ERROR;if(Y(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;void 0!==e.Message&&"string"==typeof e.Message&&(i=`${t}: ${e.Message}`);const o=String(e.Message??"").toLowerCase();o.includes("insufficient")||o.includes("balance")?r=sc.INSUFFICIENT_BALANCE:o.includes("lock")&&o.includes("not found")?r=sc.LOCK_NOT_FOUND:o.includes("not found")||o.includes("token")?r=sc.TOKEN_NOT_FOUND:o.includes("authority")?r=sc.NOT_LOCK_AUTHORITY:o.includes("expired")&&(r=sc.LOCK_EXPIRED)}}else X(e)&&(i=`${t}: ${Q(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new cc(i,r,Object.keys(o).length>0?o:void 0)}async resolveTokenInstance(e){return Ji(async()=>{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!==t){const n=Ka(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:Ks(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n},`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof lc)throw new cc(Q(t),sc.TOKEN_NOT_FOUND);throw new cc(`Failed to resolve token '${e}': ${Q(t)}`,sc.TOKEN_NOT_FOUND,{tokenName:e})})}}class gc{static validateAmount(e){const t=es(e);try{ys(t,"amount")}catch(t){throw new lc(t.message,ac.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!Nt(e)&&It(e)){if(e.length>tt.MAX_LENGTH)throw new re(`Unique key too long. Maximum length: ${tt.MAX_LENGTH}`);if(!tt.PATTERN.test(e))throw new lc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',ac.INVALID_AMOUNT,{uniqueKey:e})}}}class fc extends m{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,i,r){let o;if("string"==typeof i){o={...Xa(i),instance:"0"}}else o={collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey,instance:"0"};return new fc({from:e,to:t,quantity:n,tokenInstance:o,uniqueKey:r??Qa()})}static forGALA(e,t,n,i){return new fc({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:i??Qa()})}getTokenClassKey(){return xa(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}class pc extends m{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={...Xa(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 pc({tokenInstances:n,uniqueKey:t?.uniqueKey??Qa()})}static fromTokenClassKey(e,t,n){return pc.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new pc({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??Qa()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return xa(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}function mc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return It(t.amount)&&(void 0!==t.tokenId||It(t.tokenName))}function yc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(mc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const wc=50;var kc;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(kc||(kc={}));class bc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const vc="gala-transfer-successful",Sc="token-transfer-successful",Ac="token-locked-successfully",Tc="token-unlocked-successfully",Ec="transfer-successful-no-id",Ic=50;class Cc extends Xs{constructor(e,t,n,i=!1){super(e,i),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new Ya(t):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new lc("Wallet required for GALA transfer operations",ac.WALLET_REQUIRED);try{const t=zt(e.recipientAddress),n=zt(this.wallet.address),i=fc.forGALA(n,t,e.amount,e.uniqueKey),r=await this.signatureHelper.signTransferToken(i.toSigningPayload()),o=new fc({...i.toSigningPayload(),signedPayload:r});this.logger.debug("[DEBUG] Full GALA Transfer Request Payload:",JSON.stringify(o,null,2));const s=await this.http.post("/api/asset/token-contract/TransferToken",o);if(null==s)throw new lc("No response from GalaChain transfer service",ac.NETWORK_ERROR);return this.logger.debug("[DEBUG] Transfer response:",JSON.stringify(s,null,2)),this.extractTransactionIdFromResponse(s,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new lc("Wallet required for token transfer operations",ac.WALLET_REQUIRED);try{const t=zt(e.to),n=zt(this.wallet.address);let i;if(null!==e.tokenId&&void 0!==e.tokenId)i=$a(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",JSON.stringify(i,null,2));else{if(null===e.tokenName||void 0===e.tokenName)throw new lc("Must provide either tokenId or tokenName for token identification",ac.TOKEN_NOT_FOUND);i=await this.resolveTokenInstance(e.tokenName)}const r=new fc({from:n,to:t,quantity:e.amount,tokenInstance:i,uniqueKey:e.uniqueKey??Qa()}),o=await this.signatureHelper.signTransferToken(r.toSigningPayload()),s=new fc({...r.toSigningPayload(),signedPayload:o});this.logger.debug("[DEBUG] Full Transfer Request Payload:",JSON.stringify(s,null,2));const a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(null==a)throw new lc("No response from GalaChain transfer service",ac.NETWORK_ERROR);return this.logger.debug("[DEBUG] Token transfer response:",JSON.stringify(a,null,2)),this.extractTransactionIdFromResponse(a,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,JSON.stringify(t,null,2)),t}catch(t){if(t instanceof lc)throw t;throw new lc(`Failed to resolve token class key for '${e}': ${Q(t)}`,ac.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new bc("Wallet required for token burn operations",kc.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=$a(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new bc("Must provide either tokenId or tokenName for token identification",kc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new pc({tokenInstances:t,uniqueKey:e.uniqueKey??Qa()}),i=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),r=new pc({...n.toSigningPayload(),signedPayload:i});this.logger.debug("[DEBUG] Full Burn Request Payload:",JSON.stringify(r,null,2));const o=await this.http.post("/api/asset/token-contract/BurnTokens",r);if(null==o)throw new bc("No response from GalaChain burn service",kc.NETWORK_ERROR);try{ee(o,"Token burn operation")}catch(e){throw new oe(Q(e),500)}return this.logger.debug("[DEBUG] Token burn response:",JSON.stringify(o,null,2)),this.extractBurnResult(o)}catch(t){throw this.handleBurnError(t,"Token burn failed",e)}}validateTransferGalaData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return It(t.recipientAddress)&&It(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new re("Invalid GALA transfer data: missing required fields");if(!Xt(e.recipientAddress))throw new lc("Invalid recipient address format",ac.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});gc.validateAmount(e.amount),gc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return It(t.to)&&It(t.amount)&&(void 0!==t.tokenId||It(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new re("Invalid token transfer data: missing required fields");if(!Xt(e.to))throw new lc("Invalid recipient address format",ac.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new lc("Must provide either tokenId or tokenName for token identification",ac.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Lt(e.tokenName,"tokenName")}catch{throw new lc("Invalid token name format",ac.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}gc.validateAmount(e.amount),gc.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!yc(e))throw new bc("Invalid burn data: missing required fields",kc.VALIDATION_ERROR);if(e.tokens.length>Ic)throw new bc(`Batch size exceeds maximum limit of ${Ic} tokens per burn operation`,kc.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 bc("Must provide either tokenId or tokenName for token identification",kc.TOKEN_NOT_FOUND);const e=es(t.amount);try{ps(e)}catch{throw new bc("Burn amount must be a positive number",kc.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!=t){const n=Ka(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):\n Vault Address: ${t}\n Token Instance: ${JSON.stringify(n,null,2)}`),n}const n={collection:Ks(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug(`[DEBUG] Token resolution for '${e}' (standard format):\n Token Instance: ${JSON.stringify(n,null,2)}`),n}catch(t){if(t instanceof lc)throw t;throw new lc(`Failed to resolve token '${e}': ${Q(t)}`,ac.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransactionIdFromResponse(e,t){if(null!=e&&"object"==typeof e){if("Status"in e&&"Data"in e)try{ee(e,"Extract transaction ID");const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return vc;case"token":return Sc;case"lock":return Ac;case"unlock":return Tc}return Ec}catch{}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return e.transactionId}throw new lc("Operation succeeded but transaction ID could not be extracted",ac.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 lc)return e;if(e instanceof re)return new lc(Q(e),ac.INVALID_AMOUNT);if(Y(e)&&e.response){const t=e.response.status,i=e.response.data;if(400===t){const e="string"==typeof i?.message?i.message:void 0;return new lc(e??"Invalid transfer request",ac.INVALID_AMOUNT)}if(403===t)return new lc("Insufficient balance for transfer",ac.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new lc("Token not found",ac.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Z(e)||"ETIMEDOUT"===Z(e)))return new lc("Transfer request timed out",ac.NETWORK_ERROR);const i=Q(e);return new lc(i??t,ac.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof bc)return e;let i=t,r=kc.NETWORK_ERROR;if(Y(e)){const n=e.response?.data;if("object"==typeof n&&null!==n&&"string"==typeof n.Message&&n.Message.length>0){i=`${t}: ${n.Message}`;const e=n.Message.toLowerCase();e.includes("insufficient")||e.includes("balance")?r=kc.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(r=kc.TOKEN_NOT_FOUND)}}else X(e)&&(i=`${t}: ${Q(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new bc(i,r,Object.keys(o).length>0?o:void 0)}}class Nc extends Xs{constructor(e,t,n,i=!1,r){super(e,i),this.wallet=t,this.tokenResolver=n,this.publicAxios=r,this.balanceService=new Oa(e,i),this.tokenService=new za(e,i,r),this.lockService=new hc(e,t,n,i),this.transferService=new Cc(e,t,n,i)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);Zi(()=>ee(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw ke(Q(e),500)});const n=t.Data.reverseBondingCurveConfiguration,i=n?.minFeePortion??"0",r=n?.maxFeePortion??"0",o=!us(i)||!us(r),s=t.Data;return s.reverseBondingCurveMinFeePortion=i,s.reverseBondingCurveMaxFeePortion=r,s.hasReverseBondingCurveFee=o,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return Zi(()=>ee(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw ke(Q(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!Ia(e))throw ye("data","Fetch pool details data");if(void 0===e.vaultAddress||""===e.vaultAddress||"string"!=typeof e.vaultAddress)throw ye("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new re("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 xc extends Qs{constructor(e,t,n,i=!1){super(i),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=Pt(e,"tokenName","tokenId",{description:"token identifier"});if(!0===n&&null!=t)return this.logger.debug(`Fetching spot price by tokenId: ${t}`),this._fetchDexTokenSpotPrice(t);throw new re("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw ye("tokenId","Token ID");try{const t=$a(e),n=Na(t),i=Va(n);if(this.logger.debug(`Fetching DEX spot price for token: ${i}`),!this.dexBackendHttp)throw ke("DEX Backend API client not configured");const r=Xi(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:i}}));if(null==r||"string"!=typeof r)throw new re("Invalid price response: data must be a string, got "+typeof r,"data","INVALID_RESPONSE");const o=function(e,t){if(Nt(e)||""===e)throw ye(t);const n="number"==typeof e?e:parseFloat(String(e));if(isNaN(n))throw Ce(t,e);if(!isFinite(n))throw Ce(t,e);return n}(r,"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): $${o}`),{symbol:a,price:o}}this.logger.debug(`Symbol cache miss for ${s}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(s,{symbol:a}),this.logger.debug(`Cached symbol for ${s}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${X(e)?e.message:String(e)}`),a=Gs("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${a} (fallback): $${o}`)}return{symbol:a,price:o}}catch(e){if(e instanceof re)throw e;throw ke(`Failed to fetch DEX spot price: ${Q(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!It(e))throw new re(nr,"tokenName",ie.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=Na(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Q(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const i=await t({tokenName:e,amount:"1",type:"native"}),r=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==r)throw ke("GALA price not available");const o=lt(i.amount,0)/1e18;if(o<=0)throw new re(`Invalid token amount calculation: ${o}`,"amount","INVALID_CALCULATION");const s=r.price/o;return{symbol:Gs(e),price:s}}catch(t){if(X(t))throw ke(`Failed to calculate launchpad token spot price for ${e}: ${Q(t)}`);throw ke(`Failed to calculate launchpad token spot price for ${e}: ${Q(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw ke("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 re||X(t))&&("NetworkError"===t.name||Q(t).includes("Token not found")))throw t;throw ke(`Failed to fetch token details from GalaChain for ${e}: ${Q(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw ke("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=Xi(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:St(t?.start??null),end:St(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(X(e)&&Q(e).includes("not configured"))throw e;if(Y(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw ke(`Failed to fetch DEX seasons: ${Q(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{Re(e,"seasonId")}catch{throw ye("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw ke("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 i=Xi(t);if(null!=i&&"object"==typeof i&&Array.isArray(i.leaderboard))n=i.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(i))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=i}}}const i=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 ${i.length} entries`),{entries:i,seasonId:e,totalEntries:i.length}}catch(t){if(X(t)&&Q(t).includes("must be a positive number"))throw t;throw ke(`Failed to fetch DEX leaderboard for season ${e}: ${Q(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 ke("DEX Backend API client not configured");const e=Xi(await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}));if(!e)throw ke("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 ke(`Failed to fetch DEX volume summary: ${Q(e)}`)}}}function _c(e){return{maxAcceptableReverseBondingCurveFee:yt(e.maxAcceptableReverseBondingCurveFee)}}const Bc={BuyNativeDto:class extends m{constructor(e,t,n="0",i={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=yt(t),this.expectedToken=wt(n),this.extraFees=_c(i)}},BuyExactDto:class extends m{constructor(e,t,n,i={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=wt(t),this.expectedNativeToken=yt(n),this.extraFees=_c(i)}},SellExactDto:class extends m{constructor(e,t,n="0",i={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=wt(t),this.expectedNativeToken=yt(n),this.extraFees=_c(i)}},SellNativeDto:class extends m{constructor(e,t,n,i={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=yt(t),this.expectedToken=wt(n),this.extraFees=_c(i)}}};class Pc extends Qs{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),i=y(e),r={...e,prefix:i},{signature:o,domain:s}=await this.signWithEthersWallet(n,r),a={...e,signature:o,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(a),signatureLength:o.length}),a}catch(e){this.logger.error("❌ Signature generation failed:",e);throw ve(`Failed to sign DTO: ${Q(e)}`)}}async signWithEthersWallet(e,t){try{let n,i;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},i=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw be("Wallet provider does not support typed data signing","walletProvider");{const r=await this.walletProvider.getNetwork();n={name:r.name,chainId:ht(r.chainId,1)},i=await this.walletProvider.signTypedData(n,e,t)}}return{signature:i,domain:n}}catch(e){throw ve(`Ethers.js signing failed: ${Q(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const i=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),r=(e,t,i,o=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=r(e,t[0],i,!0);return o||n[i].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 re(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).forEach(([t,n])=>{r(t,n,e)}),o||n[i].push({name:e,type:e}),e}{let r;switch(typeof t){case"string":r="string";break;case"number":r="uint256";break;case"boolean":r="bool";break;default:throw new re(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return o||n[i].push({name:e,type:r}),r}}};return Object.entries(i).forEach(([t,n])=>{r(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class Dc extends Qs{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),i=this.createGalaInstance(),r=`$service$${n.toStringKey()}$launchpad`,o=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${i.toStringKey()}$${e}`,c=[r,o,s,a,`$tokenBalance$${i.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Q(e);throw new re(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new S;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new S;return e.collection="GALA",e.category="Unit",e.type="none",e.additionalKey="none",this.logger.debug("🟡 Created GALA instance:",{stringKey:e.toStringKey()}),e}extractTokenSymbolFromVault(e){if(!It(e))throw ye("vaultAddress","Vault address");try{const t=Ga(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof re)throw we("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!It(e))throw ye("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw we("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw we("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!It(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 we("vaultAddress","valid vault address format (service|Token$Unit$SYMBOL$eth:address$launchpad)");const n=t.tokenSymbol;if(""===n||null===n||!/^[A-Za-z]{1,10}$/.test(n))throw we("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,i){return`${e}$${t}$${n}$${i}`}parseTokenClassKeyString(e){try{return Xa(e)}catch(e){if(e instanceof re)throw we("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Rc(e,t,n){let i;Pe(t,0,1,"slippageToleranceFactor");try{i=ft(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const r=i.multipliedBy(t);let o;switch(n){case"buy-native":case"sell-exact":o=i.minus(r);break;case"buy-exact":case"sell-native":o=i.plus(r);break;default:throw new Error(`Unknown operation type: ${n}`)}return hs(o)&&(o=es(0)),ts(o)}class Mc extends Xs{constructor(e,t,n=!1,i,r,o=.05,s=.01){super(e,n),this.tokenResolver=t,this.walletProvider=i,this.userAddress=r,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",null!=i&&null!=r&&(this.signatureService=new Pc(i,n),this.tokenKeyService=new Dc(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 Us(()=>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:ji(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof re)return{success:!1,error:Q(e)};throw e}}validateBundleData(e){if(null==e)throw ye("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw ye("signedDto","Signed DTO");if(!It(e.method))throw ye("method","Method name");if(!Array.isArray(e.stringsInstructions))throw we("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new re("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw we("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!It(e))throw new re(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Ma(e))throw new re(`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=Xi(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(Y(e)&&null!==e.response&&void 0!==e.response){const t=Xi(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return String(e.error);if(null!==e.message&&void 0!==e.message)return String(e.message)}}return Q(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!It(e))throw ye("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Us(()=>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 re)return{success:!1,error:Q(e)};throw e}}async cancelTransaction(e){try{if(!It(e))throw ye("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Us(()=>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 re)return{success:!1,error:Q(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Us(()=>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:i,expectedAmount:r}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===i){if(null==r||""===r)throw new re("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Rc(r,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:o,adjustedMinTokens:e});const t=new Bc.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==r||""===r)throw new re("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Rc(r,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:o,adjustedMaxGalaCost:e});const t=new Bc.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:i,expectedAmount:r}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===i){if(null==r||""===r)throw new re("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Rc(r,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:o,adjustedMinGala:e});const t=new Bc.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==r||""===r)throw new re("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Rc(r,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new Bc.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,i){const{effectiveSlippageFactor:r,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,i),s=await this.resolveTokenNameToVault(e);if(null==s)throw me(e);return{effectiveSlippageFactor:r,effectiveMaxFee:o,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const i=n??this.defaultSlippageToleranceFactor,r=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e??"0";return null!=e&&(o=Rc(e,r,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:r,adjustedMaxFee:o})),{effectiveSlippageFactor:i,effectiveFeeSlippageFactor:r,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw be("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw ye("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${v()}-${Date.now()}-${this.userAddress}`;const i=await this.signatureService.signDTO(e,t,this.userAddress),r=this.tokenKeyService.generateStringsInstructions(n),o={stringsInstructions:r,method:t,signedDto:i};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(i)});const s=await this.submitTransaction(o);if(s.success){const e=Xi(s);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}throw new ae(String(s.error??"Bundle transaction failed"),void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class Lc{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 i=n??this.defaultTtlMs,r={value:t};i>0&&(r.expiresAt=Date.now()+i),this.cache.set(e,r)}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 Fc(e,t,n,i={}){const{logger:r,cacheNullish:o=!1,keyGenerator:s}=i,a=s?s(e):String(e),c=n.get(a);if(void 0!==c)return r&&r.debug(`Cache hit for key: ${a}`),c;r&&r.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),r&&r.debug(`Cached result for key: ${a}`)):o&&(n.set(a,l),r&&r.debug(`Cached nullish result for key: ${a}`)),l}var Uc,Oc;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Uc||(Uc={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Oc||(Oc={}));const $c={[Uc.PROCESSED]:Oc.COMPLETED,[Uc.COMPLETED]:Oc.COMPLETED,[Uc.SUCCESS]:Oc.COMPLETED,[Uc.FAILED]:Oc.FAILED,[Uc.ERROR]:Oc.FAILED,[Uc.PROCESSING]:Oc.PROCESSING,[Uc.PENDING]:Oc.PENDING};class qc{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 Kc extends Qs{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 qc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Lc(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof T||(this.logger.warn('⚠️ Socket.IO client not available. Install "socket.io-client" package.'),!1)}catch(e){return this.logger.warn("⚠️ Socket.IO availability check failed:",e),!1}}async connect(){return new Promise((e,t)=>{Ji(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",Q(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=T(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],i=n.status??n.Status;"string"==typeof i&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${i}`),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 i=this.config.timeout??3e5,r=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(i/1e3),r={transactionId:e,status:Oc.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(r),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},i);if(this.timeouts.set(e,r),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${this.socket.id}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:Oc.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 i=t,r=i?.data,o=i?.status??i?.Status??r?.status??r?.Status;let s=i?.message??i?.Message??r?.message??r?.Message??i?.error??r?.error;It(s)||(s=o===Uc.FAILED||o===Uc.ERROR?"Transaction failed - check transaction details":o===Uc.COMPLETED||o===Uc.PROCESSED||o===Uc.SUCCESS?"Transaction completed successfully":null!=o?`Transaction status: ${o}`:"Unknown transaction status");const a=i?.blockHash??r?.blockHash,c=i?.gasUsed??r?.gasUsed,l=i?.Data??r?.Data,u={transactionId:e,status:this.mapSocketStatus(o),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}: ${o} -> ${u.status}`),this.logger.debug(`📡 Final message: "${s}"`),n(u),u.status===Oc.COMPLETED||u.status===Oc.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===Oc.COMPLETED?t(e):e.status!==Oc.FAILED&&e.status!==Oc.TIMEOUT||n(new Error(`Transaction ${e.status}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return $c[t]??Oc.PENDING}async handleReconnect(){this.reconnectionManager.shouldRetry()?(this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Attempting Socket.IO reconnect ${this.reconnectionManager.getStatusString()}`),setTimeout(()=>{this.socket&&!this.socket.connected&&this.socket.connect()},this.reconnectionManager.getNextDelay())):this.logger.error("❌ Socket.IO max reconnection attempts reached")}disconnect(){this.socket&&(this.listeners.forEach((e,t)=>{this.socket?.off(t)}),this.listeners.clear(),this.timeouts.forEach(e=>{clearTimeout(e)}),this.timeouts.clear(),this.eventBuffer.clear(),this.logger.debug("🧹 Cleared event buffer"),this.hasOnAnyListener&&(this.socket.offAny(),this.hasOnAnyListener=!1,this.logger.debug("🧹 Removed onAny debug listener")),this.socket.disconnect(),this.socket=null,this.logger.debug("🔌 Socket.IO disconnected"))}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}class Gc extends Qs{constructor(e,t=!1){super(t),this.poolService=e,this.cache=new Map}async resolveTokenToVault(e){if(!It(e))throw ye("tokenName","Token name");const t=qs(e),n=this.get(t);if(null!==n&&""!==n)return n;try{const n=await this.poolService.resolveTokenNameToVault(e);return null!==n&&""!==n&&this.set(t,n),n}catch{return null}}async resolveTokenClassKey(e){const t=await this.resolveTokenToVault(e);if(null===t||""===t)throw me(e);return this.parseVaultAddressToTokenClassKey(t)}get(e){return this.cache.get(qs(e))??null}set(e,t){this.cache.set(qs(e),t)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,keys:Array.from(this.cache.keys())}}preWarm(e){for(const{tokenName:t,vaultAddress:n}of e)this.set(t,n)}parseVaultAddressToTokenClassKey(e){try{return qa(e)}catch(e){if(e instanceof re)throw we("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}class Wc extends Xs{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw ye("tokenName","Token name");if(!this.tokenResolverService)throw be("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{Dt(e)}catch(e){throw be(Q(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 be(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Na(qa(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(X(t)&&Q(t).includes("ConfigurationError"))throw t;throw ke(`Failed to resolve token name '${e}': ${Q(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw ye("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),Ji(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 be("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return Ha}),i=Va(Na(n(t))),{from:r,to:o,sortOrder:s="DESC"}=e,a=ut(e.offset,0),c=ut(e.limit,10),l={token:i,offset:String(a),limit:String(c)};r&&(l.from=r.toISOString()),o&&(l.to=o.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 ${i}, offset ${a}, limit ${c}`);const d=await this.http.get("/price-oracle/fetch-price",l);if(null==d)throw ke("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(!ji(e))throw ke("Invalid API response: missing data wrapper",500);const t=Xi(e);if(!t||"object"!=typeof t)throw ke("Invalid API response: data is not an object",500);const n=t,i=n.data;if(!Array.isArray(i))throw ke("Invalid API response: missing or invalid data.data array",500);const r=n.meta;if(null==r||"object"!=typeof r)throw ke("Invalid API response: missing data.meta pagination info",500);const o=r,s=i.map(e=>{if("object"!=typeof e||null===e)throw ke("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:St(t.createdAt),tokenId:Na({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=dt(o.currentPage,1),c=dt(o.totalPages,1);return{snapshots:s,page:a,limit:dt(o.pageSize,50),total:dt(o.totalItems,0),totalPages:c,hasNext:a<c,hasPrevious:a>1}}async fetchAllPriceHistory(e){if(null==e)throw ye("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Ji(async()=>{const t=await Ls((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 i=e.length;return{offset:0,limit:i,total:t,totalPages:0!==i?Ps(t,i):void 0,hasNext:!1,hasPrevious:!1,[n]:e}}(t.items,t.total,"snapshots")},"Failed to fetch all price history",this.logger)}validateOptions(e){const t=ut(e.offset,0),n=ut(e.limit,10),{from:i,to:r,sortOrder:o}=e;if(Pt(e,"tokenName","tokenId",{description:"token identifier"}),i&&!At(i))throw be("from must be a valid Date","from");if(r&&!At(r))throw be("to must be a valid Date","to");null!=o&&Fe(o,"sortOrder"),xt(t,n,50)}}class Hc extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function zc(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 jc(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&zc(t.token0ClassKey)&&zc(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}class Vc{constructor(e){this.client=z(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return Ji(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new re(`GalaChain API getPoolData requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getPoolData(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&zc(t.token0ClassKey)&&zc(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(n))throw new Hc(t.status,"Invalid pool data response format",n);return n},"GalaChainGatewayClient.getPoolData",void 0,e=>{throw this.handleError(e,"getPoolData")})}async getSlot0(e){return Ji(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new re(`GalaChain API getSlot0 requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getSlot0(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetSlot0",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.liquidity}(n))throw new Hc(t.status,"Invalid slot0 data response format",n);return n},"GalaChainGatewayClient.getSlot0",void 0,e=>{throw this.handleError(e,"getSlot0")})}async getPositions(e){return Ji(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;let i;i=null!=n&&"object"==typeof n&&"positions"in n&&Array.isArray(n.positions)?n.positions:null!=n&&"object"==typeof n&&"positionId"in n?[n]:Array.isArray(n)?n:[];for(const e of i)if(!jc(e))throw new Hc(t.status,"Invalid position in response",e);return{positions:i,count:i.length}},"GalaChainGatewayClient.getPositions",void 0,e=>{throw this.handleError(e,"getPositions")})}async getPositionById(e,t,n,i,r,o,s){return Ji(async()=>{let a,c;if(void 0!==t&&void 0!==n&&void 0!==i&&void 0!==r&&void 0!==o){a={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof n?{collection:n,category:"Unit",type:"none",additionalKey:"none"}:n,fee:i,tickLower:r,tickUpper:o},null!=s&&(a.positionId=s),c=`${e}/${t}/${n}/${i}`}else a={positionId:e},c=e;const l=await this.client.post("/api/asset/dexv3-contract/GetPositions",a);this.validateResponse(l.data);const u=l.data.Data;let d;if(null!=u&&"object"==typeof u&&"positionId"in u&&!("positions"in u))d=u;else{if(!(null!=u&&Array.isArray(u.positions)&&u.positions.length>0))throw new Hc(404,`Position not found: ${c}`);d=u.positions[0]}const h={Data:d,Status:l.status};return void 0!==l.data.Message&&(h.Message=l.data.Message),h},"GalaChainGatewayClient.getPositionById",void 0,t=>{throw this.handleError(t,`getPositionById(${e})`)})}async getRemoveLiquidityEstimation(e){return Ji(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1)throw new Hc(t.status,"Invalid removal estimation response format",n);return n},"GalaChainGatewayClient.getRemoveLiquidityEstimation",void 0,e=>{throw this.handleError(e,"getRemoveLiquidityEstimation")})}validateResponse(e){if(null==e||"object"!=typeof e)throw new Hc(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new Hc(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Hc(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,t){if(e instanceof Hc)return e;if(Y(e)){const n=e.response?.status??500,i=e.response?.data,r=i?.Message??Q(e);return new Hc(n,`${t}: ${r}`,i?.Data??void 0)}return new Hc(500,`${t}: ${Q(e)}`)}}class Xc{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return Ji(async()=>{if(!It(e))throw ye("walletAddress","Wallet address");const i=Math.max(1,Math.floor(n/t)+1),r={};r.address=e,r.page=i,r.limit=t;const o=await this.http.get("/user/assets",r);if("object"!=typeof o||null===o)throw new Hc(500,"Invalid response format: not an object");const s=Xi(o);if(!s||"object"!=typeof s)throw new Hc(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new Hc(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 Hc(500,"Invalid asset in response: asset must be an object");const t=e;if(!It(t.symbol)||!It(t.name))throw new Hc(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 Hc(500,"Invalid asset in response: decimals must be a number",t);const i={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&&(i.imageUrl=t.image),"boolean"==typeof t.verify&&t.verify&&(i.verified=t.verify),c.push(i)}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 Ji(async()=>{const{address:t,search:n,page:i=1,limit:r=20}=e,o={page:i,limit:Bs(r,1,20)};"string"==typeof t&&t.length>0&&(o.address=t),"string"==typeof n&&n.length>0&&(o.search=n);const s=await this.http.get("/user/token-list",o);if("object"!=typeof s||null===s)throw new Hc(500,"Invalid response format: not an object");const a=Xi(s);if(!a||"object"!=typeof a)throw new Hc(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new Hc(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 Hc(500,"Invalid token in response: must be an object");const t=e;if(!It(t.symbol))throw new Hc(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!It(t.name))throw new Hc(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new Hc(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!It(t.compositeKey))throw new Hc(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 Hc)return e;if(Y(e)){const n=e.response?.status??500,i=e.response?.data,r=i?.message??i?.Message??Q(e),o=i?.Data??i?.data??void 0;if(i){e.config}return new Hc(n,`${t}: ${r}`,o)}return new Hc(500,`${t}: ${Q(e)}`)}}class Qc{static createClient(e,t=6e4){return z(e,t)}}function Jc(e){try{if(!It(e))throw new Error("Token must be a non-empty string");return Da(e)}catch(t){throw new re(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${Q(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const Zc=10;class Yc extends Qs{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new ja,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,void 0===e.gatewayBaseUrl||null===e.gatewayBaseUrl||""===e.gatewayBaseUrl||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 se("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.","gswapConfig");try{this.gatewayClient=new Vc({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new Xc(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new se("Failed to initialize GSwapService HTTP clients","httpClients")}}setPricingConcurrency(e){if(e<1)throw Te("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(es(e.amount).isLessThanOrEqualTo(0))throw new ce("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ce("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),[i,r]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:i,token1:r,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=es(s.currentSqrtPrice),l=es(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):es(0),d=es(s.amount0),h=es(s.amount1),g=hs(d),f=hs(h);this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":g,"amount1BN.isNegative()":f});const p=g?d:h;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:g,selectedAmount:p.toFixed(),selectedAmountAbs:p.absoluteValue().toFixed()});const m=p.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact: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:X(e)?e.message:"Unknown error"})}throw s??new ce("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",ce,e)}}async getSwapQuoteExactOutput(e){try{if(es(e.amount).isLessThanOrEqualTo(0))throw new ce("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ce("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),[i,r]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:i,token1:r,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=es(s.currentSqrtPrice),l=es(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):es(0),d=o.pool.token0,h="string"==typeof d?Pa(d).collection:"object"==typeof d&&null!==d&&"tokenName"in d?d.tokenName:String(d),g=Pa(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:X(e)?e.message:"Unknown error"})}throw s??new ce("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",ce,e)}}async executeSwap(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new se("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),i=ns(e.estimatedOutput,e.slippageTolerance??.01),r=this.getWalletAddress();if(null==r||""===r)throw new re("Wallet address required for swap execution","walletAddress",ie.REQUIRED);let o;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});o=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:o,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:Q(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:i.toFixed(),feeTier:e.feeTier,walletAddress:r,slippageTolerance:e.slippageTolerance??.01,...!Nt(o)&&{currentSqrtPrice:o}},a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance??.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",le,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return Ji(async()=>{if(!Xt(e))throw new de(we("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(de,{walletAddress:e,page:t,limit:n}))}async getAllUserAssets(e){return Ji(async()=>{if(!Xt(e))throw new de(we("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 Ls(async(n,i)=>{const r=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:i}),o=[];for(const e of r.token){if("0"===e.quantity){t=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&o.push(n)}return{items:o,page:n,limit:i,total:o.length,totalPages:1,hasNext:!t&&r.token.length===i,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(de,{walletAddress:e}))}async fetchAvailableDexTokens(e={}){return Ji(async()=>{const{search:t,offset:n=0,limit:i=20}=e,r=Math.floor(n/i)+1;this.logger.debug("Fetching available DEX tokens",{search:t,page:r,limit:i});const o=await this.dexBackendClient.fetchTokenList({...!Nt(t)&&{search:t},page:r,limit:i}),s=o.token.map(e=>this.transformRawTokenToDexToken(e)),a=Ds(n,i,o.count);return{tokens:s,count:o.count,page:r,limit:i,hasMore:a}},"Failed to fetch available DEX tokens",this.logger,this.createGSwapErrorHandler(de,{...e}))}async fetchAllAvailableDexTokens(e={}){return Ji(async()=>{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=await Ls(async(e,n)=>{const i=await this.dexBackendClient.fetchTokenList({...!Nt(t)&&{search:t},page:e,limit:n});return{items:i.token.map(e=>this.transformRawTokenToDexToken(e)),page:e,limit:n,total:i.token.length,totalPages:1,hasNext:i.token.length===n,hasPrevious:e>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.items.length}),n.items},"Failed to fetch all available DEX tokens",this.logger,this.createGSwapErrorHandler(de,e))}async getPoolInfo(e,t){try{if(null==e||""===e)throw ye("tokenA","Token A");if(null==t||""===t)throw ye("tokenB","Token B");this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:i}=this.convertTokenPair(e,t),r=[500,3e3,1e4];let o=es(0),s=0;for(const a of r)try{const e="string"==typeof n?Pa(n):n,t="string"==typeof i?Pa(i):i,r=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});null!=r&&(o=o.plus(es(r.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:r,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new ue(`Failed to fetch pool info: ${Q(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 i=0;i<e.length;i+=t)n.push(e.slice(i,i+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 i=Array.from(n.values()),r=this.chunkArray(i,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:r.length,concurrency:t});const o=new Map;for(let e=0;e<r.length;e++){const t=r[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?o.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return o}normalizePositionResponse(e,t){const n=e,i=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""},r=i(n.token0),o=i(n.tokenA),s=i(n.token1),a=i(n.tokenB),c=n.token0Symbol??(""!==r?r:""!==o?o: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 Pa(e)}catch(t){if(X(t)&&Q(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:ht(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?Pa(e.compositeKey.replace(/\$/g,"|")):Pa(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:n,balance:ts(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:Q(e)}),null}}async getUserLiquidityPositions(e,t=10,n,i){try{if(null==e||""===e)throw ye("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:t,bookmark:n});const r=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,o={user:e,limit:t,bookmark:null!=n&&""!==n?n:""};this.logger.debug("Sending position query request",{endpoint:r,payload:o});const s=await g.post(r,o,{headers:{"Content-Type":"application/json",Accept:"application/json"}}),a=Xi(s);if(200!==s.status||1!==a?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:s.status,apiStatus:a?.Status}),{items:[]};const c=a?.Data??{},l=c?.positions??[],u=c?.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:null!=u,nextBookmark:u}),i?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const f={items:d};return Nt(u)||(f.nextBookmark=u),Nt(h)||(f.prices=h),f}catch(t){Y(t)&&this.logger.error("Position query failed with HTTP error",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:e}),this.handleGSwapError("Failed to fetch user liquidity positions",he,t)}}async getAllSwapUserLiquidityPositions(e,t){try{if(null==e||""===e)throw ye("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,Zc,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},i=await async function(e,t={}){const{maxPages:n=1e4,logger:i,pageSize:r=20}=t,o=[];let s,a=0;for(;a<n;){i&&i.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${r}`,{bookmark:s});const t=await e(s,r);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)){i&&i.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(n)){i&&i.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){i&&i.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}o.push(...n),a++,i&&i.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:""!==(c??""),format:l?"BookmarkPaginationResult":"legacy-array"});const u=n.length<r;if(l&&(""===c||void 0===c)){i&&i.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){i&&i.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:r,format:l?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&i&&i.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),i&&i.debug(`Auto-pagination (bookmark): completed with total items: ${o.length}`,{pageCount:a}),{items:o,total:o.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:Zc}),r=i.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:r.length}),t?.withPrices&&r.length>0){return{items:r,prices:await this.fetchPositionPrices(r)}}return r}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",he,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{if(null==e||""===e)throw ye("ownerAddress","Owner address");if(void 0===t.token0||null===t.token0||""===t.token0)throw ye("token0","Token 0");if(void 0===t.token1||null===t.token1||""===t.token1)throw ye("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:i}=this.convertTokenPair(t.token0,t.token1),r=Jc(n),o=Jc(i),s=(await this.gatewayClient.getPositions({owner:e,token0:r,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new he("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",he,e)}}async getLiquidityPositionById(e,t,n,i,r,o,s){try{if(null==e||""===e)throw ye("ownerAddress","Owner address");if(null==t||""===t)throw ye("positionId","Position ID");let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:null!=n,hasToken1:null!=i,hasFee:null!=r,hasTickLower:!Nt(o),hasTickUpper:!Nt(s)});let c=null;const l=5,u=2e3;for(let d=1;d<=l;d++)try{if(null!=n&&""!==n&&null!=i&&""!==i&&!Nt(r)&&!Nt(o)&&!Nt(s))try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:i,feeTier:r,tickLower:o,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,i,r,o,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 he("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:d,error:X(e)?e.message:e})}try{if(a=(await this.gatewayClient.getPositionById(t)).Data,null!=a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position on attempt",{attempt:d,positionId:t});break}throw new he("Invalid position data from direct lookup",null,"INVALID_DATA")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:d,positionId:t,error:X(n)?n.message:n});const i=await this.getAllSwapUserLiquidityPositions(e),r=Array.isArray(i)?i:i.items;if(r.length>0){const e=r.find(e=>la(null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"",t));if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:d,positionId:t,totalPositions:r.length});break}}if(c=Ne(t),d<l){this.logger.warn("Fallback query did not find position, retrying",{attempt:d,positionId:t,ownerAddress:e,foundCount:r.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:Q(e)}),await new Promise(e=>setTimeout(e,u));continue}c=X(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",resultValue:JSON.stringify(a),lastError:c?.message}),c??Ne(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",he,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 i=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(null===i.positions||void 0===i.positions||0===i.positions.length)throw new he("Position not found: No position exists for this compound key",null,"NOT_FOUND");const r=i.positions[0],o=this.normalizePositionResponse(r,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:o.positionId,token0:o.token0,token1:o.token1}),o}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",he,e)}}async estimateRemoveLiquidity(e){try{if(void 0===e.token0||null===e.token0||""===e.token0)throw ye("token0","Token 0");if(void 0===e.token1||null===e.token1||""===e.token1)throw ye("token1","Token 1");if(void 0===e.liquidity||null===e.liquidity||""===e.liquidity)throw ye("liquidity","Liquidity amount");if(void 0===e.owner||null===e.owner||""===e.owner)throw ye("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),i=Jc(t),r=Jc(n),o=await this.gatewayClient.getRemoveLiquidityEstimation({token0:i,token1:r,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:o}),o}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",he,e)}}async addLiquidityByPrice(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new se("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 i=Pa(t),r=Pa(n),o=(await this.gatewayClient.getPoolData({token0:i,token1:r,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:o,fee:e.fee});const s=es(e.minPrice),a=es(e.maxPrice),c=Math.floor(os(s)),l=Math.ceil(os(a)),u=ks(c,o),d=ks(l,o);this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:u,tickUpper:d,tickSpacing:o});const h=this.getWalletAddress();if(null==h||""===h)throw new se("GSwapService: No wallet address available - cannot create position","walletAddress");const g="string"==typeof e.token0?Pa(e.token0):e.token0,f="string"==typeof e.token1?Pa(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${u}-${d}`,walletAddress:h});const p=await this.sendAddLiquidityToBundler({token0:g,token1:f,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:p};if(null!==m.positionId&&void 0!==m.positionId&&""!==m.positionId&&null!=p&&""!==p){this.logger.debug("Position ID returned directly from backend",{transactionId:p,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(p);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:e.status});const t=this.getWalletAddress();if(null!=t&&""!==t&&null!==m.positionId&&void 0!==m.positionId&&""!==m.positionId)try{const n=await this.getLiquidityPositionById(t,m.positionId),{createdAt:i,updatedAt:r,...o}=n,s=i instanceof Date?i.getTime():"number"==typeof i?i:void 0,a={...m,...o,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}};return Nt(s)||(a.createdAt=s),a}catch(t){return{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}}if(null!=p&&""!==p){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:p}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(p);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:t.status});let i=null;await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(null==t||""===t)throw new se("No wallet address available","walletAddress");const r=(await this.getUserLiquidityPositions(t,10)).items;if(null!=r&&r.length>0){const t=Pa(e.token0).collection.toUpperCase(),o=Pa(e.token1).collection.toUpperCase(),s=[];for(const n of r){if(""===(n?.positionId??""))continue;const i=null!==n.token0&&void 0!==n.token0?n.token0.toUpperCase():void 0,r=null!==n.token1&&void 0!==n.token1?n.token1.toUpperCase():void 0;if(null==i||""===i||null==r||""===r)continue;const a=ha(i,r,t,o),c=n.feeTier===e.fee;a&&c&&s.push(n)}s.length>0&&(i=s[s.length-1],n=i.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:r.length}))}}catch(e){this.logger.debug("Error waiting for position indexing",{error:Q(e)})}let r=i;if(null!=n&&""!==n)try{r=await this.getLiquidityPositionById(h,n)}catch(e){}const o=r?{ownerAddress:r.ownerAddress,token0:r.token0,token1:r.token1,feeTier:r.feeTier,tickLower:r.tickLower,tickUpper:r.tickUpper,liquidity:r.liquidity,amount0:r.amount0,amount1:r.amount1,feeAmount0:r.feeAmount0,feeAmount1:r.feeAmount1}:{};return{...m,...o,...null!=n&&""!==n&&{positionId:n},status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){if(X(e)){const t=J(e);t?.split("\n").slice(0,3).join(" | ")}this.handleGSwapError("Failed to add liquidity by price",he,e)}}async addSwapLiquidityByTicks(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new se("GSwapService not initialized with signing capability (privateKey required)","privateKey");const t=this.getWalletAddress();if(null==t||""===t)throw new se("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?Pa(e.token0):e.token0,i="string"==typeof e.token1?Pa(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendAddLiquidityToBundler({token0:n,token1:i,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:r});const o=this.webSocketService.waitForTransaction(r),s={transactionId:r};if(null!==s.positionId&&void 0!==s.positionId&&""!==s.positionId&&null!=r&&""!==r){this.logger.info("Position ID returned directly from backend",{transactionId:r,positionId:s.positionId});const e=await o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:r,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:i,updatedAt:o,...a}=n,c=i instanceof Date?i.getTime():"number"==typeof i?i: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(r)}};return Nt(c)||(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:Q(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(r)}}}}if(null!=r&&""!==r){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:r});const n=await o;let i;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:r,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 se("No wallet address available","walletAddress");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:Zc});const n=3,r=5e3,o=3e3;let s=[];for(let c=1;c<=n;c++){const l=1===c?r:o;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:Zc});if(s=(await this.getUserLiquidityPositions(t,Zc)).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?Pa(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?Pa(e.token1).collection:e.token1.collection).toUpperCase(),r=[];for(const i of s){if(""===(i?.positionId??""))continue;const o=null!==i.token0&&void 0!==i.token0?i.token0.toUpperCase():void 0,s=null!==i.token1&&void 0!==i.token1?i.token1.toUpperCase():void 0;if(null==o||""===o||null==s||""===s){this.logger.debug("Skipping position with empty tokens",{positionId:i.positionId});continue}const a=ha(o,s,t,n),c=i.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:i.positionId,tokens:`${o}/${s}`,tokensMatch:a,fee:i.feeTier,feeMatches:c}),a&&c&&r.push(i)}if(r.length>0){a=r[r.length-1],i=a.positionId,this.logger.info("Found newly created position",{positionId:i,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:i,expectedTokens:`${e.token0}/${e.token1}`,expectedFee:e.fee,positionCount:s.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:Q(e)}),this.logger.debug("Error waiting for position indexing",{error:Q(e)})}this.logger.debug("Position discovery complete",{positionId:null!=i&&""!==i?i:"not found",found:null!=i&&""!==i}),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!=i&&""!==i)try{this.logger.debug("Fetching full position details",{positionId:i}),u=await this.getLiquidityPositionById(t,i),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:i,error:Q(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!=i&&""!==i&&{positionId:i},status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(r)}}}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",he,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let i;try{const r=await t;i={status:r.status,transactionId:null!==r.transactionId&&void 0!==r.transactionId&&""!==r.transactionId?r.transactionId:e,timestamp:null!==r.timestamp&&void 0!==r.timestamp&&0!==r.timestamp?r.timestamp:Date.now(),data:r.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:i.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:Q(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:i.transactionId,status:i.status,timestamp:new Date(i.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 se("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=lt(e.liquidity,Number.NaN);if(isNaN(t))throw new re(`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 re(`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(X(e)&&Q(e).includes("Cannot remove zero liquidity"))throw e;if(X(e)&&Q(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?Pa(e.token0):e.token0,n="string"==typeof e.token1?Pa(e.token1):e.token1;await this.ensureWebSocketConnected();const i=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:i});const r=this.webSocketService.waitForTransaction(i);return this.monitorBundlerTransaction(i,r,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",he,e)}}async collectPositionFees(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new se("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 Ne(e.positionId);if(null===t.token0||void 0===t.token0||""===t.token0||null===t.token1||void 0===t.token1||""===t.token1)throw new he("Position missing token information",null,"INVALID_DATA");const{gswapToken0:n,gswapToken1:i}=this.convertTokenPair(t.token0,t.token1);return this.collectPositionFees({token0:n,token1:i,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 ye("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?Pa(e.token0):e.token0,n="string"==typeof e.token1?Pa(e.token1):e.token1;await this.ensureWebSocketConnected();const i=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:i});const r=this.webSocketService.waitForTransaction(i);return this.monitorBundlerTransaction(i,r,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",he,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:i,gswapToken1:r}=this.convertTokenPair(e,t),o=Pa(i),s=Pa(r),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(es(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",ue,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const i=await this.getPoolData(e,t,n),r=es(i.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:r.toFixed(),invertedPrice:ss(r,!0),tick:i.tick,liquidity:i.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",ue,e)}}async calculateOptimalPositionSize(e,t,n,i,r,o,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:i,desiredAmount1:r});const a=(await this.getPoolData(e,t,n)).tick,c=E(o),l=E(a),u=E(s),d=I(es(i),es(r),c,l,u),h=C(d,l,c,u),g=h[0],f=h[1],p=es(i),m=es(r);return{amount0:g.toFixed(),amount1:f.toFixed(),liquidity:d.toFixed(),ratio:ws(g,f).toFixed(),utilizationPercent:{amount0:fs(ws(g,p),100).toFixed(2),amount1:fs(ws(f,m),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",he,e)}}async validatePositionParameters(e,t,n,i,r,o,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:i,tickUpper:r});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;i%u!==0&&a.push(`tickLower must be multiple of ${u}`),r%u!==0&&a.push(`tickUpper must be multiple of ${u}`),i>=r&&a.push(`tickLower (${i}) must be less than tickUpper (${r})`);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=es(o),g=es(s);if(h.isNaN()||g.isNaN())a.push("Amounts must be valid numbers");else try{ms(h,g)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const f=d.tick;(f<i||f>r)&&c.push("Position is out of current price range - will not earn fees until price moves into range");es(d.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const p=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:p,tickSpacing:u,currentTick:f,poolLiquidity:d.liquidity}}catch(e){const t=Q(e);return a.includes(t)||a.push(`Validation failed: ${t}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}async calculateTicksForPrice(e,t,n,i,r){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:i});const o=this.getTickSpacing(r),s=es(n),a=es(i);Me(n,i,"priceRange");const c=Math.floor(os(s)),l=Math.ceil(os(a)),u=ks(c,o),d=ks(l,o),h=Math.pow(1.0001,u),g=Math.pow(1.0001,d),f=es(h),p=es(g);return{tokenA:e,tokenB:t,feeTier:r,tickLower:u,tickUpper:d,tickSpacing:o,requestedMinPrice:n,requestedMaxPrice:i,actualMinPrice:f.toFixed(8),actualMaxPrice:p.toFixed(8),priceDeviation:{minPriceDeviation:fs(f.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:fs(p.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",he,e)}}async calculatePriceForTicks(e,t,n,i){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:i});const r=Math.pow(1.0001,n),o=Math.pow(1.0001,i);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=es(r),c=es(o),l={tokenA:e,tokenB:t,tickLower:n,tickUpper:i,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:i-n};return Nt(s)||(l.currentPrice=s),l}catch(e){this.handleGSwapError("Failed to calculate price for ticks",he,e)}}calculateExecutionPrice(e,t){try{const n=es(e);return ws(es(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 we("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const i=this.getTickSpacing(n);if(e%i!==0)throw new re(`Invalid tickLower: ${e} must be a multiple of ${i} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%i!==0)throw new re(`Invalid tickUpper: ${t} must be a multiple of ${i} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){try{const t=as();return ws(e,t).pow(2)}catch{return es(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return es(0)}}async getPoolSlot0(e,t,n){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:t,fee:n});const i="string"==typeof e?Pa(e):e,r="string"==typeof t?Pa(t):t,o=await this.gatewayClient.getSlot0({token0:i,token1:r,fee:n}),s={sqrtPrice:null!==o.sqrtPrice&&void 0!==o.sqrtPrice&&""!==o.sqrtPrice?o.sqrtPrice:"0",tick:null!==o.tick&&void 0!==o.tick&&0!==o.tick?o.tick:0,liquidity:null!==o.liquidity&&void 0!==o.liquidity&&""!==o.liquidity?o.liquidity:"0",grossPoolLiquidity:null!==o.grossPoolLiquidity&&void 0!==o.grossPoolLiquidity&&""!==o.grossPoolLiquidity?o.grossPoolLiquidity:"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(i){this.handleGSwapError("Failed to fetch pool slot0 data",ue,i,{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=es(t.sqrtPrice),i={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:i.price,tick:i.tick}),i}catch(t){this.handleGSwapError("Failed to fetch position current price",ue,t,{token0:e.token0,token1:e.token1})}}calculateLiquidityFromAmount0(e,t,n){try{const i=E(t),r=E(n);return N(e,i,r)}catch{return es(0)}}calculateLiquidityFromAmount1(e,t,n){try{const i=E(t),r=E(n);return x(e,i,r)}catch{return es(0)}}calculateAmount0FromLiquidity(e,t,n){try{const i=E(t),r=E(n);return _(i,r,e)}catch{return es(0)}}calculateAmount1FromLiquidity(e,t,n){try{const i=E(t),r=E(n);return B(i,r,e)}catch{return es(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 se("GSwapService: AddLiquidity requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new se("GSwapService: Bundler URL not configured","bundlerBaseUrl");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:t.token0?.type??"unknown",token1:t.token1?.type??"unknown",fee:t.fee,tickRange:`${t.tickLower}-${t.tickUpper}`});const n=`galaswap - operation - ${v()}-${Date.now()}-${t.owner}`,i={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:n},r=new e.Wallet(this.privateKey),o={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},s={name:"ethereum",chainId:1},a=this.calculatePersonalSignPrefix(i),c={...i,prefix:a},l=await r.signTypedData(s,o,c),u={...c,signature:l,types:o,domain:s};this.logger.debug("AddLiquidity DTO signed with manual types",{signature:u.signature?.substring(0,20)+"...",prefix:u.prefix,tickLower:i.tickLower,tickUpper:i.tickUpper});const d=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),h=Qc.createClient(this.bundlerBaseUrl,3e4),g=await h.post("/bundle",{method:"AddLiquidity",signedDto:u,stringsInstructions:d}),f=Xi(g),p=f?.data??f?.transactionId??f?.id;if(null==p)throw this.logger.error("Bundler response structure",{status:g.status,data:f,dataType:typeof f}),new ae(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(f)}`,void 0,"INVALID_RESPONSE");return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:p}),p}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(t,n,i,r,o,s,a,c,l){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new se("GSwapService: Bundler URL not configured","bundlerBaseUrl");const u=new e.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${v()}-${Date.now()}-${d}`,g={tickLower:t,tickUpper:n,amount:i,token0:r,token1:o,fee:s,amount0Min:a,amount1Min:c,positionId:l,uniqueKey:h},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"}]},p={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},w=await u.signTypedData(p,f,y),k={...y,signature:w,types:f,domain:p},b=this.buildLiquidityStringsInstructions(r,o,s,d);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:t,tickUpper:n,amount:i,fee:s,positionId:l,transactionId:h});const S=Qc.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:b}),T=Xi(A),E=T?.data??T?.transactionId??T?.id;if(null==E)throw this.logger.error("Bundler response structure",{status:A.status,data:T,dataType:typeof T}),new ae(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(T)}`,void 0,"INVALID_RESPONSE");return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(t,n,i,r,o,s,a,c){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new se("GSwapService: Bundler URL not configured","bundlerBaseUrl");const l=new e.Wallet(this.privateKey),u=await l.getAddress(),d=`galaswap - operation - ${v()}-${Date.now()}-${u}`,h={token0:t,token1:n,fee:i,amount0Requested:r,amount1Requested:o,tickLower:s,tickUpper:a,positionId:c,uniqueKey:d},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},p=this.calculatePersonalSignPrefix(h),m={...h,prefix:p},y=await l.signTypedData(f,g,m),w={...m,signature:y,types:g,domain:f},k=this.buildLiquidityStringsInstructions(t,n,i,u);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:i,amount0Requested:r,amount1Requested:o,tickLower:s,tickUpper:a,positionId:c,transactionId:d});const b=Qc.createClient(this.bundlerBaseUrl,3e4),S=await b.post("/bundle",{method:"CollectPositionFees",signedDto:w,stringsInstructions:k}),A=Xi(S),T=A?.data??A?.transactionId??A?.id;if(null==T)throw this.logger.error("Bundler response structure",{status:S.status,data:A,dataType:typeof A}),new ae(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(A)}`,void 0,"INVALID_RESPONSE");return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:T}),T}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(t){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new se("GSwapService: Swap requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new se("GSwapService: Bundler URL not configured","bundlerBaseUrl");const n=[500,3e3,1e4];if(!n.includes(t.feeTier))throw new re(`GSwapService: Invalid fee tier ${t.feeTier}. Must be one of: ${n.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let n=t.fromToken,i=t.toToken;"string"==typeof n&&(n=Pa(n)),"string"==typeof i&&(i=Pa(i));const r=Na(n),o=Na(i),s=r<o?[n,i,r,o]:[i,n,o,r],[a,c,l,u]=s,d=Na("string"==typeof t.fromToken?Pa(t.fromToken):t.fromToken),h=d===l,g=`galaswap - operation - ${v()}-${Date.now()}-${t.walletAddress}`;let f;if(void 0===t.currentSqrtPrice||null===t.currentSqrtPrice||""===t.currentSqrtPrice)throw new re("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",ie.REQUIRED);const p=es(t.currentSqrtPrice),m=t.slippageTolerance??.01;if(h){const e=is(m);f=p.multipliedBy(e).toString()}else{const e=rs(m);f=p.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:t.currentSqrtPrice,slippageTolerance:100*m+"%",zeroForOne:h,sqrtPriceLimit:f,direction:h?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const y={token0:a,token1:c,fee:t.feeTier,amount:es(t.inputAmount).toFixed(),zeroForOne:h,sqrtPriceLimit:f,recipient:t.walletAddress,amountOutMinimum:es(t.minOutput).multipliedBy(-1).toFixed(),uniqueKey:g};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:l,orderedToken1String:u,fromTokenStr:d,zeroForOne:h?`TRUE (${l} → ${u})`:`FALSE (${u} → ${l})`,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:y.amount,zeroForOne:y.zeroForOne,sqrtPriceLimit:y.sqrtPriceLimit,amountOutMinimum:y.amountOutMinimum}});const w=new e.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"}]},b={name:"ethereum",chainId:1},S=this.calculatePersonalSignPrefix(y),A={...y,prefix:S},T=await w.signTypedData(b,k,A),E={...A,signature:T,types:k,domain:b};this.logger.debug("Swap DTO signed",{signature:E.signature?.substring(0,20)+"...",prefix:E.prefix,zeroForOne:y.zeroForOne});const I=this.buildLiquidityStringsInstructions(a,c,t.feeTier,t.walletAddress),C=Qc.createClient(this.bundlerBaseUrl,3e4),N=await C.post("/bundle",{method:"Swap",signedDto:E,stringsInstructions:I}),x=Xi(N),_=x?.data??x?.transactionId??x?.id;if(null==_)throw this.logger.error("Bundler response structure",{status:N.status,data:x,dataType:typeof x}),new ae(`Bundler response does not contain transaction ID. Response: ${JSON.stringify(x)}`,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,i){const r=_a(e),o=_a(t),s=`$pool${r}${o}$${n}`;return[s,`$userPosition${i}`,`$tokenBalance${r}${i}`,`$tokenBalance${o}${i}`,`$tokenBalance${r}${s}`,`$tokenBalance${o}${s}`]}createGSwapErrorHandler(e,t){return(n,i,r)=>{this.handleGSwapError(i,e,n,t)}}handleGSwapError(e,t,n,i){this.logger.error(e,n);const r=this.extractGSwapErrorCode(n),o=n,s=[`${e}: ${o?.message??Q(n)}`,n],a=t.name;throw i&&("GSwapSwapError"===a&&null!==i.transactionHash&&void 0!==i.transactionHash&&s.push(i.transactionHash),"GSwapPoolError"===a&&(null!==i.tokenA&&void 0!==i.tokenA&&s.push(i.tokenA),null!==i.tokenB&&void 0!==i.tokenB&&s.push(i.tokenB)),"GSwapAssetError"===a&&null!==i.walletAddress&&void 0!==i.walletAddress&&s.push(i.walletAddress)),null!=r&&""!==r&&s.push(r),new t(...s)}extractGSwapErrorCode(e){const t=Z(e);return void 0!==t?String(t):void 0}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}class el{}el.BASE_PRICE=1650667151e-14,el.PRICE_SCALING_FACTOR=1166069e-12,el.TRADING_FEE_FACTOR=.001,el.GAS_FEE="1",el.MIN_UNBONDING_FEE_FACTOR=0,el.MAX_UNBONDING_FEE_FACTOR=.5,el.NET_UNBONDING_FEE_FACTOR=.5,el.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7;class tl extends Qs{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 nl extends tl{constructor(e=!1){super(e)}normalizeKey(e){return qs(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>=nl.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??el.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,i)=>{n.lastUpdated<e&&(e=n.lastUpdated);let r=0;r+=2*i.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(r+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(r+=8),r+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(r+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(r+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(r+=2*n.symbol.length),r+=32,t+=r}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${qs(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${qs(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${qs(e)}`;return this.cache.has(t)}}nl.MAX_CACHE_SIZE=1e4;class il extends Xs{constructor(e,t,n=void 0,i=5,r=!1){super(e,r),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=i}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 i=e[n];t.push({poolIndex:n,token:i.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:i.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${i.token0}`,{error:Q(e)})})}),t.push({poolIndex:n,token:i.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:i.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${i.token1}`,{error:Q(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 i=t.slice(e,e+this.pricingConcurrency),r=await Promise.allSettled(i.map(e=>e.task));for(let e=0;e<i.length;e++){const t=i[e],o=r[e],s=n.get(t.poolIndex)??{};"fulfilled"===o.status&&null!=o.value&&(t.isToken0?s.token0Price=o.value:s.token1Price=o.value),n.set(t.poolIndex,s)}}const i=e.map((e,t)=>{const i=n.get(t)??{},r={...e};return void 0!==i.token0Price&&(r.token0Price=i.token0Price),void 0!==i.token1Price&&(r.token1Price=i.token1Price),r}),r=i.filter(e=>null!=e.token0Price&&null!=e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:r,failed:e.length-r}),i}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:i="desc",offset:r=0,limit:o=Cs.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:i,offset:r,limit:o,withPrices:s});const a=sa({offset:r,limit:o},20),c=new URLSearchParams({...a,sortBy:n,sortOrder:i});null!=t&&c.append("search",t);const l=`${this.dexBackendBaseUrl}/explore/pools?${c}`,u=await Fs(()=>this.http.get(l),{errorContext:"Failed to fetch DEX pools",logger:this.logger});let d=u.pools;const h=u.count,g=Math.min(o,20),f={offset:r,limit:g};return void 0!==h?(f.total=h,f.totalPages=Math.ceil(h/g)):f.total=0,s&&(d=await this.enrichPoolsWithPricing(d)),this.logger.debug("DEX pools fetched successfully",{poolCount:d.length,total:h,totalPages:f.totalPages,withPrices:s}),{items:d,meta:f}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=await Ls((t,n)=>{const i=t*n;return this.fetchDexPools({...e,offset:i,limit:n}).then(e=>({items:e.items,page:t,limit:e.meta.limit,total:e.meta.total,totalPages:e.meta.totalPages??1,hasNext:i+n<e.meta.total,hasPrevious:t>0}))},{maxPages:1e4,logger:this.logger,pageSize:20,startPage:0});return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.items.length,totalCount:t.total,withPrices:e.withPrices}),{items:t.items,meta:{offset:0,limit:t.items.length,total:t.total,totalPages:1}}}}const rl=5;class ol extends Xs{constructor(e,t,n=!1,i=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t,this.networkTimeout=i}validateFetchCompositePoolDataInput(e,t,n){if(!It(e))throw new ge("token0 must be a non-empty string",{token0:e});if(!It(t))throw new ge("token1 must be a non-empty string",{token1:t});try{Da(e),Da(t)}catch(n){throw new ge(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${Q(n)}`,{token0:e,token1:t})}try{Re(n,"fee")}catch{throw new ge(`fee must be a positive integer (got ${n})`,{fee:n})}const i=[500,3e3,1e4];if(!i.includes(n))throw new ge(`fee must be one of: ${i.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!It(e))throw new ge("amount must be a non-empty string",{amount:e});const t=es(e);try{ys(t,"amount")}catch(t){throw new ge(t.message,{amount:e})}}convertTokenClassKey(e){const t=new S;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:i,gatewayBaseUrl:r}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:i}),this.validateFetchCompositePoolDataInput(t,n,i);try{const e=Jc(t),o=Jc(n),s=this.convertTokenClassKey(e),a=this.convertTokenClassKey(o),c=new M(s,a,i),l=`${r??this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,u=await this.http.post(l,c);ee(u,`Pool not found: ${t}/${n} with fee ${i}`);const d=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 P(t.token0,t.token1,t.token0ClassKey,t.token1ClassKey,t.fee,es(t.sqrtPrice),t.protocolFees);n.bitmap=t.bitmap,n.grossPoolLiquidity=es(t.grossPoolLiquidity),n.liquidity=es(t.liquidity),n.feeGrowthGlobal0=es(t.feeGrowthGlobal0),n.feeGrowthGlobal1=es(t.feeGrowthGlobal1),n.protocolFeesToken0=es(t.protocolFeesToken0),n.protocolFeesToken1=es(t.protocolFeesToken1),n.tickSpacing=t.tickSpacing,n.maxLiquidityPerTick=es(t.maxLiquidityPerTick);const i={},r=e.tickDataMap;Object.keys(r).forEach(e=>{const t=r[e],n=t.initialised,o=t.liquidityNet,s=t.liquidityGross,a=t.feeGrowthOutside0,c=t.feeGrowthOutside1,l=new D(t.poolHash,t.tick);l.initialised=n,l.liquidityNet=es(o),l.liquidityGross=es(s),l.feeGrowthOutside0=es(a),l.feeGrowthOutside1=es(c),i[e]=l});const o=e.token0Balance,s=o.quantity,a={...o},c=new A(a);c.quantity=es(s);const l=e.token1Balance,u=l.quantity,d={...l},h=new A(d);return h.quantity=es(u),new R(n,i,c,h,e.token0Decimals,e.token1Decimals)}(u.Data),u.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:i,liquidity:d.pool.liquidity.toString()}),d}catch(e){if(e instanceof fe)throw e;const r=Q(e);if(r.includes("status indicates failure")||r.includes("Pool not found"))throw new fe(r);throw this.logger.error("Failed to fetch composite pool data",e),new ge(`Failed to fetch composite pool data: ${r}`,{token0:t,token1:n,fee:i})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:i,amount:r}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:i,amount:r}),this.validateQuoteAmount(r),null==t)throw new ge("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=Jc(n),s=Jc(i),a=this.convertTokenClassKey(o),c=this.convertTokenClassKey(s),[l,u]=n<i?[a,c]:[c,a],d=new L(l,u,t.pool.fee,es(r),e,t.compositePoolDto),h=await F(void 0,d);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new ge(`Local quote calculation failed: ${Q(e)}`,{fromToken:n,toToken:i,amount:r})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:i,amount:r}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:i,amount:r}),this.validateQuoteAmount(r),null==t)throw new ge("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=Jc(n),s=Jc(i),a=this.convertTokenClassKey(o),c=this.convertTokenClassKey(s),l=new L(a,c,t.pool.fee,es(r),e,void 0),u=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,d=await this.http.post(u,l);ee(d,"External quote failed");const h=d.Data,g=h.amount0,f=h.amount1;return this.logger.debug("External quote calculated",{amount0:g,amount1:f}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new ge(`External quote calculation failed: ${Q(e)}`,{fromToken:n,toToken:i,amount:r})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class sl{constructor(){this.eventLatencies=[],this.maxLatencySamples=1e4,this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics=new Map,this.memorySnapshots=[],this.maxMemorySnapshots=100,this.recordMemory()}recordEventLatency(e){this.eventLatencies.push(e),this.eventLatencies.length>this.maxLatencySamples&&this.eventLatencies.shift(),this.eventsProcessed++,this.lastEventTime=new Date}recordEventDropped(){this.eventsDropped++}updateQueueDepth(e){this.queueDepth=e,this.maxQueueDepth=Math.max(this.maxQueueDepth,e)}recordPoolCacheHit(e,t){const n=this.getPoolMetrics(e);n.cacheHits++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}recordPoolCacheMiss(e,t){const n=this.getPoolMetrics(e);n.cacheMisses++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}getLatencyPercentiles(){if(0===this.eventLatencies.length)return{p50:0,p95:0,p99:0};const e=[...this.eventLatencies].sort((e,t)=>e-t),t=ut(Math.floor(.5*e.length),0),n=ut(Math.floor(.95*e.length),0),i=ut(Math.floor(.99*e.length),0);return{p50:e[t]??0,p95:e[n]??0,p99:e[i]??0}}getCacheHitRate(){if(0===this.eventsProcessed)return 0;let e=0;for(const t of this.perPoolMetrics.values())e+=t.cacheHits;return ut(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=ut(Tt(this.startTime)/1e3,0);return 0===e?0:ut(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&"function"==typeof process.memoryUsage){const e=ut(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?ut(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?ut(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:ut(t.cacheHits/n*100,0)}getHealthMetrics(e,t,n,i,r){const o=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:o.p50,latencyP95:o.p95,latencyP99:o.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:ut(ts(s,1),0),maxMB:r,percentUsed:Math.min(100,ut(ts(s/r*100,1),0))},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:i}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.lastEventTime=void 0,this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?ut(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:ut(ts(e,0),0),memoryUsedMB:ut(ts(this.getMemoryUsedMB(),1),0),throughputPerSecond:ut(ts(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 al{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!It(e))return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),i=t[1]?.trim(),r=t[2]?.trim();if(""===n||""===i||""===r)return null;const o=dt(r,-1);return o<0?null:{token0:n,token1:i,feeTier:o}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const i=this.parsePoolKey(e);if(!i)return!1;const r=i.token0===t||i.token1===t,o=i.token0===n||i.token1===n;return r&&o&&t!==n}static normalizeFee(e){if(Nt(e))return null;const t="number"==typeof e?e:pt(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`${ts(es(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class cl{constructor(e){this.logger=e??new bt({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],i=new WeakSet,r=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(null!=e&&"string"!=typeof e&&"object"==typeof e){if(i.has(e))return;i.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))r(t,o+1)}};return r(e,0),n}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(null===t)return null;const n=e.Data,i=null==n||"object"!=typeof n||Array.isArray(n)?e:n,r=this.extractToken(i,"token0","fromToken","source"),o=this.extractToken(i,"token1","toToken","destination");if(null===r||null===o)return null;const s=this.extractAmount(i,"amount0","amountIn","inputAmount"),a=this.extractAmount(i,"amount1","amountOut","outputAmount");if(null===s||null===a)return null;const c=this.extractFeeTier(i);if(null===c)return null;const l=this.extractTimestamp(i),u=this.buildPoolKey(r,o,c),d=this.determineDirection(i,r,o),h={transactionId:t,poolKey:u,token0:r,token1:o,amount0:s,amount1:a,feeTier:c,direction:d,timestamp:l,exactInput:this.determineExactInput(i,d)},g=this.extractUser(i);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(It(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(It(t))return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(!Nt(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],i=this.normalizeFee(t);if(null!==i)return i}return null}normalizeFee(e){if(Nt(e))return null;const t="number"==typeof e?e:pt(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(It(t))return t}}determineDirection(e,t,n){const i=e.zeroForOne??e.direction;if("boolean"==typeof i)return i?"zeroForOne":"oneForZero";if("string"==typeof i){if(la(i,"zerotoone")||"0to1"===i)return"zeroForOne";if(la(i,"onetozero")||"1to0"===i)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const r=this.extractAmount(e,"amount0","amountIn");return null!==r&&lt(r,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,i=void 0!==e.amountOut&&null!==e.amountOut,r=void 0!==e.inputAmount&&null!==e.inputAmount,o=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||i)||!(i&&!n)&&(!(!r||o)||!(o&&!r))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class ll{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,es(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])}}}ll.CACHE=new Map,ll.ZERO=gt(0),ll.ONE=gt(1),ll.FEE_PIPS=gt(1e6),ll.MIN_SQRT_RATIO=gt("4295128739"),ll.MAX_SQRT_RATIO=new k("1461446703485210103287273052203988822378723970342");const ul={maxIterations:100,enableBigNumberCache:!0,roundingMode:k.ROUND_DOWN,debugLogging:!1};class dl{static calculateSwapDelta(e,t,n={}){const i=Date.now(),r={...ul,...n};try{const n=this.initializeSwapState(e,t,r);r.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const o=this.computeSwapLoop(n,e,t,r);r.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length,priceHitLimit:o.priceHitLimit});const s=this.createUpdatedPool(e.pool,o.state,t,r),a=this.calculateFinalAmounts(n,o.state,t);let c;if(void 0!==t.actualSqrtPrice&&""!==t.actualSqrtPrice){const e=es(s.sqrtPrice),n=es(t.actualSqrtPrice),i=e.minus(n).abs();c=ut(ws(i,n).times(100).toNumber(),0)}const l=Tt(i);r.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length}),o.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:o.stepCount}),o.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length});return{updatedPool:s,updatedTicks:o.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:o.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:o.stepCount,priceHitLimit:o.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${Q(e)}`)}}static initializeSwapState(e,t,n){const{pool:i}=e;if(null===i.sqrtPrice||void 0===i.sqrtPrice||null===i.liquidity||void 0===i.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const r=n.enableBigNumberCache?ll.getCached.bind(ll):e=>gt(e),o="string"==typeof i.sqrtPrice?i.sqrtPrice:ts(i.sqrtPrice,0),s="string"==typeof i.liquidity?i.liquidity:ts(i.liquidity,0),a=r(o),c=r(s),l=i.tick??0,u=U(es(o)),d=Math.abs(u-l);d>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:l,calculatedTick:u,drift:d,threshold:100});const h=r(t.amountSpecified);ys(h,"amountSpecified");const g="string"==typeof i.feeGrowthGlobal1?i.feeGrowthGlobal1:ts(i.feeGrowthGlobal1,0),f="string"==typeof i.feeGrowthGlobal0?i.feeGrowthGlobal0:ts(i.feeGrowthGlobal0,0),p=t.zeroForOne?r(g):r(f);return{sqrtPrice:a,liquidity:c,tick:l,amountSpecifiedRemaining:h,amountCalculated:ll.ZERO,feeGrowthGlobalX:p,protocolFee:ll.ZERO}}static computeSwapLoop(e,t,n,i){const{pool:r,tickDataMap:o}=t,s=[],a={};let c=0;const l=n.zeroForOne?ll.MIN_SQRT_RATIO:ll.MAX_SQRT_RATIO,u=es("0.000001");for(;e.amountSpecifiedRemaining.gt(u)&&!e.sqrtPrice.eq(l)&&c<i.maxIterations;){c++;const[t,u]=this.findNextInitializedTick(o,e.tick,r.tickSpacing,n.zeroForOne);let d;if(i.debugLogging&&this.logger.debug(`Swap step ${c}`,{currentTick:e.tick,tickNext:t,initialized:u,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),u&&t>=-887272&&t<=887272){const e=E(t);d=e instanceof k?e:es(String(e))}else d=l;const h=n.zeroForOne?ls(d,l):cs(d,l),g=this.executeSwapStep(e.sqrtPrice,h,e.liquidity,e.amountSpecifiedRemaining,r.fee,n.exactInput);if(e.sqrtPrice=g.sqrtPriceNext,n.exactInput){const t=g.amountIn.plus(g.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=ll.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=ll.ZERO)),e.amountCalculated=e.amountCalculated.minus(g.amountOut)}else{g.amountOut.lte(0)?e.amountSpecifiedRemaining=ll.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(g.amountOut),e.amountCalculated=e.amountCalculated.plus(g.amountIn.plus(g.feeAmount))}if(e.liquidity.gt(0)){const t=ws(g.feeAmount,e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(d)&&u){const r=o[t.toString()];if(null==r)throw new Error(`Missing tick data for initialized tick ${t}`);const c=n.zeroForOne?es(r.liquidityNet).negated():es(r.liquidityNet);if(e.liquidity=e.liquidity.plus(c),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);s.push(t),a[t.toString()]=r,i.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:c.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(d))e.tick=n.zeroForOne?t-1:t;else{const t=U(es(e.sqrtPrice.toString()));e.tick=t}}if(c>=i.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${i.maxIterations}). Possible infinite loop or very complex swap.`);const d=e.sqrtPrice.eq(l);return{state:e,ticksCrossed:s,priceHitLimit:d,stepCount:c,updatedTicks:a}}static createUpdatedPool(e,t,n,i){const r=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(r.sqrtPrice=es(t.sqrtPrice).toFixed(0),r.liquidity=es(t.liquidity).toFixed(0),r.tick=t.tick,n.zeroForOne?r.feeGrowthGlobal1=es(t.feeGrowthGlobalX).toFixed(0):r.feeGrowthGlobal0=es(t.feeGrowthGlobalX).toFixed(0),n.zeroForOne){const n=es(e.protocolFeesToken0);r.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=es(e.protocolFeesToken1);r.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return r}static calculateFinalAmounts(e,t,n){let i,r,o,s;if(n.exactInput){const e=es(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(i=e.negated(),r=a,o=ll.ZERO,s=ll.ZERO):(i=a,r=e.negated(),o=ll.ZERO,s=ll.ZERO)}else{const e=es(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(i=a.negated(),r=e,o=ll.ZERO,s=ll.ZERO):(i=e,r=a.negated(),o=ll.ZERO,s=ll.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:o=a,{amount0:i,amount1:r,feeAmount0:o,feeAmount1:s}}static findNextInitializedTick(e,t,n,i){const r=Object.keys(e).map(e=>ht(e,0)).sort((e,t)=>e-t);if(0===r.length){return[i?-887272:887272,!1]}if(i){const e=r.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=r.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,i,r,o){ms(n),ys(i,"amountRemaining");const s=[500,3e3,1e4];if(!s.includes(r))throw new Error(`Invalid fee tier: ${r}. Must be one of: ${s.join(", ")}`);const a=O(e,t,n,i,r,t.lt(e)),c=a[0],l=a[1],u=a[2],d=a[3],h=k.isBigNumber(c)?c:es(String(c)),g=k.isBigNumber(l)?l:es(String(l)),f=k.isBigNumber(u)?u:es(String(u)),p=k.isBigNumber(d)?d:es(String(d));return{sqrtPriceStart:e,tickNext:U(h),sqrtPriceNext:h,initialised:!1,amountIn:g,amountOut:f,feeAmount:p}}}dl.logger=new bt({debug:!1,context:"SwapDeltaCalculator"});class hl extends Qs{constructor(e,t,n,i){super(!1,i),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(),i={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,i),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,i,r){const o=this.cache.get(e);if(!o)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(r){const s="zeroForOne"===t,a=s?n:i,c={transactionId:r.transactionId,timestamp:r.timestamp,amountSpecified:a,zeroForOne:s,exactInput:r.exactInput},l=dl.calculateSwapDelta(o.poolData,c);o.poolData={...o.poolData,pool:l.updatedPool},o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(o.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${o.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.ticksCrossed.length} ticks crossed`)}else o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(o)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${o.swapsSinceRefetch}, drift=${(100*o.cumulativeDrift).toFixed(2)}%`),o.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),o.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(""===e)throw ye("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await Ji(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(null==e||0===e.length)throw ye("poolKeys","Pool keys array");return Ji(async()=>{const n={succeeded:0,failed:0,total:e.length};let i=0;const r=new Set;for(;i<e.length||r.size>0;){for(;i<e.length&&r.size<t;){const t=e[i];i++;const o=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});r.add(o),o.finally(()=>r.delete(o))}r.size>0&&await Promise.race(r)}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,i]of this.cache)e>i.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 gl extends Qs{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(Tt(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 i=e[n];this.eventsProcessedCount++,"rejected"===i.status&&this.logger.error(`Failed to process event ${t[n].transactionId}:`,i.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=Tt(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class fl extends Qs{constructor(e,t,n,i={},r){super(!1,r),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 sl,this.config=this.applyDefaults(i),this.eventExtractor=new cl(this.logger),this.quoteService=n,this.cacheManager=new hl(t,this.config,this.metrics,this.logger),this.eventQueue=new gl(this.config,this.metrics,this.logger),this.seenTransactions=new pl(this.maxSeenTransactions),this.reconnectionManager=new qc({maxAttempts:3,baseDelayMs:1e3,useExponentialBackoff:!0,maxDelayMs:3e4}),this.eventQueue.setProcessor(e=>this.processSwapEvent(e)),this.logger.debug("Initialized MultiPoolStateManager")}subscribe(e,t){this.listeners.push(t),e.onError&&this.onErrorCallbacks.push(e.onError),this.isActive||(this.setupWebSocketListener(e),this.isActive=!0);const n=this;return()=>{n.listeners=n.listeners.filter(e=>e!==t),e.onError&&(n.onErrorCallbacks=n.onErrorCallbacks.filter(t=>t!==e.onError)),0===n.listeners.length&&0===n.onErrorCallbacks.length&&n.unsubscribe().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()),i=this.determineHealthStatus(t,e),r={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectionManager.getAttempts()};this.socket?.connected&&(r.lastConnectionTime=new Date);const o=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(i,o,s,a,n.metrics.cacheHitRate);return{...n,status:i,websocket:r,recommendations:c,detailedMetrics:{eventQueueUtilization:o,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,i,r){const o=[];return"failed"===e&&(o.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||o.push("Reconnect WebSocket - connection lost"),t>90&&o.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(o.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&o.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),i>80&&o.push(`Memory usage ${i.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(r<50&&o.push(`Cache hit rate ${r.toFixed(1)}% is low - consider warming more pools`),i>50&&o.push("Memory usage is moderate - monitor for growth trends"),t>50&&o.push("Queue utilization is elevated - monitor for bottlenecks")),o}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){this.warmingIntervalHandle&&(clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.unsubscribe(),await this.eventQueue.shutdown(),this.cacheManager.clear(),this.metrics.reset()}setupConnectionMonitoring(){this.socket&&(this.socket.on("disconnect",()=>{this.logger.warn("WebSocket disconnected"),this.notifyError(new Error("WebSocket disconnected")),this.config.autoRecover&&this.attemptReconnection().catch(e=>{this.logger.error("Reconnection failed:",e)})}),this.socket.on("connect_error",e=>{this.logger.error("WebSocket connection error:",e),this.notifyError(X(e)?e:new Error(Q(e)))}))}async attemptReconnection(){const e=this.reconnectionManager.getAttempts(),t=this.reconnectionManager.getMaxAttempts();if(this.logger.debug(`Reconnection attempt ${e+1}/${t}`),this.reconnectionManager.isExhausted())return this.logger.error(`Max reconnection attempts (${t}) exceeded - performing full reset`),void await this.performFullReset();if(e<2)if(0===e)this.logger.debug("Tier 1: Quick reconnect");else{const e=this.reconnectionManager.getNextDelay();this.logger.debug(`Tier 2: Exponential backoff (${e}ms)`),await new Promise(t=>setTimeout(t,e))}try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectionManager.recordAttempt()}catch(e){throw this.logger.error("Failed to initiate reconnection:",e),e}}async performFullReset(){this.logger.warn("Performing full system reset due to connection failures"),this.stopBackgroundWarming();const e=this.getHealth();this.logger.debug("System state before reset:",{status:e.status,queueSize:e.eventProcessing.eventsProcessed,cachedPools:e.pools.totalMonitored,memory:`${e.memory.usedMB}MB / ${e.memory.maxMB}MB`,cacheHitRate:`${e.metrics.cacheHitRate.toFixed(2)}%`}),this.cacheManager.clear(),this.metrics.reset(),this.reconnectionManager.reset(),this.notifyError(new Error("System reset: connection lost and recovery failed - please restart monitoring")),this.logger.info("System reset complete - ready for restart")}setupWebSocketListener(e){if(this.listenerRegistered)return void this.logger.debug("WebSocket listener already registered");const t=this;this.handleSwapEvent=(n,...i)=>{try{const n=Date.now(),r=i[0],o=t.eventExtractor.walkPayloadForSwaps(r,t.seenTransactions);if(0===o.length)return;t.logger.debug(`Extracted ${o.length} swaps from payload`);for(const n of o){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=Tt(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(X(e)?e:new Error(Q(e)))}},this.socket?(this.socket.onAny(this.handleSwapEvent),this.listenerRegistered=!0,this.setupConnectionMonitoring()):this.logger.warn("Socket not available for listener registration"),this.startBackgroundWarming(),this.logger.debug("WebSocket listener registered for all events")}async unsubscribe(){this.stopBackgroundWarming(),this.handleSwapEvent&&this.listenerRegistered&&this.socket&&(this.socket.offAny(this.handleSwapEvent),this.listenerRegistered=!1),this.isActive=!1,this.listeners=[],this.onErrorCallbacks=[],this.logger.debug("Unsubscribed from swap events")}filterSwap(e,t){if(void 0!==t.tokenFilter&&""!==t.tokenFilter){if(!al.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,i]=t.pairTokens;if(!al.containsTokenPair(e.poolKey,n,i))return!1}if(void 0!==t.feeTierFilter&&""!==t.feeTierFilter){if(al.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 i=Tt(t);this.metrics.recordEventLatency(i);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(X(t)?t:new Error(Q(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 pl{constructor(e){this.map=new Map,this.maxSize=e}has(e){return this.map.has(e)}add(e){if(this.map.has(e))return this.map.delete(e),this.map.set(e,Date.now()),this;if(this.map.size>=this.maxSize){const e=this.map.keys().next().value;this.map.delete(e)}return this.map.set(e,Date.now()),this}delete(e){return this.map.delete(e)}clear(){this.map.clear()}get size(){return this.map.size}}class ml extends Qs{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return Ks(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,i=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const r=this.normalizeKey(this.extractSecondaryKey(e));i.set(r,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,i),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 i=this.secondaryIndex.get(e);i||(i=new Map,this.secondaryIndex.set(e,i));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const r=this.normalizeKey(this.extractSecondaryKey(e));i.set(r,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 i={},r={};for(const t of e)i[t]=0;for(const[e,o]of this.primaryIndex){t.push(e),n+=o.size,i[e]=o.size;const s=this.fetchTimestamps.get(e);void 0!==s&&(r[e]=s)}return{networks:t,totalItems:n,itemsByNetwork:i,fetchTimestamps:r}}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 yl=["ETHEREUM","SOLANA"];class wl extends ml{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(yl);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class kl{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new bt({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const i=Math.min(t,this.getMaxLimit()),r=this.buildApiParams(n),o=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...r,limit:i,offset:e}});if(Nt(o)||!Array.isArray(o.tokens))throw new re("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(o.tokens),rawCount:o.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:i,maxPages:r=1e4}=t,o=[];let s=0,a=!0,c=0;for(;a&&c<r;){i&&i.debug(`Auto-pagination (offset): fetching at offset ${s} with limit ${n}`);const t=await e(s,n);if(null==t||!Array.isArray(t.items)){i&&i.warn("Auto-pagination (offset): received invalid result structure, stopping");break}o.push(...t.items),a=t.rawCount===n,s+=n,c++,i&&i.debug(`Auto-pagination (offset): fetched ${o.length} items so far (hasMore=${a})`)}return c>=r&&i&&i.warn(`Auto-pagination (offset): exceeded maxPages limit of ${r}, stopping`),i&&i.debug(`Auto-pagination (offset): completed with total items: ${o.length}`),o}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Se(e,t,this.logger)}}class bl extends kl{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new wl(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),i=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),r={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:i};return void 0!==t?.contractAddress&&(r.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(r.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(r.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(r.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(r.solanaSymbol=n.symbol),void 0!==e.image&&(r.image=e.image),void 0!==e.description&&(r.description=e.description),r})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:i=this.getDefaultLimit()}=e,r=Math.min(i,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${r})`),Ji(async()=>{const e=(await this.executePaginatedRequest(n,r,{network:t})).items;return 0===n?this.cache.set(t,e):this.cache.merge(t,e),{tokens:e,network:t,fetchedAt:Date.now(),tokenCount:e.length}},`Failed to fetch bridgeable tokens for ${t}`,this.logger)}async fetchAllBridgeableTokensByNetwork(e){return Ji(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:i,logger:r,itemTypeName:o="items"}=e;if(n.has(t)){const e=n.getAll(t);return r&&r.debug(`Returning ${e.length} cached ${o} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${o} for ${t} (no cache)`);const s=await i();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,i=Wa(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const r=this.cache.getByTokenId(n,i),o=void 0!==r,s=o?"ETHEREUM"===n?r.ethereumContractAddress:r.solanaContractAddress:void 0,a={isBridgeable:o,tokenSymbol:r?.symbol??Da(i).collection,network:n};return void 0!==s&&(a.contractAddress=s),a}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"ETHEREUM"})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"SOLANA"})}async getTokenBySymbol(e,t){const n=this.cache.getBySymbol(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getBySymbol(t,e))}async getTokenByTokenId(e,t){const n=this.cache.getByTokenId(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getByTokenId(t,e))}async getContractAddress(e,t){const n=await this.getTokenBySymbol(e,t);if(n)return"ETHEREUM"===t?n.ethereumContractAddress:n.solanaContractAddress}async getSupportedTokenSymbols(e){return this.cache.has(e)||await this.fetchAllBridgeableTokensByNetwork(e),this.cache.getAll(e).map(e=>e.symbol)}async preload(){this.logger.debug("Preloading bridgeable tokens for all networks"),await Promise.all([this.fetchAllBridgeableTokensByNetwork("ETHEREUM"),this.fetchAllBridgeableTokensByNetwork("SOLANA")]),this.logger.debug("Preloading complete")}getCacheStats(){return this.cache.getStats()}clearCache(e){this.cache.clear(e)}}class vl extends tl{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return Ks(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 Sl extends vl{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 Al extends kl{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new Sl(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),null!==e.currentPrices&&void 0!==e.currentPrices&&(t.currentPrices=e.currentPrices),t})}async fetchWrappableTokens(e={}){const{offset:t=0,limit:n=this.getDefaultLimit()}=e;return this.logger.debug(`Fetching wrappable tokens (offset=${t}, limit=${Math.min(n,this.getMaxLimit())})`),Ji(async()=>{const e=(await this.executePaginatedRequest(t,n)).items;try{0===t?this.cache.setAll(e):this.cache.merge(e)}catch(e){this.logger.error("Cache operation failed (non-fatal):",e)}return{tokens:e,fetchedAt:Date.now(),tokenCount:e.length}},"Failed to fetch wrappable tokens",this.logger)}async fetchAllWrappableTokens(){return Ji(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:i,itemTypeName:r="items"}=e;if(t.has()){const e=t.getAll();return i&&i.debug(`Returning ${e.length} cached ${r}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${r} (no cache)`);const o=await n();try{t.setAll(o)}catch(e){i&&i.error("Cache operation failed (non-fatal):",e)}return{items:o,fetchedAt:Date.now(),itemCount:o.length}}({cache:this.cache,fetchFn:()=>this.autoPaginateFetch(),logger:this.logger,itemTypeName:"wrappable tokens"});return{tokens:e.items,fetchedAt:e.fetchedAt,tokenCount:e.itemCount}},"Failed to fetch wrappable tokens",this.logger)}async getWrappableToken(e){const t=Wa(e),n=this.cache.getByTokenId(t);return n||(await Fc("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=Wa(e);await Fc("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),i=void 0!==n,r={isWrappable:i,tokenId:t};return i&&(r.wrapCounterpart=n.wrapCounterpart),r}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}function Tl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function El(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 i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}),n}var Il,Cl,Nl,xl,_l,Bl;function Pl(){return xl?Nl:(xl=1,Nl={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys})}var Dl=function(){if(Bl)return _l;Bl=1;const e=Cl?Il:(Cl=1,Il={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify}),t=Pl().isFunction,n=Pl().isBoolean,i=Pl().isObject,r=Pl().isArray,o=Pl().isRegex,s=Pl().assign,a=Pl().keys;return _l=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,f=l.compare&&(p=l.compare,function(e){return function(t,n){const i={key:t,value:e[t]},r={key:n,value:e[n]};return p(i,r)}});var p;d||g(c);const m=[];return function e(t,n,s,c){const l=u?"\n"+new Array(c+1).join(u):"",p=u?": ":":";if(s=function(e){return null==e?e:o(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=h.call(t,n,s))){if(!i(s)||null===s)return g(s);if(r(s)){const t=[];for(let n=0;n<s.length;n++){const i=e(s,n,s[n],c+1)||g(null);t.push(l+u+i)}return"["+t.join(",")+l+"]"}{if(d){if(-1!==m.indexOf(s))return g("[Circular]");m.push(s)}const t=a(s).sort(f&&f(s)),n=[];for(let i=0;i<t.length;i++){const r=t[i],o=e(s,r,s[r],c+1);if(!o)continue;const a=g(r)+p+o;n.push(l+u+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},_l}(),Rl=Tl(Dl);const Ml={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},Ll={ASSET:1,MUSIC:3};function Fl(e){return Object.values(Ll).includes(e)}const Ul=12,Ol=15e3,$l=27e5,ql={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Kl="https://ethereum.publicnode.com",Gl="https://api.mainnet-beta.solana.com",Wl="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Hl="0x6a1734E09f3099a3675645D214ce547080ea67e0",zl="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",jl="https://dex-api-platform-dex-prod-gala.gala.com",Vl=[{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}],Xl=[{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 Ql(e){return"PROD"===e?Vl:Xl}function Jl(e){return"PROD"===e?Wl:Hl}const Zl=Vl,Yl=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],eu={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"}},tu=["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)"],nu=["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"],iu={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 ru(e){const t=Gs(e),n=eu[t];if(void 0!==n)return n;if(!t.startsWith("G")){const e=eu[`G${t}`];if(void 0!==e)return e}}function ou(e){const t=Gs(e);return Zl.find(e=>Gs(e.symbol)===t||Gs(e.symbol)===`G${t}`)}function su(e){const t=Gs(e);return Yl.find(e=>Gs(e.symbol)===t||Gs(e.symbol)===`G${t}`)}function au(e){return Na(e)}const cu={name:"GalaConnect",chainId:1},lu=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],uu=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],du=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],hu=[{name:"name",type:"string"},{name:"symbol",type:"string"}],gu={GalaTransaction:lu,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:uu,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:du,externalQuoteToken:hu,tokenInstance:du},fu={GalaTransaction:lu,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:uu,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:hu,externalQuoteToken:hu,externalCrossRateToken:hu,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:du,tokenInstance:du};function pu(e){return e?fu:gu}const mu={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:du};class yu extends Qs{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 re(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new re(`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 re(`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 re(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new re(`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 re(`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(null==e)throw ye("tokenId","Token identifier");if(""===t||null==t)throw ye("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new re(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new re(`Cannot wrap ${n.symbol} - it's already on asset channel`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const i=this.determineChannelRouting(n,!0);return{fee:"0",feeToken:"GALA",authorizationType:i.authType,feeChannel:i.sourceChannel}}async estimateUnwrapFee(e,t){if(null==e)throw ye("tokenId","Token identifier");if(""===t||null==t)throw ye("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new re(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new re(`Cannot unwrap ${n.symbol} - it's not on asset channel`,"tokenId","NOT_ON_ASSET_CHANNEL");const i=this.determineChannelRouting(n,!1);return{fee:"0",feeToken:"GALA",authorizationType:i.authType,feeChannel:i.sourceChannel}}async getWrapStatus(e){if(""===e||null==e)throw ye("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:i,recipient:r,isWrap:o}=e;if(void 0===this.wallet||void 0===this.walletAddress||null===this.walletAddress)throw new re("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,o),c=`galaswap-operation-${q.randomUUID()}`,l=mu,u={quantity:i,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:a.destinationChannelId,recipient:r??s,wrap:!0,uniqueKey:c};return this.logger.debug?.(`[WrapService] ${o?"Wrap":"Unwrap"} message (pre-signing):`,JSON.stringify(u,null,2)),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:i,message:u,routing:a,isWrap:o,senderAddress:s,typedDataTypes:l})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:i,message:r,routing:o,isWrap:s,typedDataTypes:a}=e;try{const e=await this.wallet.signTypedData(cu,a,r),c=`Ethereum Signed Message:\n${Rl({domain:cu,message:r,primaryType:"GalaTransaction",types:a}).length}`,l={...r,signature:e,prefix:c,types:a,domain:cu};this.logger.debug?.(`[WrapService] ${s?"Wrap":"Unwrap"} request (signed):`,JSON.stringify(l,null,2));const u=await this.galaConnectClient.requestBridgeOut(l);if(this.logger.debug?.("[WrapService] Response:",JSON.stringify(u,null,2)),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(u)){const e=`Status=${u.Status}`,r=void 0!==u.Message&&null!==u.Message?`: ${u.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:i,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`GalaChain request failed (${e}${r})`}}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 r={bridgeFromChannel:o.sourceChannel,bridgeRequestId:e};this.logger.debug?.("[WrapService] Step 2 - BridgeTokenOut payload:",JSON.stringify(r,null,2));const a=await this.galaConnectClient.bridgeTokenOut(r);return this.logger.debug?.("[WrapService] BridgeTokenOut response:",JSON.stringify(a,null,2)),1!==a.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:i,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`BridgeTokenOut failed: ${JSON.stringify(a)}`}:{success:!0,transactionId:a.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:i,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:i,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`Unexpected response format from GalaChain: ${JSON.stringify(u)}`}}catch(e){const r=Q(e);return this.logger.error?.(`[WrapService] ${s?"Wrap":"Unwrap"} operation failed:`,r),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:i,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:r}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:Ll.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:Ll.MUSIC,authType:"automatic"}}requireWallet(){if(void 0===this.walletAddress||null===this.walletAddress||""===this.walletAddress)throw new re("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:Na(e)}}const wu="x-api-key";class ku extends Xs{constructor(e,t,n,i=!1){super(e,i),this.adminApiKey=t??void 0,this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!It(e))throw ye("tokenName","Token name");const n=qs(e);if(!t.PATTERN.test(n))throw we("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!It(e))throw ye(t,n)}(e,t,n)}validateOptionalString(e,t,n,i){!function(e,t,n,i){if(null!=e){if("string"!=typeof e)throw Ie(t,"string",typeof e,n);if(e.length>i)throw Ee(t,i,e.length,n)}}(e,t,n,i)}validateOptionalNumber(e,t,n,i,r,o,s){!function(e,t,n,i,r){if(null!=e){if("number"!=typeof e)throw Ie(t,"number",typeof e,n);if(e<i||e>r)throw Ae(t,i,r,e,n)}}(e,t,n,i,r)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!At(e))throw we(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){js(e,t,n)}validateStatusFilter(e,t,n="status"){Vs(e,t,n)}buildPaginationParams(e,t){return sa(e,t)}addOptionalFilterParams(e,t,n){return aa(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,i]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(i.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 se("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[wu]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new se("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()}extractData(e){return Vi(e,"Backend request failed",!0),Qi(e,"No data in backend response")}async toggleFeature(e,t,n){this.validateTokenName(e,n);const i=this.buildEndpoint(t,{tokenName:e}),r=await this.http.post(i,{},this.getAdminHeaders()),o=this.extractData(r);return{enabled:o.enabled,tokenName:o.tokenName??qs(e)}}}const bu={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},vu={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},Su={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},Au={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},Tu=_t(bu),Eu=_t(vu),Iu=_t(Au);function Cu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Tu(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function Nu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const xu={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},_u={OWNER:"OWNER",MODERATOR:"MODERATOR"};_t(xu),_t(_u);const Bu={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"},Pu={...xu,OVERSEER:"OVERSEER"},Du={OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"};function Ru(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 Mu=_t(Pu),Lu=_t(Du);function Fu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.hasAccess&&(null===t.role||Mu(t.role))&&Ru(t.permissions)&&(null===t.accessSource||Lu(t.accessSource))&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer}function Uu(e,t="tokenName"){Dt(e,t,Ke)}function Ou(e){if(Uu(e.tokenName),!It(e.language))throw ye("language");if(!It(t=e.language)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new re('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",ie.INVALID_FORMAT);var t}const $u={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class qu extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async getStreamInfo(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(An,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async startStream(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(vn,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(Sn,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,Tn,Ke)}async enableStream(e){return this.toggleFeature(e,En,Ke)}async resetStreamKey(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(In,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Uu(e.tokenName),xt(e.offset,e.limit,rt)}(e);const t=this.buildEndpoint(Cn,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,rt),i=await this.http.get(t,n),r=this.extractData(i),o=r.limit??e.limit??20,s=e.offset??0,a=Math.floor(s/o)+1;return{recordings:r.recordings,tokenName:qs(e.tokenName),page:r.page??a,limit:o,total:r.total,hasNext:r.recordings.length===o}}async getRecordingDownload(e,t){this.validateTokenName(e,Ke),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Nn,{tokenName:e,assetId:t}),i=await this.http.get(n,this.getJwtHeaders());return this.extractData(i)}async deleteRecording(e,t){this.validateTokenName(e,Ke),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(xn,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(_n,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Uu(e.tokenName),!It(e.platform))throw ye("platform");if(!Iu(e.platform))throw new re("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",ie.INVALID_VALUE);if(!It(e.rtmpUrl))throw ye("rtmpUrl");if(!it.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new re("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",ie.INVALID_FORMAT);if(!It(e.streamKey))throw ye("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new re("name must be a string","name",ie.INVALID_TYPE)}(e);const t=this.buildEndpoint(Bn,{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,Ke),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(Pn,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(Dn);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(Rn,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(Mn,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Uu(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||It(e.nextLiveStreamAt)))throw new re("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",ie.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new re("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",ie.INVALID_FORMAT)}}}(e),t=null===e.nextLiveStreamAt?null:e.nextLiveStreamAt instanceof Date?e.nextLiveStreamAt.toISOString():e.nextLiveStreamAt;const n=this.buildEndpoint(Ln,{tokenName:e.tokenName}),i=await this.http.post(n,{nextLiveStreamAt:t},this.getDualAuthHeaders());return this.extractData(i)}async clearNextLiveStream(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(Fn,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async setStreamLanguage(e){Ou(e);const t=this.buildEndpoint(Un,{tokenName:e.tokenName}),n=await this.http.put(t,{language:e.language},this.getDualAuthHeaders());return this.extractData(n)}async getStreamRole(e){!function(e){Uu(e.tokenName)}(e);const t=this.buildEndpoint(On,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():void 0,i=await this.http.get(t,n);return this.extractData(i)}async getAvailableRoles(){const e=await this.http.get($n);return this.extractData(e)}async getTokenAccess(e){!function(e){Uu(e.tokenName)}(e);const t=this.buildEndpoint(qn,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():void 0;this.jwtAuth||this.logger.debug("getTokenAccess called without JWT authentication - will return hasAccess: false",{tokenName:e.tokenName});const i=await this.http.get(t,n);return this.extractData(i)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}Ke.MIN_LENGTH,Ke.MAX_LENGTH,Ke.PATTERN;_t({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function Ku(e){return"global"===e||"token"===e}function Gu(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&&"number"==typeof t.poolId&&"string"==typeof t.createdAt}function Wu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Gu(t.message)}function Hu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function zu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt}function ju(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}function Vu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&ju(t.pinnedMessage)}function Xu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function Qu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||Ku(t.reason))}function Ju(e){return!!It(e)&&(e.length>=Je.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Je.CHAT_MESSAGE.MAX_LENGTH)}function Zu(e){return!!It(e)&&Ke.PATTERN.test(e)}function Yu(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime}function ed(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const td=_t({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function nd(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}function id(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(nd)}class rd extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async getMessages(e){if(null==e)throw ye("options","Fetch options");return function(e){if(!It(e.tokenName))throw ye("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw ye("tokenName","Token name");if(!Ke.PATTERN.test(t))throw we("tokenName",`match pattern ${Ke.PATTERN}`,"Token name");if(xt(e.offset,e.limit,Ve),void 0!==e.cursor&&!It(e.cursor))throw Ie("cursor","a non-empty string",typeof e.cursor);if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw we("sortOrder","'asc' or 'desc'")}(e),Ji(async()=>{const t=this.buildEndpoint(Kn,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Ve);void 0!==e.cursor&&""!==e.cursor&&(n.cursor=e.cursor),void 0!==e.sortOrder&&(n.sortOrder=e.sortOrder);const i=await this.http.get(t,n),r=this.extractData(i),o=Bs(e.limit),s=e.offset??0,a=r.page??Math.floor(s/o)+1,c={messages:r.messages,tokenName:qs(e.tokenName),page:a,limit:r.limit??o,total:r.total,hasNext:r.messages.length===o||void 0!==r.nextCursor&&""!==r.nextCursor,pinnedMessage:r.pinnedMessage??null};return void 0!==r.nextCursor&&""!==r.nextCursor&&(c.nextCursor=r.nextCursor),c},"Failed to fetch chat messages",this.logger)}async sendMessage(e){if(null==e)throw ye("options","Send message options");return function(e){if(!It(e.tokenName))throw ye("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw ye("tokenName","Token name");if(!Ke.PATTERN.test(t))throw we("tokenName",`match pattern ${Ke.PATTERN}`,"Token name");if(t.length>Ke.MAX_LENGTH)throw Ee("tokenName",Ke.MAX_LENGTH,t.length,"Token name");if(!It(e.content))throw ye("content","Message content");if(e.content.length<Je.CHAT_MESSAGE.MIN_LENGTH)throw Te("content",Je.CHAT_MESSAGE.MIN_LENGTH,e.content.length,"Message content");if(e.content.length>Je.CHAT_MESSAGE.MAX_LENGTH)throw Ee("content",Je.CHAT_MESSAGE.MAX_LENGTH,e.content.length,"Message content")}(e),Ji(async()=>{const t=this.buildEndpoint(Gn,{tokenName:e.tokenName}),n=await this.http.post(t,{content:e.content},this.getJwtHeaders());return{message:this.extractData(n),tokenName:qs(e.tokenName)}},"Failed to send chat message",this.logger)}async deleteMessage(e){if(null==e)throw ye("options","Delete message options");return function(e){if(!It(e.tokenName))throw ye("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw ye("tokenName","Token name");if(!Ke.PATTERN.test(t))throw we("tokenName",`match pattern ${Ke.PATTERN}`,"Token name");if(!It(e.messageId))throw ye("messageId","Message ID")}(e),Ji(async()=>{const t=this.buildEndpoint(Wn,{tokenName:e.tokenName,messageId:e.messageId}),n=void 0!==this.adminApiKey&&null!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders(),i=await this.http.delete(t,n),r=this.extractData(i);return{messageId:r.messageId,deleted:r.deleted,tokenName:qs(e.tokenName)}},"Failed to delete chat message",this.logger)}async getChatStatus(e){if(null==e||""===e)throw ye("tokenName","Token name");return this.validateTokenName(e,Ke),Ji(async()=>{const t=this.buildEndpoint(Hn,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw ye("tokenName","Token name");return this.validateTokenName(e,Ke),Ji(async()=>{const t=this.buildEndpoint(zn,{tokenName:e}),n=await this.http.post(t,{},this.getDualAuthHeaders()),i=this.extractData(n),r={enabled:i.enabled,tokenName:i.tokenName??qs(e)};return void 0!==i.status&&null!==i.status&&(r.status=i.status),r},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw ye("tokenName","Token name");return this.validateTokenName(e,Ke),Ji(async()=>{const t=this.buildEndpoint(jn,{tokenName:e}),n=await this.http.post(t,{},this.getDualAuthHeaders()),i=this.extractData(n),r={enabled:i.enabled,tokenName:i.tokenName??qs(e)};return void 0!==i.status&&null!==i.status&&(r.status=i.status),r},`Failed to enable chat for token: ${e}`,this.logger)}async getGlobalChatStatus(){const e=await this.http.get(Jn);return this.extractData(e)}async disableGlobalChat(){const e=await this.http.post(Zn,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalChat(){const e=await this.http.post(Yn,{},this.getAdminHeaders());return this.extractData(e)}async getPinnedMessage(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(Vn,{tokenName:e}),n=await this.http.get(t),i=this.extractData(n);return{tokenName:i.tokenName??qs(e),pinnedMessage:i.pinnedMessage}}async pinMessage(e){!function(e){if(!It(e.tokenName))throw ye("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw ye("tokenName","Token name");if(!Ke.PATTERN.test(t))throw we("tokenName",`match pattern ${Ke.PATTERN}`,"Token name");if(!It(e.messageId))throw ye("messageId","Message ID")}(e);const t=this.buildEndpoint(Xn,{tokenName:e.tokenName}),n=await this.http.post(t,{messageId:e.messageId},this.getAdminHeaders()),i=this.extractData(n);return{tokenName:i.tokenName??qs(e.tokenName),pinnedMessage:i.pinnedMessage}}async unpinMessage(e){this.validateTokenName(e,Ke);const t=this.buildEndpoint(Qn,{tokenName:e}),n=await this.http.delete(t,this.getAdminHeaders()),i=this.extractData(n),r={tokenName:i.tokenName??qs(e),unpinned:i.unpinned};return void 0!==i.unpinnedMessageId&&""!==i.unpinnedMessageId&&null!==i.unpinnedMessageId&&(r.unpinnedMessageId=i.unpinnedMessageId),r}async getEngagementStats(e){if(null==e)throw ye("options","Engagement stats options");return function(e){if(!It(e.tokenName))throw ye("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw ye("tokenName","Token name");if(!Ke.PATTERN.test(t))throw we("tokenName",`match pattern ${Ke.PATTERN}`,"Token name")}(e),Ji(async()=>{const t=this.buildEndpoint(ei,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),i=this.extractData(n);return{tokenName:qs(e.tokenName),chat:i.chat,comments:i.comments}},"Failed to get engagement stats",this.logger)}}const od={SUBSCRIBE:"subscribe_token",UNSUBSCRIBE:"unsubscribe_token",AUTHENTICATE:"authenticate",SEND_CHAT:"send_stream_chat",SEND_REACTION:"send_stream_reaction",TYPING_START:"typing_start",TYPING_STOP:"typing_stop",STREAM_STATUS:"stream_status",STREAM_SUBSCRIBED:"token_subscribed",STREAM_UNSUBSCRIBED:"token_unsubscribed",VIEWER_COUNT:"viewer_count",STREAM_GLOBAL_STATUS:"stream_global_status",CHAT_MESSAGE:"stream_chat_message",CHAT_SENT:"stream_chat_sent",CHAT_ERROR:"stream_chat_error",CHAT_STATUS:"stream_chat_status",CHAT_GLOBAL_STATUS:"stream_chat_global_status",CHAT_AUTHENTICATED:"stream_chat_authenticated",CHAT_AUTH_ERROR:"stream_chat_auth_error",REACTION:"stream_reaction",REACTION_ERROR:"stream_reaction_error",USER_TYPING:"user_typing",CHAT_PINNED:"stream_chat_pinned",CHAT_UNPINNED:"stream_chat_unpinned",COUNTDOWN_UPDATED:"stream_countdown_updated",LANGUAGE_UPDATED:"stream_language_updated"};class sd extends Qs{constructor(e,t=!1){if(super(t),this.socket=null,this.isAuthenticated=!1,this.subscribedRooms=new Map,this.roomCallbacks=new Map,this.pendingSubscriptions=new Map,this.eventBuffer=new Map,this.eventBufferTimeouts=new Map,this.MAX_BUFFER_SIZE=100,this.BUFFER_CLEANUP_MS=3e4,this.globalCallbacks={},""===e.url||null==e.url)throw new se("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 qc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof T||(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:",Q(e)),!1}}getRoomName(e){return`token:${qs(e)}`}bufferEvent(e,t,n){const i=`${e}:${t}`;let r=this.eventBuffer.get(i);r||(r=[],this.eventBuffer.set(i,r)),r.length>=this.MAX_BUFFER_SIZE&&(r.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${i} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),r.push(n);const o=this.eventBufferTimeouts.get(i);o&&clearTimeout(o);const s=setTimeout(()=>{this.eventBuffer.delete(i),this.eventBufferTimeouts.delete(i),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${i}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(i,s)}processBufferedEvents(e,t){const n=qs(e),i=[{key:`${od.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${od.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${od.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${od.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${od.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${od.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${od.COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${od.LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated}];for(const{key:e,callback:t}of i){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const i of n)try{t(i)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const i=this.eventBufferTimeouts.get(e);i&&(clearTimeout(i),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(od.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(od.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onStreamStatus&&t.onStreamStatus(e),this.globalCallbacks.onStreamStatus&&this.globalCallbacks.onStreamStatus(e)}),this.socket.on(od.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=qs(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const i=this.roomCallbacks.get(t);i?.onStreamSubscribed&&i.onStreamSubscribed(e)}),this.socket.on(od.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(qs(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(od.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(od.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onViewerCount&&t.onViewerCount(e),this.globalCallbacks.onViewerCount&&this.globalCallbacks.onViewerCount(e)}),this.socket.on(od.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(od.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.message.content.slice(0,50)}...`),this.bufferEvent(od.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(od.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(od.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(od.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(od.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(od.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(od.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(od.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(od.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(od.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(od.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(qs(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(od.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(od.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(od.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(od.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(od.COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(od.COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(qs(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(od.LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(od.LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(qs(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}))}async resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(od.SUBSCRIBE,{tokenName:t})}catch(e){this.logger.error(`Failed to re-subscribe to ${t}:`,e)}}async connect(){return new Promise((e,t)=>{Ji(async()=>{if(!this.isSocketIOAvailable)throw new se('Socket.IO not available. Install "socket.io-client" package.');this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const n={};""!==this.config.authToken&&(n.token=this.config.authToken),this.socket=T(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${this.socket?.id}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")})},"Stream WebSocket connection setup",this.logger,e=>{throw t(e),e})})}authenticate(e){if(!this.socket?.connected)throw new re("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw ye("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(od.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw ye("tokenName","Token name");if(!this.socket?.connected)throw new re("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=qs(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((i,r)=>{const o=setTimeout(()=>{this.pendingSubscriptions.delete(n),r(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:i,reject:r,timeoutId:o}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(od.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=qs(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(od.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 ye("tokenName","Token name");if(""===t)throw ye("content","Message content");if(!this.socket?.connected)throw new re("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new re("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=qs(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(od.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw ye("tokenName","Token name");if(""===t)throw ye("emoji");if(!this.socket?.connected)throw new re("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new re("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const i=qs(e);this.logger.debug(`📡 Sending reaction to ${i}: ${t}`),this.socket.emit(od.SEND_REACTION,{tokenName:i,emoji:t,streamTime:n})}sendTypingStart(e){if(""===e)throw ye("tokenName","Token name");if(!this.socket?.connected)throw new re("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new re("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=qs(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(od.TYPING_START,{tokenName:t})}sendTypingStop(e){if(""===e)throw ye("tokenName","Token name");if(!this.socket?.connected)throw new re("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new re("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=qs(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(od.TYPING_STOP,{tokenName:t})}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}getSocket(){return this.socket}disconnect(){if(this.socket){this.logger.debug("🔌 Disconnecting from Stream WebSocket");try{for(const[e,t]of this.pendingSubscriptions){try{clearTimeout(t.timeoutId),t.reject(new Error("WebSocket disconnected"))}catch(t){this.logger.error(`Error cleaning up pending subscription for ${e}:`,t)}this.pendingSubscriptions.delete(e)}}catch(e){this.logger.error("Error clearing pending subscriptions:",e)}try{this.subscribedRooms.clear(),this.roomCallbacks.clear()}catch(e){this.logger.error("Error clearing room tracking:",e)}try{for(const e of this.eventBufferTimeouts.values())clearTimeout(e);this.eventBuffer.clear(),this.eventBufferTimeouts.clear()}catch(e){this.logger.error("Error clearing event buffers:",e)}this.globalCallbacks={};try{this.socket.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}this.socket=null,this.isAuthenticated=!1,this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}}}class ad extends Qs{constructor(e=!1){super(e),this.socket=null,this.isConnected=!1,this.eventRegistry=this.createEmptyRegistry()}setSocket(e){this.socket=e,this.isConnected=!0,this.logger.debug("📡 [Events] Socket attached to StreamingEventService")}clearSocket(){this.socket=null,this.isConnected=!1,this.logger.debug("📡 [Events] Socket cleared from StreamingEventService")}createEmptyRegistry(){return{stream_status:new Set,user_banned:new Set,user_unbanned:new Set,ban_enforcement:new Set,content_flagged:new Set,flag_resolved:new Set,stream_chat_message:new Set,stream_chat_updated:new Set,stream_chat_deleted:new Set,stream_chat_pinned:new Set,stream_chat_unpinned:new Set,chat_status_changed:new Set,viewer_count:new Set,recording_status:new Set,simulcast_status:new Set,download_ready:new Set,user_typing:new Set,stream_reaction:new Set,content_reaction_added:new Set,content_reaction_removed:new Set,stream_countdown_updated:new Set,stream_language_updated:new Set,stream_control_status_changed:new Set,connection:new Set,authenticated:new Set,token_subscribed:new Set,token_unsubscribed:new Set,room_subscribed:new Set,room_left:new Set}}registerCallback(e,t){const n=this.eventRegistry[e];return n.add(t),()=>{n.delete(t)}}async emitEvent(e,t){const n=this.eventRegistry[e];if(0!==n.size)for(const i of n)try{const e=i(t);e instanceof Promise&&await e}catch(t){this.logger.error(`Error in ${e} callback:`,t instanceof Error?t.message:String(t))}}onStreamStatusChanged(e){return this.registerCallback("stream_status",e)}onUserBanned(e){return this.registerCallback("user_banned",e)}onUserUnbanned(e){return this.registerCallback("user_unbanned",e)}onBanEnforcement(e){return this.registerCallback("ban_enforcement",e)}onContentFlagged(e){return this.registerCallback("content_flagged",e)}onFlagResolved(e){return this.registerCallback("flag_resolved",e)}onStreamChatMessage(e){return this.registerCallback("stream_chat_message",e)}onStreamChatUpdated(e){return this.registerCallback("stream_chat_updated",e)}onStreamChatDeleted(e){return this.registerCallback("stream_chat_deleted",e)}onStreamChatPinned(e){return this.registerCallback("stream_chat_pinned",e)}onStreamChatUnpinned(e){return this.registerCallback("stream_chat_unpinned",e)}onChatStatusChanged(e){return this.registerCallback("chat_status_changed",e)}onViewerCountChanged(e){return this.registerCallback("viewer_count",e)}onRecordingStatusChanged(e){return this.registerCallback("recording_status",e)}onSimulcastStatusChanged(e){return this.registerCallback("simulcast_status",e)}onDownloadReady(e){return this.registerCallback("download_ready",e)}onUserTyping(e){return this.registerCallback("user_typing",e)}onStreamReaction(e){return this.registerCallback("stream_reaction",e)}onContentReactionAdded(e){return this.registerCallback("content_reaction_added",e)}onContentReactionRemoved(e){return this.registerCallback("content_reaction_removed",e)}onStreamCountdownUpdated(e){return this.registerCallback("stream_countdown_updated",e)}onStreamLanguageUpdated(e){return this.registerCallback("stream_language_updated",e)}onStreamControlStatusChanged(e){return this.registerCallback("stream_control_status_changed",e)}onConnection(e){return this.registerCallback("connection",e)}onAuthenticated(e){return this.registerCallback("authenticated",e)}onTokenSubscribed(e){return this.registerCallback("token_subscribed",e)}onTokenUnsubscribed(e){return this.registerCallback("token_unsubscribed",e)}onRoomSubscribed(e){return this.registerCallback("room_subscribed",e)}onRoomLeft(e){return this.registerCallback("room_left",e)}async emitStreamStatusChanged(e){await this.emitEvent("stream_status",e)}async emitUserBanned(e){await this.emitEvent("user_banned",e)}async emitUserUnbanned(e){await this.emitEvent("user_unbanned",e)}async emitBanEnforcement(e){await this.emitEvent("ban_enforcement",e)}async emitContentFlagged(e){await this.emitEvent("content_flagged",e)}async emitFlagResolved(e){await this.emitEvent("flag_resolved",e)}async emitStreamChatMessage(e){await this.emitEvent("stream_chat_message",e)}async emitStreamChatUpdated(e){await this.emitEvent("stream_chat_updated",e)}async emitStreamChatDeleted(e){await this.emitEvent("stream_chat_deleted",e)}async emitStreamChatPinned(e){await this.emitEvent("stream_chat_pinned",e)}async emitStreamChatUnpinned(e){await this.emitEvent("stream_chat_unpinned",e)}async emitChatStatusChanged(e){await this.emitEvent("chat_status_changed",e)}async emitViewerCountChanged(e){await this.emitEvent("viewer_count",e)}async emitRecordingStatusChanged(e){await this.emitEvent("recording_status",e)}async emitSimulcastStatusChanged(e){await this.emitEvent("simulcast_status",e)}async emitDownloadReady(e){await this.emitEvent("download_ready",e)}async emitUserTyping(e){await this.emitEvent("user_typing",e)}async emitStreamReaction(e){await this.emitEvent("stream_reaction",e)}async emitContentReactionAdded(e){await this.emitEvent("content_reaction_added",e)}async emitContentReactionRemoved(e){await this.emitEvent("content_reaction_removed",e)}async emitStreamCountdownUpdated(e){await this.emitEvent("stream_countdown_updated",e)}async emitStreamLanguageUpdated(e){await this.emitEvent("stream_language_updated",e)}async emitStreamControlStatusChanged(e){await this.emitEvent("stream_control_status_changed",e)}async emitConnection(e){await this.emitEvent("connection",e)}async emitAuthenticated(e){await this.emitEvent("authenticated",e)}async emitTokenSubscribed(e){await this.emitEvent("token_subscribed",e)}async emitTokenUnsubscribed(e){await this.emitEvent("token_unsubscribed",e)}async emitRoomSubscribed(e){await this.emitEvent("room_subscribed",e)}async emitRoomLeft(e){await this.emitEvent("room_left",e)}}const cd={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},ld={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},ud=_t(ld),dd=Ft([{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}]),hd=Ft([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),gd=Ft([{field:"userAddress",type:"string"}]),fd=Ft([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"chat"===e||"comment"===e||"reaction"===e}]);function pd(e){return null==e||""===e||"string"==typeof e&&(!$t(e)&&e.length<=Je.BAN_REASON.MAX_LENGTH)}function md(e){return!!Nt(e)||"number"==typeof e&&(e>=Ye&&e<=et)}class yd extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async createBan(e){!function(e){if(Dt(e.tokenName,"tokenName",Ke),!It(e.userAddress))throw ye("userAddress");if(!pd(e.reason))throw new re(`reason must be at most ${Je.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!md(e.durationSeconds))throw new re(`durationSeconds must be between ${Ye} and ${et} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(ri,{tokenName:e.tokenName}),n={userAddress:e.userAddress};void 0!==e.reason&&(n.reason=e.reason),void 0!==e.durationSeconds&&(n.durationSeconds=e.durationSeconds);const i=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(i),tokenName:qs(e.tokenName)}}async removeBan(e){!function(e){if(Dt(e.tokenName,"tokenName",Ke),!It(e.userAddress))throw ye("userAddress")}(e);const t=this.buildEndpoint(ai,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,this.getDualAuthHeaders()),i=this.extractData(n);return{removed:i.removed,tokenName:qs(e.tokenName),userAddress:i.userAddress}}async listBans(e){!function(e){Dt(e.tokenName,"tokenName",Ke),xt(e.offset,e.limit,He)}(e);const t=this.buildEndpoint(oi,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,He);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const i=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(i);return{items:r.bans,meta:r.meta}}async getBanStatus(e){!function(e){if(Dt(e.tokenName,"tokenName",Ke),!It(e.userAddress))throw ye("userAddress")}(e);const t=this.buildEndpoint(si,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),i=this.extractData(n);return{banned:null!==i,...null!==i&&{ban:i},tokenName:qs(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Dt(e.tokenName,"tokenName",Ke),void 0!==e.type&&!ud(e.type))throw new re(`type must be one of: ${Object.values(ld).join(", ")}`,"type",ie.INVALID_VALUE)}(e);const t=this.buildEndpoint(ci,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const i=await this.http.get(t,n,this.getDualAuthHeaders());return this.extractData(i)}}function wd(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)}function kd(e){return null==e||""===e||"string"==typeof e&&(!$t(e)&&e.length<=Je.BAN_REASON.MAX_LENGTH)}function bd(e){if(Dt(e.tokenName,"tokenName",Ke),!kd(e.reason))throw new re(`reason must be at most ${Je.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function vd(e){Dt(e.tokenName,"tokenName",Ke)}function Sd(e){xt(e.offset,e.limit,He)}function Ad(e){Dt(e.tokenName,"tokenName",Ke)}class Td extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async banToken(e){bd(e);const t=xi,n={tokenName:qs(e.tokenName)};if(void 0!==e.reason)try{Le(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const i=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(i),tokenName:qs(e.tokenName)}}async unbanToken(e){vd(e);const t=this.buildEndpoint(Pi,{tokenName:e.tokenName}),n=await this.http.delete(t,this.getDualAuthHeaders());return{removed:this.extractData(n).removed,tokenName:qs(e.tokenName)}}async listTokenBans(e={}){Sd(e);const t=_i,n=this.buildPaginationParams(e,He);this.addOptionalFilterParams(n,e,["search"]);const i=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(i);return{items:r.bans,meta:r.meta}}async getTokenBan(e){Ad(e);const t=this.buildEndpoint(Bi,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),i=this.extractData(n);return{banned:null!==i,...null!==i&&{ban:i},tokenName:qs(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}const Ed={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Id=Bt(Ed),Cd={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"};function Nd(e){return Id.includes(e)}function xd(e){const t=[];void 0===e.role||null===e.role?t.push("Role is required"):Nd(e.role)||t.push(`Invalid role. Must be one of: ${Id.join(", ")}`);const n=t.length;if(ne(t,()=>{Ws(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ne(t,()=>{if(!Array.isArray(e.tokenNames))throw Ie("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Ie("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;ne(t,()=>{zs(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function _d(e){const t=[];["role","description","delegateAllTokens","tokenNames","expiresAt"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||Nd(e.role)||t.push(`Invalid role. Must be one of: ${Id.join(", ")}`);const n=t.length;if(ne(t,()=>{Ws(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;ne(t,()=>{if(!Array.isArray(e.tokenNames))throw Ie("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Ie("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;ne(t,()=>{zs(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function Bd(e){xt(e.offset,e.limit,He)}const Pd={[Ed.MODERATOR]:1,[Ed.TECHNICAL_PRODUCER]:1,[Ed.MANAGER]:2,[Ed.OWNER]:3};function Dd(e,t){return e===Ed.MANAGER?t!==Ed.OWNER:e===Ed.OWNER||e===t}class Rd extends Xs{constructor(e,t,n=!1){super(e,n,t)}extractData(e){const t={status:200,error:"error"in e?e.error:!e.success,data:e.data};return void 0!==e.message&&(t.message=e.message),Vi(t,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=xd(e);if(t.length>0)throw new re(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const i=await this.http.post(li.CREATE,n,this.getJwtHeaders()),r=this.extractData(i);return this.logger.debug("API key created",{id:r.id,keyPrefix:r.keyPrefix}),r}async findAll(e={}){Bd(e),this.logger.debug("Listing API keys",e);const t=void 0!==e.limit?Bs(e.limit,1,He):void 0,n={};void 0!==e.offset&&(n.offset=e.offset),void 0!==t&&(n.limit=t);const i={...sa(n,He)},r=await this.http.get(li.LIST,i,this.getJwtHeaders()),o=this.extractData(r);return this.logger.debug("Listed API keys",{count:o.apiKeys.length,total:o.meta.total}),o}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=li.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),i=this.extractData(n);return this.logger.debug("Got API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async update(e,t){this.validateApiKeyId(e);const n=_d(t);if(n.length>0)throw new re(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const i={};void 0!==t.role&&(i.role=t.role),void 0!==t.description&&(i.description=t.description),void 0!==t.delegateAllTokens&&(i.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(i.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(i.expiresAt=t.expiresAt);const r=li.UPDATE.replace(":id",String(e)),o=await this.http.patch(r,i,this.getJwtHeaders()),s=this.extractData(o);return this.logger.debug("Updated API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=li.REVOKE.replace(":id",String(e));await this.http.delete(t,this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Id]}}const Md={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},Ld=Bt(Md),Fd={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},Ud=Bt(Fd),Od={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},$d=Bt(Od);function qd(e){return Ld.includes(e)}function Kd(e){return $d.includes(e)}function Gd(e){return nt.PATTERN.test(e)}const Wd=Ft([{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"}]),Hd=Ft([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),zd=Ft([{field:"inviteScope",type:"string"},{field:"tokenName",type:"string",nullable:!0},{field:"tokenSymbol",type:"string",nullable:!0},{field:"role",type:"string"},{field:"status",type:"string"},{field:"invitedBy",type:"object"}]);function jd(e){return Ud.includes(e)}function Vd(e){const t=[],n=e.inviteScope??Fd.TOKEN;return void 0===e.inviteScope||jd(e.inviteScope)||ne(t,()=>{throw xe("inviteScope",e.inviteScope,Ud,"Invite scope")}),n===Fd.TOKEN?ne(t,()=>{Dt(e.tokenName??"","tokenName",Ke)}):n===Fd.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),qd(e.role)||ne(t,()=>{throw xe("role",e.role,Ld,"Role")}),void 0!==e.description&&""!==e.description&&ne(t,()=>{De(e.description,Je.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||At(e.expiresAt)||ne(t,()=>{throw function(e,t="a valid date",n){const i=pe(e,n);return new re(`${i} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function Xd(e){const t=[];return It(e)?Gd(e)||t.push("Invalid invite code format"):t.push(ye("inviteCode","Invite code").message),t}function Qd(e){const t=[];return ne(t,()=>{Dt(e.tokenName??"","tokenName",Ke)}),void 0===e.status||Kd(e.status)||ne(t,()=>{throw xe("status",e.status,$d,"Status")}),ne(t,()=>{xt(e.offset,e.limit,He)}),t}class Jd extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}validateRole(e){if(!It(e))throw ye("role","Role");if(!qd(e))throw we("role",`one of: ${Ld.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!It(e))throw ye("inviteCode","Invite code");if(!Gd(e))throw we("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!jd(e))throw new re(`Invalid invite scope. Must be one of: ${Ud.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Fd.TOKEN;if(t===Fd.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new re("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Ke)}else if(t===Fd.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName)throw new re("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",Je.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=ui,i={inviteScope:t,role:e.role};t===Fd.TOKEN&&void 0!==e.tokenName&&""!==e.tokenName&&(i.tokenName=qs(e.tokenName)),void 0!==e.description&&(i.description=e.description),void 0!==e.expiresAt&&(i.expiresAt=e.expiresAt);const r=await this.http.post(n,i,this.getJwtHeaders());return{invite:this.extractData(r)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Ke),this.validateStatusFilter(e.status,Od);const t=gi,n={...this.buildPaginationParams(e,je.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=qs(e.tokenName)),void 0!==e.status&&(n.status=e.status);const i=await this.http.get(t,n,this.getJwtHeaders()),r=this.extractData(i);return{items:r.invites,meta:r.meta}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(fi,{id:String(e)});Vi(await this.http.delete(t,this.getJwtHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(pi,{id:String(e.inviteId)}),n={role:e.role},i=await this.http.patch(t,n,this.getJwtHeaders());return{invite:this.extractData(i)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=di,n={inviteCode:e.inviteCode},i=await this.http.post(t,n,this.getJwtHeaders()),r=this.extractData(i);return"tokenName"in r&&void 0!==r.tokenName?{token:r}:{blanketAccess:r}}async getModeratedTokens(e){const t=hi,n=this.buildPaginationParams(e??{},je.MAX_LIMIT),i=await this.http.get(t,n,this.getJwtHeaders()),r=this.extractData(i);return{items:r.tokens,meta:r.meta}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(mi,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}var Zd,Yd,eh,th;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM"}(Zd||(Zd={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Yd||(Yd={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(eh||(eh={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(th||(th={}));const nh={[Yd.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[Yd.SPAM]:"Spam",[Yd.HARASSMENT]:"Harassment",[Yd.SCAM]:"Scam",[Yd.OTHER]:"Other"},ih={[eh.PENDING]:"Pending",[eh.DISMISSED]:"Dismissed",[eh.ACTIONED]:"Actioned"},rh={[th.DELETE_CONTENT]:"Delete Content",[th.BAN_USER]:"Ban User",[th.DELETE_AND_BAN]:"Delete & Ban"},oh={[Zd.CHAT_MESSAGE]:"Chat Message",[Zd.COMMENT]:"Comment",[Zd.STREAM]:"Stream"},sh=500,ah=_t(Zd),ch=_t(Yd),lh=_t(eh),uh=_t(th),dh=Ft([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:ah},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:lh}]),hh={TOKEN_NAME:Ge,CONTENT_ID:Je.CONTENT_ID,DETAILS:Je.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:He}};function gh(e,t="tokenName"){Dt(e,t,hh.TOKEN_NAME)}class fh extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async createFlag(e){!function(e){if(gh(e.tokenName),void 0===e.contentType)throw ye("contentType","Content type");if(!ah(e.contentType))throw we("contentType",`one of: ${Object.values(Zd).join(", ")}`,"Content type");if(!It(e.contentId))throw ye("contentId","Content ID");if(e.contentId.length>hh.CONTENT_ID.MAX_LENGTH)throw Ee("contentId",hh.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!It(e.reportedUserAddress))throw ye("reportedUserAddress","Reported user address");if(Qt(e.reportedUserAddress,"reportedUserAddress"),e.contentType===Zd.STREAM&&(void 0===e.reason||null===e.reason))throw ye("reason","Reason");if(void 0!==e.reason&&!ch(e.reason))throw we("reason",`one of: ${Object.values(Yd).join(", ")}`,"Reason");if(void 0!==e.details&&!It(e.details))throw Ie("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>hh.DETAILS.MAX_LENGTH)throw Ee("details",hh.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(yi.CREATE,t,this.getJwtHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){!function(e){if(gh(e.tokenName),void 0!==e.contentType&&!ah(e.contentType))throw we("contentType",`one of: ${Object.values(Zd).join(", ")}`,"Content type");if(void 0!==e.status&&!lh(e.status))throw we("status",`one of: ${Object.values(eh).join(", ")}`);if(void 0!==e.reason&&!ch(e.reason))throw we("reason",`one of: ${Object.values(Yd).join(", ")}`);if(void 0!==e.reporterAddress&&!It(e.reporterAddress))throw Ie("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Qt(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!It(e.reportedUserAddress))throw Ie("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Qt(e.reportedUserAddress,"reportedUserAddress"),xt(e.offset,e.limit,hh.PAGINATION.MAX_LIMIT)}(e);const t={};void 0!==e.offset&&(t.offset=e.offset),void 0!==e.limit&&(t.limit=e.limit);const n=sa(t,He);aa(n,e,["contentType","status","reason","reporterAddress","reportedUserAddress"]);const i=yi.LIST.replace(":tokenName",encodeURIComponent(e.tokenName)),r=await this.http.get(i,n,this.getDualAuthHeaders()),o=this.extractData(r);return{items:o.flags,meta:o.meta}}async listGlobalFlags(e={}){!function(e){if(void 0!==e.tokenName&&gh(e.tokenName),void 0!==e.contentType&&!ah(e.contentType))throw we("contentType",`one of: ${Object.values(Zd).join(", ")}`,"Content type");if(void 0!==e.status&&!lh(e.status))throw we("status",`one of: ${Object.values(eh).join(", ")}`);if(void 0!==e.reason&&!ch(e.reason))throw we("reason",`one of: ${Object.values(Yd).join(", ")}`);if(void 0!==e.reporterAddress&&!It(e.reporterAddress))throw Ie("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Qt(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!It(e.reportedUserAddress))throw Ie("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Qt(e.reportedUserAddress,"reportedUserAddress"),xt(e.offset,e.limit,hh.PAGINATION.MAX_LIMIT)}(e);const t={};void 0!==e.offset&&(t.offset=e.offset),void 0!==e.limit&&(t.limit=e.limit);const n=sa(t,He);aa(n,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const i=await this.http.get(yi.LIST_GLOBAL,n,this.getDualAuthHeaders()),r=this.extractData(i);return{items:r.flags,meta:r.meta}}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw ye("flagId","Flag ID");try{Re(e.flagId,"flagId")}catch{throw we("flagId","a positive integer","Flag ID")}}(e);const t=yi.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getDualAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw ye("flagId","Flag ID");try{Re(e.flagId,"flagId")}catch{throw we("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw ye("action","Action");if(!uh(e.action))throw we("action",`one of: ${Object.values(th).join(", ")}`,"Action")}(e);const t=yi.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getDualAuthHeaders());return{flag:this.extractData(n).flag}}}const ph={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},mh={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},yh=_t(ph),wh=_t(mh);function kh(e){if(e.status!==ph.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(St(e.expiresAt)<=new Date)return!1}return!0}function bh(e){try{Ws(e.description,"description",255)}catch(e){if(e instanceof re){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(!It(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{zs(e.expiresAt,"expiresAt")}catch(e){if(e instanceof re)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(At(e.expiresAt)){if(St(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function vh(e){if(void 0!==e.status&&!yh(e.status))throw xe("status",e.status,Object.values(ph),"status");xt(e.offset,e.limit,50)}function Sh(e){if(void 0!==e.status&&!wh(e.status))throw xe("status",e.status,Object.values(mh),"status");xt(e.offset,e.limit,50)}function Ah(e){if(!It(e))throw new Error("Invite code must be a non-empty string");De(e,100,"code")}function Th(e){if(!It(e))throw new Error("Address must be a non-empty string");try{Qt(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Eh(e){try{Hs(e,"id")}catch(e){if(e instanceof re)throw new Error("Invite ID must be a positive integer");throw e}}function Ih(e){if(null==e||"object"!=typeof e)throw new re("Options are required");if(void 0===e.offset&&void 0===e.limit||xt(e.offset,e.limit,100),void 0!==e.search){if("string"!=typeof e.search)throw new re("Search must be a string");if(0===e.search.length)throw new re("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new re("Sort field must be a string");if(0===e.sortBy.length)throw new re("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new re('Sort order must be "asc" or "desc"')}class Ch extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}validateInviteCodeFormat(e){if(!It(e))throw ye("inviteCode","Invite code");Ah(e)}validateWalletAddressFormat(e){if(!It(e))throw ye("address","Address");Th(e)}async createInvite(e={}){bh(e),this.validateOptionalString(e.description,"description","Description",Je.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=wi,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const i=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(i)}}async listInvites(e={}){vh(e),this.validateStatusFilter(e.status,ph);const t=ki,n={...this.buildPaginationParams(e,je.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const i=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(i);return{items:r.invites,meta:r.meta}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(bi,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Eh(e);const t=this.buildEndpoint(Si,{id:String(e)});Vi(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=vi,n={inviteCode:e},i=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(i)}}async listOverseers(e={}){Sh(e),this.validateStatusFilter(e.status,mh);const t=Ai,n={...this.buildPaginationParams(e,je.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const i=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(i);return{items:r.overseers,meta:r.meta}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ti,{address:e});Vi(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Ei,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Ii,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&Ih(t);const n=Ci,i={};void 0!==t.offset&&(i.offset=t.offset),void 0!==t.limit&&(i.limit=t.limit),void 0!==t.search&&""!==t.search&&(i.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(i.sortBy=t.sortBy),void 0!==t.sortOrder&&(i.sortOrder=t.sortOrder);const r=await this.http.get(n,i,this.getDualAuthHeaders()),o=this.extractData(r);return{items:o.items,meta:o.meta}}async getOverseerUserSummary(e){if(!It(e))throw ye("address","User address");Th(e);const t=this.buildEndpoint(Ni,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}}class Nh extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async fetchComments(e){!function(e){Dt(e.tokenName,"tokenName",Ge),xt(e.offset,e.limit,He)}(e);const t=qs(e.tokenName),n=void 0!==e.limit?Bs(e.limit,1,He):void 0,i={};void 0!==e.offset&&(i.offset=e.offset),void 0!==n&&(i.limit=n);const r={tokenName:t,...sa(i,He)},o=await this.http.get(Di,r),s=this.extractData(o);return{items:(s.comments??[]).map(e=>{const t={id:e.id,messageId:e.messageId,content:e.content,userAddress:e.userAddress,poolId:e.poolId,createdAt:e.createdAt};if(e.user){const n={fullName:e.user.fullName};void 0!==e.user.profileImage&&(n.profileImage=e.user.profileImage),t.user=n}return e.reactions&&(t.reactions=e.reactions),e.holderTier&&(t.holderTier=e.holderTier),t}),meta:s.meta}}async postComment(e){!function(e){if(Dt(e.tokenName,"tokenName",Ge),!It(e.content))throw ye("content");if(e.content.length>Je.COMMENT.MAX_LENGTH)throw new re(`content must be at most ${Je.COMMENT.MAX_LENGTH} characters`,"content",ie.TOO_LONG)}(e);const t=Ri,n={content:e.content.trim(),tokenName:qs(e.tokenName)},i=await this.http.post(t,n,this.getJwtHeaders()),r=this.extractData(i);return{comment:{id:r.id,messageId:r.messageId,content:r.content,userAddress:r.userAddress,poolId:r.poolId,createdAt:r.createdAt}}}async deleteComment(e){!function(e){if(void 0===e.commentId||null===e.commentId)throw ye("commentId");Hs(e.commentId,"commentId")}(e);const t=this.buildEndpoint(Mi,{commentId:String(e.commentId)});return await this.http.delete(t,void 0,this.getJwtHeaders()),{success:!0}}}const xh=["heart","fire","laugh","wow","thumbs_up"],_h={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class Bh extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}validateReactionTokenName(e){this.validateTokenName(e,Ge)}validateMessageId(e){if(!It(e))throw ye("messageId","Message ID");if(De(e,Ze.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Ze.CONTENT_REACTION.PATTERN.test(e))throw we("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!It(e))throw ye("reactionType","Reaction type");if(!xh.includes(e))throw we("reactionType",`one of: ${xh.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t={tokenName:qs(e.tokenName),messageId:e.messageId,reactionType:e.reactionType},n=await this.http.post(Li,t,this.getDualAuthHeaders()),i=this.extractData(n),{created:r,...o}=i;return{data:o,created:r}}async removeContentReaction(e){this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=this.buildEndpoint(Fi,{messageId:e.messageId,reactionType:e.reactionType}),n={tokenName:qs(e.tokenName)};return await this.http.delete(t,n,this.getDualAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}class Ph extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}validateContent(e){if(!It(e))throw ye("content","Comment content");if(0===e.trim().length)throw ye("content","Comment content");De(e,Je.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!It(e))throw ye("id","Message ID");if(e.length<10||e.length>64)throw we("id","valid message ID format","Message ID")}async getComments(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new re("At least one of tokenName or userAddress must be provided","filter","REQUIRED");void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Ge);const t={};void 0!==e.offset&&(t.offset=e.offset),void 0!==e.limit&&(t.limit=e.limit);const n={...sa(t,je.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=qs(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(n.userAddress=e.userAddress);const i=await this.http.get(Gi,n),r=this.extractData(i);return{messages:r.messages,meta:r.meta}}async createComment(e){this.validateTokenName(e.tokenName,Ge),this.validateContent(e.content);const t={tokenName:qs(e.tokenName),content:e.content.trim()},n=await this.http.post(Wi,t,this.getJwtHeaders()),i=this.extractData(n);return{comment:{id:i.messageId,tokenName:i.pool?.tokenName??"",tokenImage:i.pool?.tokenImage??null,userAddress:i.userAddress,userProfile:i.user?{fullName:i.user.fullName,profileImage:i.user.profileImage}:null,content:i.content,createdAt:i.createdAt,updatedAt:i.updatedAt,deletedAt:i.deletedAt,flagCount:0,reactions:{}}}}async updateComment(e,t){this.validateMessageId(e),this.validateContent(t.content);const n=this.buildEndpointWithId(Hi,e),i={content:t.content.trim()},r=await this.http.put(n,i,this.getJwtHeaders()),o=this.extractData(r);return{comment:{id:o.messageId,tokenName:o.pool?.tokenName??"",tokenImage:o.pool?.tokenImage??null,userAddress:o.userAddress,userProfile:o.user?{fullName:o.user.fullName,profileImage:o.user.profileImage}:null,content:o.content,createdAt:o.createdAt,updatedAt:o.updatedAt,deletedAt:o.deletedAt,flagCount:0,reactions:{}}}}async deleteComment(e){this.validateMessageId(e);const t=this.buildEndpointWithId(zi,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}}function Dh(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new re("At least one of tokenName or userAddress is required","options",ie.REQUIRED);if(void 0!==e.tokenName){if(!It(e.tokenName))throw Ie("tokenName","string");if(e.tokenName.length>We.MAX_LENGTH)throw new re(`tokenName must be at most ${We.MAX_LENGTH} characters`,"tokenName",ie.TOO_LONG)}if(void 0!==e.userAddress){if(!It(e.userAddress))throw Ie("userAddress","string");if(e.userAddress.length>Qe.MAX_LENGTH)throw new re(`userAddress must be at most ${Qe.MAX_LENGTH} characters`,"userAddress",ie.TOO_LONG)}xt(e.offset,e.limit,je.MAX_LIMIT)}function Rh(e){if(!It(e.tokenName))throw ye("tokenName");if(e.tokenName.length>We.MAX_LENGTH)throw new re(`tokenName must be at most ${We.MAX_LENGTH} characters`,"tokenName",ie.TOO_LONG);if(!It(e.content))throw ye("content");if(0===e.content.trim().length)throw new re("content cannot be empty","content",ie.REQUIRED);if(e.content.length>Je.CHAT_MESSAGES_V1.MAX_LENGTH)throw new re(`content must be at most ${Je.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",ie.TOO_LONG)}function Mh(e){if(!It(e.content))throw ye("content");if(0===e.content.trim().length)throw new re("content cannot be empty","content",ie.REQUIRED);if(e.content.length>Je.CHAT_MESSAGES_V1.MAX_LENGTH)throw new re(`content must be at most ${Je.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",ie.TOO_LONG)}function Lh(e){if(!It(e))throw ye("id","Message ID");if(!Ze.CHAT_MESSAGE.PATTERN.test(e))throw new re("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",ie.INVALID_FORMAT)}function Fh(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}class Uh extends ku{constructor(e,t,n,i=!1){super(e,t,n,i)}async getChatMessages(e){Dh(e);const t=this.buildPaginationParams(e,je.MAX_LIMIT);void 0!==e.tokenName&&""!==e.tokenName&&(t.tokenName=qs(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(t.userAddress=e.userAddress);const n=await this.http.get(Oi,t);return this.extractData(n)}async sendMessage(e){Rh(e);const t={tokenName:qs(e.tokenName),content:e.content.trim()},n=await this.http.post($i,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){Lh(e),Mh(t);const n=this.buildEndpointWithId(qi,e),i={content:t.content.trim()},r=await this.http.put(n,i,this.getJwtHeaders());return{message:this.extractData(r)}}async deleteMessage(e){Lh(e);const t=this.buildEndpointWithId(Ki,e);Vi(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to delete message")}}const Oh={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 $h(e){return parseFloat(Oh[e])}function qh(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Kh(){return Date.now()+6e4}function Gh(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function Wh(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Hh(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class zh extends Xs{constructor(e,t){super(e),this.galaChainClient=t}getCollectionClaimFee(){return Oh.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return Oh.TOKEN_CLASS_CREATE_FEE}async estimateMintFee(e){try{if(this.logger.debug("Estimating mint fee",e),void 0===e.collection||""===e.collection||void 0===e.type||""===e.type||void 0===e.category||""===e.category||void 0===e.quantity||""===e.quantity)throw new Error("Missing required parameters for mint fee estimation");if(!Hh(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=Oh.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if(null!==e.createTokenClasses&&void 0!==e.createTokenClasses&&e.createTokenClasses>0){const i=Oh.TOKEN_CLASS_CREATE_FEE,r=String(BigInt(i)*BigInt(e.createTokenClasses));n.tokenClassCreate=i,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(r))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!Gh(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:Kh(),uniqueKey:qh("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),!Hh(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),!Gh(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),void 0===e.collection||""===e.collection||void 0===e.type||""===e.type||void 0===e.category||""===e.category)throw new Error("Missing required parameters: collection, type, category");if(!Gh(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);if(null!==e.symbol&&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:null!==e.maxSupply&&void 0!==e.maxSupply?Wh(e.maxSupply):void 0,maxCapacity:null!==e.maxCapacity&&void 0!==e.maxCapacity?Wh(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Kh(),uniqueKey:qh("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),!Gh(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),void 0===e.collection||""===e.collection||void 0===e.type||""===e.type||void 0===e.category||""===e.category||void 0===e.quantity||""===e.quantity)throw new Error("Missing required parameters for minting");const t=parseInt(e.quantity,10);if(t<=0)throw new Error("Quantity must be greater than 0");if(!Hh(e.ownerAddress))throw new Error(`Invalid owner address: ${e.ownerAddress}`);const n=await this.estimateMintFee({collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,ownerAddress:e.ownerAddress});this.logger.debug("Estimated mint fee:",n);const i={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:Kh(),uniqueKey:qh("mint")};this.logger.debug("Built mint DTO",i);const r=`mint-${Date.now()}`,o=Array.from({length:t},(e,t)=>t+1);return{transactionId:r,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:o,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!Hh(e))throw new Error(`Invalid owner address: ${e}`);const n=[];return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}}function jh(e){return Fo(e).success}function Vh(e){const t=Fo(e);return t.success?[]:t.errors??["Unknown validation error"]}function Xh(e){const t=Vh(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}const Qh="/api/asset/launchpad-contract/CallNativeTokenIn",Jh="/api/asset/launchpad-contract/CallNativeTokenOut",Zh="/api/asset/launchpad-contract/CallMemeTokenIn",Yh="/api/asset/launchpad-contract/CallMemeTokenOut";class eg extends m{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)}}function tg(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}const ng={NATIVE:"native",EXACT:"exact"},ig={RECENT:"recent",POPULAR:"popular"},rg={LOCAL:"local",EXTERNAL:"external"};class og{static calculateBuyWithExact(e,t){const n=lt(e),i=lt(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=el,c=this.roundUp(r*(Math.exp((i+n)*o)-Math.exp(i*o))/o,8),l=ts(es(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateBuyWithNative(e,t){const n=lt(e),i=lt(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=el,c=Math.log(n*o/r+Math.exp(i*o))/o-i,l=ts(es(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateSellWithExact(e,t,n,i,r){const o=lt(e),s=lt(t),a=lt(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=el,h=c*(Math.exp(s*l)-Math.exp((s-o)*l))/l,g=es(h),f=i+s/a*(r-i),p=ts(g.multipliedBy(f),8),m=ts(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}}static calculateSellWithNative(e,t,n,i,r){const o=lt(e),s=lt(t),a=lt(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=el;if(o>=c*(Math.exp(s*l)-1)/l){const e=es(o),t=i+s/a*(r-i),n=ts(e.multipliedBy(t),8),c=ts(e.multipliedBy(u));return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=s-Math.log(Math.exp(s*l)-o*l/c)/l,g=es(o),f=i+s/a*(r-i),p=ts(g.multipliedBy(f),8),m=ts(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class sg{constructor(e,t,n,i,r,o,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=i,this.galaChainHttp=r,this.dexApiHttp=o,this.defaultCalculateAmountMode=s,this.metadataCache=new nl}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ss(t);const i=`${t}.png`;va(n.file,i,"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 we("file","a File object (browser) or Buffer (Node.js)");{const i=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,r=new Blob([n.file],{type:"image/png"});e.append("image",r,i)}}const i=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===i.error||200!==i.status)throw ke(void 0!==i.message&&""!==i.message?i.message:"Image upload failed - no URL returned",i.status);const r=Xi(i);if(!r?.imageUrl)throw ke("Image upload failed - no URL returned",i.status);return r.imageUrl}catch(e){if(X(e)&&e.message.includes("FormData"))throw be("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}async fetchPoolsFromAPI(e){xt(e.offset,e.limit),void 0!==e.tokenName&&""!==e.tokenName&&Ss(e.tokenName);const t={offset:e.offset.toString(),limit:e.limit.toString()};void 0!==e.type&&(t.type=e.type),void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.search&&(t.search=e.search),void 0!==e.hasUpcomingShows&&(t.hasUpcomingShows=e.hasUpcomingShows.toString()),void 0!==e.language&&(t.language=e.language),void 0!==e.recentlyStreamed&&(t.recentlyStreamed=e.recentlyStreamed.toString());const n=er(t),i=await this.http.get("/launchpad/fetch-pool",n);if(!0===i.error||200!==i.status)throw ke(void 0!==i.message&&""!==i.message?i.message:"Failed to fetch pools",i.status);const r=Xi(i);if(null==r)throw ke("Failed to fetch pools - no data returned",i.status);let o=[];if(r.tokens)if(Array.isArray(r.tokens))o=r.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",i=!us(t)||!us(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:i,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}});else{const e=r.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",i=!us(t)||!us(n);o=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:i,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}]}else r.pools&&Array.isArray(r.pools)&&(o=r.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",i=!us(t)||!us(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:i,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 WC});o.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=r.count??r.total??0,l=r.page??1,u=r.limit??e.limit??10;return{items:o,meta:{offset:(l-1)*u,limit:u,total:c,totalPages:Ps(c,u)}}}async _getAmount(e){if(function(e){const t=Jo(e);!t.success&&t.errors&&vs(t.errors,"options")}(e),!this.galaChainHttp)throw be("GalaChain client not configured. Direct GalaChain calls require galaChainHttp client.","galaChainHttp");const{endpoint:t,body:n}=((e,t,n,i)=>{if("NATIVE"===e&&"IN"===t)return{endpoint:Qh,body:{vaultAddress:n,tokenQuantity:i,IsPreMint:!1}};if("NATIVE"===e&&"OUT"===t)return{endpoint:Jh,body:{vaultAddress:n,tokenQuantity:i,IsPreMint:!1}};if("MEME"===e&&"IN"===t)return{endpoint:Zh,body:{vaultAddress:n,nativeTokenQuantity:i,IsPreMint:!1}};if("MEME"===e&&"OUT"===t)return{endpoint:Yh,body:{vaultAddress:n,nativeTokenQuantity:i,IsPreMint:!1}};throw we("type-method","one of: NATIVE-IN, NATIVE-OUT, MEME-IN, MEME-OUT")})(e.type,e.method,e.vaultAddress,e.amount);try{const e=await this.galaChainHttp.post(t,n);if(!tg(e))throw ke("Malformed response data from GalaChain gateway");try{ee(e,"GalaChain calculation")}catch(e){throw ke(Q(e),500)}const{calculatedQuantity:i,extraFees:r}=e.Data;return{amount:i,reverseBondingCurveFee:r.reverseBondingCurve,transactionFee:r.transactionFees,gasFee:"1"}}catch(i){throw this.logger.error(`GalaChain ${e.type}-${e.method} operation failed:`,{endpoint:t,requestBody:n,error:Q(i)}),ke(Q(i),500)}}async checkPool(e){As(e),void 0!==e.tokenName&&""!==e.tokenName&&Ss(e.tokenName);const t=er(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw ke(void 0!==n.message&&""!==n.message?n.message:"Failed to check pool",n.status);const i=n.data;return void 0!==e.symbol&&""!==e.symbol?i?.isSymbolExist??!1:void 0!==e.tokenName&&""!==e.tokenName?i?.isNameExist??!1:i?.exists??!1}async fetchVolumeData(e){if(!ea(e))throw we("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:i,resolution:r}=e;if(Ss(t),null==n||null==i||null==r)throw ye("graphOptions","Graph options (from, to, resolution)");const o={tokenName:t,from:n,to:i,resolution:r};Ts(o);const s=er(o),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw ke(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch graph data",a.status);const c=Xi(a);if(!c)throw ke("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={offset:e.offset??0,limit:e.limit??10};return 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 we("options","an options object");const{tokenName:t,amount:n,type:i,currentSupply:r}=e,o=e.mode??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw Ie("mode",'"local" or "external"',o);if(!It(t))throw ye("tokenName","Token name");if(!It(n))throw ye("amount","Amount");if(i!==ng.NATIVE&&i!==ng.EXACT)throw Ie("type",'"native" or "exact"',i);return"external"===o?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:i}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:i},"currentSupply",r))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:i}=e,r=await this.tokenResolver.resolveTokenToVault(t);if(null==r||""===r)throw ye("tokenName",`Token "${t}" not found. Please verify the token name is correct.`);return i===ng.EXACT?this._getAmount({type:"NATIVE",method:"IN",vaultAddress:r,amount:n}):this._getAmount({type:"MEME",method:"OUT",vaultAddress:r,amount:n})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:i,currentSupply:r,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw Ie("mode",'"local" or "external"',c);if(!It(t))throw ye("tokenName","Token name");if(!It(n))throw ye("amount","Amount");if(i!==ng.EXACT&&i!==ng.NATIVE)throw Ie("type",'"exact" or "native"',i);if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:i});{const e={tokenName:t,amount:n,type:i,...void 0!==r&&{currentSupply:r},...void 0!==o&&{maxSupply:o},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:i}=e,r=await this.tokenResolver.resolveTokenToVault(t);if(null==r||""===r)throw ye("tokenName",`Token "${t}" not found. Please verify the token name is correct.`);return i===ng.EXACT?this._getAmount({type:"NATIVE",method:"OUT",vaultAddress:r,amount:n}):this._getAmount({type:"MEME",method:"IN",vaultAddress:r,amount:n})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:i,currentSupply:r}=e;if(!It(n))throw ye("amount","Amount");if(i!==ng.NATIVE&&i!==ng.EXACT)throw Ie("type",'"native" or "exact"',i);void 0!==r&&Es(r,"currentSupply");const o=null==r||""===r;if(o&&(null==t||""===t))throw ye("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Ss(t);let s=r;if(o){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return i===ng.EXACT?og.calculateBuyWithExact(n,s):og.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:i,currentSupply:r,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!It(n))throw ye("amount","Amount");if(i!==ng.EXACT&&i!==ng.NATIVE)throw Ie("type",'"exact" or "native"',i);void 0!==r&&Es(r,"currentSupply");const c=null==r||""===r||null==o||""===o||void 0===s||void 0===a;if(c&&(null==t||""===t))throw ye("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Ss(t);let l=r,u=o,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 i===ng.EXACT?og.calculateSellWithExact(n,l,u,h,d):og.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 Js(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Zs(t,"currentSupply")}(e))throw Ie("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:i,currentSupply:r}=t;Ss(n);const o=await this.tokenResolver.resolveTokenToVault(n);if(null==o||""===o)throw new re(ir(n),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw be("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==s.Status)throw ke(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=r??ts(es(a.maxSupply).minus(a.sellingTokenQuantity)),l=a.sellingTokenQuantity;if("0"===l)throw ye("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const u={tokenName:n,amount:l,type:"exact",currentSupply:c,...void 0!==i&&{mode:i}};return{...await this.calculateBuyAmount(u),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw be("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Xh(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=lt(t);if(0===n&&"0"!==t)throw Ce("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Ce("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;Oe(t,n,"reverseBondingCurve")}let i="";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 ke("Image upload failed: No URL returned");i=t}else"string"==typeof e.tokenImage&&(i=e.tokenImage);const r=`galaswap - operation - ${v()}-${Date.now()}-${this.http.getAddress()}`,o={tokenName:e.tokenName.trim(),tokenSymbol:Gs(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:i.trim(),preBuyQuantity:(void 0!==t&&""!==t?t:"0").toString(),tokenCategory:void 0!==e.tokenCategory&&""!==e.tokenCategory?e.tokenCategory:"Unit",tokenCollection:void 0!==e.tokenCollection&&""!==e.tokenCollection?e.tokenCollection:"Token",uniqueKey:r},s=ca(e.websiteUrl);null!==s&&(o.websiteUrl=s);const a=ca(e.telegramUrl);null!==a&&(o.telegramUrl=a);const c=ca(e.twitterUrl);null!==c&&(o.twitterUrl=c);const l=ca(e.instagramUrl);null!==l&&(o.instagramUrl=l);const u=ca(e.facebookUrl);null!==u&&(o.facebookUrl=u);const d=ca(e.redditUrl);null!==d&&(o.redditUrl=d);const h=ca(e.tiktokUrl);null!==h&&(o.tiktokUrl=h),o.reverseBondingCurveConfiguration={minFeePortion:e.reverseBondingCurveConfiguration?.minFeePortion?.toString()??"0.1",maxFeePortion:e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()??"0.5"};const g=new eg(o),p=await this.http.signWithGalaChain("CreateSale",g,f.SIGN_TYPED_DATA),{signature:m,types:y,domain:w,prefix:k}=p,b={tokenName:g.tokenName,tokenSymbol:g.tokenSymbol,tokenDescription:g.tokenDescription,tokenImage:g.tokenImage,preBuyQuantity:g.preBuyQuantity,...void 0!==g.websiteUrl&&""!==g.websiteUrl?{websiteUrl:g.websiteUrl}:{},...void 0!==g.telegramUrl&&""!==g.telegramUrl?{telegramUrl:g.telegramUrl}:{},...void 0!==g.twitterUrl&&""!==g.twitterUrl?{twitterUrl:g.twitterUrl}:{},...void 0!==g.instagramUrl&&""!==g.instagramUrl?{instagramUrl:g.instagramUrl}:{},...void 0!==g.facebookUrl&&""!==g.facebookUrl?{facebookUrl:g.facebookUrl}:{},...void 0!==g.redditUrl&&""!==g.redditUrl?{redditUrl:g.redditUrl}:{},...void 0!==g.tiktokUrl&&""!==g.tiktokUrl?{tiktokUrl:g.tiktokUrl}:{},tokenCategory:g.tokenCategory,tokenCollection:g.tokenCollection,uniqueKey:g.uniqueKey,signature:m,types:y,domain:w,...null!=k?{prefix:k}:{},...void 0!==g.reverseBondingCurveConfiguration&&null!==g.reverseBondingCurveConfiguration?{reverseBondingCurveConfiguration:g.reverseBondingCurveConfiguration}:{}},S=`${e.tokenName.trim()}$Unit$none$none`,A="GALA$Unit$none$none";let T;if(lt(t,0)>0){const e=`$service$${S}$launchpad`;T=[e,`$token$${S}$${e}`,`$tokenBalance$${S}$${e}`,`$tokenBalance$${S}$${e}`,`$tokenBalance$${A}$${e}`,`$tokenBalance$${A}$${e}`]}else{const e=`$service$${S}$launchpad`;T=[e,`$token$${S}$${e}`,`$tokenBalance$${S}$${e}`]}const E={signedDto:b,stringsInstructions:T,method:"CreateSale"},I=await this.bundleHttp.post("/bundle",E);if(I.error)throw ke(void 0!==I.message&&""!==I.message?I.message:"Token launch failed");const C=Xi(I);if(null==C||""===C)throw ke("Token launch failed - no transaction ID returned");return C}async fetchTokenDistribution(e){if(null==e||""===e)throw ye("tokenName","Token name");Ss(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw ke(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=Xi(t);if(null==n)throw ke("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw ke("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 ke("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 ke("Invalid holder data: missing or invalid quantity field",t.status);const n=lt(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw ke(`Invalid holder quantity: "${e.quantity}"`,t.status)}const i=n.reduce((e,t)=>e.plus(t.quantity),es(0));return{holders:n.map(e=>{const t=ws(es(e.quantity),i,es(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:ts(i),totalHolders:n.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(null==e||""===e)throw ye("tokenName","Token name");Ss(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw ke(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token badges");const n=Xi(t);if(null==n)throw ke("Failed to fetch token badges - no data returned");return{volumeBadges:n.volumeBadge??[],engagementBadges:n.engagementBadge??[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:i}=e;try{const e=await this.fetchTokenBadges(t);if(null==e)return!1;const r=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===i);return r?.isActive??!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!Ca(e))throw we("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw be("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(!tg(n))throw ke("Malformed response data from GalaChain gateway");try{ee(n,"Pre-mint calculation")}catch(e){throw ke(Q(e),500)}const{calculatedQuantity:i,extraFees:r}=n.Data;return{amount:i,reverseBondingCurveFee:r.reverseBondingCurve,transactionFee:r.transactionFees,gasFee:"1"}}catch(e){if(X(e)&&e instanceof oe)throw e;throw ke(Q(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new re(ir(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw be("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw ke(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const i=n.Data,r=ts(es(i.maxSupply).minus(i.sellingTokenQuantity)),o=i.sellingTokenQuantity,s=i.maxSupply;let a=.5,c=0;void 0!==i.reverseBondingCurveConfiguration&&null!==i.reverseBondingCurveConfiguration?(a=pt(i.reverseBondingCurveConfiguration.maxFeePortion,.5),c=pt(i.reverseBondingCurveConfiguration.minFeePortion,0)):this.logger.debug(`Pool details missing reverseBondingCurveConfiguration for token ${e}, using defaults (min: 0.0, max: 0.5)`);const l=a-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}),{currentSupply:r,remainingTokens:o,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:l}}async fetchCurrentSupply(e){Ss(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new re(ir(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw be("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw ke(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const i=n.Data,r=ts(es(i.maxSupply).minus(i.sellingTokenQuantity)),o=i.maxSupply;return this.metadataCache.set(e,{maxSupply:o}),r}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return zt(e)}validateTokenName(e){return Ss(e)}validatePagination(e){return xt(e.offset,e.limit)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw be("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw ye("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 ke(`Failed to fetch token prices: ${Q(e)}`,void 0,X(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}class ag{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw Te("requestsPerSecond","1",e,"Requests per second");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const i=new Promise((e,i)=>{t=e,n=i});if(this.pendingPromise=this.pendingPromise.then(async()=>{const i=Date.now()-this.lastTimestamp,r=Math.max(0,this.minIntervalMs-i);r>0&&await new Promise(e=>setTimeout(e,r)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(X(e)?e:new Error(Q(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return i}}function cg(e,t){let n;try{n=ft(e,"amount")}catch(t){throw Ce("amount",`${e} (${Q(t)})`)}if(!n.isFinite())throw Ce("amount",e);const i=n.multipliedBy(es(10).pow(t));if(!i.isInteger())throw Ce("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(i.toFixed(0))}function lg(e,t){return es(e.toString()).dividedBy(es(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}function ug(e,t=6){const n=es(e);if(!n.isFinite())return"0";if(n.abs().lt(1e-6)&&!us(n))return n.toExponential(2);const i=Math.min(t,n.abs().lt(1)?t:n.abs().lt(100)?4:2);return n.toFixed(i).replace(/\.?0+$/,"")}function dg(e,t){const n=es(e),i=es(t);return n.comparedTo(i)}const hg={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},gg=new Set([408,429,500,502,503,504]),fg=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function pg(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return gg.has(t.status);if("number"==typeof t.statusCode)return gg.has(t.statusCode);const n=Z(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=Q(e);return fg.some(e=>e.test(t))}function mg(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),i=Math.min(n,t.maxDelayMs),r=i*t.jitterFactor*Math.random();return Math.floor(i+r)}function yg(e){return new Promise(t=>setTimeout(t,e))}function wg(e){let t;if("string"==typeof e)t=Da(e);else{if(!La(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:Na(t)}}function kg(e){const t={};for(const[n,i]of Object.entries(e))void 0!==i&&(i&&"object"==typeof i&&!Array.isArray(i)?t[n]=kg(i):t[n]=i);return t}function bg(e,t){const n=lt(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}function vg(e){const t="string"==typeof e.timestamp?ht(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 Sg,Ag={},Tg={};var Eg,Ig,Cg={};function Ng(){return Eg||(Eg=1,Cg.read=function(e,t,n,i,r){var o,s,a=8*r-i-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?r-1:0,h=n?-1:1,g=e[t+d];for(d+=h,o=g&(1<<-u)-1,g>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=i;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,i),o-=l}return(g?-1:1)*s*Math.pow(2,o-i)},Cg.write=function(e,t,n,i,r,o){var s,a,c,l=8*o-r-1,u=(1<<l)-1,d=u>>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,g=i?0:o-1,f=i?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=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,r),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,r),s=0));r>=8;e[n+g]=255&a,g+=f,a/=256,r-=8);for(s=s<<r|a,l+=r;l>0;e[n+g]=255&s,g+=f,s/=256,l-=8);e[n+g-f]|=128*p}),Cg}function xg(){return Ig||(Ig=1,function(e){const t=function(){if(Sg)return Tg;Sg=1,Tg.byteLength=function(e){var t=o(e),n=t[0],i=t[1];return 3*(n+i)/4-i},Tg.toByteArray=function(e){var i,r,s=o(e),a=s[0],c=s[1],l=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),u=0,d=c>0?a-4:a;for(r=0;r<d;r+=4)i=t[e.charCodeAt(r)]<<18|t[e.charCodeAt(r+1)]<<12|t[e.charCodeAt(r+2)]<<6|t[e.charCodeAt(r+3)],l[u++]=i>>16&255,l[u++]=i>>8&255,l[u++]=255&i;return 2===c&&(i=t[e.charCodeAt(r)]<<2|t[e.charCodeAt(r+1)]>>4,l[u++]=255&i),1===c&&(i=t[e.charCodeAt(r)]<<10|t[e.charCodeAt(r+1)]<<4|t[e.charCodeAt(r+2)]>>2,l[u++]=i>>8&255,l[u++]=255&i),l},Tg.fromByteArray=function(t){for(var n,i=t.length,r=i%3,o=[],s=16383,c=0,l=i-r;c<l;c+=s)o.push(a(t,c,c+s>l?l:c+s));return 1===r?(n=t[i-1],o.push(e[n>>2]+e[n<<4&63]+"==")):2===r&&(n=(t[i-2]<<8)+t[i-1],o.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"=")),o.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=0;r<64;++r)e[r]=i[r],t[i.charCodeAt(r)]=r;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function s(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var i,r=[],o=t;o<n;o+=3)i=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),r.push(s(i));return r.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,Tg}(),n=Ng(),i="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 r=2147483647;function o(e){if(e>r)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 i=o(n);const r=i.write(e,t);r!==n&&(i=i.slice(0,r));return i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(j(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return s.from(i,t,n);const r=function(e){if(s.isBuffer(e)){const t=0|h(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?o(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),o(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=o(t);for(let i=0;i<t;i+=1)n[i]=255&e[i];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 i;return i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(i,s.prototype),i}function h(e){if(e>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function g(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(r)return i?-1:W(e).length;t=(""+t).toLowerCase(),r=!0}}function f(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return I(this,t,n);case"latin1":case"binary":return C(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function p(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function m(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=s.from(t,i)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,i,r){let o,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){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(r){let i=-1;for(o=n;o<a;o++)if(l(e,o)===l(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===c)return i*s}else-1!==i&&(o-=o-i),i=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let i=0;i<c;i++)if(l(e,o+i)!==l(t,i)){n=!1;break}if(n)return o}return-1}function w(e,t,n,i){n=Number(n)||0;const r=e.length-n;i?(i=Number(i))>r&&(i=r):i=r;const o=t.length;let s;for(i>o/2&&(i=o/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(V(i))return s;e[n+s]=i}return s}function k(e,t,n,i){return z(W(t,e.length-n),e,n,i)}function b(e,t,n,i){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,i)}function v(e,t,n,i){return z(H(t),e,n,i)}function S(e,t,n,i){return z(function(e,t){let n,i,r;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),i=n>>8,r=n%256,o.push(r),o.push(i);return o}(t,e.length-n),e,n,i)}function A(e,n,i){return 0===n&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,i))}function T(e,t,n){n=Math.min(e.length,n);const i=[];let r=t;for(;r<n;){const t=e[r];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(r+s<=n){let n,i,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[r+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=c));break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(c=(15&t)<<12|(63&n)<<6|63&i,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:n=e[r+1],i=e[r+2],a=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),r+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=E));return n}(i)}e.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let r=0,o=Math.min(n,i);r<o;++r)if(e[r]!==t[r]){n=e[r],i=t[r];break}return n<i?-1:i<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 i=s.allocUnsafe(t);let r=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))r+t.length>i.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(i,r)):Uint8Array.prototype.set.call(i,t,r);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,r)}r+=t.length}return i},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)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?T(this,0,e):f.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+">"},i&&(s.prototype[i]=s.prototype.inspect),s.prototype.compare=function(e,t,n,i,r){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;let o=(r>>>=0)-(i>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),l=this.slice(i,r),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){o=l[e],a=u[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=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===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return k(this,e,t,n);case"ascii":case"latin1":case"binary":return b(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function I(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(127&e[r]);return i}function C(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(e[r]);return i}function N(e,t,n){const i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);let r="";for(let i=t;i<n;++i)r+=X[e[i]];return r}function x(e,t,n){const i=e.slice(t,n);let r="";for(let e=0;e<i.length-1;e+=2)r+=String.fromCharCode(i[e]+256*i[e+1]);return r}function _(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,n,i,r,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<o)throw new RangeError('"value" argument is out of bounds');if(n+i>e.length)throw new RangeError("Index out of range")}function P(e,t,n,i,r){$(t,i,r,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function D(e,t,n,i,r){$(t,i,r,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function R(e,t,n,i,r,o){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,i,r,o){return t=+t,i>>>=0,o||R(e,0,i,4),n.write(e,t,i,r,23,4),i+4}function L(e,t,i,r,o){return t=+t,i>>>=0,o||R(e,0,i,8),n.write(e,t,i,r,52,8),i+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 i=this.subarray(e,t);return Object.setPrototypeOf(i,s.prototype),i},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let i=this[e],r=1,o=0;for(;++o<t&&(r*=256);)i+=this[e+o]*r;return i},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let i=this[e+--t],r=1;for(;t>0&&(r*=256);)i+=this[e+--t]*r;return i},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 i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(r)<<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 i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<<BigInt(32))+BigInt(r)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let i=this[e],r=1,o=0;for(;++o<t&&(r*=256);)i+=this[e+o]*r;return r*=128,i>=r&&(i-=Math.pow(2,8*t)),i},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let i=t,r=1,o=this[e+--i];for(;i>0&&(r*=256);)o+=this[e+--i]*r;return r*=128,o>=r&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<<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 i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<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,i){if(e=+e,t>>>=0,n>>>=0,!i){B(this,e,t,n,Math.pow(2,8*n)-1,0)}let r=1,o=0;for(this[t]=255&e;++o<n&&(r*=256);)this[t+o]=e/r&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,i){if(e=+e,t>>>=0,n>>>=0,!i){B(this,e,t,n,Math.pow(2,8*n)-1,0)}let r=n-1,o=1;for(this[t+r]=255&e;--r>=0&&(o*=256);)this[t+r]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Q(function(e,t=0){return P(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);B(this,e,t,n,i-1,-i)}let r=0,o=1,s=0;for(this[t]=255&e;++r<n&&(o*=256);)e<0&&0===s&&0!==this[t+r-1]&&(s=1),this[t+r]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);B(this,e,t,n,i-1,-i)}let r=n-1,o=1,s=0;for(this[t+r]=255&e;--r>=0&&(o*=256);)e<0&&0===s&&0!==this[t+r+1]&&(s=1),this[t+r]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Q(function(e,t=0){return P(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,i){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===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(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);const r=i-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),t),r},s.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!s.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(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 r;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(r=t;r<n;++r)this[r]=e;else{const o=s.isBuffer(e)?e:s.from(e,i),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(r=0;r<n-t;++r)this[r+t]=o[r%a]}return this};const F={};function U(e,t,n){F[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 O(e){let t="",n=e.length;const i="-"===e[0]?1:0;for(;n>=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function $(e,t,n,i,r,o){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let i;throw i=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new F.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,n){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||K(t,e.length-(n+1))}(i,r,o)}function q(e,t){if("number"!=typeof e)throw new F.ERR_INVALID_ARG_TYPE(t,"number",e)}function K(e,t,n){if(Math.floor(e)!==e)throw q(e,n),new F.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new F.ERR_BUFFER_OUT_OF_BOUNDS;throw new F.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 i=`The value of "${e}" is out of range.`,r=n;return Number.isInteger(n)&&Math.abs(n)>2**32?r=O(String(n)):"bigint"==typeof n&&(r=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(r=O(r)),r+="n"),i+=` It must be ${t}. Received ${r}`,i},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const i=e.length;let r=null;const o=[];for(let s=0;s<i;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function H(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,i){let r;for(r=0;r<i&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let r=0;r<16;++r)t[i+r]=e[n]+e[r]}return t}();function Q(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(Ag)),Ag}var _g=xg();const Bg="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pg(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Dg(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Rg(e,...t){if(!Pg(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 Mg(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Dg(e.outputLen),Dg(e.blockLen)}function Lg(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 Fg(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ug(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Og(e,t){return e<<32-t|e>>>t}const $g=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),qg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Kg(e){if(Rg(e),$g)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=qg[e[n]];return t}const Gg=48,Wg=57,Hg=65,zg=70,jg=97,Vg=102;function Xg(e){return e>=Gg&&e<=Wg?e-Gg:e>=Hg&&e<=zg?e-(Hg-10):e>=jg&&e<=Vg?e-(jg-10):void 0}function Qg(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if($g)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 i=new Uint8Array(n);for(let t=0,r=0;t<n;t++,r+=2){const n=Xg(e.charCodeAt(r)),o=Xg(e.charCodeAt(r+1));if(void 0===n||void 0===o){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}i[t]=16*n+o}return i}function Jg(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)),Rg(e),e}function Zg(...e){let t=0;for(let n=0;n<e.length;n++){const i=e[n];Rg(i),t+=i.length}const n=new Uint8Array(t);for(let t=0,i=0;t<e.length;t++){const r=e[t];n.set(r,i),i+=r.length}return n}class Yg{}function ef(e){const t=t=>e().update(Jg(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function tf(e=32){if(Bg&&"function"==typeof Bg.getRandomValues)return Bg.getRandomValues(new Uint8Array(e));if(Bg&&"function"==typeof Bg.randomBytes)return Uint8Array.from(Bg.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function nf(e,t,n){return e&t^~e&n}function rf(e,t,n){return e&t^e&n^t&n}class of extends Yg{constructor(e,t,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Ug(this.buffer)}update(e){Lg(this),Rg(e=Jg(e));const{view:t,buffer:n,blockLen:i}=this,r=e.length;for(let o=0;o<r;){const s=Math.min(i-this.pos,r-o);if(s===i){const t=Ug(e);for(;i<=r-o;o+=i)this.process(t,o);continue}n.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Lg(this),function(e,t){Rg(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:i,isLE:r}=this;let{pos:o}=this;t[o++]=128,Fg(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let e=o;e<i;e++)t[e]=0;!function(e,t,n,i){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,i);const r=BigInt(32),o=BigInt(4294967295),s=Number(n>>r&o),a=Number(n&o),c=i?4:0,l=i?0:4;e.setUint32(t+c,s,i),e.setUint32(t+l,a,i)}(n,i-8,BigInt(8*this.length),r),this.process(n,0);const s=Ug(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],r)}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:i,finished:r,destroyed:o,pos:s}=this;return e.destroyed=o,e.finished=r,e.length=i,e.pos=s,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const sf=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),af=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),cf=BigInt(2**32-1),lf=BigInt(32);function uf(e,t=!1){return t?{h:Number(e&cf),l:Number(e>>lf&cf)}:{h:0|Number(e>>lf&cf),l:0|Number(e&cf)}}const df=(e,t,n)=>e>>>n,hf=(e,t,n)=>e<<32-n|t>>>n,gf=(e,t,n)=>e>>>n|t<<32-n,ff=(e,t,n)=>e<<32-n|t>>>n,pf=(e,t,n)=>e<<64-n|t>>>n-32,mf=(e,t,n)=>e>>>n-32|t<<64-n;function yf(e,t,n,i){const r=(t>>>0)+(i>>>0);return{h:e+n+(r/2**32|0)|0,l:0|r}}const wf=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),kf=(e,t,n,i)=>t+n+i+(e/2**32|0)|0,bf=(e,t,n,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),vf=(e,t,n,i,r)=>t+n+i+r+(e/2**32|0)|0,Sf=(e,t,n,i,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0)+(r>>>0),Af=(e,t,n,i,r,o)=>t+n+i+r+o+(e/2**32|0)|0,Tf=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]),Ef=new Uint32Array(64);class If extends of{constructor(e=32){super(64,e,8,!1),this.A=0|sf[0],this.B=0|sf[1],this.C=0|sf[2],this.D=0|sf[3],this.E=0|sf[4],this.F=0|sf[5],this.G=0|sf[6],this.H=0|sf[7]}get(){const{A:e,B:t,C:n,D:i,E:r,F:o,G:s,H:a}=this;return[e,t,n,i,r,o,s,a]}set(e,t,n,i,r,o,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|i,this.E=0|r,this.F=0|o,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Ef[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Ef[e-15],n=Ef[e-2],i=Og(t,7)^Og(t,18)^t>>>3,r=Og(n,17)^Og(n,19)^n>>>10;Ef[e]=r+Ef[e-7]+i+Ef[e-16]|0}let{A:n,B:i,C:r,D:o,E:s,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Og(s,6)^Og(s,11)^Og(s,25))+nf(s,a,c)+Tf[e]+Ef[e]|0,u=(Og(n,2)^Og(n,13)^Og(n,22))+rf(n,i,r)|0;l=c,c=a,a=s,s=o+t|0,o=r,r=i,i=n,n=t+u|0}n=n+this.A|0,i=i+this.B|0,r=r+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,i,r,o,s,a,c,l)}roundClean(){Fg(Ef)}destroy(){this.set(0,0,0,0,0,0,0,0),Fg(this.buffer)}}const Cf=(()=>function(e,t=!1){const n=e.length;let i=new Uint32Array(n),r=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=uf(e[o],t);[i[o],r[o]]=[n,s]}return[i,r]}(["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))))(),Nf=(()=>Cf[0])(),xf=(()=>Cf[1])(),_f=new Uint32Array(80),Bf=new Uint32Array(80);class Pf extends of{constructor(e=64){super(128,e,16,!1),this.Ah=0|af[0],this.Al=0|af[1],this.Bh=0|af[2],this.Bl=0|af[3],this.Ch=0|af[4],this.Cl=0|af[5],this.Dh=0|af[6],this.Dl=0|af[7],this.Eh=0|af[8],this.El=0|af[9],this.Fh=0|af[10],this.Fl=0|af[11],this.Gh=0|af[12],this.Gl=0|af[13],this.Hh=0|af[14],this.Hl=0|af[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:i,Ch:r,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:f,Hl:p}=this;return[e,t,n,i,r,o,s,a,c,l,u,d,h,g,f,p]}set(e,t,n,i,r,o,s,a,c,l,u,d,h,g,f,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|i,this.Ch=0|r,this.Cl=0|o,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|g,this.Hh=0|f,this.Hl=0|p}process(e,t){for(let n=0;n<16;n++,t+=4)_f[n]=e.getUint32(t),Bf[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|_f[e-15],n=0|Bf[e-15],i=gf(t,n,1)^gf(t,n,8)^df(t,0,7),r=ff(t,n,1)^ff(t,n,8)^hf(t,n,7),o=0|_f[e-2],s=0|Bf[e-2],a=gf(o,s,19)^pf(o,s,61)^df(o,0,6),c=ff(o,s,19)^mf(o,s,61)^hf(o,s,6),l=bf(r,c,Bf[e-7],Bf[e-16]),u=vf(l,i,a,_f[e-7],_f[e-16]);_f[e]=0|u,Bf[e]=0|l}let{Ah:n,Al:i,Bh:r,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:f,Gl:p,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=gf(u,d,14)^gf(u,d,18)^pf(u,d,41),w=ff(u,d,14)^ff(u,d,18)^mf(u,d,41),k=u&h^~u&f,b=Sf(y,w,d&g^~d&p,xf[e],Bf[e]),v=Af(b,m,t,k,Nf[e],_f[e]),S=0|b,A=gf(n,i,28)^pf(n,i,34)^pf(n,i,39),T=ff(n,i,28)^mf(n,i,34)^mf(n,i,39),E=n&r^n&s^r&s,I=i&o^i&a^o&a;m=0|f,y=0|p,f=0|h,p=0|g,h=0|u,g=0|d,({h:u,l:d}=yf(0|c,0|l,0|v,0|S)),c=0|s,l=0|a,s=0|r,a=0|o,r=0|n,o=0|i;const C=wf(S,T,I);n=kf(C,v,A,E),i=0|C}({h:n,l:i}=yf(0|this.Ah,0|this.Al,0|n,0|i)),({h:r,l:o}=yf(0|this.Bh,0|this.Bl,0|r,0|o)),({h:s,l:a}=yf(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:l}=yf(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=yf(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=yf(0|this.Fh,0|this.Fl,0|h,0|g)),({h:f,l:p}=yf(0|this.Gh,0|this.Gl,0|f,0|p)),({h:m,l:y}=yf(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,i,r,o,s,a,c,l,u,d,h,g,f,p,m,y)}roundClean(){Fg(_f,Bf)}destroy(){Fg(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Df=ef(()=>new If),Rf=ef(()=>new Pf),Mf=BigInt(0),Lf=BigInt(1);function Ff(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function Uf(e,t,n=""){const i=Pg(e),r=e?.length,o=void 0!==t;if(!i||o&&r!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${t}`:"")+", got "+(i?`length=${r}`:"type="+typeof e))}return e}function Of(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function $f(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Mf:BigInt("0x"+e)}function qf(e){return $f(Kg(e))}function Kf(e){return Rg(e),$f(Kg(Uint8Array.from(e).reverse()))}function Gf(e,t){return Qg(e.toString(16).padStart(2*t,"0"))}function Wf(e,t){return Gf(e,t).reverse()}function Hf(e,t,n){let i;if("string"==typeof t)try{i=Qg(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Pg(t))throw new Error(e+" must be hex string or Uint8Array");i=Uint8Array.from(t)}const r=i.length;if("number"==typeof n&&r!==n)throw new Error(e+" of length "+n+" expected, got "+r);return i}function zf(e){return Uint8Array.from(e)}const jf=e=>"bigint"==typeof e&&Mf<=e;function Vf(e,t,n,i){if(!function(e,t,n){return jf(e)&&jf(t)&&jf(n)&&t<=e&&e<n}(t,n,i))throw new Error("expected valid "+e+": "+n+" <= n < "+i+", got "+t)}function Xf(e){let t;for(t=0;e>Mf;e>>=Lf,t+=1);return t}const Qf=e=>(Lf<<BigInt(e))-Lf;function Jf(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function i(t,n,i){const r=e[t];if(i&&void 0===r)return;const o=typeof r;if(o!==n||null===r)throw new Error(`param "${t}" is invalid: expected ${n}, got ${o}`)}Object.entries(t).forEach(([e,t])=>i(e,t,!1)),Object.entries(n).forEach(([e,t])=>i(e,t,!0))}function Zf(e){const t=new WeakMap;return(n,...i)=>{const r=t.get(n);if(void 0!==r)return r;const o=e(n,...i);return t.set(n,o),o}}const Yf=BigInt(0),ep=BigInt(1),tp=BigInt(2),np=BigInt(3),ip=BigInt(4),rp=BigInt(5),op=BigInt(7),sp=BigInt(8),ap=BigInt(9),cp=BigInt(16);function lp(e,t){const n=e%t;return n>=Yf?n:t+n}function up(e,t,n){let i=e;for(;t-- >Yf;)i*=i,i%=n;return i}function dp(e,t){if(e===Yf)throw new Error("invert: expected non-zero number");if(t<=Yf)throw new Error("invert: expected positive modulus, got "+t);let n=lp(e,t),i=t,r=Yf,o=ep;for(;n!==Yf;){const e=i%n,t=r-o*(i/n);i=n,n=e,r=o,o=t}if(i!==ep)throw new Error("invert: does not exist");return lp(r,t)}function hp(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function gp(e,t){const n=(e.ORDER+ep)/ip,i=e.pow(t,n);return hp(e,i,t),i}function fp(e,t){const n=(e.ORDER-rp)/sp,i=e.mul(t,tp),r=e.pow(i,n),o=e.mul(t,r),s=e.mul(e.mul(o,tp),r),a=e.mul(o,e.sub(s,e.ONE));return hp(e,a,t),a}function pp(e){if(e<np)throw new Error("sqrt is not defined for small field");let t=e-ep,n=0;for(;t%tp===Yf;)t/=tp,n++;let i=tp;const r=vp(e);for(;1===kp(r,i);)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return gp;let o=r.pow(i,t);const s=(t+ep)/tp;return function(e,i){if(e.is0(i))return i;if(1!==kp(e,i))throw new Error("Cannot find square root");let r=n,a=e.mul(e.ONE,o),c=e.pow(i,t),l=e.pow(i,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===r)throw new Error("Cannot find square root");const i=ep<<BigInt(r-t-1),o=e.pow(a,i);r=t,a=e.sqr(o),c=e.mul(c,a),l=e.mul(l,o)}return l}}function mp(e){return e%ip===np?gp:e%sp===rp?fp:e%cp===ap?function(e){const t=vp(e),n=pp(e),i=n(t,t.neg(t.ONE)),r=n(t,i),o=n(t,t.neg(i)),s=(e+op)/cp;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,i);const c=e.mul(n,r),l=e.mul(n,o),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),g=e.cmov(n,a,h);return hp(e,g,t),g}}(e):pp(e)}const yp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function wp(e,t,n=!1){const i=new Array(t.length).fill(n?e.ZERO:void 0),r=t.reduce((t,n,r)=>e.is0(n)?t:(i[r]=t,e.mul(t,n)),e.ONE),o=e.inv(r);return t.reduceRight((t,n,r)=>e.is0(n)?t:(i[r]=e.mul(t,i[r]),e.mul(t,n)),o),i}function kp(e,t){const n=(e.ORDER-ep)/tp,i=e.pow(t,n),r=e.eql(i,e.ONE),o=e.eql(i,e.ZERO),s=e.eql(i,e.neg(e.ONE));if(!r&&!o&&!s)throw new Error("invalid Legendre symbol result");return r?1:o?0:-1}function bp(e,t){void 0!==t&&Dg(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function vp(e,t,n=!1,i={}){if(e<=Yf)throw new Error("invalid field: expected ORDER > 0, got "+e);let r,o,s,a=!1;if("object"==typeof t&&null!=t){if(i.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(r=e.BITS),e.sqrt&&(o=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(r=t),i.sqrt&&(o=i.sqrt);const{nBitLength:c,nByteLength:l}=bp(e,r);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:Qf(c),ZERO:Yf,ONE:ep,allowedLengths:s,create:t=>lp(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Yf<=t&&t<e},is0:e=>e===Yf,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&ep)===ep,neg:t=>lp(-t,e),eql:(e,t)=>e===t,sqr:t=>lp(t*t,e),add:(t,n)=>lp(t+n,e),sub:(t,n)=>lp(t-n,e),mul:(t,n)=>lp(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Yf)throw new Error("invalid exponent, negatives unsupported");if(n===Yf)return e.ONE;if(n===ep)return t;let i=e.ONE,r=t;for(;n>Yf;)n&ep&&(i=e.mul(i,r)),r=e.sqr(r),n>>=ep;return i}(d,e,t),div:(t,n)=>lp(t*dp(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>dp(t,e),sqrt:o||(t=>(u||(u=mp(e)),u(d,t))),toBytes:e=>n?Wf(e,l):Gf(e,l),fromBytes:(t,i=!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 r=n?Kf(t):qf(t);if(a&&(r=lp(r,e)),!i&&!d.isValid(r))throw new Error("invalid field element: outside of range 0..ORDER");return r},invertBatch:e=>wp(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function Sp(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 Ap(e){const t=Sp(e);return t+Math.ceil(t/2)}const Tp=BigInt(0),Ep=BigInt(1);function Ip(e,t){const n=t.negate();return e?n:t}function Cp(e,t){const n=wp(e.Fp,t.map(e=>e.Z));return t.map((t,i)=>e.fromAffine(t.toAffine(n[i])))}function Np(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function xp(e,t){Np(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Qf(e),maxNumber:n,shiftBy:BigInt(e)}}function _p(e,t,n){const{windowSize:i,mask:r,maxNumber:o,shiftBy:s}=n;let a=Number(e&r),c=e>>s;a>i&&(a-=o,c+=Ep);const l=t*i;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const Bp=new WeakMap,Pp=new WeakMap;function Dp(e){return Pp.get(e)||1}function Rp(e){if(e!==Tp)throw new Error("invalid wNAF")}class Mp{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 i=e;for(;t>Tp;)t&Ep&&(n=n.add(i)),i=i.double(),t>>=Ep;return n}precomputeWindow(e,t){const{windows:n,windowSize:i}=xp(t,this.bits),r=[];let o=e,s=o;for(let e=0;e<n;e++){s=o,r.push(s);for(let e=1;e<i;e++)s=s.add(o),r.push(s);o=s.double()}return r}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,r=this.BASE;const o=xp(e,this.bits);for(let e=0;e<o.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=_p(n,e,o);n=s,c?r=r.add(Ip(u,t[d])):i=i.add(Ip(l,t[a]))}return Rp(n),{p:i,f:r}}wNAFUnsafe(e,t,n,i=this.ZERO){const r=xp(e,this.bits);for(let e=0;e<r.windows&&n!==Tp;e++){const{nextN:o,offset:s,isZero:a,isNeg:c}=_p(n,e,r);if(n=o,!a){const e=t[s];i=i.add(c?e.negate():e)}}return Rp(n),i}getPrecomputes(e,t,n){let i=Bp.get(t);return i||(i=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(i=n(i)),Bp.set(t,i))),i}cached(e,t,n){const i=Dp(e);return this.wNAF(i,this.getPrecomputes(i,e,n),t)}unsafe(e,t,n,i){const r=Dp(e);return 1===r?this._unsafeLadder(e,t,i):this.wNAFUnsafe(r,this.getPrecomputes(r,e,n),t,i)}createCache(e,t){Np(t,this.bits),Pp.set(e,t),Bp.delete(e)}hasCache(e){return 1!==Dp(e)}}function Lp(e,t,n,i){!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)})}(i,t);const r=n.length,o=i.length;if(r!==o)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=Xf(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Qf(c),u=new Array(Number(l)+1).fill(s);let d=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(s);for(let t=0;t<o;t++){const r=i[t],o=Number(r>>BigInt(e)&l);u[o]=u[o].add(n[t])}let t=s;for(let e=u.length-1,n=s;e>0;e--)n=n.add(u[e]),t=t.add(n);if(d=d.add(t),0!==e)for(let e=0;e<c;e++)d=d.double()}return d}function Fp(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Jf(e,yp.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return vp(e,{isLE:n})}function Up(e,t,n={},i){if(void 0===i&&(i="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>Tp))throw new Error(`CURVE.${e} must be positive bigint`)}const r=Fp(t.p,n.Fp,i),o=Fp(t.n,n.Fn,i),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!r.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:r,Fn:o}}const Op=BigInt(0),$p=BigInt(1),qp=BigInt(2),Kp=BigInt(8);function Gp(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Jf(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:i}=n,{BASE:r,Fp:o,Fn:s}=e,a=n.randomBytes||tf,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(Ff(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return s.create(Kf(e))}function d(e){const{head:n,prefix:i,scalar:o}=function(e){const n=m.secretKey;e=Hf("private key",e,n);const i=Hf("hashed private key",t(e),2*n),r=c(i.slice(0,n));return{head:r,prefix:i.slice(n,2*n),scalar:u(r)}}(e),s=r.multiply(o),a=s.toBytes();return{head:n,prefix:i,scalar:o,point:s,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const r=Zg(...n);return u(t(l(r,Hf("context",e),!!i)))}const f={zip215:!0};const p=o.BYTES,m={secretKey:p,publicKey:p,signature:2*p,seed:p};function y(e=a(m.seed)){return Uf(e,m.seed,"seed")}const w={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return Pg(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),i=m.publicKey,r=32===i;if(!r&&57!==i)throw new Error("only defined for 25519 and 448");const s=r?o.div($p+n,$p-n):o.div(n-$p,n+$p);return o.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;Uf(e,n);const i=t(e.subarray(0,n));return c(i).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=Hf("message",e),i&&(e=i(e));const{prefix:o,scalar:a,pointBytes:c}=d(t),l=g(n.context,o,e),u=r.multiply(l).toBytes(),h=g(n.context,u,c,e),f=s.create(l+h*a);if(!s.isValid(f))throw new Error("sign failed: invalid s");return Uf(Zg(u,s.toBytes(f)),m.signature,"result")},verify:function(t,n,o,s=f){const{context:a,zip215:c}=s,l=m.signature;t=Hf("signature",t,l),n=Hf("message",n),o=Hf("publicKey",o,m.publicKey),void 0!==c&&Ff(c,"zip215"),i&&(n=i(n));const u=l/2,d=t.subarray(0,u),h=Kf(t.subarray(u,l));let p,y,w;try{p=e.fromBytes(o,c),y=e.fromBytes(d,c),w=r.multiplyUnsafe(h)}catch(e){return!1}if(!c&&p.isSmallOrder())return!1;const k=g(a,y.toBytes(),p.toBytes(),n);return y.add(p.multiplyUnsafe(k)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function Wp(e){const{CURVE:t,curveOpts:n,hash:i,eddsaOpts:r}=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:vp(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:i}}(e),o=function(e,t={}){const n=Up("edwards",e,t,t.FpFnLE),{Fp:i,Fn:r}=n;let o=n.CURVE;const{h:s}=o;Jf(t,{},{uvRatio:"function"});const a=qp<<BigInt(8*r.BYTES)-$p,c=e=>i.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:i.sqrt(i.div(e,t))}}catch(e){return{isValid:!1,value:Op}}});if(!function(e,t,n,i){const r=e.sqr(n),o=e.sqr(i),s=e.add(e.mul(t.a,r),o),a=e.add(e.ONE,e.mul(t.d,e.mul(r,o)));return e.eql(s,a)}(i,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return Vf("coordinate "+e,t,n?$p:Op,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const h=Zf((e,t)=>{const{X:n,Y:r,Z:o}=e,s=e.is0();null==t&&(t=s?Kp:i.inv(o));const a=c(n*t),l=c(r*t),u=i.mul(o,t);if(s)return{x:Op,y:$p};if(u!==$p)throw new Error("invZ was invalid");return{x:a,y:l}}),g=Zf(e=>{const{a:t,d:n}=o;if(e.is0())throw new Error("bad point: ZERO");const{X:i,Y:r,Z:s,T:a}=e,l=c(i*i),u=c(r*r),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(i*r)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class f{constructor(e,t,n,i){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",i),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new f(t,n,$p,c(t*n))}static fromBytes(e,t=!1){const n=i.BYTES,{a:r,d:s}=o;e=zf(Uf(e,n,"point")),Ff(t,"zip215");const u=zf(e),d=e[n-1];u[n-1]=-129&d;const h=Kf(u),g=t?a:i.ORDER;Vf("point.y",h,Op,g);const p=c(h*h),m=c(p-$p),y=c(s*p-r);let{isValid:w,value:k}=l(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const b=(k&$p)===$p,v=!!(128&d);if(!t&&k===Op&&v)throw new Error("bad point: x=0 and x_0=1");return v!==b&&(k=c(-k)),f.fromAffine({x:k,y:h})}static fromHex(e,t=!1){return f.fromBytes(Hf("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return p.createCache(this,e),t||this.multiply(qp),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:i}=this,{X:r,Y:o,Z:s}=e,a=c(t*s),l=c(r*i),u=c(n*s),h=c(o*i);return a===l&&u===h}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=o,{X:t,Y:n,Z:i}=this,r=c(t*t),s=c(n*n),a=c(qp*c(i*i)),l=c(e*r),u=t+n,d=c(c(u*u)-r-s),h=l+s,g=h-a,p=l-s,m=c(d*g),y=c(h*p),w=c(d*p),k=c(g*h);return new f(m,y,k,w)}add(e){d(e);const{a:t,d:n}=o,{X:i,Y:r,Z:s,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,p=c(i*l),m=c(r*u),y=c(a*n*g),w=c(s*h),k=c((i+r)*(l+u)-p-m),b=w-y,v=w+y,S=c(m-t*p),A=c(k*b),T=c(v*S),E=c(k*S),I=c(b*v);return new f(A,T,I,E)}subtract(e){return this.add(e.negate())}multiply(e){if(!r.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=p.cached(this,e,e=>Cp(f,e));return Cp(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!r.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===Op?f.ZERO:this.is0()||e===$p?this:p.unsafe(this,e,e=>Cp(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return s===$p?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=i.toBytes(t);return n[n.length-1]|=e&$p?128:0,n}toHex(){return Kg(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 Cp(f,e)}static msm(e,t){return Lp(f,r,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(o.Gx,o.Gy,$p,c(o.Gx*o.Gy)),f.ZERO=new f(Op,$p,$p,Op),f.Fp=i,f.Fn=r;const p=new Mp(f,r.BITS);return f.BASE.precompute(8),f}(t,n);return function(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,Gp(o,i,r))}const Hp=BigInt(1),zp=BigInt(2);BigInt(3);const jp=BigInt(5),Vp=BigInt(8),Xp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qp=(()=>({p:Xp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Vp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Jp(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Zp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Yp(e,t){const n=Xp,i=lp(t*t*t,n),r=function(e){const t=BigInt(10),n=BigInt(20),i=BigInt(40),r=BigInt(80),o=Xp,s=e*e%o*e%o,a=up(s,zp,o)*s%o,c=up(a,Hp,o)*e%o,l=up(c,jp,o)*c%o,u=up(l,t,o)*l%o,d=up(u,n,o)*u%o,h=up(d,i,o)*d%o,g=up(h,r,o)*h%o,f=up(g,r,o)*h%o,p=up(f,t,o)*l%o;return{pow_p_5_8:up(p,zp,o)*e%o,b2:s}}(e*lp(i*i*t,n)).pow_p_5_8;let o=lp(e*i*r,n);const s=lp(t*o*o,n),a=o,c=lp(o*Zp,n),l=s===e,u=s===lp(-e,n),d=s===lp(-e*Zp,n);return l&&(o=a),(u||d)&&(o=c),(lp(o,n)&ep)===ep&&(o=lp(-o,n)),{isValid:l||u,value:o}}const em=(()=>vp(Qp.p,{isLE:!0}))(),tm=(()=>({...Qp,Fp:em,hash:Rf,adjustScalarBytes:Jp,uvRatio:Yp}))(),nm=(()=>Wp(tm))();var im,rm={exports:{}},om=El(Object.freeze({__proto__:null,default:{}})),sm=rm.exports;function am(){return im||(im=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function r(e,t,n){if(r.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var o;"object"==typeof e?e.exports=r:t.BN=r,r.BN=r,r.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:om.Buffer}catch(e){}function s(e,t){var i=e.charCodeAt(t);return i>=48&&i<=57?i-48:i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:void n(!1,"Invalid character in "+e)}function a(e,t,n){var i=s(e,n);return n-1>=t&&(i|=s(e,n-1)<<4),i}function c(e,t,i,r){for(var o=0,s=0,a=Math.min(e.length,i),c=t;c<a;c++){var l=e.charCodeAt(c)-48;o*=r,s=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&s<r,"Invalid character"),o+=s}return o}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(r.isBN=function(e){return e instanceof r||null!==e&&"object"==typeof e&&e.constructor.wordSize===r.wordSize&&Array.isArray(e.words)},r.max=function(e,t){return e.cmp(t)>0?e:t},r.min=function(e,t){return e.cmp(t)<0?e:t},r.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r<e.length&&(16===t?this._parseHex(e,r,i):(this._parseBase(e,t,r),"le"===i&&this._initArray(this.toArray(),t,i)))},r.prototype._initNumber=function(e,t,i){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"===i&&this._initArray(this.toArray(),t,i)},r.prototype._initArray=function(e,t,i){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 r=0;r<this.length;r++)this.words[r]=0;var o,s,a=0;if("be"===i)for(r=e.length-1,o=0;r>=0;r-=3)s=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===i)for(r=0,o=0;r<e.length;r+=3)s=e[r]|e[r+1]<<8|e[r+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},r.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var r,o=0,s=0;if("be"===n)for(i=e.length-1;i>=t;i-=2)r=a(e,t,i)<<o,this.words[s]|=67108863&r,o>=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;else for(i=(e.length-t)%2==0?t+1:t;i<e.length;i+=2)r=a(e,t,i)<<o,this.words[s]|=67108863&r,o>=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;this._strip()},r.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var i=0,r=1;r<=67108863;r*=t)i++;i--,r=r/t|0;for(var o=e.length-n,s=o%i,a=Math.min(o,o-s)+n,l=0,u=n;u<a;u+=i)l=c(e,u,u+i,t),this.imuln(r),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()},r.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},r.prototype._move=function(e){l(e,this)},r.prototype.clone=function(){var e=new r(null);return this.copy(e),e},r.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},r.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},r.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{r.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){r.prototype.inspect=u}else r.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],g=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,n){n.negative=t.negative^e.negative;var i=e.length+t.length|0;n.length=i,i=i-1|0;var r=0|e.words[0],o=0|t.words[0],s=r*o,a=67108863&s,c=s/67108864|0;n.words[0]=a;for(var l=1;l<i;l++){for(var u=c>>>26,d=67108863&c,h=Math.min(l,t.length-1),g=Math.max(0,l-e.length+1);g<=h;g++){var f=l-g|0;u+=(s=(r=0|e.words[f])*(o=0|t.words[g])+d)/67108864|0,d=67108863&s}n.words[l]=0|d,c=0|u}return 0!==c?n.words[l]=0|c:n.length--,n._strip()}r.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<r|o)).toString(16);o=a>>>24-r&16777215,(r+=2)>=26&&(r-=26,s--),i=0!==o||s!==this.length-1?d[6-c.length]+c+i:c+i}for(0!==o&&(i=o.toString(16)+i);i.length%t!==0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var l=h[e],u=g[e];i="";var f=this.clone();for(f.negative=0;!f.isZero();){var p=f.modrn(u).toString(e);i=(f=f.idivn(u)).isZero()?p+i:d[l-p.length]+p+i}for(this.isZero()&&(i="0"+i);i.length%t!==0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},r.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},r.prototype.toJSON=function(){return this.toString(16,2)},o&&(r.prototype.toBuffer=function(e,t){return this.toArrayLike(o,e,t)}),r.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},r.prototype.toArrayLike=function(e,t,i){this._strip();var r=this.byteLength(),o=i||Math.max(1,r);n(r<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,r),s},r.prototype._toArrayLikeLE=function(e,t){for(var n=0,i=0,r=0,o=0;r<this.length;r++){var s=this.words[r]<<o|i;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===o?(n<e.length&&(e[n++]=s>>24&255),i=0,o=0):(i=s>>>24,o+=2)}if(n<e.length)for(e[n++]=i;n<e.length;)e[n++]=0},r.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,i=0,r=0,o=0;r<this.length;r++){var s=this.words[r]<<o|i;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===o?(n>=0&&(e[n--]=s>>24&255),i=0,o=0):(i=s>>>24,o+=2)}if(n>=0)for(e[n--]=i;n>=0;)e[n--]=0},Math.clz32?r.prototype._countBits=function(e){return 32-Math.clz32(e)}:r.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},r.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},r.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},r.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},r.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},r.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},r.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},r.prototype.isNeg=function(){return 0!==this.negative},r.prototype.neg=function(){return this.clone().ineg()},r.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},r.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()},r.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},r.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},r.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},r.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()},r.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},r.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},r.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},r.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var i=0;i<n.length;i++)this.words[i]=t.words[i]^n.words[i];if(this!==t)for(;i<t.length;i++)this.words[i]=t.words[i];return this.length=t.length,this._strip()},r.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},r.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},r.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},r.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r<t;r++)this.words[r]=67108863&~this.words[r];return i>0&&(this.words[r]=~this.words[r]&67108863>>26-i),this._strip()},r.prototype.notn=function(e){return this.clone().inotn(e)},r.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<<r:this.words[i]&~(1<<r),this._strip()},r.prototype.iadd=function(e){var t,n,i;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,i=e):(n=e,i=this);for(var r=0,o=0;o<i.length;o++)t=(0|n.words[o])+(0|i.words[o])+r,this.words[o]=67108863&t,r=t>>>26;for(;0!==r&&o<n.length;o++)t=(0|n.words[o])+r,this.words[o]=67108863&t,r=t>>>26;if(this.length=n.length,0!==r)this.words[this.length]=r,this.length++;else if(n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this},r.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)},r.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,i,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(n=this,i=e):(n=e,i=this);for(var o=0,s=0;s<i.length;s++)o=(t=(0|n.words[s])-(0|i.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<n.length;s++)o=(t=(0|n.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this._strip()},r.prototype.sub=function(e){return this.clone().isub(e)};var p=function(e,t,n){var i,r,o,s=e.words,a=t.words,c=n.words,l=0,u=0|s[0],d=8191&u,h=u>>>13,g=0|s[1],f=8191&g,p=g>>>13,m=0|s[2],y=8191&m,w=m>>>13,k=0|s[3],b=8191&k,v=k>>>13,S=0|s[4],A=8191&S,T=S>>>13,E=0|s[5],I=8191&E,C=E>>>13,N=0|s[6],x=8191&N,_=N>>>13,B=0|s[7],P=8191&B,D=B>>>13,R=0|s[8],M=8191&R,L=R>>>13,F=0|s[9],U=8191&F,O=F>>>13,$=0|a[0],q=8191&$,K=$>>>13,G=0|a[1],W=8191&G,H=G>>>13,z=0|a[2],j=8191&z,V=z>>>13,X=0|a[3],Q=8191&X,J=X>>>13,Z=0|a[4],Y=8191&Z,ee=Z>>>13,te=0|a[5],ne=8191&te,ie=te>>>13,re=0|a[6],oe=8191&re,se=re>>>13,ae=0|a[7],ce=8191&ae,le=ae>>>13,ue=0|a[8],de=8191&ue,he=ue>>>13,ge=0|a[9],fe=8191&ge,pe=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(l+(i=Math.imul(d,q))|0)+((8191&(r=(r=Math.imul(d,K))+Math.imul(h,q)|0))<<13)|0;l=((o=Math.imul(h,K))+(r>>>13)|0)+(me>>>26)|0,me&=67108863,i=Math.imul(f,q),r=(r=Math.imul(f,K))+Math.imul(p,q)|0,o=Math.imul(p,K);var ye=(l+(i=i+Math.imul(d,W)|0)|0)+((8191&(r=(r=r+Math.imul(d,H)|0)+Math.imul(h,W)|0))<<13)|0;l=((o=o+Math.imul(h,H)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,i=Math.imul(y,q),r=(r=Math.imul(y,K))+Math.imul(w,q)|0,o=Math.imul(w,K),i=i+Math.imul(f,W)|0,r=(r=r+Math.imul(f,H)|0)+Math.imul(p,W)|0,o=o+Math.imul(p,H)|0;var we=(l+(i=i+Math.imul(d,j)|0)|0)+((8191&(r=(r=r+Math.imul(d,V)|0)+Math.imul(h,j)|0))<<13)|0;l=((o=o+Math.imul(h,V)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,i=Math.imul(b,q),r=(r=Math.imul(b,K))+Math.imul(v,q)|0,o=Math.imul(v,K),i=i+Math.imul(y,W)|0,r=(r=r+Math.imul(y,H)|0)+Math.imul(w,W)|0,o=o+Math.imul(w,H)|0,i=i+Math.imul(f,j)|0,r=(r=r+Math.imul(f,V)|0)+Math.imul(p,j)|0,o=o+Math.imul(p,V)|0;var ke=(l+(i=i+Math.imul(d,Q)|0)|0)+((8191&(r=(r=r+Math.imul(d,J)|0)+Math.imul(h,Q)|0))<<13)|0;l=((o=o+Math.imul(h,J)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,i=Math.imul(A,q),r=(r=Math.imul(A,K))+Math.imul(T,q)|0,o=Math.imul(T,K),i=i+Math.imul(b,W)|0,r=(r=r+Math.imul(b,H)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,H)|0,i=i+Math.imul(y,j)|0,r=(r=r+Math.imul(y,V)|0)+Math.imul(w,j)|0,o=o+Math.imul(w,V)|0,i=i+Math.imul(f,Q)|0,r=(r=r+Math.imul(f,J)|0)+Math.imul(p,Q)|0,o=o+Math.imul(p,J)|0;var be=(l+(i=i+Math.imul(d,Y)|0)|0)+((8191&(r=(r=r+Math.imul(d,ee)|0)+Math.imul(h,Y)|0))<<13)|0;l=((o=o+Math.imul(h,ee)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,i=Math.imul(I,q),r=(r=Math.imul(I,K))+Math.imul(C,q)|0,o=Math.imul(C,K),i=i+Math.imul(A,W)|0,r=(r=r+Math.imul(A,H)|0)+Math.imul(T,W)|0,o=o+Math.imul(T,H)|0,i=i+Math.imul(b,j)|0,r=(r=r+Math.imul(b,V)|0)+Math.imul(v,j)|0,o=o+Math.imul(v,V)|0,i=i+Math.imul(y,Q)|0,r=(r=r+Math.imul(y,J)|0)+Math.imul(w,Q)|0,o=o+Math.imul(w,J)|0,i=i+Math.imul(f,Y)|0,r=(r=r+Math.imul(f,ee)|0)+Math.imul(p,Y)|0,o=o+Math.imul(p,ee)|0;var ve=(l+(i=i+Math.imul(d,ne)|0)|0)+((8191&(r=(r=r+Math.imul(d,ie)|0)+Math.imul(h,ne)|0))<<13)|0;l=((o=o+Math.imul(h,ie)|0)+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,i=Math.imul(x,q),r=(r=Math.imul(x,K))+Math.imul(_,q)|0,o=Math.imul(_,K),i=i+Math.imul(I,W)|0,r=(r=r+Math.imul(I,H)|0)+Math.imul(C,W)|0,o=o+Math.imul(C,H)|0,i=i+Math.imul(A,j)|0,r=(r=r+Math.imul(A,V)|0)+Math.imul(T,j)|0,o=o+Math.imul(T,V)|0,i=i+Math.imul(b,Q)|0,r=(r=r+Math.imul(b,J)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,J)|0,i=i+Math.imul(y,Y)|0,r=(r=r+Math.imul(y,ee)|0)+Math.imul(w,Y)|0,o=o+Math.imul(w,ee)|0,i=i+Math.imul(f,ne)|0,r=(r=r+Math.imul(f,ie)|0)+Math.imul(p,ne)|0,o=o+Math.imul(p,ie)|0;var Se=(l+(i=i+Math.imul(d,oe)|0)|0)+((8191&(r=(r=r+Math.imul(d,se)|0)+Math.imul(h,oe)|0))<<13)|0;l=((o=o+Math.imul(h,se)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,i=Math.imul(P,q),r=(r=Math.imul(P,K))+Math.imul(D,q)|0,o=Math.imul(D,K),i=i+Math.imul(x,W)|0,r=(r=r+Math.imul(x,H)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,H)|0,i=i+Math.imul(I,j)|0,r=(r=r+Math.imul(I,V)|0)+Math.imul(C,j)|0,o=o+Math.imul(C,V)|0,i=i+Math.imul(A,Q)|0,r=(r=r+Math.imul(A,J)|0)+Math.imul(T,Q)|0,o=o+Math.imul(T,J)|0,i=i+Math.imul(b,Y)|0,r=(r=r+Math.imul(b,ee)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,ee)|0,i=i+Math.imul(y,ne)|0,r=(r=r+Math.imul(y,ie)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,ie)|0,i=i+Math.imul(f,oe)|0,r=(r=r+Math.imul(f,se)|0)+Math.imul(p,oe)|0,o=o+Math.imul(p,se)|0;var Ae=(l+(i=i+Math.imul(d,ce)|0)|0)+((8191&(r=(r=r+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((o=o+Math.imul(h,le)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,i=Math.imul(M,q),r=(r=Math.imul(M,K))+Math.imul(L,q)|0,o=Math.imul(L,K),i=i+Math.imul(P,W)|0,r=(r=r+Math.imul(P,H)|0)+Math.imul(D,W)|0,o=o+Math.imul(D,H)|0,i=i+Math.imul(x,j)|0,r=(r=r+Math.imul(x,V)|0)+Math.imul(_,j)|0,o=o+Math.imul(_,V)|0,i=i+Math.imul(I,Q)|0,r=(r=r+Math.imul(I,J)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,J)|0,i=i+Math.imul(A,Y)|0,r=(r=r+Math.imul(A,ee)|0)+Math.imul(T,Y)|0,o=o+Math.imul(T,ee)|0,i=i+Math.imul(b,ne)|0,r=(r=r+Math.imul(b,ie)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,ie)|0,i=i+Math.imul(y,oe)|0,r=(r=r+Math.imul(y,se)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,se)|0,i=i+Math.imul(f,ce)|0,r=(r=r+Math.imul(f,le)|0)+Math.imul(p,ce)|0,o=o+Math.imul(p,le)|0;var Te=(l+(i=i+Math.imul(d,de)|0)|0)+((8191&(r=(r=r+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((o=o+Math.imul(h,he)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,i=Math.imul(U,q),r=(r=Math.imul(U,K))+Math.imul(O,q)|0,o=Math.imul(O,K),i=i+Math.imul(M,W)|0,r=(r=r+Math.imul(M,H)|0)+Math.imul(L,W)|0,o=o+Math.imul(L,H)|0,i=i+Math.imul(P,j)|0,r=(r=r+Math.imul(P,V)|0)+Math.imul(D,j)|0,o=o+Math.imul(D,V)|0,i=i+Math.imul(x,Q)|0,r=(r=r+Math.imul(x,J)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,J)|0,i=i+Math.imul(I,Y)|0,r=(r=r+Math.imul(I,ee)|0)+Math.imul(C,Y)|0,o=o+Math.imul(C,ee)|0,i=i+Math.imul(A,ne)|0,r=(r=r+Math.imul(A,ie)|0)+Math.imul(T,ne)|0,o=o+Math.imul(T,ie)|0,i=i+Math.imul(b,oe)|0,r=(r=r+Math.imul(b,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0,i=i+Math.imul(y,ce)|0,r=(r=r+Math.imul(y,le)|0)+Math.imul(w,ce)|0,o=o+Math.imul(w,le)|0,i=i+Math.imul(f,de)|0,r=(r=r+Math.imul(f,he)|0)+Math.imul(p,de)|0,o=o+Math.imul(p,he)|0;var Ee=(l+(i=i+Math.imul(d,fe)|0)|0)+((8191&(r=(r=r+Math.imul(d,pe)|0)+Math.imul(h,fe)|0))<<13)|0;l=((o=o+Math.imul(h,pe)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,i=Math.imul(U,W),r=(r=Math.imul(U,H))+Math.imul(O,W)|0,o=Math.imul(O,H),i=i+Math.imul(M,j)|0,r=(r=r+Math.imul(M,V)|0)+Math.imul(L,j)|0,o=o+Math.imul(L,V)|0,i=i+Math.imul(P,Q)|0,r=(r=r+Math.imul(P,J)|0)+Math.imul(D,Q)|0,o=o+Math.imul(D,J)|0,i=i+Math.imul(x,Y)|0,r=(r=r+Math.imul(x,ee)|0)+Math.imul(_,Y)|0,o=o+Math.imul(_,ee)|0,i=i+Math.imul(I,ne)|0,r=(r=r+Math.imul(I,ie)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,ie)|0,i=i+Math.imul(A,oe)|0,r=(r=r+Math.imul(A,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,i=i+Math.imul(b,ce)|0,r=(r=r+Math.imul(b,le)|0)+Math.imul(v,ce)|0,o=o+Math.imul(v,le)|0,i=i+Math.imul(y,de)|0,r=(r=r+Math.imul(y,he)|0)+Math.imul(w,de)|0,o=o+Math.imul(w,he)|0;var Ie=(l+(i=i+Math.imul(f,fe)|0)|0)+((8191&(r=(r=r+Math.imul(f,pe)|0)+Math.imul(p,fe)|0))<<13)|0;l=((o=o+Math.imul(p,pe)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,i=Math.imul(U,j),r=(r=Math.imul(U,V))+Math.imul(O,j)|0,o=Math.imul(O,V),i=i+Math.imul(M,Q)|0,r=(r=r+Math.imul(M,J)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,J)|0,i=i+Math.imul(P,Y)|0,r=(r=r+Math.imul(P,ee)|0)+Math.imul(D,Y)|0,o=o+Math.imul(D,ee)|0,i=i+Math.imul(x,ne)|0,r=(r=r+Math.imul(x,ie)|0)+Math.imul(_,ne)|0,o=o+Math.imul(_,ie)|0,i=i+Math.imul(I,oe)|0,r=(r=r+Math.imul(I,se)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,se)|0,i=i+Math.imul(A,ce)|0,r=(r=r+Math.imul(A,le)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,le)|0,i=i+Math.imul(b,de)|0,r=(r=r+Math.imul(b,he)|0)+Math.imul(v,de)|0,o=o+Math.imul(v,he)|0;var Ce=(l+(i=i+Math.imul(y,fe)|0)|0)+((8191&(r=(r=r+Math.imul(y,pe)|0)+Math.imul(w,fe)|0))<<13)|0;l=((o=o+Math.imul(w,pe)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,i=Math.imul(U,Q),r=(r=Math.imul(U,J))+Math.imul(O,Q)|0,o=Math.imul(O,J),i=i+Math.imul(M,Y)|0,r=(r=r+Math.imul(M,ee)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,ee)|0,i=i+Math.imul(P,ne)|0,r=(r=r+Math.imul(P,ie)|0)+Math.imul(D,ne)|0,o=o+Math.imul(D,ie)|0,i=i+Math.imul(x,oe)|0,r=(r=r+Math.imul(x,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,i=i+Math.imul(I,ce)|0,r=(r=r+Math.imul(I,le)|0)+Math.imul(C,ce)|0,o=o+Math.imul(C,le)|0,i=i+Math.imul(A,de)|0,r=(r=r+Math.imul(A,he)|0)+Math.imul(T,de)|0,o=o+Math.imul(T,he)|0;var Ne=(l+(i=i+Math.imul(b,fe)|0)|0)+((8191&(r=(r=r+Math.imul(b,pe)|0)+Math.imul(v,fe)|0))<<13)|0;l=((o=o+Math.imul(v,pe)|0)+(r>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,i=Math.imul(U,Y),r=(r=Math.imul(U,ee))+Math.imul(O,Y)|0,o=Math.imul(O,ee),i=i+Math.imul(M,ne)|0,r=(r=r+Math.imul(M,ie)|0)+Math.imul(L,ne)|0,o=o+Math.imul(L,ie)|0,i=i+Math.imul(P,oe)|0,r=(r=r+Math.imul(P,se)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,se)|0,i=i+Math.imul(x,ce)|0,r=(r=r+Math.imul(x,le)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,le)|0,i=i+Math.imul(I,de)|0,r=(r=r+Math.imul(I,he)|0)+Math.imul(C,de)|0,o=o+Math.imul(C,he)|0;var xe=(l+(i=i+Math.imul(A,fe)|0)|0)+((8191&(r=(r=r+Math.imul(A,pe)|0)+Math.imul(T,fe)|0))<<13)|0;l=((o=o+Math.imul(T,pe)|0)+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,i=Math.imul(U,ne),r=(r=Math.imul(U,ie))+Math.imul(O,ne)|0,o=Math.imul(O,ie),i=i+Math.imul(M,oe)|0,r=(r=r+Math.imul(M,se)|0)+Math.imul(L,oe)|0,o=o+Math.imul(L,se)|0,i=i+Math.imul(P,ce)|0,r=(r=r+Math.imul(P,le)|0)+Math.imul(D,ce)|0,o=o+Math.imul(D,le)|0,i=i+Math.imul(x,de)|0,r=(r=r+Math.imul(x,he)|0)+Math.imul(_,de)|0,o=o+Math.imul(_,he)|0;var _e=(l+(i=i+Math.imul(I,fe)|0)|0)+((8191&(r=(r=r+Math.imul(I,pe)|0)+Math.imul(C,fe)|0))<<13)|0;l=((o=o+Math.imul(C,pe)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,i=Math.imul(U,oe),r=(r=Math.imul(U,se))+Math.imul(O,oe)|0,o=Math.imul(O,se),i=i+Math.imul(M,ce)|0,r=(r=r+Math.imul(M,le)|0)+Math.imul(L,ce)|0,o=o+Math.imul(L,le)|0,i=i+Math.imul(P,de)|0,r=(r=r+Math.imul(P,he)|0)+Math.imul(D,de)|0,o=o+Math.imul(D,he)|0;var Be=(l+(i=i+Math.imul(x,fe)|0)|0)+((8191&(r=(r=r+Math.imul(x,pe)|0)+Math.imul(_,fe)|0))<<13)|0;l=((o=o+Math.imul(_,pe)|0)+(r>>>13)|0)+(Be>>>26)|0,Be&=67108863,i=Math.imul(U,ce),r=(r=Math.imul(U,le))+Math.imul(O,ce)|0,o=Math.imul(O,le),i=i+Math.imul(M,de)|0,r=(r=r+Math.imul(M,he)|0)+Math.imul(L,de)|0,o=o+Math.imul(L,he)|0;var Pe=(l+(i=i+Math.imul(P,fe)|0)|0)+((8191&(r=(r=r+Math.imul(P,pe)|0)+Math.imul(D,fe)|0))<<13)|0;l=((o=o+Math.imul(D,pe)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,i=Math.imul(U,de),r=(r=Math.imul(U,he))+Math.imul(O,de)|0,o=Math.imul(O,he);var De=(l+(i=i+Math.imul(M,fe)|0)|0)+((8191&(r=(r=r+Math.imul(M,pe)|0)+Math.imul(L,fe)|0))<<13)|0;l=((o=o+Math.imul(L,pe)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863;var Re=(l+(i=Math.imul(U,fe))|0)+((8191&(r=(r=Math.imul(U,pe))+Math.imul(O,fe)|0))<<13)|0;return l=((o=Math.imul(O,pe))+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863,c[0]=me,c[1]=ye,c[2]=we,c[3]=ke,c[4]=be,c[5]=ve,c[6]=Se,c[7]=Ae,c[8]=Te,c[9]=Ee,c[10]=Ie,c[11]=Ce,c[12]=Ne,c[13]=xe,c[14]=_e,c[15]=Be,c[16]=Pe,c[17]=De,c[18]=Re,0!==l&&(c[19]=l,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var i=0,r=0,o=0;o<n.length-1;o++){var s=r;r=0;for(var a=67108863&i,c=Math.min(o,t.length-1),l=Math.max(0,o-e.length+1);l<=c;l++){var u=o-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),r+=(s=(s=s+(d/67108864|0)|0)+(h>>>26)|0)>>>26,s&=67108863}n.words[o]=a,i=s,s=r}return 0!==i?n.words[o]=i:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(p=f),r.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):n<63?f(this,e,t):n<1024?m(this,e,t):y(this,e,t)},r.prototype.mul=function(e){var t=new r(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},r.prototype.mulf=function(e){var t=new r(null);return t.words=new Array(this.length+e.length),y(this,e,t)},r.prototype.imul=function(e){return this.clone().mulTo(e,this)},r.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var i=0,r=0;r<this.length;r++){var o=(0|this.words[r])*e,s=(67108863&o)+(67108863&i);i>>=26,i+=o/67108864|0,i+=s>>>26,this.words[r]=67108863&s}return 0!==i&&(this.words[r]=i,this.length++),t?this.ineg():this},r.prototype.muln=function(e){return this.clone().imuln(e)},r.prototype.sqr=function(){return this.mul(this)},r.prototype.isqr=function(){return this.imul(this.clone())},r.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var i=n/26|0,r=n%26;t[n]=e.words[i]>>>r&1}return t}(e);if(0===t.length)return new r(1);for(var n=this,i=0;i<t.length&&0===t[i];i++,n=n.sqr());if(++i<t.length)for(var o=n.sqr();i<t.length;i++,o=o.sqr())0!==t[i]&&(n=n.mul(o));return n},r.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,i=e%26,r=(e-i)/26,o=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<i;this.words[t]=c|s,s=a>>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t<r;t++)this.words[t]=0;this.length+=r}return this._strip()},r.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},r.prototype.iushrn=function(e,t,i){var r;n("number"==typeof e&&e>=0),r=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=i;if(r-=s,r=Math.max(0,r),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>=r);l--){var d=0|this.words[l];this.words[l]=u<<26-o|d>>>o,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},r.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},r.prototype.shln=function(e){return this.clone().ishln(e)},r.prototype.ushln=function(e){return this.clone().iushln(e)},r.prototype.shrn=function(e){return this.clone().ishrn(e)},r.prototype.ushrn=function(e){return this.clone().iushrn(e)},r.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<<t;return!(this.length<=i||!(this.words[i]&r))},r.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<<t;this.words[this.length-1]&=r}return this._strip()},r.prototype.maskn=function(e){return this.clone().imaskn(e)},r.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)},r.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},r.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()},r.prototype.addn=function(e){return this.clone().iaddn(e)},r.prototype.subn=function(e){return this.clone().isubn(e)},r.prototype.iabs=function(){return this.negative=0,this},r.prototype.abs=function(){return this.clone().iabs()},r.prototype._ishlnsubmul=function(e,t,i){var r,o,s=e.length+i;this._expand(s);var a=0;for(r=0;r<e.length;r++){o=(0|this.words[r+i])+a;var c=(0|e.words[r])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[r+i]=67108863&o}for(;r<this.length-i;r++)a=(o=(0|this.words[r+i])+a)>>26,this.words[r+i]=67108863&o;if(0===a)return this._strip();for(n(-1===a),a=0,r=0;r<this.length;r++)a=(o=-(0|this.words[r])+a)>>26,this.words[r]=67108863&o;return this.negative=1,this._strip()},r.prototype._wordDiv=function(e,t){var n=(this.length,e.length),i=this.clone(),o=e,s=0|o.words[o.length-1];0!=(n=26-this._countBits(s))&&(o=o.ushln(n),i.iushln(n),s=0|o.words[o.length-1]);var a,c=i.length-o.length;if("mod"!==t){(a=new r(null)).length=c+1,a.words=new Array(a.length);for(var l=0;l<a.length;l++)a.words[l]=0}var u=i.clone()._ishlnsubmul(o,1,c);0===u.negative&&(i=u,a&&(a.words[c]=1));for(var d=c-1;d>=0;d--){var h=67108864*(0|i.words[o.length+d])+(0|i.words[o.length+d-1]);for(h=Math.min(h/s|0,67108863),i._ishlnsubmul(o,h,d);0!==i.negative;)h--,i.negative=0,i._ishlnsubmul(o,1,d),i.isZero()||(i.negative^=1);a&&(a.words[d]=h)}return a&&a._strip(),i._strip(),"div"!==t&&0!==n&&i.iushrn(n),{div:a||null,mod:i}},r.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new r(0),mod:new r(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(o=a.div.neg()),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:o,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(o=a.div.neg()),{div:o,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new r(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new r(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new r(this.modrn(e.words[0]))}:this._wordDiv(e,t);var o,s,a},r.prototype.div=function(e){return this.divmod(e,"div",!1).div},r.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},r.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},r.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,i=e.ushrn(1),r=e.andln(1),o=n.cmp(i);return o<0||1===r&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},r.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=(1<<26)%e,r=0,o=this.length-1;o>=0;o--)r=(i*r+(0|this.words[o]))%e;return t?-r:r},r.prototype.modn=function(e){return this.modrn(e)},r.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=0,r=this.length-1;r>=0;r--){var o=(0|this.words[r])+67108864*i;this.words[r]=o/e|0,i=o%e}return this._strip(),t?this.ineg():this},r.prototype.divn=function(e){return this.clone().idivn(e)},r.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o=new r(1),s=new r(0),a=new r(0),c=new r(1),l=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++l;for(var u=i.clone(),d=t.clone();!t.isZero();){for(var h=0,g=1;0===(t.words[0]&g)&&h<26;++h,g<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(u),s.isub(d)),o.iushrn(1),s.iushrn(1);for(var f=0,p=1;0===(i.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(i.iushrn(f);f-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(d)),a.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),o.isub(a),s.isub(c)):(i.isub(t),a.isub(o),c.isub(s))}return{a:a,b:c,gcd:i.iushln(l)}},r.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o,s=new r(1),a=new r(0),c=i.clone();t.cmpn(1)>0&&i.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===(i.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(i.iushrn(d);d-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(a)):(i.isub(t),a.isub(s))}return(o=0===t.cmpn(1)?s:a).cmpn(0)<0&&o.iadd(e),o},r.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 i=0;t.isEven()&&n.isEven();i++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var r=t.cmp(n);if(r<0){var o=t;t=n,n=o}else if(0===r||0===n.cmpn(1))break;t.isub(n)}return n.iushln(i)},r.prototype.invm=function(e){return this.egcd(e).a.umod(e)},r.prototype.isEven=function(){return!(1&this.words[0])},r.prototype.isOdd=function(){return!(1&~this.words[0])},r.prototype.andln=function(e){return this.words[0]&e},r.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<<t;if(this.length<=i)return this._expand(i+1),this.words[i]|=r,this;for(var o=r,s=i;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},r.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},r.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this._strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:r<e?-1:1}return 0!==this.negative?0|-t:t},r.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},r.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 i=0|this.words[n],r=0|e.words[n];if(i!==r){i<r?t=-1:i>r&&(t=1);break}}return t},r.prototype.gtn=function(e){return 1===this.cmpn(e)},r.prototype.gt=function(e){return 1===this.cmp(e)},r.prototype.gten=function(e){return this.cmpn(e)>=0},r.prototype.gte=function(e){return this.cmp(e)>=0},r.prototype.ltn=function(e){return-1===this.cmpn(e)},r.prototype.lt=function(e){return-1===this.cmp(e)},r.prototype.lten=function(e){return this.cmpn(e)<=0},r.prototype.lte=function(e){return this.cmp(e)<=0},r.prototype.eqn=function(e){return 0===this.cmpn(e)},r.prototype.eq=function(e){return 0===this.cmp(e)},r.red=function(e){return new T(e)},r.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)},r.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},r.prototype._forceRed=function(e){return this.red=e,this},r.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},r.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},r.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},r.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},r.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},r.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},r.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},r.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},r.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},r.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},r.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},r.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},r.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},r.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function k(e,t){this.name=e,this.p=new r(t,16),this.n=this.p.bitLength(),this.k=new r(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){k.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){k.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function S(){k.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function A(){k.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function T(e){if("string"==typeof e){var t=r._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){T.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new r(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}k.prototype._tmp=function(){var e=new r(null);return e.words=new Array(Math.ceil(this.n/13)),e},k.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var i=t<this.n?-1:n.ucmp(this.p);return 0===i?(n.words[0]=0,n.length=1):i>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},k.prototype.split=function(e,t){e.iushrn(this.n,0,t)},k.prototype.imulK=function(e){return e.imul(this.k)},i(b,k),b.prototype.split=function(e,t){for(var n=4194303,i=Math.min(e.length,9),r=0;r<i;r++)t.words[r]=e.words[r];if(t.length=i,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&n,r=10;r<e.length;r++){var s=0|e.words[r];e.words[r-10]=(s&n)<<4|o>>>22,o=s}o>>>=22,e.words[r-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},b.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var i=0|e.words[n];t+=977*i,e.words[n]=67108863&t,t=64*i+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},i(v,k),i(S,k),i(A,k),A.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var i=19*(0|e.words[n])+t,r=67108863&i;i>>>=26,e.words[n]=r,t=i}return 0!==t&&(e.words[e.length++]=t),e},r._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new b;else if("p224"===e)t=new v;else if("p192"===e)t=new S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new A}return w[e]=t,t},T.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},T.prototype._verify2=function(e,t){n(0===(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},T.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},T.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},T.prototype.add=function(e,t){this._verify2(e,t);var n=e.add(t);return n.cmp(this.m)>=0&&n.isub(this.m),n._forceRed(this)},T.prototype.iadd=function(e,t){this._verify2(e,t);var n=e.iadd(t);return n.cmp(this.m)>=0&&n.isub(this.m),n},T.prototype.sub=function(e,t){this._verify2(e,t);var n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n._forceRed(this)},T.prototype.isub=function(e,t){this._verify2(e,t);var n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n},T.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},T.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},T.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},T.prototype.isqr=function(e){return this.imul(e,e.clone())},T.prototype.sqr=function(e){return this.mul(e,e)},T.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new r(1)).iushrn(2);return this.pow(e,i)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);n(!o.isZero());var a=new r(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new r(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,o),h=this.pow(e,o.addn(1).iushrn(1)),g=this.pow(e,o),f=s;0!==g.cmp(a);){for(var p=g,m=0;0!==p.cmp(a);m++)p=p.redSqr();n(m<f);var y=this.pow(d,new r(1).iushln(f-m-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),f=m}return h},T.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},T.prototype.pow=function(e,t){if(t.isZero())return new r(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new r(1).toRed(this),n[1]=e;for(var i=2;i<n.length;i++)n[i]=this.mul(n[i-1],e);var o=n[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),i=t.length-1;i>=0;i--){for(var l=t.words[i],u=c-1;u>=0;u--){var d=l>>u&1;o!==n[0]&&(o=this.sqr(o)),0!==d||0!==s?(s<<=1,s|=d,(4===++a||0===i&&0===u)&&(o=this.mul(o,n[s]),a=0,s=0)):a=0}c=26}return o},T.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},T.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},r.mont=function(e){return new E(e)},i(E,T),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var n=e.imul(t),i=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=n.isub(i).iushrn(this.shift),o=r;return r.cmp(this.m)>=0?o=r.isub(this.m):r.cmpn(0)<0&&(o=r.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new r(0)._forceRed(this);var n=e.mul(t),i=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=n.isub(i).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(rm,sm)),rm.exports}var cm,lm,um,dm,hm,gm=Tl(am()),fm={exports:{}};function pm(){return cm||(cm=1,function(e,t){var n=xg(),i=n.Buffer;function r(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return i(e,t,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(r(n,t),t.Buffer=o),r(i,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(fm,fm.exports)),fm.exports}var mm=function(){if(hm)return dm;hm=1;var e=function(){if(um)return lm;um=1;var e=pm().Buffer;return lm=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),i=0;i<n.length;i++)n[i]=255;for(var r=0;r<t.length;r++){var o=t.charAt(r),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=r}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 i=0,r=0,o=0;t[i]===c;)r++,i++;for(var s=(t.length-i)*l+1>>>0,u=new Uint8Array(s);i<t.length;){var d=t.charCodeAt(i);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,f=s-1;(0!==h||g<o)&&-1!==f;f--,g++)h+=a*u[f]>>>0,u[f]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");o=g,i++}for(var p=s-o;p!==s&&0===u[p];)p++;var m=e.allocUnsafe(r+(s-p));m.fill(0,0,r);for(var y=r;p!==s;)m[y++]=u[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var i=0,r=0,o=0,s=n.length;o!==s&&0===n[o];)o++,i++;for(var l=(s-o)*u+1>>>0,d=new Uint8Array(l);o!==s;){for(var h=n[o],g=0,f=l-1;(0!==h||g<r)&&-1!==f;f--,g++)h+=256*d[f]>>>0,d[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");r=g,o++}for(var p=l-r;p!==l&&0===d[p];)p++;for(var m=c.repeat(i);p<l;++p)m+=t.charAt(d[p]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},lm}();return dm=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}(),ym=Tl(mm);const wm=Df;var km,bm,vm,Sm,Am={};function Tm(){if(Sm)return vm;Sm=1;var e=function(){if(bm)return km;bm=1;var e=pm().Buffer;return km=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),i=0;i<n.length;i++)n[i]=255;for(var r=0;r<t.length;r++){var o=t.charAt(r),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=r}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 i=0,r=0,o=0;t[i]===c;)r++,i++;for(var s=(t.length-i)*l+1>>>0,u=new Uint8Array(s);i<t.length;){var d=t.charCodeAt(i);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,f=s-1;(0!==h||g<o)&&-1!==f;f--,g++)h+=a*u[f]>>>0,u[f]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");o=g,i++}for(var p=s-o;p!==s&&0===u[p];)p++;var m=e.allocUnsafe(r+(s-p));m.fill(0,0,r);for(var y=r;p!==s;)m[y++]=u[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var i=0,r=0,o=0,s=n.length;o!==s&&0===n[o];)o++,i++;for(var l=(s-o)*u+1>>>0,d=new Uint8Array(l);o!==s;){for(var h=n[o],g=0,f=l-1;(0!==h||g<r)&&-1!==f;f--,g++)h+=256*d[f]>>>0,d[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");r=g,o++}for(var p=l-r;p!==l&&0===d[p];)p++;for(var m=c.repeat(i);p<l;++p)m+=t.charAt(d[p]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},km}();return vm=e("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}function Em(e,t,n){return t<=e&&e<=n}function Im(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function Cm(e){this.tokens=[].slice.call(e)}Cm.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 Nm=-1;function xm(e,t){if(e)throw TypeError("Decoder error");return t||65533}var _m="utf-8";function Bm(e,t){if(!(this instanceof Bm))return new Bm(e,t);if((e=void 0!==e?String(e).toLowerCase():_m)!==_m)throw new Error("Encoding not supported. Only utf-8 is supported");t=Im(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 Pm(e,t){if(!(this instanceof Pm))return new Pm(e,t);if((e=void 0!==e?String(e).toLowerCase():_m)!==_m)throw new Error("Encoding not supported. Only utf-8 is supported");t=Im(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Dm(e){var t=e.fatal,n=0,i=0,r=0,o=128,s=191;this.handler=function(e,a){if(-1===a&&0!==r)return r=0,xm(t);if(-1===a)return Nm;if(0===r){if(Em(a,0,127))return a;if(Em(a,194,223))r=1,n=a-192;else if(Em(a,224,239))224===a&&(o=160),237===a&&(s=159),r=2,n=a-224;else{if(!Em(a,240,244))return xm(t);240===a&&(o=144),244===a&&(s=143),r=3,n=a-240}return n<<=6*r,null}if(!Em(a,o,s))return n=r=i=0,o=128,s=191,e.prepend(a),xm(t);if(o=128,s=191,n+=a-128<<6*(r-(i+=1)),i!==r)return null;var c=n;return n=r=i=0,c}}function Rm(e){e.fatal,this.handler=function(e,t){if(-1===t)return Nm;if(Em(t,0,127))return t;var n,i;Em(t,128,2047)?(n=1,i=192):Em(t,2048,65535)?(n=2,i=224):Em(t,65536,1114111)&&(n=3,i=240);for(var r=[(t>>6*n)+i];n>0;){var o=t>>6*(n-1);r.push(128|63&o),n-=1}return r}}Bm.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=Im(t),this._streaming||(this._decoder=new Dm({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var i,r=new Cm(n),o=[];!r.endOfStream()&&(i=this._decoder.handler(r,r.read()))!==Nm;)null!==i&&(Array.isArray(i)?o.push.apply(o,i):o.push(i));if(!this._streaming){do{if((i=this._decoder.handler(r,r.read()))===Nm)break;null!==i&&(Array.isArray(i)?o.push.apply(o,i):o.push(i))}while(!r.endOfStream());this._decoder=null}return o.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===o[0]?(this._BOMseen=!0,o.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var i=e[n];i<=65535?t+=String.fromCharCode(i):(i-=65536,t+=String.fromCharCode(55296+(i>>10),56320+(1023&i)))}return t}(o)}},Pm.prototype={encode:function(e,t){e=e?String(e):"",t=Im(t),this._streaming||(this._encoder=new Rm(this._options)),this._streaming=Boolean(t.stream);for(var n,i=[],r=new Cm(function(e){for(var t=String(e),n=t.length,i=0,r=[];i<n;){var o=t.charCodeAt(i);if(o<55296||o>57343)r.push(o);else if(56320<=o&&o<=57343)r.push(65533);else if(55296<=o&&o<=56319)if(i===n-1)r.push(65533);else{var s=e.charCodeAt(i+1);if(56320<=s&&s<=57343){var a=1023&o,c=1023&s;r.push(65536+(a<<10)+c),i+=1}else r.push(65533)}i+=1}return r}(e));!r.endOfStream()&&(n=this._encoder.handler(r,r.read()))!==Nm;)Array.isArray(n)?i.push.apply(i,n):i.push(n);if(!this._streaming){for(;(n=this._encoder.handler(r,r.read()))!==Nm;)Array.isArray(n)?i.push.apply(i,n):i.push(n);this._encoder=null}return new Uint8Array(i)}};var Mm,Lm=El(Object.freeze({__proto__:null,TextDecoder:Bm,TextEncoder:Pm}));var Fm,Um=function(){if(Mm)return Am;Mm=1;var e=Am&&Am.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[n]}})}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),t=Am&&Am.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Am&&Am.__decorate||function(e,t,n,i){var r,o=arguments.length,s=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,i);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,n,s):r(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},i=Am&&Am.__importStar||function(n){if(n&&n.__esModule)return n;var i={};if(null!=n)for(var r in n)"default"!==r&&Object.hasOwnProperty.call(n,r)&&e(i,n,r);return t(i,n),i},r=Am&&Am.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Am,"__esModule",{value:!0}),Am.deserializeUnchecked=Am.deserialize=Am.serialize=Am.BinaryReader=Am.BinaryWriter=Am.BorshError=Am.baseDecode=Am.baseEncode=void 0;const o=r(am()),s=r(Tm()),a=i(Lm),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Am.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},Am.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(".")}}Am.BorshError=u;class d{constructor(){this.buf=Buffer.alloc(l),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(l)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(l)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function h(e,t,n){const i=n.value;n.value=function(...e){try{return i.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}}}Am.BinaryWriter=d;class g{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new o.default(e,"le")}readU128(){const e=this.readBuffer(16);return new o.default(e,"le")}readU256(){const e=this.readBuffer(32);return new o.default(e,"le")}readU512(){const e=this.readBuffer(64);return new o.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new u(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new u(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let i=0;i<t;++i)n.push(e());return n}}function f(e){return e.charAt(0).toUpperCase()+e.slice(1)}function p(e,t,n,i,r){try{if("string"==typeof i)r[`write${f(i)}`](n);else if(i instanceof Array)if("number"==typeof i[0]){if(n.length!==i[0])throw new u(`Expecting byte array of length ${i[0]}, but got ${n.length} bytes`);r.writeFixedArray(n)}else if(2===i.length&&"number"==typeof i[1]){if(n.length!==i[1])throw new u(`Expecting byte array of length ${i[1]}, but got ${n.length} bytes`);for(let t=0;t<i[1];t++)p(e,null,n[t],i[0],r)}else r.writeArray(n,n=>{p(e,t,n,i[0],r)});else if(void 0!==i.kind)switch(i.kind){case"option":null==n?r.writeU8(0):(r.writeU8(1),p(e,t,n,i.type,r));break;case"map":r.writeU32(n.size),n.forEach((n,o)=>{p(e,t,o,i.key,r),p(e,t,n,i.value,r)});break;default:throw new u(`FieldType ${i} unrecognized`)}else m(e,n,r)}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 i=e.get(t.constructor);if(!i)throw new u(`Class ${t.constructor.name} is missing in schema`);if("struct"===i.kind)i.fields.map(([i,r])=>{p(e,i,t[i],r,n)});else{if("enum"!==i.kind)throw new u(`Unexpected schema kind: ${i.kind} for ${t.constructor.name}`);{const r=t[i.field];for(let o=0;o<i.values.length;++o){const[s,a]=i.values[o];if(s===r){n.writeU8(o),p(e,s,t[s],a,n);break}}}}}function y(e,t,n,i){try{if("string"==typeof n)return i[`read${f(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return i.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let r=0;r<n[1];r++)t.push(y(e,null,n[0],i));return t}return i.readArray(()=>y(e,t,n[0],i))}if("option"===n.kind){return i.readU8()?y(e,t,n.type,i):void 0}if("map"===n.kind){let r=new Map;const o=i.readU32();for(let s=0;s<o;s++){const o=y(e,t,n.key,i),s=y(e,t,n.value,i);r.set(o,s)}return r}return w(e,n,i)}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 i=e.get(t);if(!i)throw new u(`Class ${t.name} is missing in schema`);if("struct"===i.kind){const i={};for(const[r,o]of e.get(t).fields)i[r]=y(e,r,o,n);return new t(i)}if("enum"===i.kind){const r=n.readU8();if(r>=i.values.length)throw new u(`Enum index: ${r} is out of range`);const[o,s]=i.values[r],a=y(e,o,s,n);return new t({[o]:a})}throw new u(`Unexpected schema kind: ${i.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),Am.BinaryReader=g,Am.serialize=function(e,t,n=d){const i=new n;return m(e,t,i),i.toArray()},Am.deserialize=function(e,t,n,i=g){const r=new i(n),o=w(e,t,r);if(r.offset<n.length)throw new u(`Unexpected ${n.length-r.offset} bytes after deserialized data`);return o},Am.deserializeUnchecked=function(e,t,n,i=g){return w(e,t,new i(n))},Am}(),Om={};var $m=function(){if(Fm)return Om;Fm=1,Object.defineProperty(Om,"__esModule",{value:!0}),Om.s16=Om.s8=Om.nu64be=Om.u48be=Om.u40be=Om.u32be=Om.u24be=Om.u16be=Om.nu64=Om.u48=Om.u40=Om.u32=Om.u24=Om.u16=Om.u8=Om.offset=Om.greedy=Om.Constant=Om.UTF8=Om.CString=Om.Blob=Om.Boolean=Om.BitField=Om.BitStructure=Om.VariantLayout=Om.Union=Om.UnionLayoutDiscriminator=Om.UnionDiscriminator=Om.Structure=Om.Sequence=Om.DoubleBE=Om.Double=Om.FloatBE=Om.Float=Om.NearInt64BE=Om.NearInt64=Om.NearUInt64BE=Om.NearUInt64=Om.IntBE=Om.Int=Om.UIntBE=Om.UInt=Om.OffsetLayout=Om.GreedyCount=Om.ExternalLayout=Om.bindConstructorLayout=Om.nameWithProperty=Om.Layout=Om.uint8ArrayToBuffer=Om.checkUint8Array=void 0,Om.constant=Om.utf8=Om.cstr=Om.blob=Om.unionLayoutDiscriminator=Om.union=Om.seq=Om.bits=Om.struct=Om.f64be=Om.f64=Om.f32be=Om.f32=Om.ns64be=Om.s48be=Om.s40be=Om.s32be=Om.s24be=Om.s16be=Om.ns64=Om.s48=Om.s40=Om.s32=Om.s24=void 0;const e=xg();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)}Om.checkUint8Array=t,Om.uint8ArrayToBuffer=n;let i=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 r(e,t){return t.property?e+"["+t.property+"]":e}Om.Layout=i,Om.nameWithProperty=r,Om.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 i))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class o extends i{isCount(){throw new Error("ExternalLayout is abstract")}}Om.ExternalLayout=o;class s extends o{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const i=e.length-n;return Math.floor(i/this.elementSpan)}encode(e,t,n){return 0}}Om.GreedyCount=s;class a extends o{constructor(e,t=0,n){if(!(e instanceof i))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)}}Om.OffsetLayout=a;class c extends i{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,i=0){return n(t).writeUIntLE(e,i,this.span),this.span}}Om.UInt=c;class l extends i{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,i=0){return n(t).writeUIntBE(e,i,this.span),this.span}}Om.UIntBE=l;class u extends i{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,i=0){return n(t).writeIntLE(e,i,this.span),this.span}}Om.Int=u;class d extends i{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,i=0){return n(t).writeIntBE(e,i,this.span),this.span}}Om.IntBE=d;const h=Math.pow(2,32);function g(e){const t=Math.floor(e/h);return{hi32:t,lo32:e-t*h}}function f(e,t){return e*h+t}class p extends i{constructor(e){super(8,e)}decode(e,t=0){const i=n(e),r=i.readUInt32LE(t);return f(i.readUInt32LE(t+4),r)}encode(e,t,i=0){const r=g(e),o=n(t);return o.writeUInt32LE(r.lo32,i),o.writeUInt32LE(r.hi32,i+4),8}}Om.NearUInt64=p;class m extends i{constructor(e){super(8,e)}decode(e,t=0){const i=n(e);return f(i.readUInt32BE(t),i.readUInt32BE(t+4))}encode(e,t,i=0){const r=g(e),o=n(t);return o.writeUInt32BE(r.hi32,i),o.writeUInt32BE(r.lo32,i+4),8}}Om.NearUInt64BE=m;class y extends i{constructor(e){super(8,e)}decode(e,t=0){const i=n(e),r=i.readUInt32LE(t);return f(i.readInt32LE(t+4),r)}encode(e,t,i=0){const r=g(e),o=n(t);return o.writeUInt32LE(r.lo32,i),o.writeInt32LE(r.hi32,i+4),8}}Om.NearInt64=y;class w extends i{constructor(e){super(8,e)}decode(e,t=0){const i=n(e);return f(i.readInt32BE(t),i.readUInt32BE(t+4))}encode(e,t,i=0){const r=g(e),o=n(t);return o.writeInt32BE(r.hi32,i),o.writeUInt32BE(r.lo32,i+4),8}}Om.NearInt64BE=w;class k extends i{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatLE(t)}encode(e,t,i=0){return n(t).writeFloatLE(e,i),4}}Om.Float=k;class b extends i{constructor(e){super(4,e)}decode(e,t=0){return n(e).readFloatBE(t)}encode(e,t,i=0){return n(t).writeFloatBE(e,i),4}}Om.FloatBE=b;class v extends i{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleLE(t)}encode(e,t,i=0){return n(t).writeDoubleLE(e,i),8}}Om.Double=v;class S extends i{constructor(e){super(8,e)}decode(e,t=0){return n(e).readDoubleBE(t)}encode(e,t,i=0){return n(t).writeDoubleBE(e,i),8}}Om.DoubleBE=S;class A extends i{constructor(e,t,n){if(!(e instanceof i))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof o&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let r=-1;!(t instanceof o)&&0<e.span&&(r=t*e.span),super(r,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,i=this.count;if(i instanceof o&&(i=i.decode(e,t)),0<this.elementLayout.span)n=i*this.elementLayout.span;else{let r=0;for(;r<i;)n+=this.elementLayout.getSpan(e,t+n),++r}return n}decode(e,t=0){const n=[];let i=0,r=this.count;for(r instanceof o&&(r=r.decode(e,t));i<r;)n.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),i+=1;return n}encode(e,t,n=0){const i=this.elementLayout,r=e.reduce((e,r)=>e+i.encode(r,t,n+e),0);return this.count instanceof o&&this.count.encode(e.length,t,n),r}}Om.Sequence=A;class T extends i{constructor(e,t,n){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof i,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof t&&void 0===n&&(n=t,t=void 0);for(const t of e)if(0>t.span&&void 0===t.property)throw new Error("fields cannot contain unnamed variable-length layout");let r=-1;try{r=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(r,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,i)=>{const r=i.getSpan(e,t);return t+=r,n+r},0)}catch(e){throw new RangeError("indeterminate span")}return n}decode(e,n=0){t(e);const i=this.makeDestinationObject();for(const t of this.fields)if(void 0!==t.property&&(i[t.property]=t.decode(e,n)),n+=t.getSpan(e,n),this.decodePrefixes&&e.length===n)break;return i}encode(e,t,n=0){const i=n;let r=0,o=0;for(const i of this.fields){let s=i.span;if(o=0<s?s:0,void 0!==i.property){const r=e[i.property];void 0!==r&&(o=i.encode(r,t,n),0>s&&(s=i.getSpan(t,n)))}r=n,n+=s}return r+o-i}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)}}}Om.Structure=T;class E{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,n){throw new Error("UnionDiscriminator is abstract")}}Om.UnionDiscriminator=E;class I extends E{constructor(e,t){if(!(e instanceof o&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}Om.UnionLayoutDiscriminator=I;class C extends i{constructor(e,t,n){let r;if(e instanceof c||e instanceof l)r=new I(new a(e));else if(e instanceof o&&e.isCount())r=new I(e);else{if(!(e instanceof E))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");r=e}if(void 0===t&&(t=null),!(null===t||t instanceof i))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+=r.layout.span)),super(s,n),this.discriminator=r,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 i=this.discriminator,r=i.decode(e,t),o=this.registry[r];if(void 0===o){const o=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=i.layout.span),n=this.makeDestinationObject(),n[i.property]=r,n[o.property]=o.decode(e,t+s)}else n=o.decode(e,t);return n}encode(e,t,n=0){const i=this.getSourceVariant(e);if(void 0===i){const i=this.discriminator,r=this.defaultLayout;let o=0;return this.usesPrefixDiscriminator&&(o=i.layout.span),i.encode(e[i.property],t,n),o+r.encode(e[r.property],t,n+o)}return i.encode(e,t,n)}addVariant(e,t,n){const i=new N(this,e,t,n);return this.registry[e]=i,i}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}Om.Union=C;class N extends i{constructor(e,t,n,r){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===r&&(r=n,n=null),n){if(!(n instanceof i))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 r)throw new TypeError("variant must have a String property")}let o=e.span;0>e.span&&(o=n?n.span:0,0<=o&&e.usesPrefixDiscriminator&&(o+=e.discriminator.layout.span)),super(o,r),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 i=0;return this.layout&&(i=this.layout.getSpan(e,t+n)),n+i}decode(e,t=0){const n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let i=0;return this.union.usesPrefixDiscriminator&&(i=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+i):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let i=0;if(this.union.usesPrefixDiscriminator&&(i=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 r=i;if(this.layout&&(this.layout.encode(e[this.property],t,n+i),r+=this.layout.getSpan(t,n+i),0<=this.union.span&&r>this.union.span))throw new Error("encoded variant overruns containing union");return r}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function x(e){return 0>e&&(e+=4294967296),e}Om.VariantLayout=N;class _ extends i{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 i=0;this._packedSetValue=function(e){return i=x(e),this},this._packedGetValue=function(){return i}}decode(e,t=0){const n=this.makeDestinationObject(),i=this.word.decode(e,t);this._packedSetValue(i);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const i=this.word.decode(t,n);this._packedSetValue(i);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new B(this,e,t);return this.fields.push(n),n}addBoolean(e){const t=new P(this,e);return this.fields.push(t),t}fieldFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}}Om.BitStructure=_;class B{constructor(e,t,n){if(!(e instanceof _))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const i=8*e.span,r=e.fields.reduce((e,t)=>e+t.bits,0);if(t+r>i)throw new Error("bits too long for span remainder ("+(i-r)+" of "+i+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=r,this.container.msb&&(this.start=i-r-t),this.wordMask=x(this.valueMask<<this.start),this.property=n}decode(e,t){return x(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==x(e&this.valueMask))throw new TypeError(r("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=x(e<<this.start);this.container._packedSetValue(x(t&~this.wordMask)|n)}}Om.BitField=B;class P extends B{constructor(e,t){super(e,1,t)}decode(e,t){return!!super.decode(e,t)}encode(e){"boolean"==typeof e&&(e=+e),super.encode(e)}}Om.Boolean=P;class D extends i{constructor(e,t){if(!(e instanceof o&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof o||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let i=this.span;return 0>i&&(i=this.length.decode(e,t)),n(e).slice(t,t+i)}encode(e,t,i){let s=this.length;if(this.length instanceof o&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(r("Blob.encode",this)+" requires (length "+s+") Uint8Array as src");if(i+s>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),i,s,"hex"),this.length instanceof o&&this.length.encode(s,t,i),s}}Om.Blob=D;class R extends i{constructor(e){super(-1,e)}getSpan(e,n=0){t(e);let i=n;for(;i<e.length&&0!==e[i];)i+=1;return 1+i-n}decode(e,t=0){const i=this.getSpan(e,t);return n(e).slice(t,t+i-1).toString("utf-8")}encode(t,i,r=0){"string"!=typeof t&&(t=String(t));const o=e.Buffer.from(t,"utf8"),s=o.length;if(r+s>i.length)throw new RangeError("encoding overruns Buffer");const a=n(i);return o.copy(a,r),a[r+s]=0,s+1}}Om.CString=R;class M extends i{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 i=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<i)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+i).toString("utf-8")}encode(t,i,r=0){"string"!=typeof t&&(t=String(t));const o=e.Buffer.from(t,"utf8"),s=o.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(r+s>i.length)throw new RangeError("encoding overruns Buffer");return o.copy(n(i),r),s}}Om.UTF8=M;class L extends i{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,n){return 0}}return Om.Constant=L,Om.greedy=(e,t)=>new s(e,t),Om.offset=(e,t,n)=>new a(e,t,n),Om.u8=e=>new c(1,e),Om.u16=e=>new c(2,e),Om.u24=e=>new c(3,e),Om.u32=e=>new c(4,e),Om.u40=e=>new c(5,e),Om.u48=e=>new c(6,e),Om.nu64=e=>new p(e),Om.u16be=e=>new l(2,e),Om.u24be=e=>new l(3,e),Om.u32be=e=>new l(4,e),Om.u40be=e=>new l(5,e),Om.u48be=e=>new l(6,e),Om.nu64be=e=>new m(e),Om.s8=e=>new u(1,e),Om.s16=e=>new u(2,e),Om.s24=e=>new u(3,e),Om.s32=e=>new u(4,e),Om.s40=e=>new u(5,e),Om.s48=e=>new u(6,e),Om.ns64=e=>new y(e),Om.s16be=e=>new d(2,e),Om.s24be=e=>new d(3,e),Om.s32be=e=>new d(4,e),Om.s40be=e=>new d(5,e),Om.s48be=e=>new d(6,e),Om.ns64be=e=>new w(e),Om.f32=e=>new k(e),Om.f32be=e=>new b(e),Om.f64=e=>new v(e),Om.f64be=e=>new S(e),Om.struct=(e,t,n)=>new T(e,t,n),Om.bits=(e,t,n)=>new _(e,t,n),Om.seq=(e,t,n)=>new A(e,t,n),Om.union=(e,t,n)=>new C(e,t,n),Om.unionLayoutDiscriminator=(e,t)=>new I(e,t),Om.blob=(e,t)=>new D(e,t),Om.cstr=e=>new R(e),Om.utf8=(e,t)=>new M(e,t),Om.constant=(e,t)=>new L(e,t),Om}(),qm=1,Km=2,Gm=3,Wm=4,Hm=5,zm=6,jm=7,Vm=8,Xm=9,Qm=10,Jm=-32700,Zm=-32603,Ym=-32602,ey=-32601,ty=-32600,ny=-32016,iy=-32015,ry=-32014,oy=-32013,sy=-32012,ay=-32011,cy=-32010,ly=-32009,uy=-32008,dy=-32007,hy=-32006,gy=-32005,fy=-32004,py=-32003,my=-32002,yy=-32001,wy=28e5,ky=2800001,by=2800002,vy=2800003,Sy=2800004,Ay=2800005,Ty=2800006,Ey=2800007,Iy=2800008,Cy=2800009,Ny=2800010,xy=2800011,_y=323e4,By=32300001,Py=3230002,Dy=3230003,Ry=3230004,My=361e4,Ly=3610001,Fy=3610002,Uy=3610003,Oy=3610004,$y=3610005,qy=3610006,Ky=3610007,Gy=3611e3,Wy=3704e3,Hy=3704001,zy=3704002,jy=3704003,Vy=3704004,Xy=4128e3,Qy=4128001,Jy=4128002,Zy=4615e3,Yy=4615001,ew=4615002,tw=4615003,nw=4615004,iw=4615005,rw=4615006,ow=4615007,sw=4615008,aw=4615009,cw=4615010,lw=4615011,uw=4615012,dw=4615013,hw=4615014,gw=4615015,fw=4615016,pw=4615017,mw=4615018,yw=4615019,ww=4615020,kw=4615021,bw=4615022,vw=4615023,Sw=4615024,Aw=4615025,Tw=4615026,Ew=4615027,Iw=4615028,Cw=4615029,Nw=4615030,xw=4615031,_w=4615032,Bw=4615033,Pw=4615034,Dw=4615035,Rw=4615036,Mw=4615037,Lw=4615038,Fw=4615039,Uw=4615040,Ow=4615041,$w=4615042,qw=4615043,Kw=4615044,Gw=4615045,Ww=4615046,Hw=4615047,zw=4615048,jw=4615049,Vw=4615050,Xw=4615051,Qw=4615052,Jw=4615053,Zw=4615054,Yw=5508e3,ek=5508001,tk=5508002,nk=5508003,ik=5508004,rk=5508005,ok=5508006,sk=5508007,ak=5508008,ck=5508009,lk=5508010,uk=5508011,dk=5663e3,hk=5663001,gk=5663002,fk=5663003,pk=5663004,mk=5663005,yk=5663006,wk=5663007,kk=5663008,bk=5663009,vk=5663010,Sk=5663011,Ak=5663012,Tk=5663013,Ek=5663014,Ik=5663015,Ck=5663016,Nk=5663017,xk=5663018,_k=5663019,Bk=5663020,Pk=705e4,Dk=7050001,Rk=7050002,Mk=7050003,Lk=7050004,Fk=7050005,Uk=7050006,Ok=7050007,$k=7050008,qk=7050009,Kk=7050010,Gk=7050011,Wk=7050012,Hk=7050013,zk=7050014,jk=7050015,Vk=7050016,Xk=7050017,Qk=7050018,Jk=7050019,Zk=7050020,Yk=7050021,eb=7050022,tb=7050023,nb=7050024,ib=7050025,rb=7050026,ob=7050027,sb=7050028,ab=7050029,cb=7050030,lb=7050031,ub=7050032,db=7050033,hb=7050034,gb=7050035,fb=7050036,pb=8078e3,mb=8078001,yb=8078002,wb=8078003,kb=8078004,bb=8078005,vb=8078006,Sb=8078007,Ab=8078008,Tb=8078009,Eb=8078010,Ib=8078011,Cb=8078012,Nb=8078013,xb=8078014,_b=8078015,Bb=8078016,Pb=8078017,Db=8078018,Rb=8078019,Mb=8078020,Lb=8078021,Fb=8078022,Ub=81e5,Ob=8100001,$b=8100002,qb=8100003,Kb=819e4,Gb=8190001,Wb=8190002,Hb=8190003,zb=8190004,jb=99e5,Vb=9900001,Xb=9900002,Qb=9900003,Jb=9900004;function Zb(e){if(Array.isArray(e)){return"%5B"+e.map(Zb).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Yb([e,t]){return`${e}=${Zb(t)}`}var ev={[_y]:"Account not found at address: $address",[Ry]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[Dy]:"Expected decoded account at address: $address",[Py]:"Failed to decode account data at address: $address",[By]:"Accounts not found at addresses: $addresses",[Cy]:"Unable to find a viable program address bump seed.",[by]:"$putativeAddress is not a base58-encoded address.",[wy]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[vy]:"The `CryptoKey` must be an `Ed25519` public key.",[xy]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Iy]:"Invalid seeds; point must fall off the Ed25519 curve.",[Sy]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Ty]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Ey]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Ay]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Ny]:"Program address cannot end with PDA marker.",[ky]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Wm]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[qm]:"The network has progressed past the last block for which this transaction could have been committed.",[pb]:"Codec [$codecDescription] cannot decode empty byte arrays.",[Fb]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[Mb]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[bb]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[vb]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[kb]:"Encoder and decoder must either both be fixed-size or variable-size.",[Ab]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[yb]:"Expected a fixed-size codec, got a variable-size one.",[Nb]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[wb]:"Expected a variable-size codec, got a fixed-size one.",[Rb]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[mb]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[Db]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Tb]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Eb]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[_b]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Sb]:"Expected [$codecDescription] to have $expected items, got $actual.",[Cb]:"Invalid value $value for base $base with alphabet $alphabet.",[Bb]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Ib]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[xb]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[Lb]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[Pb]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[Gy]:"No random values implementation could be found.",[aw]:"instruction requires an uninitialized account",[vw]:"instruction tries to borrow reference for an account which is already borrowed",[Sw]:"instruction left account with an outstanding borrowed reference",[kw]:"program other than the account's owner changed the size of the account data",[iw]:"account data too small for instruction",[bw]:"instruction expected an executable account",[Ww]:"An account does not have enough lamports to be rent-exempt",[zw]:"Program arithmetic overflowed",[Gw]:"Failed to serialize or deserialize account data: $encodedData",[Zw]:"Builtin programs must consume compute units",[_w]:"Cross-program invocation call depth too deep",[Lw]:"Computational budget exceeded",[Tw]:"custom program error: #$code",[pw]:"instruction contains duplicate accounts",[Aw]:"instruction modifications of multiply-passed account differ",[Nw]:"executable accounts must be rent exempt",[Iw]:"instruction changed executable accounts data",[Cw]:"instruction changed the balance of an executable account",[mw]:"instruction changed executable bit of an account",[hw]:"instruction modified data of an account it does not own",[dw]:"instruction spent from the balance of an account it does not own",[Yy]:"generic instruction error",[Vw]:"Provided owner is not allowed",[qw]:"Account is immutable",[Kw]:"Incorrect authority provided",[ow]:"incorrect program id for instruction",[rw]:"insufficient funds for instruction",[nw]:"invalid account data for instruction",[Hw]:"Invalid account owner",[ew]:"invalid program argument",[Ew]:"program returned invalid error code",[tw]:"invalid instruction data",[Mw]:"Failed to reallocate account data",[Rw]:"Provided seeds do not result in a valid address",[Xw]:"Accounts data allocations exceeded the maximum allowed per transaction",[Qw]:"Max accounts exceeded",[Jw]:"Max instruction trace length exceeded",[Dw]:"Length of the seed is too long for address generation",[Bw]:"An account required by the instruction is missing",[sw]:"missing required signature for instruction",[uw]:"instruction illegally modified the program id of an account",[ww]:"insufficient account keys for instruction",[Fw]:"Cross-program invocation with unauthorized signer or writable account",[Uw]:"Failed to create program execution environment",[$w]:"Program failed to compile",[Ow]:"Program failed to complete",[fw]:"instruction modified data of a read-only account",[gw]:"instruction changed the balance of a read-only account",[Pw]:"Cross-program invocation reentrancy not allowed for this instruction",[yw]:"instruction modified rent epoch of an account",[lw]:"sum of account balances before and after instruction do not match",[cw]:"instruction requires an initialized account",[Zy]:"",[xw]:"Unsupported program id",[jw]:"Unsupported sysvar",[Xy]:"The instruction does not have any accounts.",[Qy]:"The instruction does not have any data.",[Jy]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[Hm]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[Km]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[Xb]:"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",[Jb]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[Vb]:"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",[jb]:"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",[Qb]:"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",[Zm]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Ym]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[ty]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[ey]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Jm]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[sy]:"$__serverMessage",[yy]:"$__serverMessage",[fy]:"$__serverMessage",[ry]:"$__serverMessage",[cy]:"$__serverMessage",[ly]:"$__serverMessage",[ny]:"Minimum context slot has not been reached",[gy]:"Node is unhealthy; behind by $numSlotsBehind slots",[uy]:"No snapshot",[my]:"Transaction simulation failed",[dy]:"$__serverMessage",[ay]:"Transaction history is not available from this node",[hy]:"$__serverMessage",[oy]:"Transaction signature length mismatch",[py]:"Transaction signature verification failure",[iy]:"$__serverMessage",[Wy]:"Key pair bytes must be of length 64, got $byteLength.",[Hy]:"Expected private key bytes with length 32. Actual length: $actualLength.",[zy]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[Vy]:"The provided private key does not match the provided public key.",[jy]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[zm]:"Lamports value must be in the range [0, 2e64-1]",[jm]:"`$value` cannot be parsed as a `BigInt`",[Qm]:"$message",[Vm]:"`$value` cannot be parsed as a `Number`",[Gm]:"No nonce account could be found at address `$nonceAccountAddress`",[Kb]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[Wb]:"WebSocket was closed before payload could be added to the send buffer",[Hb]:"WebSocket connection closed",[zb]:"WebSocket failed to connect",[Gb]:"Failed to obtain a subscription id from the server",[qb]:"Could not find an API plan for RPC method: `$method`",[Ub]:"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`.",[$b]:"HTTP error ($statusCode): $message",[Ob]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Yw]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[ek]:"The provided value does not implement the `KeyPairSigner` interface",[nk]:"The provided value does not implement the `MessageModifyingSigner` interface",[ik]:"The provided value does not implement the `MessagePartialSigner` interface",[tk]:"The provided value does not implement any of the `MessageSigner` interfaces",[ok]:"The provided value does not implement the `TransactionModifyingSigner` interface",[sk]:"The provided value does not implement the `TransactionPartialSigner` interface",[ak]:"The provided value does not implement the `TransactionSendingSigner` interface",[rk]:"The provided value does not implement any of the `TransactionSigner` interfaces",[ck]:"More than one `TransactionSendingSigner` was identified.",[lk]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[uk]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Ky]:"Cannot export a non-extractable key.",[Ly]:"No digest implementation could be found.",[My]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[Fy]:"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.",[Uy]:"No signature verification implementation could be found.",[Oy]:"No key generation implementation could be found.",[$y]:"No signing implementation could be found.",[qy]:"No key export implementation could be found.",[Xm]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Vk]:"Transaction processing left an account with an outstanding borrowed reference",[Dk]:"Account in use",[Rk]:"Account loaded twice",[Mk]:"Attempt to debit an account but found no record of a prior credit.",[tb]:"Transaction loads an address table account that doesn't exist",[Ok]:"This transaction has already been processed",[$k]:"Blockhash not found",[qk]:"Loader call chain is too deep",[jk]:"Transactions are currently disabled due to cluster maintenance",[cb]:"Transaction contains a duplicate instruction ($index) that is not allowed",[Fk]:"Insufficient funds for fee",[lb]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[Uk]:"This account may not be used to pay transaction fees",[Gk]:"Transaction contains an invalid account reference",[ib]:"Transaction loads an address table account with invalid data",[rb]:"Transaction address table lookup uses an invalid index",[nb]:"Transaction loads an address table account with an invalid owner",[db]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[Hk]:"This program may not be used for executing instructions",[ob]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Jk]:"Transaction loads a writable account that cannot be written",[ub]:"Transaction exceeded max loaded accounts data size cap",[Kk]:"Transaction requires a fee but has no signature present",[Lk]:"Attempt to load a program that does not exist",[gb]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[hb]:"ResanitizationNeeded",[zk]:"Transaction failed to sanitize accounts offsets correctly",[Wk]:"Transaction did not pass signature verification",[eb]:"Transaction locked too many accounts",[fb]:"Sum of account balances before and after transaction do not match",[Pk]:"The transaction failed with the error `$errorName`",[Qk]:"Transaction version is unsupported",[Yk]:"Transaction would exceed account data limit within the block",[ab]:"Transaction would exceed total account data limit",[Zk]:"Transaction would exceed max account limit within the block",[Xk]:"Transaction would exceed max Block Cost Limit",[sb]:"Transaction would exceed max Vote Cost Limit",[Ik]:"Attempted to sign a transaction with an address that is not a signer for it",[vk]:"Transaction is missing an address at index: $index.",[Ck]:"Transaction has no expected signers therefore it cannot be encoded",[Bk]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[gk]:"Transaction does not have a blockhash lifetime",[fk]:"Transaction is not a durable nonce transaction",[mk]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[yk]:"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",[kk]:"No fee payer set in CompiledTransaction",[wk]:"Could not find program address at index $index",[xk]:"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",[_k]:"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",[Sk]:"Transaction is missing a fee payer.",[Ak]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Ek]:"Transaction first instruction is not advance nonce account instruction.",[Tk]:"Transaction with no instructions cannot be durable nonce transaction.",[dk]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[hk]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Nk]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[bk]:"Transaction is missing signatures for addresses: $addresses.",[pk]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},tv="i",nv="t";function iv(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=ev[e];if(0===n.length)return"";let i;function r(e){if(2===i[nv]){const r=n.slice(i[tv]+1,e);o.push(r in t?`${t[r]}`:`$${r}`)}else 1===i[nv]&&o.push(n.slice(i[tv],e))}const o=[];return n.split("").forEach((e,t)=>{if(0===t)return void(i={[tv]:0,[nv]:"\\"===n[0]?0:"$"===n[0]?2:1});let o;switch(i[nv]){case 0:o={[tv]:t,[nv]:1};break;case 1:"\\"===e?o={[tv]:t,[nv]:0}:"$"===e&&(o={[tv]:t,[nv]:2});break;case 2:"\\"===e?o={[tv]:t,[nv]:0}:"$"===e?o={[tv]:t,[nv]:2}:e.match(/\w/)||(o={[tv]:t,[nv]:1})}o&&(i!==o&&r(t),i=o)}),r(),o.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Yb).join("&");return btoa(t)}(t)}'`),`${n}\``}}var rv=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,i;if(t){const{cause:e,...r}=t;e&&(i={cause:e}),Object.keys(r).length>0&&(n=r)}super(iv(e,n),i),this.context={__code:e,...n},this.name="SolanaError"}};function ov(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function sv(e){return 1!==e?.endian}function av(e){return t={fixedSize:e.size,write(t,n,i){e.range&&function(e,t,n,i){if(i<t||i>n)throw new rv(Ib,{codecDescription:e,max:n,min:t,value:i})}(e.name,e.range[0],e.range[1],t);const r=new ArrayBuffer(e.size);return e.set(new DataView(r),t,sv(e.config)),n.set(new Uint8Array(r),i),i+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 cv(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new rv(pb,{codecDescription:e})}(e.name,t,n),function(e,t,n,i=0){const r=n.length-i;if(r<t)throw new rv(mb,{bytesLength:r,codecDescription:e,expected:t})}(e.name,e.size,t,n);const i=new DataView(function(e,t,n){const i=e.byteOffset+(t??0),r=n??e.byteLength;return e.buffer.slice(i,i+r)}(t,n,e.size));return[e.get(i,sv(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var lv=(e={})=>function(e,t){if(ov(e)!==ov(t))throw new rv(kb);if(ov(e)&&ov(t)&&e.fixedSize!==t.fixedSize)throw new rv(bb,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!ov(e)&&!ov(t)&&e.maxSize!==t.maxSize)throw new rv(vb,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>av({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>cv({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class uv extends TypeError{constructor(e,t){let n;const{message:i,explanation:r,...o}=e,{path:s}=e,a=0===s.length?i:`At path: ${s.join(".")} -- ${i}`;super(r??a),null!=r&&(this.cause=a),Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function dv(e){return"object"==typeof e&&null!=e}function hv(e){return dv(e)&&!Array.isArray(e)}function gv(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function fv(e,t,n,i){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:r,branch:o}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${gv(i)}\``}=e;return{value:i,type:s,refinement:a,key:r[r.length-1],path:r,branch:o,...e,message:c}}function*pv(e,t,n,i){var r;dv(r=e)&&"function"==typeof r[Symbol.iterator]||(e=[e]);for(const r of e){const e=fv(r,t,n,i);e&&(yield e)}}function*mv(e,t,n={}){const{path:i=[],branch:r=[e],coerce:o=!1,mask:s=!1}=n,a={path:i,branch:r,mask:s};o&&(e=t.coercer(e,a));let c="valid";for(const i of t.validator(e,a))i.explanation=n.message,c="not_valid",yield[i,void 0];for(let[l,u,d]of t.entries(e,a)){const t=mv(u,d,{path:void 0===l?i:[...i,l],branch:void 0===l?r:[...r,u],coerce:o,mask:s,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):o&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):dv(e)&&(void 0!==u||l in e)&&(e[l]=u))}if("not_valid"!==c)for(const i of t.refiner(e,a))i.explanation=n.message,c="not_refined",yield[i,void 0];"valid"===c&&(yield[void 0,e])}let yv=class{constructor(e){const{type:t,schema:n,validator:i,refiner:r,coercer:o=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=o,this.validator=i?(e,t)=>pv(i(e,t),t,this,e):()=>[],this.refiner=r?(e,t)=>pv(r(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const i=bv(e,t,{message:n});if(i[0])throw i[0]}(e,this,t)}create(e,t){return wv(e,this,t)}is(e){return kv(e,this)}mask(e,t){return function(e,t,n){const i=bv(e,t,{coerce:!0,mask:!0,message:n});if(i[0])throw i[0];return i[1]}(e,this,t)}validate(e,t={}){return bv(e,this,t)}};function wv(e,t,n){const i=bv(e,t,{coerce:!0,message:n});if(i[0])throw i[0];return i[1]}function kv(e,t){return!bv(e,t)[0]}function bv(e,t,n={}){const i=mv(e,t,n),r=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(i);if(r[0]){return[new uv(r[0],function*(){for(const e of i)e[0]&&(yield e[0])}),void 0]}return[void 0,r[1]]}function vv(e,t){return new yv({type:e,schema:null,validator:t})}function Sv(e){return new yv({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[n,i]of t.entries())yield[n,i,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${gv(e)}`})}function Av(){return vv("boolean",e=>"boolean"==typeof e)}function Tv(e){return vv("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${gv(t)}`)}function Ev(e){const t=gv(e),n=typeof e;return new yv({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${gv(n)}`})}function Iv(e){return new yv({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Cv(){return vv("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${gv(e)}`)}function Nv(e){return new yv({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function xv(e,t){return new yv({type:"record",schema:null,*entries(n){if(dv(n))for(const i in n){const r=n[i];yield[i,i,e],yield[i,r,t]}},validator:e=>hv(e)||`Expected an object, but received: ${gv(e)}`,coercer:e=>hv(e)?{...e}:e})}function _v(){return vv("string",e=>"string"==typeof e||`Expected a string, but received: ${gv(e)}`)}function Bv(e){const t=vv("never",()=>!1);return new yv({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const i=Math.max(e.length,n.length);for(let r=0;r<i;r++)yield[r,n[r],e[r]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${gv(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function Pv(e){const t=Object.keys(e);return new yv({type:"type",schema:e,*entries(n){if(dv(n))for(const i of t)yield[i,n[i],e[i]]},validator:e=>hv(e)||`Expected an object, but received: ${gv(e)}`,coercer:e=>hv(e)?{...e}:e})}function Dv(e){const t=e.map(e=>e.type).join(" | ");return new yv({type:"union",schema:null,coercer(t,n){for(const i of e){const[e,r]=i.validate(t,{coerce:!0,mask:n.mask});if(!e)return r}return t},validator(n,i){const r=[];for(const t of e){const[...e]=mv(n,t,i),[o]=e;if(!o[0])return[];for(const[t]of e)t&&r.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${gv(n)}`,...r]}})}function Rv(){return vv("unknown",()=>!0)}function Mv(e,t,n){return new yv({...e,coercer:(i,r)=>kv(i,t)?e.coercer(n(i,r),r):e.coercer(i,r)})}var Lv,Fv,Uv,Ov;var $v,qv=function(){if(Ov)return Uv;Ov=1;const e=b.v4,t=function(){if(Fv)return Lv;Fv=1;const e=b.v4;return Lv=function(t,n,i,r){if("string"!=typeof t)throw new TypeError(t+" must be a string");const o="number"==typeof(r=r||{}).version?r.version:2;if(1!==o&&2!==o)throw new TypeError(o+" must be 1 or 2");const s={method:t};if(2===o&&(s.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");s.params=n}if(void 0===i){const t="function"==typeof r.generator?r.generator:function(){return e()};s.id=t(s,r)}else 2===o&&null===i?r.notificationIdNull&&(s.id=null):s.id=i;return s}}(),n=function(t,i){if(!(this instanceof n))return new n(t,i);i||(i={}),this.options={reviver:void 0!==i.reviver?i.reviver:null,replacer:void 0!==i.replacer?i.replacer:null,generator:void 0!==i.generator?i.generator:function(){return e()},version:void 0!==i.version?i.version:2,notificationIdNull:"boolean"==typeof i.notificationIdNull&&i.notificationIdNull},this.callServer=t};return Uv=n,n.prototype.request=function(e,n,i,r){const o=this;let s=null;const a=Array.isArray(e)&&"function"==typeof n;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&e&&"object"==typeof e&&"function"==typeof n)r=n,s=e;else{"function"==typeof i&&(r=i,i=void 0);const o="function"==typeof r;try{s=t(e,n,i,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(o)return void r(e);throw e}if(!o)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return void r(e)}return this.callServer(c,function(e,t){o._parseResponse(e,t,r)}),s},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return void n();let i;try{i=JSON.parse(t,this.options.reviver)}catch(e){return void n(e)}if(3!==n.length)n(null,i);else{if(Array.isArray(i)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return void n(null,i.filter(e),i.filter(t))}n(null,i.error,i.result)}},Uv}(),Kv=Tl(qv),Gv={exports:{}};var Wv=($v||($v=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function i(){}function r(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,i,o,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var a=new r(i,o||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new i:delete e._events[t]}function a(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,i,r=[];if(0===this._eventsCount)return r;for(i in e=this._events)t.call(e,i)&&r.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},a.prototype.listeners=function(e){var t=n?n+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,o=i.length,s=new Array(o);r<o;r++)s[r]=i[r].fn;return s},a.prototype.listenerCount=function(e){var t=n?n+e:e,i=this._events[t];return i?i.fn?1:i.length:0},a.prototype.emit=function(e,t,i,r,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,i),!0;case 4:return u.fn.call(u.context,t,i,r),!0;case 5:return u.fn.call(u.context,t,i,r,o),!0;case 6:return u.fn.call(u.context,t,i,r,o,s),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var h,g=u.length;for(l=0;l<g;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),d){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,i);break;case 4:u[l].fn.call(u[l].context,t,i,r);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,i,r){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||r&&!a.once||i&&a.context!==i||s(this,o);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||r&&!a[c].once||i&&a[c].context!==i)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new i,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}(Gv)),Gv.exports),Hv=Tl(Wv),zv=class extends Hv{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 i=n||t;try{this.socket.send(e),i()}catch(e){i(e)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,n){this.socket.addEventListener(e,t,n)}};var jv=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Vv=class extends Hv{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:i=!0,reconnect_interval:r=1e3,max_reconnects:o=5,...s}={},a,c){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=i,this.reconnect_timer_id=void 0,this.reconnect_interval=r,this.max_reconnects=o,this.rest_options=s,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new jv,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,i){return i||"object"!=typeof n||(i=n,n=null),new Promise((r,o)=>{if(!this.ready)return o(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),i,e=>{if(e)return o(e);this.queue[s]={promise:[r,o]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],o(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,i)=>{if(!this.ready)return i(new Error("socket not ready"));const r={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(r),e=>{if(e)return i(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=_g.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:i})=>{this.ready&&setTimeout(()=>this.emit("close",n,i),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,i),1))})}};class Xv extends Yg{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Mg(e);const n=Jg(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 i=this.blockLen,r=new Uint8Array(i);r.set(n.length>i?e.create().update(n).digest():n);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Fg(r)}update(e){return Lg(this),this.iHash.update(e),this}digestInto(e){Lg(this),Rg(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:i,destroyed:r,blockLen:o,outputLen:s}=this;return e.finished=i,e.destroyed=r,e.blockLen=o,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Qv=(e,t,n)=>new Xv(e,t).update(n).digest();Qv.create=(e,t)=>new Xv(e,t);const Jv=(e,t)=>(e+(e>=0?t:-t)/rS)/t;function Zv(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Yv(e,t){const n={};for(let i of Object.keys(t))n[i]=void 0===e[i]?t[i]:e[i];return Ff(n.lowS,"lowS"),Ff(n.prehash,"prehash"),void 0!==n.format&&Zv(n.format),n}class eS extends Error{constructor(e=""){super(e)}}const tS={Err:eS,_tlv:{encode:(e,t)=>{const{Err:n}=tS;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const i=t.length/2,r=Of(i);if(r.length/2&128)throw new n("tlv.encode: long form length too big");const o=i>127?Of(r.length/2|128):"";return Of(e)+o+r+t},decode(e,t){const{Err:n}=tS;let i=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new n("tlv.decode: wrong tlv");const r=t[i++];let o=0;if(!!(128&r)){const e=127&r;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(i,i+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)o=o<<8|e;if(i+=e,o<128)throw new n("tlv.decode(long): not minimal encoding")}else o=r;const s=t.subarray(i,i+o);if(s.length!==o)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(i+o)}}},_int:{encode(e){const{Err:t}=tS;if(e<nS)throw new t("integer: negative integers are not allowed");let n=Of(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}=tS;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 qf(e)}},toSig(e){const{Err:t,_int:n,_tlv:i}=tS,r=Hf("signature",e),{v:o,l:s}=i.decode(48,r);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,o),{v:l,l:u}=i.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}=tS,i=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,i)}},nS=BigInt(0),iS=BigInt(1),rS=BigInt(2),oS=BigInt(3),sS=BigInt(4);function aS(e,t){const{BYTES:n}=e;let i;if("bigint"==typeof t)i=t;else{let r=Hf("private key",t);try{i=e.fromBytes(r)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}function cS(e,t={}){const n=Up("weierstrass",e,t),{Fp:i,Fn:r}=n;let o=n.CURVE;const{h:s,n:a}=o;Jf(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!i.is0(o.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=uS(i,r);function u(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,n){const{x:r,y:o}=t.toAffine(),s=i.toBytes(r);if(Ff(n,"isCompressed"),n){u();return Zg(lS(!i.isOdd(o)),s)}return Zg(Uint8Array.of(4),s,i.toBytes(o))},h=t.fromBytes||function(e){Uf(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,r=e.length,o=e[0],s=e.subarray(1);if(r!==t||2!==o&&3!==o){if(r===n&&4===o){const e=i.BYTES,t=i.fromBytes(s.subarray(0,e)),n=i.fromBytes(s.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${r}, expected compressed=${t} or uncompressed=${n}`)}{const e=i.fromBytes(s);if(!i.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=g(e);let n;try{n=i.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}u();return!(1&~o)!==i.isOdd(n)&&(n=i.neg(n)),{x:e,y:n}}};function g(e){const t=i.sqr(e),n=i.mul(t,e);return i.add(i.add(n,i.mul(e,o.a)),o.b)}function f(e,t){const n=i.sqr(t),r=g(e);return i.eql(n,r)}if(!f(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const p=i.mul(i.pow(o.a,oS),sS),m=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(p,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!i.isValid(t)||n&&i.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof A))throw new Error("ProjectivePoint expected")}function k(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[i,r],[o,s]]=t,a=Jv(s*e,n),c=Jv(-r*e,n);let l=e-a*i-c*o,u=-a*r-c*s;const d=l<nS,h=u<nS;d&&(l=-l),h&&(u=-u);const g=Qf(Math.ceil(Xf(n)/2))+iS;if(l<nS||l>=g||u<nS||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,r.ORDER)}const b=Zf((e,t)=>{const{X:n,Y:r,Z:o}=e;if(i.eql(o,i.ONE))return{x:n,y:r};const s=e.is0();null==t&&(t=s?i.ONE:i.inv(o));const a=i.mul(n,t),c=i.mul(r,t),l=i.mul(o,t);if(s)return{x:i.ZERO,y:i.ZERO};if(!i.eql(l,i.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=Zf(e=>{if(e.is0()){if(t.allowInfinityPoint&&!i.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:r}=e.toAffine();if(!i.isValid(n)||!i.isValid(r))throw new Error("bad point: x or y not field elements");if(!f(n,r))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,r,o){return n=new A(i.mul(n.X,e),n.Y,n.Z),t=Ip(r,t),n=Ip(o,n),t.add(n)}class A{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!i.isValid(t)||!i.isValid(n))throw new Error("invalid affine point");if(e instanceof A)throw new Error("projective point not allowed");return i.is0(t)&&i.is0(n)?A.ZERO:new A(t,n,i.ONE)}static fromBytes(e){const t=A.fromAffine(h(Uf(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(Hf("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return E.createCache(this,e),t||this.multiply(oS),this}assertValidity(){v(this)}hasEvenY(){const{y:e}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(e)}equals(e){w(e);const{X:t,Y:n,Z:r}=this,{X:o,Y:s,Z:a}=e,c=i.eql(i.mul(t,a),i.mul(o,r)),l=i.eql(i.mul(n,a),i.mul(s,r));return c&&l}negate(){return new A(this.X,i.neg(this.Y),this.Z)}double(){const{a:e,b:t}=o,n=i.mul(t,oS),{X:r,Y:s,Z:a}=this;let c=i.ZERO,l=i.ZERO,u=i.ZERO,d=i.mul(r,r),h=i.mul(s,s),g=i.mul(a,a),f=i.mul(r,s);return f=i.add(f,f),u=i.mul(r,a),u=i.add(u,u),c=i.mul(e,u),l=i.mul(n,g),l=i.add(c,l),c=i.sub(h,l),l=i.add(h,l),l=i.mul(c,l),c=i.mul(f,c),u=i.mul(n,u),g=i.mul(e,g),f=i.sub(d,g),f=i.mul(e,f),f=i.add(f,u),u=i.add(d,d),d=i.add(u,d),d=i.add(d,g),d=i.mul(d,f),l=i.add(l,d),g=i.mul(s,a),g=i.add(g,g),d=i.mul(g,f),c=i.sub(c,d),u=i.mul(g,h),u=i.add(u,u),u=i.add(u,u),new A(c,l,u)}add(e){w(e);const{X:t,Y:n,Z:r}=this,{X:s,Y:a,Z:c}=e;let l=i.ZERO,u=i.ZERO,d=i.ZERO;const h=o.a,g=i.mul(o.b,oS);let f=i.mul(t,s),p=i.mul(n,a),m=i.mul(r,c),y=i.add(t,n),k=i.add(s,a);y=i.mul(y,k),k=i.add(f,p),y=i.sub(y,k),k=i.add(t,r);let b=i.add(s,c);return k=i.mul(k,b),b=i.add(f,m),k=i.sub(k,b),b=i.add(n,r),l=i.add(a,c),b=i.mul(b,l),l=i.add(p,m),b=i.sub(b,l),d=i.mul(h,k),l=i.mul(g,m),d=i.add(l,d),l=i.sub(p,d),d=i.add(p,d),u=i.mul(l,d),p=i.add(f,f),p=i.add(p,f),m=i.mul(h,m),k=i.mul(g,k),p=i.add(p,m),m=i.sub(f,m),m=i.mul(h,m),k=i.add(k,m),f=i.mul(p,k),u=i.add(u,f),f=i.mul(b,k),l=i.mul(y,l),l=i.sub(l,f),f=i.mul(y,p),d=i.mul(b,d),d=i.add(d,f),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(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let i,o;const s=e=>E.cached(this,e,e=>Cp(A,e));if(n){const{k1neg:t,k1:r,k2neg:a,k2:c}=k(e),{p:l,f:u}=s(r),{p:d,f:h}=s(c);o=u.add(h),i=S(n.beta,l,d,t,a)}else{const{p:t,f:n}=s(e);i=t,o=n}return Cp(A,[i,o])[0]}multiplyUnsafe(e){const{endo:n}=t,i=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===nS||i.is0())return A.ZERO;if(e===iS)return i;if(E.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:r,k2neg:o,k2:s}=k(e),{p1:a,p2:c}=function(e,t,n,i){let r=t,o=e.ZERO,s=e.ZERO;for(;n>Tp||i>Tp;)n&Ep&&(o=o.add(r)),i&Ep&&(s=s.add(r)),r=r.double(),n>>=Ep,i>>=Ep;return{p1:o,p2:s}}(A,i,r,s);return S(n.beta,a,c,t,o)}return E.unsafe(i,e)}multiplyAndAddUnsafe(e,t,n){const i=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return i.is0()?void 0:i}toAffine(e){return b(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===iS||(e?e(A,this):E.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===iS?this:e?e(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return Ff(e,"isCompressed"),this.assertValidity(),d(A,this,e)}toHex(e=!0){return Kg(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 Cp(A,e)}static msm(e,t){return Lp(A,r,e,t)}static fromPrivateKey(e){return A.BASE.multiply(aS(r,e))}}A.BASE=new A(o.Gx,o.Gy,i.ONE),A.ZERO=new A(i.ZERO,i.ONE,i.ZERO),A.Fp=i,A.Fn=r;const T=r.BITS,E=new Mp(A,t.endo?Math.ceil(T/2):T);return A.BASE.precompute(8),A}function lS(e){return Uint8Array.of(e?2:3)}function uS(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function dS(e,t={}){const{Fn:n}=e,i=t.randomBytes||tf,r=Object.assign(uS(e.Fp,n),{seed:Ap(n.ORDER)});function o(e){try{return!!aS(n,e)}catch(e){return!1}}function s(e=i(r.seed)){return function(e,t,n=!1){const i=e.length,r=Sp(t),o=Ap(t);if(i<16||i<o||i>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+i);const s=lp(n?Kf(e):qf(e),t-ep)+ep;return n?Wf(s,r):Gf(s,r)}(Uf(e,r.seed,"seed"),n.ORDER)}function a(t,i=!0){return e.BASE.multiply(aS(n,t)).toBytes(i)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:i,publicKey:o,publicKeyUncompressed:s}=r;if(n.allowedLengths||i===o)return;const a=Hf("key",t).length;return a===o||a===s}const l={isValidSecretKey:o,isValidPublicKey:function(t,n){const{publicKey:i,publicKeyUncompressed:o}=r;try{const r=t.length;return(!0!==n||r===i)&&((!1!==n||r===o)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:o,randomPrivateKey:s,normPrivateKeyToScalar:e=>aS(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,i,r=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(i))throw new Error("second arg must be public key");const o=aS(n,t);return e.fromHex(i).multiply(o).toBytes(r)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:r})}function hS(e,t,n={}){Mg(t),Jf(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const i=n.randomBytes||tf,r=n.hmac||((e,...n)=>Qv(t,e,Zg(...n))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=dS(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},p="compact";function m(e){return e>a>>iS}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=p){let n;if(function(e,t){Zv(t);const n=g.signature;Uf(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=tS.toSig(Uf(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const i=s.BYTES,r=e.subarray(0,i),o=e.subarray(i,2*i);return new w(s.fromBytes(r),s.fromBytes(o),n)}static fromHex(e,t){return this.fromBytes(Qg(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=o.ORDER,{r:i,s:r,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*rS<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?i+a:i;if(!o.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=o.toBytes(l),d=e.fromBytes(Zg(lS(!(1&c)),u)),h=s.inv(l),g=b(Hf("msgHash",t)),f=s.create(-g*h),p=s.create(r*h),m=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(p));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=p){if(Zv(e),"der"===e)return Qg(tS.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 Zg(Uint8Array.of(this.recovery),t,n)}return Zg(t,n)}toHex(e){return Kg(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(Hf("sig",e),"compact")}static fromDER(e){return w.fromBytes(Hf("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 Kg(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Kg(this.toBytes("compact"))}}const k=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=qf(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},b=n.bits2int_modN||function(e){return s.create(k(e))},v=Qf(c);function S(e){return Vf("num < 2^"+c,e,nS,v),s.toBytes(e)}function A(e,n){return Uf(e,void 0,"message"),n?Uf(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g,Point:e,sign:function(n,o,a={}){n=Hf("message",n);const{seed:c,k2sig:l}=function(t,n,r){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{lowS:o,prehash:a,extraEntropy:c}=Yv(r,f);t=A(t,a);const l=b(t),u=aS(s,n),d=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?i(g.secretKey):c;d.push(Hf("extraEntropy",e))}const h=Zg(...d),p=l;return{seed:h,k2sig:function(t){const n=k(t);if(!s.isValidNot0(n))return;const i=s.inv(n),r=e.BASE.multiply(n).toAffine(),a=s.create(r.x);if(a===nS)return;const c=s.create(i*s.create(p+a*u));if(c===nS)return;let l=(r.x===a?0:2)|Number(r.y&iS),d=c;return o&&m(c)&&(d=s.neg(c),l^=1),new w(a,d,l)}}}(n,o,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const i=e=>new Uint8Array(e),r=e=>Uint8Array.of(e);let o=i(e),s=i(e),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},l=(...e)=>n(s,o,...e),u=(e=i(0))=>{s=l(r(0),e),o=l(),0!==e.length&&(s=l(r(1),e),o=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){o=l();const t=o.slice();n.push(t),e+=o.length}return Zg(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,s.BYTES,r)(c,l)},verify:function(t,n,i,r={}){const{lowS:o,prehash:a,format:c}=Yv(r,f);if(i=Hf("publicKey",i),n=A(Hf("message",n),a),"strict"in r)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||Pg(e),i=!n&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!n&&!i)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(i)t=new w(e.r,e.s);else if(n){try{t=w.fromBytes(Hf("sig",e),"der")}catch(e){if(!(e instanceof tS.Err))throw e}if(!t)try{t=w.fromBytes(Hf("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(Hf("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(i);if(o&&l.hasHighS())return!1;const{r:r,s:a}=l,c=b(n),u=s.inv(a),d=s.create(c*u),h=s.create(r*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return s.create(g.x)===r}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:i}=Yv(n,f);return t=A(t,i),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function gS(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 i=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:vp(t.n,{BITS:e.nBitLength,allowedLengths:i,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),i={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:i}}function fS(e){const{CURVE:t,curveOpts:n,hash:i,ecdsaOpts:r}=gS(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,bp(n.Fn.ORDER,n.Fn.BITS))})}(e,hS(cS(t,n),i,r))}const pS={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},mS={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},yS=BigInt(2);const wS=vp(pS.p,{sqrt:function(e){const t=pS.p,n=BigInt(3),i=BigInt(6),r=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=up(u,n,t)*u%t,h=up(d,n,t)*u%t,g=up(h,yS,t)*l%t,f=up(g,r,t)*g%t,p=up(f,o,t)*f%t,m=up(p,a,t)*p%t,y=up(m,c,t)*m%t,w=up(y,a,t)*p%t,k=up(w,n,t)*u%t,b=up(k,s,t)*f%t,v=up(b,i,t)*l%t,S=up(v,yS,t);if(!wS.eql(wS.sqr(S),e))throw new Error("Cannot find square root");return S}}),kS=function(e,t){const n=t=>fS({...e,hash:t});return{...n(t),create:n}}({...pS,Fp:wS,lowS:!0,endo:mS},Df);nm.utils.randomPrivateKey;const bS=()=>{const e=nm.utils.randomPrivateKey(),t=vS(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},vS=nm.getPublicKey;function SS(e){try{return nm.ExtendedPoint.fromHex(e),!0}catch{return!1}}const AS=nm.verify,TS=e=>_g.Buffer.isBuffer(e)?e:e instanceof Uint8Array?_g.Buffer.from(e.buffer,e.byteOffset,e.byteLength):_g.Buffer.from(e);class ES{constructor(e){Object.assign(this,e)}encode(){return _g.Buffer.from(Um.serialize(IS,this))}static decode(e){return Um.deserialize(IS,this,e)}static decodeUnchecked(e){return Um.deserializeUnchecked(IS,this,e)}}const IS=new Map;var CS;const NS=32;let xS=1;class _S extends ES{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=ym.decode(e);if(t.length!=NS)throw new Error("Invalid public key input");this._bn=new gm(t)}else this._bn=new gm(e);if(this._bn.byteLength()>NS)throw new Error("Invalid public key input")}}static unique(){const e=new _S(xS);return xS+=1,new _S(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return ym.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(_g.Buffer);if(e.length===NS)return e;const t=_g.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 i=_g.Buffer.concat([e.toBuffer(),_g.Buffer.from(t),n.toBuffer()]),r=wm(i);return new _S(r)}static createProgramAddressSync(e,t){let n=_g.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=_g.Buffer.concat([n,TS(e)])}),n=_g.Buffer.concat([n,t.toBuffer(),_g.Buffer.from("ProgramDerivedAddress")]);const i=wm(n);if(SS(i))throw new Error("Invalid seeds, address must fall off the curve");return new _S(i)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,i=255;for(;0!=i;){try{const r=e.concat(_g.Buffer.from([i]));n=this.createProgramAddressSync(r,t)}catch(e){if(e instanceof TypeError)throw e;i--;continue}return[n,i]}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 SS(new _S(e).toBytes())}}CS=_S,_S.default=new CS("11111111111111111111111111111111"),IS.set(_S,{kind:"struct",fields:[["_bn","u256"]]}),new _S("BPFLoader1111111111111111111111111111111111");const BS=1232;class PS extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(PS.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class DS 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(DS.prototype,"name",{value:"TransactionExpiredTimeoutError"});class RS extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(RS.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class MS{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 LS=(e="publicKey")=>$m.blob(32,e),FS=(e="string")=>{const t=$m.struct([$m.u32("length"),$m.u32("lengthPadding"),$m.blob($m.offset($m.u32(),-8),"chars")],e),n=t.decode.bind(t),i=t.encode.bind(t),r=t;return r.decode=(e,t)=>n(e,t).chars.toString(),r.encode=(e,t,n)=>{const r={chars:_g.Buffer.from(e,"utf8")};return i(r,t,n)},r.alloc=e=>$m.u32().span+$m.u32().span+_g.Buffer.from(e,"utf8").length,r};function US(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 i=t[e.property];if(Array.isArray(i))return i.length*n(e.elementLayout)}else if("fields"in e)return US({layout:e},t[e.property]);return 0};let i=0;return e.layout.fields.forEach(e=>{i+=n(e)}),i}function OS(e){let t=0,n=0;for(;;){let i=e.shift();if(t|=(127&i)<<7*n,n+=1,!(128&i))break}return t}function $S(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 qS(e,t){if(!e)throw new Error(t||"Assertion failed")}class KS{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,i=e=>{const t=e.toBase58();let i=n.get(t);return void 0===i&&(i={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,i)),i},r=i(t);r.isSigner=!0,r.isWritable=!0;for(const t of e){i(t.programId).isInvoked=!0;for(const e of t.keys){const t=i(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}}return new KS(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];qS(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),i=e.filter(([,e])=>!e.isSigner&&e.isWritable),r=e.filter(([,e])=>!e.isSigner&&!e.isWritable),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:r.length};{qS(t.length>0,"Expected at least one writable signer key");const[e]=t[0];qS(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new _S(e)),...n.map(([e])=>new _S(e)),...i.map(([e])=>new _S(e)),...r.map(([e])=>new _S(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[i,r]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==i.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:i},{writable:n,readonly:r}]}drainKeysFoundInLookupTable(e,t){const n=new Array,i=new Array;for(const[r,o]of this.keyMetaMap.entries())if(t(o)){const t=new _S(r),o=e.findIndex(e=>e.equals(t));o>=0&&(qS(o<256,"Max lookup table index exceeded"),n.push(o),i.push(t),this.keyMetaMap.delete(r))}return[n,i]}}const GS="Reached end of buffer unexpectedly";function WS(e){if(0===e.length)throw new Error(GS);return e.shift()}function HS(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(GS);return e.splice(...t)}class zS{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 _S(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:ym.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new MS(this.staticAccountKeys)}static compile(e){const t=KS.compile(e.instructions,e.payerKey),[n,i]=t.getMessageComponents(),r=new MS(i).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:ym.encode(e.data)}));return new zS({header:n,accountKeys:i,recentBlockhash:e.recentBlockhash,instructions:r})}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=[];$S(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,i=Array.from(ym.decode(e.data));let r=[];$S(r,t.length);let o=[];return $S(o,i.length),{programIdIndex:n,keyIndicesCount:_g.Buffer.from(r),keyIndices:t,dataLength:_g.Buffer.from(o),data:i}});let i=[];$S(i,n.length);let r=_g.Buffer.alloc(BS);_g.Buffer.from(i).copy(r);let o=i.length;n.forEach(e=>{const t=$m.struct([$m.u8("programIdIndex"),$m.blob(e.keyIndicesCount.length,"keyIndicesCount"),$m.seq($m.u8("keyIndex"),e.keyIndices.length,"keyIndices"),$m.blob(e.dataLength.length,"dataLength"),$m.seq($m.u8("userdatum"),e.data.length,"data")]).encode(e,r,o);o+=t}),r=r.slice(0,o);const s=$m.struct([$m.blob(1,"numRequiredSignatures"),$m.blob(1,"numReadonlySignedAccounts"),$m.blob(1,"numReadonlyUnsignedAccounts"),$m.blob(t.length,"keyCount"),$m.seq(LS("key"),e,"keys"),LS("recentBlockhash")]),a={numRequiredSignatures:_g.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:_g.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:_g.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:_g.Buffer.from(t),keys:this.accountKeys.map(e=>TS(e.toBytes())),recentBlockhash:ym.decode(this.recentBlockhash)};let c=_g.Buffer.alloc(2048);const l=s.encode(a,c);return r.copy(c,l),c.slice(0,l+r.length)}static from(e){let t=[...e];const n=WS(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const i=WS(t),r=WS(t),o=OS(t);let s=[];for(let e=0;e<o;e++){const e=HS(t,0,NS);s.push(new _S(_g.Buffer.from(e)))}const a=HS(t,0,NS),c=OS(t);let l=[];for(let e=0;e<c;e++){const e=WS(t),n=HS(t,0,OS(t)),i=HS(t,0,OS(t)),r=ym.encode(_g.Buffer.from(i));l.push({programIdIndex:e,accounts:n,data:r})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:i,numReadonlyUnsignedAccounts:r},recentBlockhash:ym.encode(_g.Buffer.from(a)),accountKeys:s,instructions:l};return new zS(u)}}class jS{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 MS(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 i=e.find(e=>e.key.equals(n.accountKey));if(!i)throw new Error(`Failed to find address lookup table account for table key ${n.accountKey.toBase58()}`);for(const e of n.writableIndexes){if(!(e<i.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.writable.push(i.state.addresses[e])}for(const e of n.readonlyIndexes){if(!(e<i.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${n.accountKey.toBase58()}`);t.readonly.push(i.state.addresses[e])}}return t}static compile(e){const t=KS.compile(e.instructions,e.payerKey),n=new Array,i={writable:new Array,readonly:new Array},r=e.addressLookupTableAccounts||[];for(const e of r){const r=t.extractTableLookup(e);if(void 0!==r){const[e,{writable:t,readonly:o}]=r;n.push(e),i.writable.push(...t),i.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new MS(s,i).compileInstructions(e.instructions);return new jS({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();$S(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();$S(n,this.compiledInstructions.length);const i=this.serializeAddressTableLookups(),r=Array();$S(r,this.addressTableLookups.length);const o=$m.struct([$m.u8("prefix"),$m.struct([$m.u8("numRequiredSignatures"),$m.u8("numReadonlySignedAccounts"),$m.u8("numReadonlyUnsignedAccounts")],"header"),$m.blob(e.length,"staticAccountKeysLength"),$m.seq(LS(),this.staticAccountKeys.length,"staticAccountKeys"),LS("recentBlockhash"),$m.blob(n.length,"instructionsLength"),$m.blob(t.length,"serializedInstructions"),$m.blob(r.length,"addressTableLookupsLength"),$m.blob(i.length,"serializedAddressTableLookups")]),s=new Uint8Array(BS),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:ym.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(r),serializedAddressTableLookups:i},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(BS);for(const n of this.compiledInstructions){const i=Array();$S(i,n.accountKeyIndexes.length);const r=Array();$S(r,n.data.length);e+=$m.struct([$m.u8("programIdIndex"),$m.blob(i.length,"encodedAccountKeyIndexesLength"),$m.seq($m.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),$m.blob(r.length,"encodedDataLength"),$m.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(i),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(r),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(BS);for(const n of this.addressTableLookups){const i=Array();$S(i,n.writableIndexes.length);const r=Array();$S(r,n.readonlyIndexes.length);e+=$m.struct([LS("accountKey"),$m.blob(i.length,"encodedWritableIndexesLength"),$m.seq($m.u8(),n.writableIndexes.length,"writableIndexes"),$m.blob(r.length,"encodedReadonlyIndexesLength"),$m.seq($m.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(i),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(r),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=WS(t),i=127&n;qS(n!==i,"Expected versioned message but received legacy message");qS(0===i,`Expected versioned message with version 0 but found version ${i}`);const r={numRequiredSignatures:WS(t),numReadonlySignedAccounts:WS(t),numReadonlyUnsignedAccounts:WS(t)},o=[],s=OS(t);for(let e=0;e<s;e++)o.push(new _S(HS(t,0,NS)));const a=ym.encode(HS(t,0,NS)),c=OS(t),l=[];for(let e=0;e<c;e++){const e=WS(t),n=HS(t,0,OS(t)),i=OS(t),r=new Uint8Array(HS(t,0,i));l.push({programIdIndex:e,accountKeyIndexes:n,data:r})}const u=OS(t),d=[];for(let e=0;e<u;e++){const e=new _S(HS(t,0,NS)),n=HS(t,0,OS(t)),i=HS(t,0,OS(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:i})}return new jS({header:r,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}let VS=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 XS=_g.Buffer.alloc(64).fill(0);class QS{constructor(e){this.keys=void 0,this.programId=void 0,this.data=_g.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 JS{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 QS(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 i=[],r=[];t.forEach(e=>{e.keys.forEach(e=>{r.push({...e})});const t=e.programId.toString();i.includes(t)||i.push(t)}),i.forEach(e=>{r.push({pubkey:new _S(e),isSigner:!1,isWritable:!1})});const o=[];r.forEach(e=>{const t=e.pubkey.toString(),n=o.findIndex(e=>e.pubkey.toString()===t);n>-1?(o[n].isWritable=o[n].isWritable||e.isWritable,o[n].isSigner=o[n].isSigner||e.isSigner):o.push(e)}),o.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=o.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=o.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);o[t].isSigner||(o[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];o.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(u.push(e.toString()),a+=1,n||(c+=1)):(d.push(e.toString()),n||(l+=1))});const h=u.concat(d),g=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:h.indexOf(n.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:ym.encode(t)}});return g.forEach(e=>{qS(e.programIdIndex>=0),e.accounts.forEach(e=>qS(e>=0))}),new zS({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 i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),n.push(i))}this.signatures=n.map(e=>({signature:null,publicKey:e.publicKey}));const i=this._compile();this._partialSign(i,...n)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,n=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),n.push(i))}const i=this._compile();this._partialSign(i,...n)}_partialSign(e,...t){const n=e.serialize();t.forEach(e=>{const t=((e,t)=>nm.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,TS(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){qS(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=_g.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:i,publicKey:r}of this.signatures)null===i?t&&(n.missing||=[]).push(r):AS(i,e,r.toBytes())||(n.invalid||=[]).push(r);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),i=this.serializeMessage();if(n){const e=this._getMessageSignednessErrors(i,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(i)}_serialize(e){const{signatures:t}=this,n=[];$S(n,t.length);const i=n.length+64*t.length+e.length,r=_g.Buffer.alloc(i);return qS(t.length<256),_g.Buffer.from(n).copy(r,0),t.forEach(({signature:e},t)=>{null!==e&&(qS(64===e.length,"signature has invalid length"),_g.Buffer.from(e).copy(r,n.length+64*t))}),e.copy(r,n.length+64*t.length),qS(r.length<=BS,`Transaction too large: ${r.length} > 1232`),r}get keys(){return qS(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return qS(1===this.instructions.length),this.instructions[0].programId}get data(){return qS(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=OS(t);let i=[];for(let e=0;e<n;e++){const e=HS(t,0,64);i.push(ym.encode(_g.Buffer.from(e)))}return JS.populate(zS.from(t),i)}static populate(e,t=[]){const n=new JS;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,i)=>{const r={signature:t==ym.encode(XS)?null:ym.decode(t),publicKey:e.accountKeys[i]};n.signatures.push(r)}),e.instructions.forEach(t=>{const i=t.accounts.map(t=>{const i=e.accountKeys[t];return{pubkey:i,isSigner:n.signatures.some(e=>e.publicKey.toString()===i.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new QS({keys:i,programId:e.accountKeys[t.programIdIndex],data:ym.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new _S("SysvarC1ock11111111111111111111111111111111"),new _S("SysvarEpochSchedu1e111111111111111111111111"),new _S("Sysvar1nstructions1111111111111111111111111");const ZS=new _S("SysvarRecentB1ockHashes11111111111111111111"),YS=new _S("SysvarRent111111111111111111111111111111111");new _S("SysvarRewards111111111111111111111111111111"),new _S("SysvarS1otHashes111111111111111111111111111"),new _S("SysvarS1otHistory11111111111111111111111111"),new _S("SysvarStakeHistory1111111111111111111111111");class eA extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:i}){const r=i?`Logs: \n${JSON.stringify(i.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${n}. `+r+o;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+r+o;break;default:s=`Unknown action '${e}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=i||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 tA extends Error{constructor({code:e,message:t,data:n},i){super(null!=i?`${i}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=n,this.name="SolanaJSONRPCError"}}function nA(e){return new Promise(t=>setTimeout(t,e))}function iA(e,t){const n=e.layout.span>=0?e.layout.span:US(e,t),i=_g.Buffer.alloc(n),r=Object.assign({instruction:e.index},t);return e.layout.encode(r,i),i}const rA=$m.nu64("lamportsPerSignature"),oA=$m.struct([$m.u32("version"),$m.u32("state"),LS("authorizedPubkey"),LS("nonce"),$m.struct([rA],"feeCalculator")]),sA=oA.span;class aA{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=oA.decode(TS(e),0);return new aA({authorizedPubkey:new _S(t.authorizedPubkey),nonce:new _S(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function cA(e){const t=$m.blob(8,e),n=t.decode.bind(t),i=t.encode.bind(t),r=t,o=lv();return r.decode=(e,t)=>{const i=n(e,t);return o.decode(i)},r.encode=(e,t,n)=>{const r=o.encode(e);return i(r,t,n)},r}const lA=Object.freeze({Create:{index:0,layout:$m.struct([$m.u32("instruction"),$m.ns64("lamports"),$m.ns64("space"),LS("programId")])},Assign:{index:1,layout:$m.struct([$m.u32("instruction"),LS("programId")])},Transfer:{index:2,layout:$m.struct([$m.u32("instruction"),cA("lamports")])},CreateWithSeed:{index:3,layout:$m.struct([$m.u32("instruction"),LS("base"),FS("seed"),$m.ns64("lamports"),$m.ns64("space"),LS("programId")])},AdvanceNonceAccount:{index:4,layout:$m.struct([$m.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:$m.struct([$m.u32("instruction"),$m.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:$m.struct([$m.u32("instruction"),LS("authorized")])},AuthorizeNonceAccount:{index:7,layout:$m.struct([$m.u32("instruction"),LS("authorized")])},Allocate:{index:8,layout:$m.struct([$m.u32("instruction"),$m.ns64("space")])},AllocateWithSeed:{index:9,layout:$m.struct([$m.u32("instruction"),LS("base"),FS("seed"),$m.ns64("space"),LS("programId")])},AssignWithSeed:{index:10,layout:$m.struct([$m.u32("instruction"),LS("base"),FS("seed"),LS("programId")])},TransferWithSeed:{index:11,layout:$m.struct([$m.u32("instruction"),cA("lamports"),FS("seed"),LS("programId")])},UpgradeNonceAccount:{index:12,layout:$m.struct([$m.u32("instruction")])}});class uA{constructor(){}static createAccount(e){const t=iA(lA.Create,{lamports:e.lamports,space:e.space,programId:TS(e.programId.toBuffer())});return new QS({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=iA(lA.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:TS(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=iA(lA.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new QS({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=iA(lA.AssignWithSeed,{base:TS(e.basePubkey.toBuffer()),seed:e.seed,programId:TS(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=iA(lA.Assign,{programId:TS(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new QS({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=iA(lA.CreateWithSeed,{base:TS(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:TS(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 QS({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new JS;"basePubkey"in e&&"seed"in e?t.add(uA.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:sA,programId:this.programId})):t.add(uA.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:sA,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=iA(lA.InitializeNonceAccount,{authorized:TS(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:ZS,isSigner:!1,isWritable:!1},{pubkey:YS,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new QS(n)}static nonceAdvance(e){const t=iA(lA.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:ZS,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new QS(n)}static nonceWithdraw(e){const t=iA(lA.WithdrawNonceAccount,{lamports:e.lamports});return new QS({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:ZS,isSigner:!1,isWritable:!1},{pubkey:YS,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=iA(lA.AuthorizeNonceAccount,{authorized:TS(e.newAuthorizedPubkey.toBuffer())});return new QS({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=iA(lA.AllocateWithSeed,{base:TS(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:TS(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=iA(lA.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new QS({keys:n,programId:this.programId,data:t})}}function dA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hA,gA;function fA(){if(gA)return hA;gA=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(i,r){var o,s,a,c,l,u,d;if(!0===i)return"true";if(!1===i)return"false";switch(typeof i){case"object":if(null===i)return null;if(i.toJSON&&"function"==typeof i.toJSON)return n(i.toJSON(),r);if("[object Array]"===(d=e.call(i))){for(a="[",s=i.length-1,o=0;o<s;o++)a+=n(i[o],!0)+",";return s>-1&&(a+=n(i[o],!0)),a+"]"}if("[object Object]"===d){for(s=(c=t(i).sort()).length,a="",o=0;o<s;)void 0!==(u=n(i[l=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),o++;return"{"+a+"}"}return JSON.stringify(i);case"function":case"undefined":return r?null:void 0;case"string":return JSON.stringify(i);default:return isFinite(i)?i:null}}return hA=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}uA.programId=new _S("11111111111111111111111111111111"),new _S("BPFLoader2111111111111111111111111111111111");var pA=dA(fA());function mA(e){let t=0;for(;e>1;)e/=2,t++;return t}class yA{constructor(e,t,n,i,r){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=i,this.firstNormalSlot=r}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=mA(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)))-mA(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+mA(32)):this.slotsPerEpoch}}var wA=globalThis.fetch;class kA extends Vv{constructor(e,t,n){super(e=>{const n=function(e,t){return new zv(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 bA{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}(vA,e),n=e.length-56;qS(n>=0,"lookup table is invalid"),qS(n%32==0,"lookup table is invalid");const i=n/32,{addresses:r}=$m.struct([$m.seq(LS(),i,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new _S(t.authority[0]):void 0,addresses:r.map(e=>new _S(e))}}}const vA={index:1,layout:$m.struct([$m.u32("typeIndex"),cA("deactivationSlot"),$m.nu64("lastExtendedSlot"),$m.u8("lastExtendedStartIndex"),$m.u8(),$m.seq(LS(),$m.offset($m.u8(),-1),"authority")])},SA=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const AA=Mv(Tv(_S),_v(),e=>new _S(e)),TA=Bv([_v(),Ev("base64")]),EA=Mv(Tv(_g.Buffer),TA,e=>_g.Buffer.from(e[0],"base64"));function IA(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:i,...r}=e;t=i,n=r}return{commitment:t,config:n}}function CA(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function NA(e){return Dv([Pv({jsonrpc:Ev("2.0"),id:_v(),result:e}),Pv({jsonrpc:Ev("2.0"),id:_v(),error:Pv({code:Rv(),message:_v(),data:Nv(vv("any",()=>!0))})})])}const xA=NA(Rv());function _A(e){return Mv(NA(e),xA,t=>"error"in t?t:{...t,result:wv(t.result,e)})}function BA(e){return _A(Pv({context:Pv({slot:Cv()}),value:e}))}function PA(e){return Pv({context:Pv({slot:Cv()}),value:e})}function DA(e,t){return 0===e?new jS({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new _S(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:ym.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new zS(t)}const RA=Pv({foundation:Cv(),foundationTerm:Cv(),initial:Cv(),taper:Cv(),terminal:Cv()}),MA=_A(Sv(Iv(Pv({epoch:Cv(),effectiveSlot:Cv(),amount:Cv(),postBalance:Cv(),commission:Nv(Iv(Cv()))})))),LA=Sv(Pv({slot:Cv(),prioritizationFee:Cv()})),FA=Pv({total:Cv(),validator:Cv(),foundation:Cv(),epoch:Cv()}),UA=Pv({epoch:Cv(),slotIndex:Cv(),slotsInEpoch:Cv(),absoluteSlot:Cv(),blockHeight:Nv(Cv()),transactionCount:Nv(Cv())}),OA=Pv({slotsPerEpoch:Cv(),leaderScheduleSlotOffset:Cv(),warmup:Av(),firstNormalEpoch:Cv(),firstNormalSlot:Cv()}),$A=xv(_v(),Sv(Cv())),qA=Iv(Dv([Pv({}),_v()])),KA=Pv({err:qA}),GA=Ev("receivedSignature"),WA=Pv({"solana-core":_v(),"feature-set":Nv(Cv())}),HA=Pv({program:_v(),programId:AA,parsed:Rv()}),zA=Pv({programId:AA,accounts:Sv(AA),data:_v()}),jA=BA(Pv({err:Iv(Dv([Pv({}),_v()])),logs:Iv(Sv(_v())),accounts:Nv(Iv(Sv(Iv(Pv({executable:Av(),owner:_v(),lamports:Cv(),data:Sv(_v()),rentEpoch:Nv(Cv())}))))),unitsConsumed:Nv(Cv()),returnData:Nv(Iv(Pv({programId:_v(),data:Bv([_v(),Ev("base64")])}))),innerInstructions:Nv(Iv(Sv(Pv({index:Cv(),instructions:Sv(Dv([HA,zA]))}))))})),VA=BA(Pv({byIdentity:xv(_v(),Sv(Cv())),range:Pv({firstSlot:Cv(),lastSlot:Cv()})}));const XA=_A(RA),QA=_A(FA),JA=_A(LA),ZA=_A(UA),YA=_A(OA),eT=_A($A),tT=_A(Cv()),nT=BA(Pv({total:Cv(),circulating:Cv(),nonCirculating:Cv(),nonCirculatingAccounts:Sv(AA)})),iT=Pv({amount:_v(),uiAmount:Iv(Cv()),decimals:Cv(),uiAmountString:Nv(_v())}),rT=BA(Sv(Pv({address:AA,amount:_v(),uiAmount:Iv(Cv()),decimals:Cv(),uiAmountString:Nv(_v())}))),oT=BA(Sv(Pv({pubkey:AA,account:Pv({executable:Av(),owner:AA,lamports:Cv(),data:EA,rentEpoch:Cv()})}))),sT=Pv({program:_v(),parsed:Rv(),space:Cv()}),aT=BA(Sv(Pv({pubkey:AA,account:Pv({executable:Av(),owner:AA,lamports:Cv(),data:sT,rentEpoch:Cv()})}))),cT=BA(Sv(Pv({lamports:Cv(),address:AA}))),lT=Pv({executable:Av(),owner:AA,lamports:Cv(),data:EA,rentEpoch:Cv()}),uT=Pv({pubkey:AA,account:lT}),dT=Mv(Dv([Tv(_g.Buffer),sT]),Dv([TA,sT]),e=>Array.isArray(e)?wv(e,EA):e),hT=Pv({executable:Av(),owner:AA,lamports:Cv(),data:dT,rentEpoch:Cv()}),gT=Pv({pubkey:AA,account:hT}),fT=Pv({state:Dv([Ev("active"),Ev("inactive"),Ev("activating"),Ev("deactivating")]),active:Cv(),inactive:Cv()}),pT=_A(Sv(Pv({signature:_v(),slot:Cv(),err:qA,memo:Iv(_v()),blockTime:Nv(Iv(Cv()))}))),mT=_A(Sv(Pv({signature:_v(),slot:Cv(),err:qA,memo:Iv(_v()),blockTime:Nv(Iv(Cv()))}))),yT=Pv({subscription:Cv(),result:PA(lT)}),wT=Pv({pubkey:AA,account:lT}),kT=Pv({subscription:Cv(),result:PA(wT)}),bT=Pv({parent:Cv(),slot:Cv(),root:Cv()}),vT=Pv({subscription:Cv(),result:bT}),ST=Dv([Pv({type:Dv([Ev("firstShredReceived"),Ev("completed"),Ev("optimisticConfirmation"),Ev("root")]),slot:Cv(),timestamp:Cv()}),Pv({type:Ev("createdBank"),parent:Cv(),slot:Cv(),timestamp:Cv()}),Pv({type:Ev("frozen"),slot:Cv(),timestamp:Cv(),stats:Pv({numTransactionEntries:Cv(),numSuccessfulTransactions:Cv(),numFailedTransactions:Cv(),maxTransactionsPerEntry:Cv()})}),Pv({type:Ev("dead"),slot:Cv(),timestamp:Cv(),err:_v()})]),AT=Pv({subscription:Cv(),result:ST}),TT=Pv({subscription:Cv(),result:PA(Dv([KA,GA]))}),ET=Pv({subscription:Cv(),result:Cv()}),IT=Pv({pubkey:_v(),gossip:Iv(_v()),tpu:Iv(_v()),rpc:Iv(_v()),version:Iv(_v())}),CT=Pv({votePubkey:_v(),nodePubkey:_v(),activatedStake:Cv(),epochVoteAccount:Av(),epochCredits:Sv(Bv([Cv(),Cv(),Cv()])),commission:Cv(),lastVote:Cv(),rootSlot:Iv(Cv())}),NT=_A(Pv({current:Sv(CT),delinquent:Sv(CT)})),xT=Dv([Ev("processed"),Ev("confirmed"),Ev("finalized")]),_T=Pv({slot:Cv(),confirmations:Iv(Cv()),err:qA,confirmationStatus:Nv(xT)}),BT=BA(Sv(Iv(_T))),PT=_A(Cv()),DT=Pv({accountKey:AA,writableIndexes:Sv(Cv()),readonlyIndexes:Sv(Cv())}),RT=Pv({signatures:Sv(_v()),message:Pv({accountKeys:Sv(_v()),header:Pv({numRequiredSignatures:Cv(),numReadonlySignedAccounts:Cv(),numReadonlyUnsignedAccounts:Cv()}),instructions:Sv(Pv({accounts:Sv(Cv()),data:_v(),programIdIndex:Cv()})),recentBlockhash:_v(),addressTableLookups:Nv(Sv(DT))})}),MT=Pv({pubkey:AA,signer:Av(),writable:Av(),source:Nv(Dv([Ev("transaction"),Ev("lookupTable")]))}),LT=Pv({accountKeys:Sv(MT),signatures:Sv(_v())}),FT=Pv({parsed:Rv(),program:_v(),programId:AA}),UT=Pv({accounts:Sv(AA),data:_v(),programId:AA}),OT=Mv(Dv([UT,FT]),Dv([Pv({parsed:Rv(),program:_v(),programId:_v()}),Pv({accounts:Sv(_v()),data:_v(),programId:_v()})]),e=>wv(e,"accounts"in e?UT:FT)),$T=Pv({signatures:Sv(_v()),message:Pv({accountKeys:Sv(MT),instructions:Sv(OT),recentBlockhash:_v(),addressTableLookups:Nv(Iv(Sv(DT)))})}),qT=Pv({accountIndex:Cv(),mint:_v(),owner:Nv(_v()),programId:Nv(_v()),uiTokenAmount:iT}),KT=Pv({writable:Sv(AA),readonly:Sv(AA)}),GT=Pv({err:qA,fee:Cv(),innerInstructions:Nv(Iv(Sv(Pv({index:Cv(),instructions:Sv(Pv({accounts:Sv(Cv()),data:_v(),programIdIndex:Cv()}))})))),preBalances:Sv(Cv()),postBalances:Sv(Cv()),logMessages:Nv(Iv(Sv(_v()))),preTokenBalances:Nv(Iv(Sv(qT))),postTokenBalances:Nv(Iv(Sv(qT))),loadedAddresses:Nv(KT),computeUnitsConsumed:Nv(Cv()),costUnits:Nv(Cv())}),WT=Pv({err:qA,fee:Cv(),innerInstructions:Nv(Iv(Sv(Pv({index:Cv(),instructions:Sv(OT)})))),preBalances:Sv(Cv()),postBalances:Sv(Cv()),logMessages:Nv(Iv(Sv(_v()))),preTokenBalances:Nv(Iv(Sv(qT))),postTokenBalances:Nv(Iv(Sv(qT))),loadedAddresses:Nv(KT),computeUnitsConsumed:Nv(Cv()),costUnits:Nv(Cv())}),HT=Dv([Ev(0),Ev("legacy")]),zT=Pv({pubkey:_v(),lamports:Cv(),postBalance:Iv(Cv()),rewardType:Iv(_v()),commission:Nv(Iv(Cv()))}),jT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),transactions:Sv(Pv({transaction:RT,meta:Iv(GT),version:Nv(HT)})),rewards:Nv(Sv(zT)),blockTime:Iv(Cv()),blockHeight:Iv(Cv())}))),VT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),rewards:Nv(Sv(zT)),blockTime:Iv(Cv()),blockHeight:Iv(Cv())}))),XT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),transactions:Sv(Pv({transaction:LT,meta:Iv(GT),version:Nv(HT)})),rewards:Nv(Sv(zT)),blockTime:Iv(Cv()),blockHeight:Iv(Cv())}))),QT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),transactions:Sv(Pv({transaction:$T,meta:Iv(WT),version:Nv(HT)})),rewards:Nv(Sv(zT)),blockTime:Iv(Cv()),blockHeight:Iv(Cv())}))),JT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),transactions:Sv(Pv({transaction:LT,meta:Iv(WT),version:Nv(HT)})),rewards:Nv(Sv(zT)),blockTime:Iv(Cv()),blockHeight:Iv(Cv())}))),ZT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),rewards:Nv(Sv(zT)),blockTime:Iv(Cv()),blockHeight:Iv(Cv())}))),YT=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),transactions:Sv(Pv({transaction:RT,meta:Iv(GT)})),rewards:Nv(Sv(zT)),blockTime:Iv(Cv())}))),eE=_A(Iv(Pv({blockhash:_v(),previousBlockhash:_v(),parentSlot:Cv(),signatures:Sv(_v()),blockTime:Iv(Cv())}))),tE=_A(Iv(Pv({slot:Cv(),meta:Iv(GT),blockTime:Nv(Iv(Cv())),transaction:RT,version:Nv(HT)}))),nE=_A(Iv(Pv({slot:Cv(),transaction:$T,meta:Iv(WT),blockTime:Nv(Iv(Cv())),version:Nv(HT)}))),iE=BA(Pv({blockhash:_v(),lastValidBlockHeight:Cv()})),rE=BA(Av()),oE=_A(Sv(Pv({slot:Cv(),numTransactions:Cv(),numSlots:Cv(),samplePeriodSecs:Cv()}))),sE=BA(Iv(Pv({feeCalculator:Pv({lamportsPerSignature:Cv()})}))),aE=_A(_v()),cE=_A(_v()),lE=Pv({err:qA,logs:Sv(_v()),signature:_v()}),uE=Pv({result:PA(lE),subscription:Cv()}),dE={"solana-client":"js/1.0.0-maintenance"};class hE{constructor(e,t){let n,i,r,o,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:n,config:i}=IA(t),r=this._buildArgs([],n,void 0,i),o=pA(r);return e[o]=e[o]??(async()=>{try{const e=wv(await this._rpcRequest("getBlockHeight",r),_A(Cv()));if("error"in e)throw new tA(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,i=t.httpHeaders,r=t.fetch,o=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=n||function(e){const t=e.match(SA);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,i,r,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==r?null:parseInt(r.slice(1),10);return`${s}//${i}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,n,i,r){const o=n||wA;let s;return i&&(s=async(e,t)=>{const n=await new Promise((n,r)=>{try{i(e,t,(e,t)=>n([e,t]))}catch(e){r(e)}});return await o(...n)}),new Kv(async(n,i)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},dE)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await o(e,a),429===t.status&&!0!==r&&(n-=1,0!==n);)await nA(c),c*=2;const l=await t.text();t.ok?i(null,l):i(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(e){e instanceof Error&&i(e)}},{})}(e,i,r,o,s),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((n,i)=>{c.request(e,t,(e,t)=>{e?i(e):n(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((n,i)=>{0===t.length&&n([]);const r=t.map(t=>e.request(t.methodName,t.args));e.request(r,(e,t)=>{e?i(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new kA(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:i}=IA(t),r=this._buildArgs([e.toBase58()],n,void 0,i),o=wv(await this._rpcRequest("getBalance",r),BA(Cv()));if("error"in o)throw new tA(o.error,`failed to get balance for ${e.toBase58()}`);return o.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=wv(await this._rpcRequest("getBlockTime",[e]),_A(Iv(Cv())));if("error"in t)throw new tA(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=wv(await this._rpcRequest("minimumLedgerSlot",[]),_A(Cv()));if("error"in e)throw new tA(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=wv(await this._rpcRequest("getFirstAvailableBlock",[]),tT);if("error"in e)throw new tA(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=wv(await this._rpcRequest("getSupply",[t]),nT);if("error"in n)throw new tA(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),i=wv(await this._rpcRequest("getTokenSupply",n),BA(iT));if("error"in i)throw new tA(i.error,"failed to get token supply");return i.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),i=wv(await this._rpcRequest("getTokenAccountBalance",n),BA(iT));if("error"in i)throw new tA(i.error,"failed to get token account balance");return i.result}async getTokenAccountsByOwner(e,t,n){const{commitment:i,config:r}=IA(n);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,i,"base64",r),a=wv(await this._rpcRequest("getTokenAccountsByOwner",s),oT);if("error"in a)throw new tA(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,n){let i=[e.toBase58()];"mint"in t?i.push({mint:t.mint.toBase58()}):i.push({programId:t.programId.toBase58()});const r=this._buildArgs(i,n,"jsonParsed"),o=wv(await this._rpcRequest("getTokenAccountsByOwner",r),aT);if("error"in o)throw new tA(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],i=wv(await this._rpcRequest("getLargestAccounts",n),cT);if("error"in i)throw new tA(i.error,"failed to get largest accounts");return i.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),i=wv(await this._rpcRequest("getTokenLargestAccounts",n),rT);if("error"in i)throw new tA(i.error,"failed to get token largest accounts");return i.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgs([e.toBase58()],n,"base64",i),o=wv(await this._rpcRequest("getAccountInfo",r),BA(Iv(lT)));if("error"in o)throw new tA(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgs([e.toBase58()],n,"jsonParsed",i),o=wv(await this._rpcRequest("getAccountInfo",r),BA(Iv(hT)));if("error"in o)throw new tA(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:i}=IA(t),r=e.map(e=>e.toBase58()),o=this._buildArgs([r],n,"jsonParsed",i),s=wv(await this._rpcRequest("getMultipleAccounts",o),BA(Sv(Iv(hT))));if("error"in s)throw new tA(s.error,`failed to get info for accounts ${r}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:i}=IA(t),r=e.map(e=>e.toBase58()),o=this._buildArgs([r],n,"base64",i),s=wv(await this._rpcRequest("getMultipleAccounts",o),BA(Sv(Iv(lT))));if("error"in s)throw new tA(s.error,`failed to get info for accounts ${r}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:i,config:r}=IA(t),o=this._buildArgs([e.toBase58()],i,void 0,{...r,epoch:null!=n?n:r?.epoch}),s=wv(await this._rpcRequest("getStakeActivation",o),_A(fT));if("error"in s)throw new tA(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:i}=IA(t),{encoding:r,...o}=i||{},s=this._buildArgs([e.toBase58()],n,r||"base64",{...o,...o.filters?{filters:CA(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Sv(uT),l=!0===o.withContext?wv(a,BA(c)):wv(a,_A(c));if("error"in l)throw new tA(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgs([e.toBase58()],n,"jsonParsed",i),o=wv(await this._rpcRequest("getProgramAccounts",r),_A(Sv(gT)));if("error"in o)throw new tA(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.result}async confirmTransaction(e,t){let n,i;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{i=ym.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return qS(64===i.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,i,r=!1;return{abortConfirmation:()=>{i&&(i(),i=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((o,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const i={context:t,value:e};o({__type:VS.PROCESSED,response:i})},e);const a=new Promise(e=>{null==n?e():i=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,r)return;const n=await this.getSignatureStatus(t);if(r)return;if(null==n)return;const{context:i,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}r=!0,o({__type:VS.PROCESSED,response:{context:i,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:i}}){let r=!1;const o=new Promise(t=>{const i=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await i();if(!r){for(;e<=n;){if(await nA(1e3),r)return;if(e=await i(),r)return}t({__type:VS.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,o]);if(e.__type!==VS.PROCESSED)throw new PS(i);l=e.response}finally{r=!0,s()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:i,nonceValue:r,signature:o}}){let s=!1;const a=new Promise(t=>{let o=r,a=null;const c=async()=>{try{const{context:t,value:r}=await this.getNonceAndContext(i,{commitment:e,minContextSlot:n});return a=t.slot,r?.nonce}catch(e){return o}};(async()=>{if(o=await c(),!s)for(;;){if(r!==o)return void t({__type:VS.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await nA(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===VS.PROCESSED)d=t.response;else{let i;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){i=e;break}await nA(400)}if(!i?.value)throw new RS(o);{const t=e||"finalized",{confirmationStatus:n}=i.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new RS(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new RS(o);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new RS(o)}d={context:i.context,value:{err:i.value.err}}}}}finally{s=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const i=new Promise(t=>{let i=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":i=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:VS.TIMED_OUT,timeoutMs:i}),i)}),{abortConfirmation:r,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,i]);if(e.__type!==VS.PROCESSED)throw new DS(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),r()}return s}async getClusterNodes(){const e=wv(await this._rpcRequest("getClusterNodes",[]),_A(Sv(IT)));if("error"in e)throw new tA(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=wv(await this._rpcRequest("getVoteAccounts",t),NT);if("error"in n)throw new tA(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=IA(e),i=this._buildArgs([],t,void 0,n),r=wv(await this._rpcRequest("getSlot",i),_A(Cv()));if("error"in r)throw new tA(r.error,"failed to get slot");return r.result}async getSlotLeader(e){const{commitment:t,config:n}=IA(e),i=this._buildArgs([],t,void 0,n),r=wv(await this._rpcRequest("getSlotLeader",i),_A(_v()));if("error"in r)throw new tA(r.error,"failed to get slot leader");return r.result}async getSlotLeaders(e,t){const n=[e,t],i=wv(await this._rpcRequest("getSlotLeaders",n),_A(Sv(AA)));if("error"in i)throw new tA(i.error,"failed to get slot leaders");return i.result}async getSignatureStatus(e,t){const{context:n,value:i}=await this.getSignatureStatuses([e],t);qS(1===i.length);return{context:n,value:i[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const i=wv(await this._rpcRequest("getSignatureStatuses",n),BT);if("error"in i)throw new tA(i.error,"failed to get signature status");return i.result}async getTransactionCount(e){const{commitment:t,config:n}=IA(e),i=this._buildArgs([],t,void 0,n),r=wv(await this._rpcRequest("getTransactionCount",i),_A(Cv()));if("error"in r)throw new tA(r.error,"failed to get transaction count");return r.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=wv(await this._rpcRequest("getInflationGovernor",t),XA);if("error"in n)throw new tA(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:i,config:r}=IA(n),o=this._buildArgs([e.map(e=>e.toBase58())],i,void 0,{...r,epoch:null!=t?t:r?.epoch}),s=wv(await this._rpcRequest("getInflationReward",o),MA);if("error"in s)throw new tA(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=wv(await this._rpcRequest("getInflationRate",[]),QA);if("error"in e)throw new tA(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=IA(e),i=this._buildArgs([],t,void 0,n),r=wv(await this._rpcRequest("getEpochInfo",i),ZA);if("error"in r)throw new tA(r.error,"failed to get epoch info");return r.result}async getEpochSchedule(){const e=wv(await this._rpcRequest("getEpochSchedule",[]),YA);if("error"in e)throw new tA(e.error,"failed to get epoch schedule");const t=e.result;return new yA(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=wv(await this._rpcRequest("getLeaderSchedule",[]),eT);if("error"in e)throw new tA(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),i=wv(await this._rpcRequest("getMinimumBalanceForRentExemption",n),PT);return"error"in i?0:i.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=wv(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),oE);if("error"in t)throw new tA(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),i=wv(await this._rpcRequest("getFeeCalculatorForBlockhash",n),sE);if("error"in i)throw new tA(i.error,"failed to get fee calculator");const{context:r,value:o}=i.result;return{context:r,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const n=TS(e.serialize()).toString("base64"),i=this._buildArgs([n],t),r=wv(await this._rpcRequest("getFeeForMessage",i),BA(Iv(Cv())));if("error"in r)throw new tA(r.error,"failed to get fee for message");if(null===r.result)throw new Error("invalid blockhash");return r.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],i=wv(await this._rpcRequest("getRecentPrioritizationFees",n),JA);if("error"in i)throw new tA(i.error,"failed to get recent prioritization fees");return i.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}=IA(e),i=this._buildArgs([],t,void 0,n),r=wv(await this._rpcRequest("getLatestBlockhash",i),iE);if("error"in r)throw new tA(r.error,"failed to get latest blockhash");return r.result}async isBlockhashValid(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgs([e],n,void 0,i),o=wv(await this._rpcRequest("isBlockhashValid",r),rE);if("error"in o)throw new tA(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=wv(await this._rpcRequest("getVersion",[]),_A(WA));if("error"in e)throw new tA(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=wv(await this._rpcRequest("getGenesisHash",[]),_A(_v()));if("error"in e)throw new tA(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgsAtLeastConfirmed([e],n,void 0,i),o=await this._rpcRequest("getBlock",r);try{switch(i?.transactionDetails){case"accounts":{const e=wv(o,XT);if("error"in e)throw e.error;return e.result}case"none":{const e=wv(o,VT);if("error"in e)throw e.error;return e.result}default:{const e=wv(o,jT);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:DA(n,e.message)},version:n}))}:null}}}catch(e){throw new tA(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",i),o=await this._rpcRequest("getBlock",r);try{switch(i?.transactionDetails){case"accounts":{const e=wv(o,JT);if("error"in e)throw e.error;return e.result}case"none":{const e=wv(o,ZT);if("error"in e)throw e.error;return e.result}default:{const e=wv(o,QT);if("error"in e)throw e.error;return e.result}}}catch(e){throw new tA(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:i,...r}=e;n=i,t=r}const i=this._buildArgs([],n,"base64",t),r=wv(await this._rpcRequest("getBlockProduction",i),VA);if("error"in r)throw new tA(r.error,"failed to get block production information");return r.result}async getTransaction(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgsAtLeastConfirmed([e],n,void 0,i),o=wv(await this._rpcRequest("getTransaction",r),tE);if("error"in o)throw new tA(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:DA(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:i}=IA(t),r=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",i),o=wv(await this._rpcRequest("getTransaction",r),nE);if("error"in o)throw new tA(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:n,config:i}=IA(t),r=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",i)}));return(await this._rpcBatchRequest(r)).map(e=>{const t=wv(e,nE);if("error"in t)throw new tA(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:i}=IA(t),r=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,i)}));return(await this._rpcBatchRequest(r)).map(e=>{const t=wv(e,tE);if("error"in t)throw new tA(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:DA(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),i=wv(await this._rpcRequest("getBlock",n),YT);if("error"in i)throw new tA(i.error,"failed to get confirmed block");const r=i.result;if(!r)throw new Error("Confirmed block "+e+" not found");const o={...r,transactions:r.transactions.map(({transaction:e,meta:t})=>{const n=new zS(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:JS.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const i=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),r=wv(await this._rpcRequest("getBlocks",i),_A(Sv(Cv())));if("error"in r)throw new tA(r.error,"failed to get blocks");return r.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),i=wv(await this._rpcRequest("getBlock",n),eE);if("error"in i)throw new tA(i.error,"failed to get block");const r=i.result;if(!r)throw new Error("Block "+e+" not found");return r}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),i=wv(await this._rpcRequest("getBlock",n),eE);if("error"in i)throw new tA(i.error,"failed to get confirmed block");const r=i.result;if(!r)throw new Error("Confirmed block "+e+" not found");return r}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),i=wv(await this._rpcRequest("getTransaction",n),tE);if("error"in i)throw new tA(i.error,"failed to get transaction");const r=i.result;if(!r)return r;const o=new zS(r.transaction.message),s=r.transaction.signatures;return{...r,transaction:JS.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),i=wv(await this._rpcRequest("getTransaction",n),nE);if("error"in i)throw new tA(i.error,"failed to get confirmed transaction");return i.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=wv(e,nE);if("error"in t)throw new tA(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let i={},r=await this.getFirstAvailableBlock();for(;!("until"in i)&&!(--t<=0||t<r);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(i.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let o=await this.getSlot("finalized");for(;!("before"in i||++n>o);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(i.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,i)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const i=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),r=wv(await this._rpcRequest("getConfirmedSignaturesForAddress2",i),pT);if("error"in r)throw new tA(r.error,"failed to get confirmed signatures for address");return r.result}async getSignaturesForAddress(e,t,n){const i=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),r=wv(await this._rpcRequest("getSignaturesForAddress",i),mT);if("error"in r)throw new tA(r.error,"failed to get signatures for address");return r.result}async getAddressLookupTable(e,t){const{context:n,value:i}=await this.getAccountInfoAndContext(e,t);let r=null;return null!==i&&(r=new bA({key:e,state:bA.deserialize(i.data)})),{context:n,value:r}}async getNonceAndContext(e,t){const{context:n,value:i}=await this.getAccountInfoAndContext(e,t);let r=null;return null!==i&&(r=aA.fromAccountData(i.data)),{context:n,value:r}}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=wv(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),aE);if("error"in n)throw new tA(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await nA(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 nA(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}=IA(e),i=this._buildArgs([],t,"base64",n),r=wv(await this._rpcRequest("getStakeMinimumDelegation",i),BA(Cv()));if("error"in r)throw new tA(r.error,"failed to get stake minimum delegation");return r.result}async simulateTransaction(e,t,n){if("message"in e){const i=e.serialize(),r=_g.Buffer.from(i).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[r,o],a=wv(await this._rpcRequest("simulateTransaction",s),jA);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let i;if(e instanceof JS){let t=e;i=new JS,i.feePayer=t.feePayer,i.instructions=e.instructions,i.nonceInfo=t.nonceInfo,i.signatures=t.signatures}else i=JS.populate(e),i._message=i._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(i.nonceInfo&&r)i.sign(...r);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(i.lastValidBlockHeight=t.lastValidBlockHeight,i.recentBlockhash=t.blockhash,!r)break;if(i.sign(...r),!i.signature)throw new Error("!signature");const n=i.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const o=i._compile(),s=o.serialize(),a=i._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:o.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}r&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=wv(await this._rpcRequest("simulateTransaction",l),jA);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 eA({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 i=t;if(e.nonceInfo)e.sign(...i);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...i),!e.signature)throw new Error("!signature");const r=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(r)){this._blockhashInfo.transactionSignatures.push(r);break}t=!0}}const r=e.serialize();return await this.sendRawTransaction(r,n)}async sendRawTransaction(e,t){const n=TS(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},i=t&&t.skipPreflight,r=!0===i?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),i&&(n.skipPreflight=i),r&&(n.preflightCommitment=r);const o=[e,n],s=wv(await this._rpcRequest("sendTransaction",o),cE);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new eA({action:i?"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 i=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return i.add(t),()=>{i.delete(t),0===i.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:i,method:r}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(r,i);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(i){if(!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await(async()=>{const{serverSubscriptionId:i,unsubscribeMethod:r}=n;if(this._subscriptionsAutoDisposedByRpc.has(i))this._subscriptionsAutoDisposedByRpc.delete(i);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(r,[i])}catch(i){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}=wv(e,yT);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,i=pA([e.method,t]),r=this._subscriptionsByHash[i];return void 0===r?this._subscriptionsByHash[i]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:r.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=i,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const t=this._subscriptionsByHash[i];qS(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:i,config:r}=IA(n),o=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",r);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=wv(e,kT);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,i){const{commitment:r,config:o}=IA(n),s=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",o||(i?{filters:CA(i)}: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 i=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],n||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},i)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:n}=wv(e,uE);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=wv(e,vT);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}=wv(e,AT);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,i){const r=t||this._commitment;if(r||n||i){let t={};n&&(t.encoding=n),r&&(t.commitment=r),i&&(t=Object.assign(t,i)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,i){const r=t||this._commitment;if(r&&!["confirmed","finalized"].includes(r))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,i)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=wv(e,TT);"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 i=this._buildArgs([e],n||this._commitment||"finalized"),r=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(r)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return r}onSignatureWithOptions(e,t,n){const{commitment:i,...r}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},o=this._buildArgs([e],i,void 0,r),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=wv(e,ET);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 gE{constructor(e){this._keypair=void 0,this._keypair=e??bS()}static generate(){return new gE(bS())}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),i=vS(t);for(let e=0;e<32;e++)if(n[e]!==i[e])throw new Error("provided secretKey is invalid")}return new gE({publicKey:n,secretKey:e})}static fromSeed(e){const t=vS(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new gE({publicKey:t,secretKey:n})}get publicKey(){return new _S(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:$m.struct([$m.u32("instruction"),cA("recentSlot"),$m.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:$m.struct([$m.u32("instruction")])},ExtendLookupTable:{index:2,layout:$m.struct([$m.u32("instruction"),cA(),$m.seq(LS(),$m.offset($m.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:$m.struct([$m.u32("instruction")])},CloseLookupTable:{index:4,layout:$m.struct([$m.u32("instruction")])}}),new _S("AddressLookupTab1e1111111111111111111111111");const fE=Object.freeze({RequestUnits:{index:0,layout:$m.struct([$m.u8("instruction"),$m.u32("units"),$m.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:$m.struct([$m.u8("instruction"),$m.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:$m.struct([$m.u8("instruction"),$m.u32("units")])},SetComputeUnitPrice:{index:3,layout:$m.struct([$m.u8("instruction"),cA("microLamports")])}});class pE{constructor(){}static requestUnits(e){const t=iA(fE.RequestUnits,e);return new QS({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=iA(fE.RequestHeapFrame,e);return new QS({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=iA(fE.SetComputeUnitLimit,e);return new QS({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=iA(fE.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new QS({keys:[],programId:this.programId,data:t})}}var mE;pE.programId=new _S("ComputeBudget111111111111111111111111111111"),$m.struct([$m.u8("numSignatures"),$m.u8("padding"),$m.u16("signatureOffset"),$m.u16("signatureInstructionIndex"),$m.u16("publicKeyOffset"),$m.u16("publicKeyInstructionIndex"),$m.u16("messageDataOffset"),$m.u16("messageDataSize"),$m.u16("messageInstructionIndex")]),new _S("Ed25519SigVerify111111111111111111111111111"),kS.utils.isValidPrivateKey,$m.struct([$m.u8("numSignatures"),$m.u16("signatureOffset"),$m.u8("signatureInstructionIndex"),$m.u16("ethAddressOffset"),$m.u8("ethAddressInstructionIndex"),$m.u16("messageDataOffset"),$m.u16("messageDataSize"),$m.u8("messageInstructionIndex"),$m.blob(20,"ethAddress"),$m.blob(64,"signature"),$m.u8("recoveryId")]),new _S("KeccakSecp256k11111111111111111111111111111"),new _S("StakeConfig11111111111111111111111111111111");class yE{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}}mE=yE,yE.default=new mE(0,0,_S.default),Object.freeze({Initialize:{index:0,layout:$m.struct([$m.u32("instruction"),((e="authorized")=>$m.struct([LS("staker"),LS("withdrawer")],e))(),((e="lockup")=>$m.struct([$m.ns64("unixTimestamp"),$m.ns64("epoch"),LS("custodian")],e))()])},Authorize:{index:1,layout:$m.struct([$m.u32("instruction"),LS("newAuthorized"),$m.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:$m.struct([$m.u32("instruction")])},Split:{index:3,layout:$m.struct([$m.u32("instruction"),$m.ns64("lamports")])},Withdraw:{index:4,layout:$m.struct([$m.u32("instruction"),$m.ns64("lamports")])},Deactivate:{index:5,layout:$m.struct([$m.u32("instruction")])},Merge:{index:7,layout:$m.struct([$m.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:$m.struct([$m.u32("instruction"),LS("newAuthorized"),$m.u32("stakeAuthorizationType"),FS("authoritySeed"),LS("authorityOwner")])}}),new _S("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:$m.struct([$m.u32("instruction"),((e="voteInit")=>$m.struct([LS("nodePubkey"),LS("authorizedVoter"),LS("authorizedWithdrawer"),$m.u8("commission")],e))()])},Authorize:{index:1,layout:$m.struct([$m.u32("instruction"),LS("newAuthorized"),$m.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:$m.struct([$m.u32("instruction"),$m.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:$m.struct([$m.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:$m.struct([$m.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>$m.struct([$m.u32("voteAuthorizationType"),LS("currentAuthorityDerivedKeyOwnerPubkey"),FS("currentAuthorityDerivedKeySeed"),LS("newAuthorized")],e))()])}}),new _S("Vote111111111111111111111111111111111111111"),new _S("Va1idator1nfo111111111111111111111111111111"),Pv({name:_v(),website:Nv(_v()),details:Nv(_v()),iconUrl:Nv(_v()),keybaseUsername:Nv(_v())}),new _S("Vote111111111111111111111111111111111111111"),$m.struct([LS("nodePubkey"),LS("authorizedWithdrawer"),$m.u8("commission"),$m.nu64(),$m.seq($m.struct([$m.nu64("slot"),$m.u32("confirmationCount")]),$m.offset($m.u32(),-8),"votes"),$m.u8("rootSlotValid"),$m.nu64("rootSlot"),$m.nu64(),$m.seq($m.struct([$m.nu64("epoch"),LS("authorizedVoter")]),$m.offset($m.u32(),-8),"authorizedVoters"),$m.struct([$m.seq($m.struct([LS("authorizedPubkey"),$m.nu64("epochOfLastAuthorizedSwitch"),$m.nu64("targetEpoch")]),32,"buf"),$m.nu64("idx"),$m.u8("isEmpty")],"priorVoters"),$m.nu64(),$m.seq($m.struct([$m.nu64("epoch"),$m.nu64("credits"),$m.nu64("prevCredits")]),$m.offset($m.u32(),-8),"epochCredits"),$m.struct([$m.nu64("slot"),$m.nu64("timestamp")],"lastTimestamp")]);function wE(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function kE(e){const t=new Map;for(const n of e)t.set(Ks(n.symbol),n);return t}function bE(e,t,n){const i=function(e,t){return e.get(Ks(t))}(e,t);if(!i){throw be(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return i}function vE(e){if(null==e||!wE(e))throw we("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}class SE{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=Gs(e),n=this.cache.get(t);if(n)return n;const i=eu[t];if(void 0!==i)return this.cache.set(t,i),i;const r=await this.fetchFromApi(e);return this.cache.set(t,r),r}hasMetadata(e){const t=Gs(e);return this.cache.has(t)||t in eu}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),i=n.find(e=>Gs(e.symbol)===Gs(t)&&e.verified);if(i||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),i=n.find(e=>Gs(e.symbol)===Gs(t)&&e.verified)),!i)throw new Error(`Unable to locate token metadata for ${e}`);return r={collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},o=i.decimals,s=i.channel,{descriptor:{collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey},decimals:o,...void 0!==s?{channel:s}:{}};var r,o,s}}async function AE(e,t){const{wallet:n}=t,i=e.uniqueKey??`galaconnect-operation-${$.randomUUID()}`,r="string"==typeof e.destinationChainId?ht(e.destinationChainId,1):e.destinationChainId,o=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?ht(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?ht(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?ht(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?ht(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?ht(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?ht(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(o.galaExchangeCrossRate),a={destinationChainId:r,destinationChainTxFee:kg(s?{...o,galaExchangeRate:void 0}:{...o,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:i},c=pu(s),l=await n.signTypedData(cu,c,a),u=`Ethereum Signed Message:\n${Rl({domain:cu,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:cu}}const TE=5,EE=6,IE=7;function CE(e){const t=ht(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===TE,isFailed:t===EE||t===IE}}const NE="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",xE="Bridge request ID missing from RequestTokenBridgeOut response",_E="BridgeTokenOut response missing transaction hash";function BE(e){if(void 0===e||""===e)throw be(NE,"tokenSymbol");return e}function PE(e,t){if(!n(e)){throw we(t??"address","a valid 0x-prefixed Ethereum address",e)}}function DE(e,t){try{return new _S(e)}catch{throw we(t??"address","a valid Solana address (base58)",e)}}function RE(e){try{return new _S(e)}catch{throw we("address","a valid Solana address (base58)",e)}}function ME(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function LE(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function FE(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function UE(e,t,n){const i=e.find(e=>e.symbol===t);if(!i){const i=e.map(e=>e.symbol).join(", ");throw ye("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${i}`)}return i}const OE={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function $E(e,t,n){if(void 0===e)throw be(n??OE[t],`${t.toLowerCase()}Strategy`);return e}function qE(e){return{direction:"inbound",fromChain:e.fromChain,toChain:"GalaChain",transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}function KE(e,t){return $E(e.get("Ethereum"),"Ethereum",t)}function GE(e,t){return $E(e.get("Solana"),"Solana",t)}function WE(e,t){return e??t.getWalletAddress()}async function HE(e,t){const{amount:n,recipientAddress:i,tokenSymbol:r}=e,{galaConnectClient:o,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=BE(r);bg(n,d),u(i,"recipient");const h=await s.getTokenMetadata(d),g=await o.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),f=function(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:"0"}}}({destinationChainId:c,bridgeFee:g,amount:n,recipientAddress:i,tokenDescriptor:h.descriptor}),p=await AE(f,{wallet:a}),m=function(e){if(void 0===e||""===e)throw be(xE,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}(await o.requestBridgeOut(p)));return function(e){return{direction:"outbound",fromChain:"GalaChain",toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}({toChain:l,transactionHash:function(e){const t=e.Hash??e.hash??"";if(""===t)throw be(_E,"transactionHash");return t}(await o.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:o.getBaseUrl()})}class zE 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 jE=jl,VE="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",XE=12,QE=!0,JE=3,ZE=1e3;class YE{constructor(e){this.baseUrl=e.baseUrl??jE,this.galachainBaseUrl=e.galachainBaseUrl??VE,this.walletAddress=e.walletAddress,this.rateLimiter=new ag(e.requestsPerSecond??XE),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??QE;this.retryOptions=t?{maxRetries:e.maxRetries??JE,initialDelayMs:e.retryInitialDelayMs??ZE,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>pg(e instanceof zE?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Ji(async()=>{const t=new URL("/v1/connect/bridge-configurations",this.baseUrl);t.searchParams.set("searchprefix",e);const n=await this.request(t.toString(),{method:"GET"});if(!n.ok){const e=await n.text();let t;throw t=""!==e?ct(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new zE(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof zE)throw e;throw Se(e,"GalaConnectClient.getBridgeConfigurations")})}async fetchBridgeFee(e){return this.postJson("/v1/bridge/fee",e,{skipWalletHeader:!0})}async requestBridgeOut(e){return this.postJson("/v1/RequestTokenBridgeOut",e)}async bridgeTokenOut(e){return this.postJson("/v1/BridgeTokenOut",e)}async getBridgeStatus(e){return this.postJson("/v1/bridge/status",{hash:e})}async registerBridgeTransaction(e){return this.postJson("/v1/bridge/transaction",e)}async fetchBalances(e="asset"){return this.postJson("/v1/FetchBalances",{owner:this.walletAddress,channel:e},{baseUrl:this.galachainBaseUrl})}async postJson(e,t,n={}){return Ji(async()=>{const i=n.baseUrl??this.baseUrl,r=new URL(e,i),o=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(r.toString(),{method:"POST",headers:o,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!s.ok){const t=await s.text(),n=500,i=ct(t,{rawBody:t.slice(0,n)});throw new zE(s.status,e,i)}const a=await s.text();if(""!==a){const t=function(e){if(Ct(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: ${Q(e)}`}}}(a);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${t.error}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t,n)=>{if(e instanceof zE)throw e;throw Se(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"]&&void 0!==n["X-Wallet-Address"]||(n["X-Wallet-Address"]=this.walletAddress);const i=await fetch(e,{...t,headers:n});if(this.retryOptions&&!i.ok){const t=i.status;if(429===t||t>=500){const n=i.clone(),r=await this.safeParseJson(n);throw new zE(t,e,r)}}return i});return this.retryOptions?async function(e,t={}){const n={...hg,...t},i=t.shouldRetry??(e=>pg(e));let r;for(let o=1;o<=n.maxRetries+1;o++)try{return await e()}catch(e){if(r=e,o>n.maxRetries)break;if(!i(e,o))break;const s=mg(o,n);t.onRetry&&t.onRetry(e,o,s),await new Promise(e=>setTimeout(e,s))}throw r}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var eI;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(eI||(eI={}));class tI{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:i=27e5,onStatusUpdate:r}=t,o=Date.now();for(;;){const t=await this.getStatus(e);if(r&&r(t),t.status===eI.COMPLETED||t.status===eI.FAILED||t.status===eI.DELIVERY_FAILED)return t;if(Tt(o)>i)throw ve(`Bridge transaction timed out after ${i}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class nI extends tI{constructor(e){super(),this.network="Ethereum",this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,vE(e.ethereumPrivateKey);const t=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new i(t),this.ethereumWallet=new r(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const n=e.tokenConfigs??Zl;this.tokenConfigs=kE(n),this.tokenMetadataResolver=new SE({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return vg(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return HE(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Ml.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:PE})}async bridgeIn(e){const{amount:n,sourcePrivateKey:i,recipientAddress:s,tokenSymbol:a}=e,c=BE(a);if(bg(n,c),void 0!==i&&""!==i&&!wE(i))throw we("sourcePrivateKey","0x-prefixed 64-character hex string",i.slice(0,10)+"...");const l=void 0!==i&&""!==i?new r(i,this.ethereumProvider):this.ethereumWallet,u=bE(this.tokenConfigs,c,"Ethereum bridge"),d=await this.tokenMetadataResolver.getTokenMetadata(c),h=new o(u.contractAddress,tu,l),g=ht(await h.decimals(),18),f=cg(n,g),p=BigInt(await h.balanceOf(l.address));if(p<f){throw be(`Insufficient ${c} balance on Ethereum. Needed ${lg(f,g)}, have ${lg(p,g)}`,"amount")}const m=function(e){const n=new Gt;if("client"===n.detectFormat(e))return e;const i=n.normalizeInput(e);if(null==i)throw we("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const r=n.extractHex(i);return`eth|${t("0x"+r).slice(2)}`}(s??this.galaChainWalletAddress);return qE({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:l,tokenContract:h,tokenConfig:u,amountBaseUnits:f,decimals:g,recipient:m,metadata:d})).txHash,tokenSymbol:c,amount:n,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return CE(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(Ks(e))}isValidAddress(e){return Et.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=bE(this.tokenConfigs,e,"Ethereum"),i=t??this.ethereumWalletAddress;PE(i);const r=new o(n.contractAddress,tu,this.ethereumProvider);return lg(await r.balanceOf(i),n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;PE(t);return lg(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 we("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>=nI.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: ${Q(e)}`}}}async executeBridgeDeposit(e){const t=new o(this.ethereumBridgeContract,nu,e.wallet),n=(new TextEncoder).encode(e.recipient);let i;i=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n);if(!await i.wait())throw be("Bridge transaction receipt not available","ethereumRpcUrl");await yg(3e4);const r={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:lg(e.amountBaseUnits,e.decimals),tokenInstance:r,fromChain:"Ethereum",toChain:"GC",hash:i.hash}),{txHash:i.hash}}async bridgeWithPermit(e,t,n,i,r,o){const a=await this.ethereumProvider.getNetwork(),c=await t.name(),l=await t.nonces(e.address),u=BigInt(Math.floor(Date.now()/1e3)+3600),d=await e.signTypedData({name:c,version:"1",chainId:ht(a.chainId,1),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:r,nonce:l,deadline:u}),h=s.from(d);return await i.bridgeOutWithPermit(n.contractAddress,r,Ml.GALA_CHAIN,o,u,h.v,h.r,h.s)}async bridgeWithApproval(e,t,n,i,r,o){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<r){const e=await t.approve(this.ethereumBridgeContract,r);await e.wait()}return await n.bridgeOut(i.contractAddress,r,0,Ml.GALA_CHAIN,o)}}nI.ETHEREUM_FINALITY_THRESHOLD=12;const iI=new _S("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new _S("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const rI=new _S("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new _S("So11111111111111111111111111111111111111112"),new _S("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const oI=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var sI,aI={};var cI=(sI||(sI=1,Object.defineProperty(aI,"__esModule",{value:!0}),aI.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},aI.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},aI.toBufferLE=function(e,t){{const n=e.toString(16),i=Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex");return i.reverse(),i}},aI.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}}),aI);const lI=(uI=8,e=>{const t=$m.blob(uI,e),{encode:n,decode:i}=oI(t),r=t;return r.decode=(e,t)=>{const n=i(e,t);return cI.toBigIntLE(Buffer.from(n))},r.encode=(e,t,i)=>{const r=cI.toBufferLE(e,uI);return n(r,t,i)},r});var uI;const dI=e=>{const t=$m.blob(32,e),{encode:n,decode:i}=oI(t),r=t;return r.decode=(e,t)=>{const n=i(e,t);return new _S(n)},r.encode=(e,t,i)=>{const r=e.toBuffer();return n(r,t,i)},r};var hI;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(hI||(hI={}));const gI=$m.struct([dI("mint"),dI("owner"),lI("amount"),$m.u32("delegateOption"),dI("delegate"),$m.u8("state"),$m.u32("isNativeOption"),lI("isNative"),lI("delegatedAmount"),$m.u32("closeAuthorityOption"),dI("closeAuthority")]);gI.span;var fI=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 i=e.charAt(n),r=i.charCodeAt(0);if(255!==t[r])throw new TypeError(i+" is ambiguous");t[r]=n}const n=e.length,i=e.charAt(0),r=Math.log(n)/Math.log(256),o=Math.log(256)/Math.log(n);function s(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let o=0,s=0,a=0;for(;e[o]===i;)s++,o++;const c=(e.length-o)*r+1>>>0,l=new Uint8Array(c);for(;o<e.length;){const i=e.charCodeAt(o);if(i>255)return;let r=t[i];if(255===r)return;let s=0;for(let e=c-1;(0!==r||s<a)&&-1!==e;e--,s++)r+=n*l[e]>>>0,l[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw new Error("Non-zero carry");a=s,o++}let u=c-a;for(;u!==c&&0===l[u];)u++;const d=new Uint8Array(s+(c-u));let h=s;for(;u!==c;)d[h++]=l[u++];return d}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let r=0,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,r++;const l=(c-a)*o+1>>>0,u=new Uint8Array(l);for(;a!==c;){let e=t[a],i=0;for(let t=l-1;(0!==e||i<s)&&-1!==t;t--,i++)e+=256*u[t]>>>0,u[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");s=i,a++}let d=l-s;for(;d!==l&&0===u[d];)d++;let h=i.repeat(r);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 pI(e,t,n,i,r){const[o]=_S.findProgramAddressSync([t.toBuffer(),i.toBuffer(),e.toBuffer()],r);return o}class mI extends tI{constructor(e){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,vE(e.ethereumPrivateKey);const t=new i("https://ethereum.publicnode.com");this.ethereumWallet=new r(e.ethereumPrivateKey,t);const n=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let o;this.solanaConnection=new hE(n,"confirmed");try{o=fI.decode(e.solanaPrivateKeyBase58)}catch{throw we("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==o.length)throw we("solanaPrivateKeyBase58","64 bytes when decoded",`${o.length} bytes`);this.solanaKeypair=gE.fromSecretKey(o);const s=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new _S(s),[this.solanaBridgeTokenAuthority]=_S.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=_S.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=_S.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const a=e.tokenConfigs??Yl;this.tokenConfigs=kE(a),this.tokenMetadataResolver=new SE({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return vg(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return HE(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:Ml.SOLANA,destinationChain:"Solana",validateRecipientAddress:DE})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:i,tokenSymbol:r}=e,o=BE(r);bg(t,o);let s=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=fI.decode(n)}catch{throw we("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw we("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=gE.fromSecretKey(e)}const a=bE(this.tokenConfigs,o,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(o),l=cg(t,c.decimals),u=i??this.galaChainWalletAddress;return qE({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:o,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return CE(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(Ks(e))}isValidAddress(e){try{return new _S(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=bE(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const i=t??this.solanaKeypair.publicKey.toBase58(),r=RE(i),o=pI(new _S(n.mintAddress),r,0,iI,rI);try{const e=await async function(e,t,n,i){const r=await e.getAccountInfo(t);if(!r)throw new Error(`could not find account ${t.toBase58()}`);if(!r.owner.equals(i))throw new Error(`account owner mismatch: expected ${i.toBase58()}, got ${r.owner.toBase58()}`);return{amount:gI.decode(r.data).amount,decimals:0}}(this.solanaConnection,o,0,iI),t=n.decimals??8;return lg(e.amount,t)}catch(t){if(X(t)&&t.message.includes("could not find")){return lg(0n,n.decimals??8)}throw be(`Failed to fetch ${e} balance for ${i}: ${Q(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=RE(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return lg(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){Pe(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?RE(t):this.solanaKeypair.publicKey,i=this.solanaConnection.rpcEndpoint;if(!i.includes("devnet"))throw be(`Solana devnet faucet only available on devnet. Current RPC: ${i}. Ensure SDK is configured with environment='STAGE' for devnet access.`,"solanaRpcUrl");const r=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,r)}async getSolanaTransactionStatus(e){if(!It(e))throw we("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw we("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 _S(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),i=n?void 0:await this.getSolanaBridgeAccounts(t),r=n?void 0:pI(t,e.keypair.publicKey,0,iI,rI),o=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(o.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,o):this.buildTokenBridgeInstruction(e.keypair.publicKey,r,t,i,s,a,o),l=new JS;l.add(pE.setComputeUnitPrice({microLamports:375e3}),pE.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 i=null;for(let r=1;r<=n;r++){try{const o=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=o.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:o.blockhash,lastValidBlockHeight:o.lastValidBlockHeight},"confirmed"),s}catch(e){const t=X(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const o=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===o.value[0]?.confirmationStatus||"finalized"===o.value[0]?.confirmationStatus)return s;i=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${r}/${n})`)}}catch(e){i=X(e)?e:new Error(Q(e));const t=i.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||r===n)throw i}const o=Math.min(1e3*Math.pow(2,r-1),5e3);await yg(o)}throw i??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,i){const r=Buffer.concat([iu.BRIDGE_OUT_NATIVE,t,n,i]);return new QS({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:uA.programId,isSigner:!1,isWritable:!1}],data:r})}buildTokenBridgeInstruction(e,t,n,i,r,o,s){const a=Buffer.concat([iu.BRIDGE_OUT,r,o,s]);return new QS({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:i.mintLookup,isSigner:!1,isWritable:!1},{pubkey:i.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:i.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:uA.programId,isSigner:!1,isWritable:!1},{pubkey:iI,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[i]=_S.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),r=await this.solanaConnection.getAccountInfo(i,"confirmed");if(!r)throw be(`Mint lookup account not found for ${i.toBase58()}`,"solanaBridgeProgram");if(!r.owner.equals(this.solanaBridgeProgramId))throw be("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(r.data.length<40)throw be("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:i,tokenBridge:new _S(r.data.slice(8,40)),bridgeTokenAccount:pI(e,this.solanaBridgeTokenAuthority,0,iI,rI)};return this.solanaBridgeAccountCache.set(t,o),o}}const yI={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function wI(e){return yI[e]}const kI={PROD:{ethereum:"https://ethereum.publicnode.com",solana:"https://api.mainnet-beta.solana.com"},STAGE:{ethereum:"https://ethereum-sepolia.publicnode.com",solana:"https://api.devnet.solana.com"}},bI={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class vI{static normalizeGalaChainAddress(e){const t=new Gt;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 i=t.normalizeInput(n);if(null==i)throw be(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const r=t.extractHex(i);return`eth|${vI.checksumAddress(r)}`}static checksumAddress(e){const t=e.toLowerCase(),n=qt(a(c(t)));let i="";for(let e=0;e<t.length;e++){const r=t[e];parseInt(n[e],16)>=8?i+=r.toUpperCase():i+=r}return i}constructor(e){const t=vI.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",i=yI[n],r=kI[n],o={galaConnectBaseUrl:e.galaConnectBaseUrl??i.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??i.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??r.ethereum,solanaRpcUrl:e.solanaRpcUrl??r.solana,ethereumBridgeContract:e.ethereumBridgeContract??Jl(n),solanaBridgeProgram:e.solanaBridgeProgram??bI.solanaBridgeProgram,rateLimit:e.rateLimit??bI.rateLimit,pollInterval:e.pollInterval??bI.pollInterval,pollTimeout:e.pollTimeout??bI.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=null!==e.solanaPrivateKey&&void 0!==e.solanaPrivateKey?{...o,solanaPrivateKey:e.solanaPrivateKey}:o,this.galaConnectClient=new YE({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=Ql(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 nI(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:Yl};this.strategies.set("Solana",new mI(e))}}async resolveTokenSymbol(e,t){return Ji(async()=>{if(!this.bridgeableTokenService)throw be("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=wg(e).stringified,i="Ethereum"===t?"ETHEREUM":"SOLANA",r=await this.bridgeableTokenService.getTokenByTokenId(n,i);if(!r){throw be([`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('${i}')`," - 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 r.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return Ji(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain);return this.getStrategy(e.destinationChain).estimateFee(t,e.amount??"0")},"BridgeService.estimateBridgeFee")}async bridgeOut(e){return Ji(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw be(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw be(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return Ji(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw be(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return Ji(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let i;if(n)try{return await n.getStatus(e)}catch(e){i=X(e)?e:new Error(Q(e))}const r=this.strategies.get("Solana");if(r)try{return await r.getStatus(e)}catch(e){i=X(e)?e:new Error(Q(e))}const o=i?` (last error: ${i.message})`:"";throw ve(`Unable to get status for transaction ${e}${o}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Ji(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},i=this.strategies.get("Ethereum");if(i)try{return await i.getStatus(e),i.waitForCompletion(e,n)}catch{}const r=this.strategies.get("Solana");if(r)return r.waitForCompletion(e,n);throw ve(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=Ql(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 Yl){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(null!=t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return Ji(async()=>KE(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Ji(async()=>KE(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Ji(async()=>GE(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Ji(async()=>GE(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Ji(async()=>{const n=KE(this.strategies),i=UE(Ql(this.config.environment),e,"Ethereum"),r=WE(t,n);return LE(i,await n.getEthereumTokenBalance(e,r))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Ji(async()=>{const t=KE(this.strategies),n=WE(e,t);return ME("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Ji(async()=>{const n=GE(this.strategies),i=UE(Yl,e,"Solana"),r=WE(t,n);return FE(i,await n.getSolanaTokenBalance(e,r))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Ji(async()=>{const t=GE(this.strategies),n=WE(e,t);return ME("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Ji(async()=>GE(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Ji(async()=>GE(this.strategies,"Solana bridge strategy not configured. This method requires Solana wallet configuration. Initialize SDK with solanaPrivateKey to use Solana features.").getSolanaTransactionStatus(e),"BridgeService.getSolanaTransactionStatus")}async getEthereumTransactionStatus(e){return Ji(async()=>KE(this.strategies,"Ethereum bridge strategy not configured. This method requires Ethereum wallet configuration. Initialize SDK with ethereumPrivateKey to use Ethereum features.").getEthereumTransactionStatus(e),"BridgeService.getEthereumTransactionStatus")}async fetchEthereumWalletAllBalances(e){return Ji(async()=>{const t=KE(this.strategies),n=WE(e,t),i=Ql(this.config.environment),[r,...o]=await Promise.all([t.getEthereumNativeBalance(n),...i.map(async e=>LE(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:ME("ETH",r,18),tokens:o,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Ji(async()=>{const t=GE(this.strategies),n=WE(e,t),[i,...r]=await Promise.all([t.getSolanaNativeBalance(n),...Yl.map(async e=>FE(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:ME("SOL",i,9),tokens:r,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw be(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}class SI extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class AI extends SI{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class TI 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 EI(e,t){if(Nt(e))throw new SI(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new SI(`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 SI(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function II(e,t,n,i){EI(e,t);const r=e,o=r.data??{};if(!function(e){if(Nt(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new SI(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===i.type?"native":"exact",inputAmount:o.inputQuantity??i.amount,outputAmount:o.outputQuantity??i.expectedAmount??"0",totalFees:o.totalFees??"0",tokenName:i.tokenName,vaultAddress:o.vaultAddress??"",timestamp:Date.now()};return void 0!==r.blockHash&&(s.blockHash=r.blockHash),void 0!==r.gasUsed&&(s.gasUsed=r.gasUsed),void 0!==i.slippageToleranceFactor&&(s.slippageTolerance=i.slippageToleranceFactor),s}const CI="5.0.4-beta.6";class NI{constructor(e){this.logger=e??new bt({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],i=new WeakSet,r=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(null!=e&&!It(e)&&"object"==typeof e){if(i.has(e))return;i.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))r(t,o+1)}};return r(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(null===t||""===t)return null;const n=e.Data,i=null==n||"object"!=typeof n||Array.isArray(n)?e:n,r=this.extractPositionId(i),o=this.extractPoolHash(i),s=this.extractAmounts(i),a=this.extractUserAddress(i),c=this.extractPoolFee(i);if(null===r||""===r||null===o||""===o||null===s||null===a||""===a||null===c)return null;const l=this.extractPoolAlias(i),u=this.extractUserBalanceDelta(i),d=this.extractTimestamp(i),h=u?.token0Balance?.collection,g=u?.token1Balance?.collection,f={transactionId:t,positionId:r,poolHash:o,poolFee:c,amounts:s,userAddress:a};return void 0!==h&&(f.token0=h),void 0!==g&&(f.token1=g),void 0!==d&&(f.timestamp=d),void 0!==l&&(f.poolAlias=l),void 0!==u&&(f.userBalanceDelta=u),f}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(It(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(It(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","poolId","pool"];for(const n of t){const t=e[n];if(It(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(It(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,i=e.amount1??e.amount1Desired;return void 0!==n&&void 0!==i?[String(n),String(i)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const n of t){const t=e[n];if(It(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(It(t)){const e=lt(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(It(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,i=this.extractBalanceObject(n.token0Balance),r=this.extractBalanceObject(n.token1Balance);if(!i&&!r)return;const o={};return void 0!==i&&(o.token0Balance=i),void 0!==r&&(o.token1Balance=r),o}extractBalanceObject(e){if(null==e||"object"!=typeof e)return;const t=e,n=t.collection,i=t.category,r=t.type,o=t.additionalKey,s=t.quantity,a=t.owner;return It(n)&&It(i)&&It(r)&&It(o)&&It(s)&&It(a)?{collection:n,category:i,type:r,additionalKey:o,quantity:s,owner:a}:void 0}}class xI{constructor(e){this.wallet=e.wallet;let t=null,n="STAGE";if(void 0!==e.env?(n=e.env,t=wI(e.env)):e.baseUrl?.includes("prod")?(n="PROD",t=wI("PROD")):(n="STAGE",t=wI("STAGE")),this.environment=n,this.config={baseUrl:t.launchpadBaseUrl,galaChainBaseUrl:t.galaChainBaseUrl,bundleBaseUrl:t.bundleBaseUrl,webSocketUrl:t.webSocketUrl,dexApiBaseUrl:t.dexApiBaseUrl,dexBackendBaseUrl:t.dexBackendBaseUrl,launchpadFrontendUrl:t.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new bt({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?xI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?xI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??xI.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency??5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new en({wallet:e.wallet,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new nn,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new tr(this.auth,this.config),this.sessionAuth=new Yi(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new tr(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new tr(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new tr(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new tr(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=z(this.config.galaChainBaseUrl,this.config.timeout??3e4),this.galaChainClient=new Vc({baseUrl:this.config.galaChainBaseUrl,timeout:this.config.timeout??3e4}),this.cache=new nl(e.debug??!1),this.launchpadService=new Aa(this.http,this.jwtAuth),this.tokenResolverService=new Gc(this.launchpadService.poolService),this.launchpadAPI=new sg(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Nc(this.galaChainHttp,e.wallet,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new xc(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new Mc(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,e.wallet,e.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Kc({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Wc(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService),this.dexQuoteService=new ol(this.galaChainHttp,this.config.galaChainBaseUrl,e.debug??!1,e.dexQuoteNetworkTimeout??3e4),this.gswapService=new Yc({privateKey:e.wallet?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new il(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug??!1),this.nftCollectionService=new zh(this.galaChainHttp,this.galaChainClient)}createOverrideSdk(e){if(!It(e))throw be("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw be('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new r(e),n={...this.config,wallet:t};return new xI(n)}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 ye("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new re("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e)}getWallet(){return this.wallet}hasWallet(){return void 0!==this.wallet}getConfig(){const{wallet:e,...t}=this.config;return{...t,environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:el.GAS_FEE}}getVersion(){return CI}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw be("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:i}=Pt(e,"tokenName","tokenId",{description:"token identifier"});if(i&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const r=n;try{return await this.dexService.fetchTokenPrice({tokenId:r})}catch(e){const t=function(e){if(Y(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=qs((await this.fetchTokenDetails(r)).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: ${Q(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(ir(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,i=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=i.currentSupply,n.reverseBondingCurveMaxFeeFactor=i.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=i.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=i.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 Yt}),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 vI({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 bl(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new Al(this.dexApiHttp,this.config.debug??!1)),this._wrappableTokenService}getGalaConnectClient(){if(null===this._galaConnectClient||void 0===this._galaConnectClient){const e=this.getAddress();if(void 0===e)throw new Error("GalaConnectClient requires a wallet. Configure SDK with a wallet first.");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 YE({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 yu({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new qu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new rd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._streamChatService}getBanService(){return this._banService??(this._banService=new yd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Td(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._tokenBanService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new Rd(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Jd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new fh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new Ch(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._overseerService}getCommentService(){return this._commentService??(this._commentService=new Nh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Bh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._contentReactionService}getCommentsService(){return this._commentsService??(this._commentsService=new Ph(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._commentsService}getChatMessagesService(){return this._chatMessagesService??(this._chatMessagesService=new Uh(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1)),this._chatMessagesService}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 sd({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new ad(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}async getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}logout(){this.sessionAuth.logout()}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async getStreamInfo(e){return this.getStreamingService().getStreamInfo(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async getEngagementStats(e){if(null===ca(e.tokenName))throw ye("tokenName","tokenName is required and cannot be empty");return this.getStreamChatService().getEngagementStats(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getGlobalChatStatus(){return this.getStreamChatService().getGlobalChatStatus()}async setGlobalChatEnabled(e){const t=this.getStreamChatService();return e?t.enableGlobalChat():t.disableGlobalChat()}async getPinnedChatMessage(e){return this.getStreamChatService().getPinnedMessage(e)}async pinChatMessage(e,t){return this.getStreamChatService().pinMessage({tokenName:e,messageId:t})}async unpinChatMessage(e){return this.getStreamChatService().unpinMessage(e)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){return this.getCommentsService().getComments(e)}async createComment(e){return this.getCommentsService().createComment(e)}async updateComment(e,t){return this.getCommentsService().updateComment(e,t)}async deleteComment(e){return this.getCommentsService().deleteComment(e)}async getChatMessages(e){return this.getChatMessagesService().getChatMessages(e)}async sendChatMessage(e){return this.getChatMessagesService().sendMessage(e)}async updateChatMessage(e,t){return this.getChatMessagesService().updateMessage(e,t)}async deleteChatMessage(e){return this.getChatMessagesService().deleteMessage(e)}async getTrades(e){return this.launchpadService.getTrades(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getWallet();if(!e)throw new Error("WebSocket authentication requires a wallet. Configure SDK with a wallet first.");const t=this.getStreamWebSocketService(),n=this.getAddress(),i=Date.now(),r=`Authenticate stream access for ${n} at ${i}`,o=await e.signMessage(r),s=JSON.stringify({address:n,timestamp:i,message:r,signature:o});t.authenticate(s)}async subscribeToStream(e){return this.getStreamWebSocketService().subscribeToStream(e)}async unsubscribeFromStream(e){return this.getStreamWebSocketService().unsubscribeFromStream(e)}async sendStreamChatViaWebSocket(e,t){return this.getStreamWebSocketService().sendChatMessage(e,t)}async sendStreamReaction(e,t,n=0){return this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}async getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return Ha}),i=t(e.tokenId),{collection:r,category:o,type:s,additionalKey:a}=i;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:o,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Gs(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const i=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,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,offset:0,limit:1,...void 0!==n?{address:n}:{}})).tokens[0];if(null==t)return null;const i=t.collection??"Token",r={collection:i,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.quantity,collection:i,category:"Unit",tokenId:Na(r),symbol:t.symbol,name:t.name}}throw ye("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:i,privateKey:r,calculateAmountMode:o,currentSupply:s}=e;let a=t;void 0===o&&void 0===s||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.remainingTokens,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==i&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=i),void 0!==r&&(l.privateKey=r),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,...i}=e;return t.buy(i)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw ve("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>II(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...i}=e;return t.sell(i)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw ve("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>II(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,...i}=e;return t.launchToken(i)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{EI(n,t);const i=n?.data??{};if(!function(e){if(Nt(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)}(i))throw new SI(`Invalid launch data received for transaction ${t}`);const r={transactionId:t,vaultAddress:i.vaultAddress??"",tokenStringKey:i.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:i.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&null!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed&&null!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(r.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(r.preBuyQuantity=e.preBuyQuantity),void 0!==r.vaultAddress&&""!==r.vaultAddress&&this.tokenResolverService.set(e.tokenName,r.vaultAddress),r})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...i}=e;return t.uploadTokenImage(i)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async updateTokenSocials(e){return this.launchpadService.updateTokenSocials(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(yn,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 Yt}),i=n(e.address);if(void 0===i)throw new re(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=i}else t=this.getAddress();const n=e?.page??1,i=e?.limit??10,r={pageNumber:n,limit:i,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(wn,r,{"x-wallet-address":t});if(!Array.isArray(o))throw new oe("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:i,hasMore:o.length===i}}async fetchAllReferrals(e){const t=await Ls((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 Yt}),i=n(e.address);if(void 0===i)throw new re(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=i}else t=this.getAddress();const n=await this.dexApiHttp.get(kn,void 0,{"x-wallet-address":t});if(null==n||"number"!=typeof n.referralCount||null===n.rewardTotals||void 0===n.rewardTotals)throw new oe(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async registerAccount(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 Yt}),i=n(e.address);if(void 0===i)throw new re(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=i}else t=this.getAddress();const n=await this.dexApiHttp.post(bn,{address:t});if(null==n||"boolean"!=typeof n.exists)throw new oe(`Unexpected API response: expected { exists, walletAlias? }, got ${JSON.stringify(n)}`);if(n.exists){if(void 0===n.walletAlias||""===n.walletAlias)throw new oe(`Unexpected API response: exists=true but walletAlias is missing, got ${JSON.stringify(n)}`);return{exists:!0,walletAlias:n.walletAlias}}return{exists:!1,walletAlias:n.walletAlias??t}}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...i}=n;return e.updateProfile(i)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...i}=n;return e.uploadProfileImage(i)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n=t(e?.address)??this.getAddress(),i={offset:e?.offset??0,limit:e?.limit??10,address:n};return void 0!==e?.tokenName&&""!==e.tokenName&&(i.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(i.search=e.search),this.launchpadService.fetchTokensHeld(i)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n={type:"DEFI",address:t(e?.address)??this.getAddress(),offset:e?.offset??0,limit:e?.limit??10};return void 0!==e?.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(n.search=e.search),this.launchpadService.fetchTokenList(n)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...i}=n;return e.transferGala(i)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...i}=n;return e.transferToken(i)}return this.validateWallet(),this.galaChainService.transferToken(n)}async resolveTokenClassKey(e){return this.galaChainService.resolveTokenClassKey(e)}async lockTokens(e){const t=await Promise.all(e.tokens.map(async e=>{if(void 0!==e.lockAuthority&&""!==e.lockAuthority){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Yt});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,...i}=n;return e.lockTokens(i)}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,...i}=e;return t.unlockTokens(i)}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,...i}=e;return t.burnTokens(i)}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||(null!==this._bridgeableTokenService&&void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),null!==this._wrappableTokenService&&void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{Pe(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw be("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw be("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw be(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw be(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.galaChainBaseUrl&&""!==this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw be(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw be(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw be(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=lt("string"==typeof e||"number"==typeof e?e:String(e),xI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${e}, using default: ${xI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),xI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=lt("string"==typeof e||"number"==typeof e?e:String(e),xI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid fee slippage factor: ${e}, using default: ${xI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),xI.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 TI(e,n.status,n.message);let i;try{i=t(n)}catch(t){if(t instanceof SI)throw t;throw new SI(`Failed to transform WebSocket response for transaction ${e}`,X(t)?t:new Error(Q(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,i),i}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof TI||t instanceof SI)throw t;throw new SI(`WebSocket confirmation failed for transaction ${e}`,X(t)?t:new Error(Q(t)))}}async warmCacheFromPools(e){if(null==e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return WC});e.forEach(e=>{if(!n(e))return;const i=t(e,this.logger);i&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,i)})}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,i,r,o=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:i,feeTier:r,slippageTolerance:o})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,i){let r,o;"string"==typeof n?(r=n,o=i):"object"==typeof n?o=n:i&&(o=i);return await this.gswapService.getUserLiquidityPositions(e,t,r,o)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(null!=n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,n,i,r,o,s){return this.gswapService.getLiquidityPositionById(e,t,n,i,r,o,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const n=1e3,i=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 r=t?.minTVL,o=t?.tokens,s=new Map;let a=!0,c=null;let l=0;const u=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.items.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),null!=r){if((t.token0Tvl+t.token1Tvl)/2<r)return}if(o&&o.length>0){if(!(o.includes(t.token0)||o.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=Q(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=i*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,i=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 r=t?.creatorAddress,o=new Map;let s=!0,a=null;let c=0;const l=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",limit:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),void 0!==r&&""!==r&&t.creatorAddress!==r||e(t))})}catch(e){c++;const t=Q(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=i*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;const t=pt("string"==typeof e||"number"==typeof e?e:String(e),Number.NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:!Number.isInteger(t)||500!==t&&3e3!==t&&1e4!==t?null:t}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(null!==n[e]&&void 0!==n[e])return String(n[e]);return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();return al.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")??"",i=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol")??"",r=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return""===n||""===i||null===r?null:`${n}/${i}/${r}`}parsePoolPairString(e){const t=al.parsePoolKey(e);if(!t)return null;const n=Ra(t.token0)?Da(t.token0).collection:t.token0,i=Ra(t.token1)?Da(t.token1).collection:t.token1,r=t.feeTier.toString();return""===n||""===i||""===r?null:{token0:n,token1:i,fee:r,poolPair:e}}serializeBalanceToken(e){if(null==e||"object"!=typeof e)return"";const t=e,n=t.collection??t.token??"",i=t.category??"",r=t.type??"",o=t.additionalKey??"none";return[""!==n?n:"",""!==i?i:"none",""!==r?r:"none",""!==o?o:"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 i=n,r=i.token0Balance??i.token0??i.baseBalance??i.primaryBalance,o=i.token1Balance??i.token1??i.quoteBalance??i.secondaryBalance,s=this.serializeBalanceToken(r),a=this.serializeBalanceToken(o),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 i=this.buildPoolPairFromBalances(t);if(null!=i)return this.parsePoolPairString(i);const r=this.buildPoolPairFromObject(t);if(null!=r)return this.parsePoolPairString(r);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,i]=t.pairTokens,r=e.token0===n||e.token1===n,o=e.token0===i||e.token1===i;if(!r||!o||n===i)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 be("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,i=null;const r=(n,...i)=>{try{if(i.length>0&&"object"==typeof i[0]&&null!==i[0]){const n=i[0].data;if(null!=n?.Data&&"object"==typeof n.Data){const i=n.Data;if("CreateSale"===i.functionName){const n={tokenName:""!==i.tokenName?i.tokenName:"",symbol:""!==i.symbol?i.symbol:"",creatorAddress:""!==i.creatorAddress?i.creatorAddress:"",description:""!==i.description?i.description:"",image:""!==i.image?i.image:"",vaultAddress:""!==i.vaultAddress?i.vaultAddress:"",tokenStringKey:""!==i.tokenStringKey?i.tokenStringKey:"",preBuyQuantity:""!==i.initialBuyQuantity?i.initialBuyQuantity:"0",websiteUrl:""!==i.websiteUrl?i.websiteUrl:"",telegramUrl:""!==i.telegramUrl?i.telegramUrl:"",twitterUrl:""!==i.twitterUrl?i.twitterUrl:"",instagramUrl:""!==i.instagramUrl?i.instagramUrl:"",facebookUrl:""!==i.facebookUrl?i.facebookUrl:"",redditUrl:""!==i.redditUrl?i.redditUrl:"",tiktokUrl:""!==i.tiktokUrl?i.tiktokUrl:"",isFinalized:!1!==i.isFinalized&&null!==i.isFinalized&&void 0!==i.isFinalized&&i.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Q(e)}`)}};let o=this.websocketService.getSocket();if(o)o.onAny(r),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: ${Q(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(o=this.websocketService.getSocket(),!o&&e<xI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(i=setTimeout(()=>s(),xI.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=xI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${xI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*xI.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}return()=>{try{if(null!==i&&(clearTimeout(i),i=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(r),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 i=[];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),i.push(e))}return i}if("object"!=typeof e||null===e)return i;if(n.has(e))return i;n.add(e);const r=this.extractPoolDataFromPayload(e);r&&!t.has(r.poolPair)&&(t.add(r.poolPair),i.push(r));for(const r of Object.values(e)){const e=this.walkPayloadForPools(r,t,n);i.push(...e)}return i}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&&null!==t.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw be("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,i=null;const r=new Set,o=(n,...i)=>{try{for(const n of i){const i=this.walkPayloadForPools(n,r);for(const n of i)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${Q(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(o),n=!0,this.logger.debug("DEX pool broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${Q(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const r=()=>{if(s=this.websocketService.getSocket(),!s&&e<xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(i=setTimeout(()=>r(),xI.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS*xI.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(o),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};r()}return()=>{try{if(null!==i&&(clearTimeout(i),i=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(o),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens&&null!==t.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw be("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=null,i=null,r=null,o=!1;const s=async e=>{const t=al.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));o=!0,i=new fl(c,s,this.dexQuoteService,t??{},this.logger),r=i.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: ${Q(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),r&&o&&r(),i&&i.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&&null!==t.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw be("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,i=null;const r=new Set,o=new NI(this.logger),s=(n,...i)=>{try{for(const n of i){const i=o.walkPayloadForLiquidityEvents(n,r);for(const n of i)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${Q(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${Q(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${Q(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: ${Q(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const r=()=>{if(a=this.websocketService.getSocket(),!a&&e<xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(i=setTimeout(()=>r(),xI.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS*xI.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"))};r()}return async()=>{try{if(null!==i&&(clearTimeout(i),i=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&&da(e.token0,t.tokenFilter),i=void 0!==e.token1&&""!==e.token1&&da(e.token1,t.tokenFilter);if(!n&&!i)return!1}if(void 0!==t.pairTokens&&null!==t.pairTokens){const[n,i]=t.pairTokens,r=e.token0??"",o=e.token1??"",s=da(r,n)&&da(o,i),a=da(r,i)&&da(o,n);if(!s&&!a)return!1}if(void 0!==t.minAmount&&""!==t.minAmount){const n=lt(t.minAmount),i=lt(e.amounts[0]),r=lt(e.amounts[1]);if(Math.abs(i)<n&&Math.abs(r)<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(Nt(e))return t;if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const n=String(e).trim();if(n.endsWith("%")){const e=lt(n.replace("%",""));return Math.floor(1e4*e)}const i=parseFloat(n);return isNaN(i)?t:i<100?Math.floor(1e4*i):Math.floor(i)}(e)}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}async estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}async claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}async fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}async isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}async createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}async fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}async mintNft(e){return this.nftCollectionService.mintNft(e)}async fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{this.logger.debug("Starting cleanup..."),this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),null!==this._streamWebSocketService&&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 bt({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup...");const{WebSocketService:n}=require("./services/WebSocketService");n.cleanupAll(e),t.debug("Global cleanup completed")}}xI.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,xI.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,xI.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=el.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,xI.DEFAULT_CALCULATE_AMOUNT_MODE=rg.LOCAL,xI.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,xI.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,xI.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,xI.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class _I{static generateWallet(){try{const e=r.createRandom();if(void 0===e.mnemonic?.phrase||""===e.mnemonic?.phrase)throw ye("mnemonic","Mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new r(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),n=new r(t),i=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:n}}throw e}}static fromPrivateKey(e){const t=new r(e),n=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:n,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const n=l.fromPhrase(e),i=u.fromMnemonic(n,`m/44'/60'/0'/0/${t}`),o=new r(i.privateKey),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}catch(n){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const n=`test-mnemonic-index-${t}-${e}`,i="0x"+Buffer.from(n).toString("hex").padStart(64,"1").slice(0,64),o=new r(i),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}throw n}}static toGalaAddress(e){const t=Ht(e);if(!/^[a-fA-F0-9]{40}$/.test(t))throw we("address","a valid Ethereum address (40 hex characters)");return`eth|${t}`}static toEthereumAddress(e){try{return jt(e)}catch(t){const n=Q(t);if(n.includes("required")||!e?.startsWith("eth|"))throw ye("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw we("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=Ht(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===Zt(e)}static generateMultipleWallets(e=1){Pe(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}`,i="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(i))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${e.mnemonic??"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function BI(e){if(void 0===e)return _I.generateWallet();const t=e.trim();if(!It(t))throw we("input","a non-empty string");if(function(e){const t=Ht(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return _I.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 _I.fromMnemonic(t);throw we("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function PI(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw we("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new d(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function DI(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw we("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t(h(e))}function RI(){const e=gE.generate();return{privateKey:fI.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}}function MI(e){Nt(e)&&(e={});const{wallet:t,env:n,config:i={},...o}=e,s={...o,...i},{wallet:a,env:c,config:l,...u}=s;let d;if(Nt(t)){d=BI().wallet}else if("string"==typeof t){d=BI(t).wallet}else{if(!(t instanceof r))throw be("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");d=t}const h={wallet:d,...null!=n?{env:n}:{},debug:!1,timeout:3e4,...u};return new xI(h)}function LI(){const e=K.join(process.cwd(),"..","..",".env");G.existsSync(e)&&W.config({path:e});const t=K.join(process.cwd(),".env");G.existsSync(t)&&W.config({path:t})}function FI(e,t){const n=process.env[e];if(Nt(n)||!It(n)){throw ye(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n}function UI(e,t){return process.env[e]??t}_I.testCounter=0;class OI{static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),i=e.galaChainAddress??process.env.WALLET_ADDRESS,r={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!==i&&""!==i?{galaChainAddress:i}:{}},o=new xI(r),s={sdk:o,wallet:n,config:r};if(!1!==e.autoValidate){const e=await this.validateSetup(o,n);return{...s,validation:e}}return s}static async readOnlySetup(e={}){const t=e.environment??this.detectEnvironment(),n=e.galaChainAddress??process.env.WALLET_ADDRESS,i={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}:{}};return{sdk:new xI(i),config:i}}static async validateSetup(e,t){const n=[],i=[],r={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(r.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=lt(t.quantity,0);r.hasBalance=e>0,r.canTrade=e>=.1,r.canCreateTokens=e>=100,0===e?i.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?i.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&i.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: ${Q(e)}`)}try{const t=await e.fetchPools({type:"recent",offset:0,limit:1});null!==t.items&&void 0!==t.items&&0!==t.items.length||i.push("Pool listing not accessible - some features may be limited")}catch(e){i.push(`Pool access test failed: ${Q(e)}`)}return{ready:0===n.length&&r.connectionHealthy,sdk:e,wallet:t??_I.generateWallet(),issues:n,warnings:i,capabilities:r}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4)}return n}static async multiWalletSetup(e,t="development"){const n={};for(const[i,r]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:r,agentId:`multi-wallet-${i}`,autoValidate:!1});n[i]=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?_I.fromPrivateKey(e):_I.generateWallet()}return"generate"===e?_I.generateWallet():_I.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}}function $I(e,t,n){const i="number"==typeof e?new k(e):e;if(i.isLessThan(0)||i.isGreaterThan(1))throw new Error(`Progress must be between 0 and 1, got: ${i.toString()}`);if(n<t)throw new Error(`maxFee must be >= minFee, got minFee: ${t}, maxFee: ${n}`);const r=n-t;return new k(t).plus(new k(r).multipliedBy(i))}function qI(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}}function KI(e,t,n=60){const i=es(e),r=es(t);if(i.isLessThanOrEqualTo(0)||r.isLessThanOrEqualTo(0))throw new Error("Prices must be positive");if(i.isGreaterThanOrEqualTo(r))throw new Error(`minPrice must be < maxPrice, got: ${i.toString()} >= ${r.toString()}`);const o=Math.floor(os(i)),s=Math.ceil(os(r)),a=Math.floor(o/n)*n,c=Math.ceil(s/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new k(1.0001).pow(a),actualMaxPrice:new k(1.0001).pow(c)}}function GI(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),i=Math.floor(n);return Math.min(i,e.length-1)}function WI(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=es(e),i=new k(10).pow(t);return n.multipliedBy(i).integerValue(k.ROUND_UP).dividedBy(i)}function HI(e,t,n,i="0"){const r=es(t);if(us(r))return es(i);const o=es(e).dividedBy(r);if(null!=n){const e=es(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o}function zI(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function jI(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return es(e).multipliedBy(t).integerValue(k.ROUND_DOWN)}function VI(e,t){const n=new Map;for(const i of e){const e=t(i);n.has(e)||n.set(e,[]),n.get(e).push(i)}return n}function XI(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(It(t.name)?t.name:void 0)??(It(t.tokenName)?t.tokenName:void 0)??"";if(!It(n))throw new Error("Token name is required and must be a non-empty string");const i=(It(t.symbol)?t.symbol:void 0)??(It(t.tokenSymbol)?t.tokenSymbol:void 0)??(It(t.collection)?t.collection:void 0)??"";if(!It(i))throw new Error("Token symbol is required and must be a non-empty string");let r=8;"number"==typeof t.decimals&&t.decimals>=0&&(r=Math.floor(t.decimals));const o={name:n,symbol:i,decimals:r};return It(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o}function QI(e,t,n=null){if(null==e||"object"!=typeof e)return n;const i=e;for(const e of t){const t=e.split(".");let n=i;for(const e of t){if(null==n||"object"!=typeof n){n=null;break}n=n[e]}if(It(n))return n;if(null!=n&&""!==n)return n}return n}function JI(e,t){return e.map(e=>{const n={};for(const[i,r]of Object.entries(t)){const t=r(e);void 0!==t&&(n[i]=t)}return n})}function ZI(e,t,n=!0){const i=new Map;if(e.forEach((e,n)=>{const r=t(e);i.set(r,n)}),n){const n=new Set;return e.filter(e=>{const i=t(e);return!n.has(i)&&(n.add(i),!0)})}return e.filter((e,n)=>{const r=t(e);return i.get(r)===n})}function YI(e,t){const n={...e};for(const[e,i]of Object.entries(t))void 0!==i&&(n[e]=i);return n}class eC{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}}class tC{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,i=(e,r=0)=>{if(r>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(null!==o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))i(t,r+1)};return i(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}}class nC{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}}class iC{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 i of n)try{i(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)}}class rC{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}}class oC{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:i}=this.listeners[t];try{await i()}catch(t){const i=t instanceof Error?t:new Error(String(t));e.push(i),this.logger?.error(`Cleanup error for listener ${n}:`,i)}}return this.listeners=[],e}clear(){this.listeners=[]}get size(){return this.listeners.length}}class sC{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class aC{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping,this.logger=t}indicate(e,t){const n=`${e}:${t}`,i=this.pendingIndicators.get(n);i&&clearTimeout(i),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const r=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,r)}stopTyping(e,t){const n=`${e}:${t}`,i=this.pendingIndicators.get(n);i&&(clearTimeout(i),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}}function cC(e){return e.filter(e=>ds(e.liquidity))}function lC(e,t){const n=es(t);return e.filter(e=>es(e.liquidity).isGreaterThanOrEqualTo(n))}function uC(e,t="desc"){return[...e].sort((e,n)=>{const i=es(e.liquidity),r=es(n.liquidity);return"desc"===t?r.minus(i).toNumber():i.minus(r).toNumber()})}function dC(e,t,n){const i=t.toUpperCase(),r=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===i&&n===r||t===r&&n===i})}function hC(e,t){return e.filter(e=>la(e.token0,t)||la(e.token1,t))}function gC(e,t){return e.filter(e=>e.feeTier===t)}function fC(e){return VI(e,e=>`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`)}function pC(e){return VI(e,e=>e.feeTier)}function mC(e,t,n,i){const r=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===r&&n===o||t===o&&n===r)&&e.feeTier===i})}function yC(e){return VI(e,e=>`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`)}const wC=8,kC=18,bC={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},vC={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"};async function SC(e,t,n,i){const r=i?.logger,o=new Array(e.length);let s=0,a=0;r?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let i=0;i<e.length;i+=t){const c=e.slice(i,i+t),l=i;try{const t=c.map((t,i)=>{const c=l+i;return(async()=>{try{const i=await n(t);return o[c]=i,s++,r?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),i}catch(n){throw a++,r?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Q(n)}`),n}})()}),i=await Promise.allSettled(t);for(let e=0;e<i.length;e++){"rejected"===i[e].status&&r?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){r?.error(`Batch processing error at index ${i}: ${Q(e)}`)}}return r?.debug(`Batch complete: ${s} succeeded, ${a} failed`),o}function AC(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,i=ht(String(n.page??n.Page??n.current??1),t.page),r=ht(String(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,s=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof s?.totalItems?s.totalItems:"number"==typeof o?.count?o.count:ht(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:i,pageSize:r,totalCount:a,hasMore:c}}function TC(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,i]of Object.entries(e)){if(Ct(i))continue;let e;e="string"==typeof i?i:"number"==typeof i||"boolean"==typeof i?String(i):Array.isArray(i)?i.map(e=>String(e)).join(","):"object"==typeof i?JSON.stringify(i):String(i);const r=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${r}=${o}`)}return t.length>0?`?${t.join("&")}`:""}async function EC(e,t){const n=t?.maxRetries??3,i=t?.backoffMs??100,r=t?.retryableStatus??[429,503,504];let o,s=0;for(;s<=n;)try{return await e()}catch(e){o=e,s++;const t=NC(e),a=r.includes(t);if(s>n||!a)throw e;const c=i*Math.pow(2,s-1);await new Promise(e=>setTimeout(e,c))}throw o}function IC(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let i=t.statusCode;"number"==typeof n.status?i=n.status:"number"==typeof n.statusCode?i=n.statusCode:"number"==typeof n.code&&(i=n.code);let r,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const s=n.response;if(s){const e=s.data;if("object"==typeof e&&null!==e){r=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:i,errorMessage:o,raw:e};return null!=r&&(a.errorData=r),a}async function CC(e,t,n){const i=n?.logger,r=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});i?.debug(`Aggregating from ${e.length} endpoints`);const o=e.map(async(t,n)=>{try{const o=await r(t);return i?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(r){return void i?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Q(r)}`)}}),s=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return i?.debug(`Aggregating ${s.filter(e=>void 0!==e).length} successful results`),t(s)}function NC(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}class xC{static fastValidation(e,t,n,i=xC.DEFAULT_CONFIG){const r=Date.now();let o=!0;try{const s=es(e.sqrtPrice),a=es(t.sqrtPrice);n.zeroForOne?a.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1):a.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1);const c=es(e.liquidity),l=es(t.liquidity);if(!us(c)){const e=ws(l.minus(c).abs(),c);e.gt(i.maxLiquidityChangePct)&&this.logger.warn("Fast validation warning: large liquidity change detected (could be legitimate)",{originalLiquidity:c.toString(),updatedLiquidity:l.toString(),changePct:ts(e.times(100),2)})}const u=es(e.feeGrowthGlobal0),d=es(t.feeGrowthGlobal0),h=es(e.feeGrowthGlobal1),g=es(t.feeGrowthGlobal1);n.zeroForOne?g.lt(h)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:h.toString(),updatedFeeGrowth1:g.toString()}),o=!1):d.lt(u)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:u.toString(),updatedFeeGrowth0:d.toString()}),o=!1);const f=es(e.protocolFeesToken0),p=es(t.protocolFeesToken0),m=es(e.protocolFeesToken1),y=es(t.protocolFeesToken1);p.lt(f)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:f.toString(),updatedProtocolFees0:p.toString()}),o=!1),y.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:y.toString()}),o=!1);const w=Tt(r);return this.logger.debug("Fast validation completed",{passed:o,elapsedMs:w}),o}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=xC.DEFAULT_CONFIG){const i=Date.now(),r=[];let o=0;try{if(void 0!==t.actualSqrtPrice){const i=es(e.sqrtPrice),s=es(t.actualSqrtPrice),a=this.calculateDriftPercentage(i,s);o=a,a>100*n.maxDriftThreshold&&r.push(`Price drift detected: ${ts(a,4)}% (threshold: ${ts(100*n.maxDriftThreshold,4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:i.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const s=es(e.sqrtPrice),a=ws(s,as()),c=U(a),l=e.tick??0,u=Math.abs(c-l);u>n.maxTickDrift&&r.push(`Tick/price mismatch: tick=${l}, calculated=${c}, drift=${u}`);const d=es(e.feeGrowthGlobal0),h=es(e.feeGrowthGlobal1),g=es(e.liquidity);try{ms(d,h,g)}catch(e){r.push(e.message)}const f=0===r.length,p=!f||o>100*n.maxDriftThreshold,m=Tt(i);return this.logger.debug("Moderate validation completed",{isValid:f,shouldRefetch:p,driftPercentage:o,errorCount:r.length,elapsedMs:m}),this.buildValidationResult(f,o,p,r)}catch(e){return this.logger.error("Moderate validation exception",e),this.buildValidationResult(!1,0,!0,[`Exception during validation: ${Q(e)}`])}}static async fullValidation(e,t,n){const i=Date.now(),r=[];let o=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=es(t.pool.sqrtPrice),c=es(s.pool.sqrtPrice),l=this.calculateDriftPercentage(a,c);o=Math.max(o,l),l>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&r.push(`Price drift: ${l.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const u=es(t.pool.liquidity),d=es(s.pool.liquidity),h=this.calculateDriftPercentage(u,d);o=Math.max(o,h),h>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&r.push(`Liquidity drift: ${h.toFixed(4)}% (cached: ${u.toString()}, fresh: ${d.toString()})`);const g=Object.keys(t.tickDataMap).length,f=Object.keys(s.tickDataMap).length;if(f>0){const e=Math.abs(f-g)/f;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&r.push(`Tick data incomplete: cached has ${g} ticks, fresh has ${f} ticks (${(100*e).toFixed(2)}% difference)`)}const p=0===r.length,m=!p,y=Tt(i);return this.logger.debug("Full validation completed",{poolKey:e,isValid:p,shouldRefetch:m,maxDriftPercentage:o,priceDrift:l,liquidityDrift:h,cachedTickCount:g,freshTickCount:f,errorCount:r.length,elapsedMs:y}),this.buildValidationResult(p,o,m,r)}catch(t){return this.logger.error("Full validation exception",{poolKey:e,error:t}),this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${Q(t)}`])}}static calculateDriftPercentage(e,t){if(us(t))return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return ws(t.minus(e).abs(),t).times(100).toNumber()}static buildValidationResult(e,t,n,i=[]){let r;if(n&&i.length>0){const e=i.join(" ").toLowerCase();r=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const o={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:i};return void 0!==r&&(o.refetchReason=r),o}}xC.logger=new bt({debug:!1,context:"PoolStateValidator"}),xC.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class _C extends Qs{static calculatePoolStateHash(e){const t=`${e.sqrtPrice.toString()}|${e.liquidity.toString()}|${e.tick??0}`;return H.createHash("sha256").update(t).digest("hex").substring(0,16)}constructor(e,t){super(t?.debug??!1);const n={maxIterations:t?.maxIterations??100,enableBigNumberCache:t?.enableBigNumberCache??!0,roundingMode:t?.roundingMode??k.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=xC.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:_C.calculatePoolStateHash(this.pool)};if(!xC.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new re("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 ye("swapEvent","Swap event");if(""===e.transactionId||null==e.transactionId)throw ye("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 ae(`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},i=dl.calculateSwapDelta(t,e,n);this.lastSwapMetrics={calculationTimeMs:i.metadata.calculationTimeMs,swapSteps:i.metadata.swapSteps,timestamp:Date.now()},this.config.enablePerformanceWarnings&&i.metadata.calculationTimeMs>this.config.performanceWarningThreshold&&this.logger.warn("Slow swap calculation",{calculationTimeMs:i.metadata.calculationTimeMs,swapSteps:i.metadata.swapSteps,threshold:this.config.performanceWarningThreshold});if(!xC.fastValidation(t.pool,i.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new re("Swap validation failed","swapResult","VALIDATION_FAILED");if(null!=e.actualAmount0&&null!=e.actualAmount1&&null!=e.actualSqrtPrice){const t=es(e.actualAmount0),n=es(e.actualAmount1),r=i.amount0.minus(t).abs(),o=i.amount1.minus(n).abs(),s=ws(r,t.abs(),es(0)).times(100).toNumber(),a=ws(o,n.abs(),es(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=_C.calculatePoolStateHash(this.pool),this.logger.info("Full refetch completed",{sqrtPrice:this.pool.sqrtPrice.toString()})}return this.pool=i.updatedPool,Object.assign(this.tickDataMap,i.updatedTicks),this.metadata.swapsSinceRefetch++,this.metadata.stateHash=_C.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:i.amount0.toString(),amount1:i.amount1.toString(),sqrtPriceNew:this.pool.sqrtPrice.toString()}),i}catch(n){const i=Q(n);if(this.logger.error("Failed to apply swap delta",{transactionId:e.transactionId,error:i}),this.config.strictValidation)throw n;return{updatedPool:this.pool,updatedTicks:{},amount0:es(0),amount1:es(0),feeAmount0:es(0),feeAmount1:es(0),ticksCrossed:[],metadata:{calculationTimeMs:Tt(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:_C.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}function BC(e,t){return new _C(e,t)}class PC extends Qs{constructor(e=!1){super(e),this.cache={},this.cacheExpiry=36e5}async 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 i=this.extractMetadata(e);return this.cache[t]={data:i,timestamp:Date.now()},i}async getTokenSymbol(e){return(await this.resolveTokenMetadata(e)).symbol}async getTokenDecimals(e){return(await 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 qs(e);const t=e;return qs(`${t.type??t.symbol??"unknown"}|${t.additionalKey??"none"}`)}extractMetadata(e){let t,n,i="Token",r="Unit",o="none";if("string"==typeof e)if(Ra(e)){const s=Da(e);"Token"===s.collection&&""!==s.type?(i=s.collection,r=""!==s.category?s.category:"Unit",t=s.type,o=""!==s.additionalKey?s.additionalKey:"none",n=t):(t=s.collection,n=t,r=""!==s.category?s.category:"Unit",o=""!==s.additionalKey?s.additionalKey:"none")}else t=e,n=e;else{const s=e;t=s.type??"unknown",i=s.collection??"Token",r=s.category??"Unit",o=s.additionalKey??"none";const a=s.symbol??("Token"===i?t:i);n=""!==a?a:"unknown"}const s=this.getDecimalsForToken(n);return{symbol:n.toUpperCase(),decimals:s,collection:i,category:r,type:t.toUpperCase(),additionalKey:o,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return Tt(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}}class DC{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 re(`Invalid fee tier: ${e}. Valid values are 500, 3000, or 10000.`,"feeTier",ie.INVALID_FEE_TIER)}}validateTickSpacing(e,t,n){const i=this.getTickSpacing(n);if(e%i!==0)throw new re(`Invalid tickLower: ${e} must be a multiple of ${i} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%i!==0)throw new re(`Invalid tickUpper: ${t} must be a multiple of ${i} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){return Zi(()=>{const t=as();return ws(e,t).pow(2)},"calculatePriceFromSqrtPriceX96 failed",this.logger)}calculatePriceFromSqrtPriceDecimal(e){return Zi(()=>e.pow(2),"calculatePriceFromSqrtPriceDecimal failed",this.logger)}calculateLiquidityFromAmount0(e,t,n){return Zi(()=>{const i=E(t),r=E(n);return N(e,i,r)},"calculateLiquidityFromAmount0 failed",this.logger)}calculateLiquidityFromAmount1(e,t,n){return Zi(()=>{const i=E(t),r=E(n);return x(e,i,r)},"calculateLiquidityFromAmount1 failed",this.logger)}calculateAmount0FromLiquidity(e,t,n){return Zi(()=>{const i=E(t),r=E(n);return _(i,r,e)},"calculateAmount0FromLiquidity failed",this.logger)}calculateAmount1FromLiquidity(e,t,n){return Zi(()=>{const i=E(t),r=E(n);return B(i,r,e)},"calculateAmount1FromLiquidity failed",this.logger)}calculateOptimalPositionSize(e,t,n,i,r){if(""===t)throw ye("desiredAmount0","Desired amount 0");if(""===n)throw ye("desiredAmount1","Desired amount 1");const o=E(i),s=E(e),a=E(r),c=I(es(t),es(n),o,s,a),l=C(c,s,o,a),u=l[0],d=l[1],h=es(t),g=es(n);us(es(d))&&this.logger?.warn("GSwapPoolCalculationService: Calculated amount1 is zero - position may be heavily skewed to amount0",{desiredAmount0:t,desiredAmount1:n,currentTick:i,tickUpper:r});const f=ws(u,d,es(0));return{amount0:ts(u),amount1:ts(d),liquidity:ts(c),ratio:ts(f),utilizationPercent:{amount0:ts(fs(ws(u,h),100),2),amount1:ts(fs(ws(d,g),100),2)}}}validatePositionParameters(e,t,n,i,r,o,s){if(""===i)throw ye("amount0","Amount 0");if(""===r)throw ye("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=Zi(()=>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=es(i),h=es(r);if(d.isNaN()||h.isNaN())a.push("Amounts must be valid numbers");else try{Zi(()=>ms(d,h),"validatePositionParameters amounts validation",this.logger)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}if(void 0!==o&&(o<t||o>n)&&c.push("Position is out of current price range - will not earn fees until price moves into range"),void 0!==s){es(s).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance")}const g=0===a.length?35e4:0,f={valid:0===a.length,errors:a,warnings:c,gasEstimate:g};return void 0!==u&&(f.tickSpacing=u),void 0!==o&&(f.currentTick=o),void 0!==s&&(f.poolLiquidity=s),f}calculateTicksForPrice(e,t,n){if(""===e)throw ye("minPrice","Minimum price");if(""===t)throw ye("maxPrice","Maximum price");const i=this.getTickSpacing(n),r=es(e),o=es(t);Me(e,t,"priceRange");const s=ut(Math.floor(os(r)),0),a=ut(Math.ceil(os(o)),0),c=ut(ks(s,i),0),l=ut(ks(a,i),0),u=ut(Math.pow(1.0001,c),0===c?1:NaN),d=ut(Math.pow(1.0001,l),0===l?1:NaN),h=es(u),g=es(d);return{tickLower:c,tickUpper:l,tickSpacing:i,requestedMinPrice:e,requestedMaxPrice:t,actualMinPrice:h.toFixed(8),actualMaxPrice:g.toFixed(8),priceDeviation:{minPriceDeviation:fs(ws(h.minus(r),r),100).toFixed(4),maxPriceDeviation:fs(ws(g.minus(o),o),100).toFixed(4)}}}calculatePriceForTicks(e,t){const n=ut(Math.pow(1.0001,e),1),i=ut(Math.pow(1.0001,t),1),r=es(n),o=es(i);return{tickLower:e,tickUpper:t,minPrice:r.toFixed(8),maxPrice:o.toFixed(8),priceRange:`${r.toFixed(4)} - ${o.toFixed(4)}`,tickSpread:ut(t-e,0)}}calculateExecutionPrice(e,t){if(null==e||"string"==typeof e&&""===e)throw ye("inputAmount","Input amount");if(null==t||"string"==typeof t&&""===t)throw ye("outputAmount","Output amount");return Zi(()=>{const n=es(e);return ts(ws(es(t),n,es("0")))},"calculateExecutionPrice failed",this.logger)}}class RC extends Qs{constructor(e){super(e.debugMode??!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new ja}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:i,gswapToken1:r}=this.convertTokenPair(e,t),o=Pa(i),s=Pa(r),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculationService.calculatePriceFromSqrtPriceX96(es(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 ue(`Failed to get pool data: ${Q(n)}`,n,e,t)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:i}=this.convertTokenPair(e,t),r=[500,3e3,1e4];let o=es(0),s=0;for(const a of r)try{const e=Pa(n),t=Pa(i),r=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});null!=r&&(o=o.plus(es(r.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:r,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new ue(`Failed to fetch pool info: ${Q(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 i="string"==typeof e?Pa(e):e,r="string"==typeof t?Pa(t):t,o=await this.gatewayClient.getSlot0({token0:i,token1:r,fee:n}),s={sqrtPrice:""!==o.sqrtPrice?o.sqrtPrice:"0",tick:0!==o.tick?o.tick:0,liquidity:""!==o.liquidity?o.liquidity:"0",grossPoolLiquidity:o.grossPoolLiquidity??"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(e){throw this.logger.error("Failed to fetch pool slot0 data",e),new ue(`Failed to fetch pool slot0 data: ${Q(e)}`,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const i=await this.getPoolData(e,t,n),r=es(i.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:r.toFixed(),invertedPrice:ss(r,!0),tick:i.tick,liquidity:i.liquidity}}catch(n){throw this.logger.error("Failed to calculate spot price",n),new ue(`Failed to calculate spot price: ${Q(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=es(t.sqrtPrice),i={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:i.price,tick:i.tick}),i}catch(e){throw this.logger.error("Failed to fetch position current price",e),new ue(`Failed to fetch position current price: ${Q(e)}`,e)}}chunkArray(e,t){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}}class MC extends Qs{constructor(e){super(e.debugMode??!1),this.dexBackendBaseUrl=e.dexBackendBaseUrl,e.dexBackendHttp?this.dexBackendHttp=e.dexBackendHttp:this.dexBackendHttp=z(e.dexBackendBaseUrl,3e4)}parseTokenFlexible(e){try{return Pa(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 i=Xi(await this.dexBackendHttp.get("/api/tokens/balances",{params:{wallet:e,limit:t,page:n}})),r=i?.data??{},o=Array.isArray(r?.tokens)?r.tokens:[],s="number"==typeof r?.count?r.count:o.length;return{assets:o.map(e=>this.transformRawTokenToUserAsset(e)),count:s,page:n,limit:t,hasMore:n*t<s}}catch(t){throw this.logger.error("Failed to fetch user assets",t),new de(`Failed to fetch user assets: ${Q(t)}`,t,e)}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets",{walletAddress:e});return(await Ls(async(t,n)=>{const i=await this.getUserAssets(e,n,t);return{items:i.assets,page:t,limit:n,total:i.count,totalPages:Ps(i.count,n),hasNext:i.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 de(`Failed to fetch all user assets: ${Q(t)}`,t,e)}}async fetchAvailableDexTokens(e={}){try{const{search:t,limit:n=20,offset:i=0}=e,r=Math.floor(i/n)+1;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 s=Xi(await this.dexBackendHttp.get("/api/tokens",{params:o})),a=s?.data??{},c=Array.isArray(a?.tokens)?a.tokens:[],l="number"==typeof a?.count?a.count:c.length;return{tokens:c.map(e=>this.transformRawTokenToDexToken(e)),count:l,page:r,limit:n,hasMore:r*n<l}}catch(e){throw this.logger.error("Failed to fetch available DEX tokens",e),new de(`Failed to fetch available DEX tokens: ${Q(e)}`,e)}}async fetchAllAvailableDexTokens(e={}){try{this.logger.debug("Fetching all available DEX tokens",e);return(await Ls(async(t,n)=>{const i=(t-1)*n,r=await this.fetchAvailableDexTokens({...e,limit:n,offset:i});return{items:r.tokens,page:t,limit:n,total:r.count,totalPages:Ps(r.count,n),hasNext:r.hasMore,hasPrevious:t>1}},{maxPages:100,pageSize:100,logger:this.logger})).items}catch(e){throw this.logger.error("Failed to fetch all available DEX tokens",e),new de(`Failed to fetch all available DEX tokens: ${Q(e)}`,e)}}}class LC extends Qs{constructor(e){super(e.debugMode??!1),this.gatewayClient=e.gatewayClient,this.galaChainBaseUrl=e.galaChainBaseUrl,this.calculationService=e.calculationService,this.tokenConverter=new ja}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}parseTokenFlexible(e){try{return Pa(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 i=n;Array.isArray(n.positions)&&n.positions.length>0&&(i=n.positions[0]);const r=i.positionId??i.id??n.positionId??n.id??"",o=this.extractTokenSymbol(i.token0),s=this.extractTokenSymbol(i.token1),a=i.feeTier??i.fee??i.feeAmount??3e3,c=i.tickLower??i.lowerTick??0,l=i.tickUpper??i.upperTick??0,u=i.liquidity?.toString()??i.liquidityAmount?.toString()??"0",d=i.amount0?.toString()??i.amountA?.toString()??"0",h=i.amount1?.toString()??i.amountB?.toString()??"0",g=i.feeAmount0?.toString()??i.feesA?.toString()??i.tokensOwed0?.toString()??"0",f=i.feeAmount1?.toString()??i.feesB?.toString()??i.tokensOwed1?.toString()??"0";return{positionId:r,ownerAddress:t,token0:o,token1:s,feeTier:ht(a,3e3),tickLower:ht(c,0),tickUpper:ht(l,0),liquidity:u,amount0:d,amount1:h,feeAmount0:g,feeAmount1:f}}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:i}=this.convertTokenPair(t.token0,t.token1),r=Jc(n),o=Jc(i),s=(await this.gatewayClient.getPositions({owner:e,token0:r,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new he("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:Q(e)}),new he(`Failed to fetch liquidity position: ${Q(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),i=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(!Array.isArray(i.positions)||0===i.positions.length)throw new he("Position not found: API returned no position data",null,"NOT_FOUND");const r=i.positions[0];return this.normalizePositionResponse(r,e.owner)}catch(e){throw this.logger.error("Failed to fetch swap position via compound key",{error:Q(e)}),new he(`Failed to fetch swap position: ${Q(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),i=Jc(t),r=Jc(n);return await this.gatewayClient.getRemoveLiquidityEstimation({token0:i,token1:r,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:Q(e)}),new he(`Failed to estimate liquidity removal: ${Q(e)}`,e,"ESTIMATE_FAILED")}}}class FC extends Qs{constructor(e){super(e.debugMode??!1),this.bundlerClient=null,this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.gatewayClient=e.gatewayClient,this.bundlerBaseUrl=e.bundlerBaseUrl,this.galaChainBaseUrl=e.galaChainBaseUrl,this.webSocketService=e.webSocketService,this.calculationService=e.calculationService,this.liquidityQueryService=e.liquidityQueryService,this.tokenConverter=new ja,""!==e.bundlerBaseUrl&&(this.bundlerClient=Qc.createClient(e.bundlerBaseUrl,3e4))}getBundlerClient(){if(""===this.bundlerBaseUrl)throw new se("Bundler URL not configured","bundlerBaseUrl");return this.bundlerClient??(this.bundlerClient=Qc.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,i){const r=_a(e),o=_a(t),s=`$pool${r}${o}$${n}`;return[s,`$userPosition${i}`,`$tokenBalance${r}${i}`,`$tokenBalance${o}${i}`,`$tokenBalance${r}${s}`,`$tokenBalance${o}${s}`]}async monitorBundlerTransaction(e,t,n){return{...{transactionId:e,liquidity:"0",amount0:"0",amount1:"0",status:"pending"},wait:async(i=12e4)=>Ji(async()=>{const r=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${e} timed out after ${i}ms`)),i)});await Promise.race([t,r]),this.logger.debug(`${n} confirmed`,{transactionId:e})},`${n} failed or timed out`,this.logger,(t,i,r)=>{throw r?.error(`GSwapLiquidityMutationService: ${i}`,{error:Q(t),operationType:n,transactionId:e}),t})}}async sendAddLiquidityToBundler(t){if(void 0===this.privateKey)throw new se("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===this.bundlerBaseUrl)throw new se("Bundler URL not configured","bundlerBaseUrl");return Ji(async()=>{const n=`galaswap - operation - ${v()}-${Date.now()}-${t.owner}`,i={token0:t.token0,token1:t.token1,fee:t.fee,owner:t.owner,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Desired:t.amount0Desired,amount1Desired:t.amount1Desired,amount0Min:t.amount0Min,amount1Min:t.amount1Min,positionId:"",uniqueKey:n},r=new e.Wallet(this.privateKey),o={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},s={name:"ethereum",chainId:1},a=this.calculatePersonalSignPrefix(i),c={...i,prefix:a},l=await r.signTypedData(s,o,c),u={...c,signature:l,types:o,domain:s},d=this.buildLiquidityStringsInstructions(t.token0,t.token1,t.fee,t.owner),h=Xi(await this.getBundlerClient().post("/bundle",{method:"AddLiquidity",signedDto:u,stringsInstructions:d})),g="string"==typeof h?.data?h.data:h?.data?.transactionId??h?.data?.id??h?.transactionId??h?.id;if(void 0===g)throw new ae("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return g},"Failed to send AddLiquidity to bundler",this.logger)}async sendRemoveLiquidityToBundler(t,n,i,r,o,s,a,c,l){if(void 0===this.privateKey)throw new se("RemoveLiquidity requires wallet (full-access mode)","privateKey");return Ji(async()=>{const u=new e.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${v()}-${Date.now()}-${d}`,g={tickLower:t,tickUpper:n,amount:i,token0:r,token1:o,fee:s,amount0Min:a,amount1Min:c,positionId:l,uniqueKey:h},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"}]},p={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},w=await u.signTypedData(p,f,y),k={...y,signature:w,types:f,domain:p},b=this.buildLiquidityStringsInstructions(r,o,s,d),S=Xi(await this.getBundlerClient().post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:b})),A="string"==typeof S?.data?S.data:S?.data?.transactionId??S?.data?.id??S?.transactionId??S?.id;if(void 0===A)throw new ae("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return A},"Failed to send RemoveLiquidity to bundler",this.logger)}async sendCollectPositionFeesToBundler(t,n,i,r,o,s,a,c){if(void 0===this.privateKey)throw new se("CollectPositionFees requires wallet (full-access mode)","privateKey");return Ji(async()=>{const l=new e.Wallet(this.privateKey),u=await l.getAddress(),d=`galaswap - operation - ${v()}-${Date.now()}-${u}`,h={token0:t,token1:n,fee:i,amount0Requested:r,amount1Requested:o,tickLower:s,tickUpper:a,positionId:c,uniqueKey:d},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},p=this.calculatePersonalSignPrefix(h),m={...h,prefix:p},y=await l.signTypedData(f,g,m),w={...m,signature:y,types:g,domain:f},k=this.buildLiquidityStringsInstructions(t,n,i,u),b=Xi(await this.getBundlerClient().post("/bundle",{method:"CollectPositionFees",signedDto:w,stringsInstructions:k})),S="string"==typeof b?.data?b.data:b?.data?.transactionId??b?.data?.id??b?.transactionId??b?.id;if(void 0===S)throw new ae("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 se("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===e.token0)throw ye("token0","Token 0");if(""===e.token1)throw ye("token1","Token 1");if(""===e.minPrice)throw ye("minPrice","Minimum price");if(""===e.maxPrice)throw ye("maxPrice","Maximum price");if(""===e.amount0Desired)throw ye("amount0Desired","Desired amount 0");if(""===e.amount1Desired)throw ye("amount1Desired","Desired amount 1");return Ji(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 i=Pa(t),r=Pa(n),o=(await this.gatewayClient.getPoolData({token0:i,token1:r,fee:e.fee})).tickSpacing,s=es(e.minPrice),a=es(e.maxPrice),c=Math.floor(os(s)),l=Math.ceil(os(a)),u=ks(c,o),d=ks(l,o),h=this.getWalletAddress();if(void 0===h)throw new se("Wallet address not available","walletAddress");const g=await this.sendAddLiquidityToBundler({token0:i,token1:r,fee:e.fee,tickLower:u,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min??"0",amount1Min:e.amount1Min??"0",owner:h}),f=this.webSocketService.waitForTransaction(g);return this.monitorBundlerTransaction(g,f,"addLiquidityByPrice")},"Failed to add liquidity by price",this.logger,(e,t,n)=>{throw n?.error(t,{error:Q(e)}),new he(`${t}: ${Q(e)}`,e,"ADD_FAILED")})}async addSwapLiquidityByTicks(e){if(void 0===this.privateKey)throw new se("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===e.token0)throw ye("token0","Token 0");if(""===e.token1)throw ye("token1","Token 1");if(""===e.amount0Desired)throw ye("amount0Desired","Desired amount 0");if(""===e.amount1Desired)throw ye("amount1Desired","Desired amount 1");return Ji(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 i=Pa(t),r=Pa(n),o=this.getWalletAddress();if(void 0===o)throw new se("Wallet address not available","walletAddress");const s=await this.sendAddLiquidityToBundler({token0:i,token1:r,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min??"0",amount1Min:e.amount1Min??"0",owner:o}),a=this.webSocketService.waitForTransaction(s);return this.monitorBundlerTransaction(s,a,"addSwapLiquidityByTicks")},"Failed to add liquidity by ticks",this.logger,(e,t,n)=>{throw n?.error(t,{error:Q(e)}),new he(`${t}: ${Q(e)}`,e,"ADD_FAILED")})}async removeLiquidity(e){if(void 0===this.privateKey)throw new se("RemoveLiquidity requires wallet (full-access mode)","privateKey");if("string"==typeof e.token0&&""===e.token0||"string"!=typeof e.token0&&void 0===e.token0)throw ye("token0","Token 0");if("string"==typeof e.token1&&""===e.token1||"string"!=typeof e.token1&&void 0===e.token1)throw ye("token1","Token 1");if(""===e.liquidity)throw ye("liquidity","Liquidity amount");return Ji(async()=>{this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=es(e.liquidity);try{ms(t)}catch(t){const n=`Invalid liquidity value: "${e.liquidity}". Must be a valid number.`;throw this.logger.error(n,{error:Q(t)}),new re(n,"liquidity","INVALID_VALUE")}if(us(t))throw new re("Cannot remove zero liquidity from position.","liquidity","ZERO_VALUE");const n="string"==typeof e.token0?Pa(e.token0):e.token0,i="string"==typeof e.token1?Pa(e.token1):e.token1;await this.ensureWebSocketConnected();const r=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,n,i,e.fee,e.amount0Min??"0",e.amount1Min??"0",e.positionId??""),o=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,o,"removeLiquidity")},"Failed to remove liquidity",this.logger,(e,t,n)=>{throw n?.error(t,{error:Q(e)}),new he(`${t}: ${Q(e)}`,e,"REMOVE_FAILED")})}async collectPositionFees(e){if(void 0===this.privateKey)throw new se("CollectPositionFees requires wallet (full-access mode)","privateKey");if(void 0===e.positionId)throw ye("positionId","Position ID");return Ji(async()=>{if(void 0!==e.ownerAddress&&void 0!==e.positionId&&("string"==typeof e.token0?""===e.token0:void 0===e.token0))throw new re("collectPositionFees requires direct parameters: token0, token1, fee, tickLower, tickUpper. Use GSwapService.collectPositionFees() for automatic position lookup.","parameters",ie.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 re("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required","parameters",ie.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 i="string"==typeof e.token0?Pa(e.token0):e.token0,r="string"==typeof e.token1?Pa(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendCollectPositionFeesToBundler(i,r,e.fee,e.amount0Requested??"0",e.amount1Requested??"0",e.tickLower,e.tickUpper,e.positionId??""),s=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,s,"collectPositionFees")},"Failed to collect position fees",this.logger,(e,t,n)=>{throw n?.error(t,{error:Q(e)}),new he(`${t}: ${Q(e)}`,e,"COLLECT_FAILED")})}}class UC extends Qs{constructor(e){super(e.debugMode??!1),this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.webSocketService=e.webSocketService,this.dexQuoteService=e.dexQuoteService,this.tokenConverter=new ja}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=es(e),i=es(t);return ts(ws(i,n,es("0")))}catch(n){return this.logger.warn("Failed to calculate execution price",{inputAmount:e,outputAmount:t,error:Q(n)}),"0"}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildSwapStringsInstructions(e,t,n,i){const r=_a(e),o=_a(t),s=`$pool${r}${o}$${n}`;return[s,`$userPosition${i}`,`$tokenBalance${r}${i}`,`$tokenBalance${o}${i}`,`$tokenBalance${r}${s}`,`$tokenBalance${o}${s}`]}async sendSwapToBundler(t){return Ji(async()=>{if("string"!=typeof this.privateKey||0===this.privateKey.length)throw new se("Swap requires wallet (full-access mode)","privateKey");if("string"!=typeof this.bundlerBaseUrl||0===this.bundlerBaseUrl.length)throw new se("Bundler URL not configured","bundlerBaseUrl");const n=[500,3e3,1e4];if(!n.includes(t.feeTier))throw new re(`Invalid fee tier ${t.feeTier}. Must be one of: ${n.join(", ")}`,"feeTier","INVALID_FEE_TIER");this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof t.fromToken?t.fromToken:t.fromToken?.type??"unknown",toToken:"string"==typeof t.toToken?t.toToken:t.toToken?.type??"unknown",inputAmount:t.inputAmount,minOutput:t.minOutput,feeTier:t.feeTier});let i=t.fromToken,r=t.toToken;"string"==typeof i&&(i=Pa(i)),"string"==typeof r&&(r=Pa(r));const o=Na(i),s=Na(r),a=o<s?[i,r,o,s]:[r,i,s,o],[c,l,u,d]=a,h=Na("string"==typeof t.fromToken?Pa(t.fromToken):t.fromToken),g=h===u,f=`galaswap - operation - ${v()}-${Date.now()}-${t.walletAddress}`;let p;if("string"!=typeof t.currentSqrtPrice||0===t.currentSqrtPrice.length)throw ye("currentSqrtPrice","Current sqrt price");const m=es(t.currentSqrtPrice),y=t.slippageTolerance??.01;if(g){const e=is(y);p=ts(m.multipliedBy(e))}else{const e=rs(y);p=ts(m.multipliedBy(e))}const w={token0:c,token1:l,fee:t.feeTier,amount:ts(es(t.inputAmount)),zeroForOne:g,sqrtPriceLimit:p,recipient:t.walletAddress,amountOutMinimum:ts(es(t.minOutput).multipliedBy(-1)),uniqueKey:f};this.logger.info("SWAP DTO DETAILS",{orderedToken0String:u,orderedToken1String:d,fromTokenStr:h,zeroForOne:g?`TRUE (${u} -> ${d})`:`FALSE (${d} -> ${u})`,inputAmount:t.inputAmount,expectedOutput:t.minOutput,slippageTolerance:100*(t.slippageTolerance??.01)+"%"});const k=new e.Wallet(this.privateKey),b={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(w),T={...w,prefix:A},E=await k.signTypedData(S,b,T),I={...T,signature:E,types:b,domain:S},C=this.buildSwapStringsInstructions(c,l,t.feeTier,t.walletAddress),N=Qc.createClient(this.bundlerBaseUrl,3e4),x=Xi(await N.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:C})),_=x?.data??x?.transactionId??x?.id;if("string"!=typeof _||0===_.length)throw new ae("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return _},"Failed to send Swap to bundler",this.logger)}async getSwapQuoteExactInput(e){return Ji(async()=>{if(es(e.amount).isLessThanOrEqualTo(0))throw new ce("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ce("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),[i,r]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await Ji(async()=>{const o=await a.fetchCompositePoolData({token0:i,token1:r,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),l=es(s.currentSqrtPrice),u=es(s.newSqrtPrice),d=l.gt(u)?ws(l.minus(u),l,"0"):es(0),h=es(s.amount0),g=es(s.amount1);if(!hs(h)&&!hs(g))throw new ce("Unexpected quote result: neither amount is negative (no output from pool)",{amount0:s.amount0,amount1:s.amount1,fromToken:e.fromToken,toToken:e.toToken});const f=(hs(h)?h:g).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:f,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,f),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:Q(e)})}throw s??new ce("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact input quote",this.logger,(t,n,i)=>{throw i?.error(n,t),new ce(`${n}: ${Q(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async getSwapQuoteExactOutput(e){return Ji(async()=>{if(es(e.amount).isLessThanOrEqualTo(0))throw new ce("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new ce("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),[i,r]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await Ji(async()=>{const o=await a.fetchCompositePoolData({token0:i,token1:r,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),l=es(s.currentSqrtPrice),u=es(s.newSqrtPrice),d=l.gt(u)?ws(l.minus(u),l,"0"):es(0),h=es(s.amount0),g=es(s.amount1),f=(ds(h)?h:ds(g)?g:h).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:f,estimatedOutput:e.amount,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(f,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:Q(e)})}throw s??new ce("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact output quote",this.logger,(t,n,i)=>{throw i?.error(n,t),new ce(`${n}: ${Q(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async executeSwap(e){return Ji(async()=>{if("string"!=typeof this.privateKey||0===this.privateKey.length)throw new se("ExecuteSwap requires wallet (full-access mode)","privateKey");this.logger.debug("Executing swap",e);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),i=e.slippageTolerance??.01,r=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount}),o=ns(e.estimatedOutput,i).toFixed();await this.ensureWebSocketConnected();const s=this.getWalletAddress();if("string"!=typeof s||0===s.length)throw new se("Wallet address not available","walletAddress");const a=await this.sendSwapToBundler({fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o,feeTier:e.feeTier,walletAddress:s,currentSqrtPrice:r.currentSqrtPrice,slippageTolerance:i}),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:i,timestamp:new Date,wait:async(e=12e4)=>{await Ji(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:Q(e)}),e})}}},"Failed to execute swap",this.logger,(e,t,n)=>{throw n?.error(t,e),new le(`${t}: ${Q(e)}`,e)})}}function OC(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.type&&["stream_status","user_banned","user_unbanned","ban_enforcement","content_flagged","flag_resolved","stream_chat_message","stream_chat_updated","stream_chat_deleted","stream_chat_pinned","stream_chat_unpinned","chat_status_changed","viewer_count","recording_status","simulcast_status","download_ready","user_typing","stream_reaction","content_reaction_added","content_reaction_removed","stream_countdown_updated","stream_language_updated","stream_control_status_changed","connection","authenticated","token_subscribed","token_unsubscribed","room_subscribed","room_left"].includes(t.type)}const $C={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6};function qC(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw function(e){if(e.length<2)return ye(void 0!==e[0]&&""!==e[0]?e[0]:"field");let t;t=2===e.length?e.join(" or "):`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`;return new re(`At least one of ${t} must be provided`,e[0],"REQUIRED")}(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:i}=Ge;if(e.tokenName.length<t||e.tokenName.length>n||!i.test(e.tokenName))throw we("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}xt(e.offset,e.limit,je.MAX_LIMIT)}function KC(e){if(!It(e.tokenName))throw ye("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:i}=Ge;if(e.tokenName.length<t||e.tokenName.length>n||!i.test(e.tokenName))throw we("tokenName",`${t}-${n} alphanumeric characters`,"Token name");if(!It(e.content))throw ye("content");if(0===e.content.trim().length)throw Be("content","Content");if(e.content.length>Je.COMMENTS_V1.MAX_LENGTH)throw _e("content",Je.COMMENTS_V1.MAX_LENGTH,e.content.length)}function GC(e){if(!It(e.content))throw ye("content");if(0===e.content.trim().length)throw Be("content","Content");if(e.content.length>Je.COMMENTS_V1.MAX_LENGTH)throw _e("content",Je.COMMENTS_V1.MAX_LENGTH,e.content.length)}"undefined"!=typeof process&&null!==process.env&&void 0!==process.env&&(process.env.CORE_CHAINCODE_LOGGING_LEVEL=process.env.CORE_CHAINCODE_LOGGING_LEVEL??"ERROR");var WC=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const i=lt(e.reverseBondingCurveMinFeePortion,NaN);isNaN(i)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=i}if(void 0!==e.reverseBondingCurveMaxFeePortion){const i=lt(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(i)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=i}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{Du as ACCESS_SOURCE,ld as ACTIVE_USER_TYPE,Cd as API_KEY_PERMISSION,Ed as API_KEY_ROLE,Id as API_KEY_ROLES,Pd as API_KEY_ROLE_HIERARCHY,Gt as AddressFormatter,OI as AgentConfig,V as AuthError,j as AuthErrorType,cd as BAN_DURATIONS,nu as BRIDGE_CONTRACT_ABI,eu as BRIDGE_TOKEN_METADATA,tI as BaseBridgeStrategy,ag as BridgeRateLimiter,eI as BridgeStatusCode,bc as BurnError,kc as BurnErrorType,rg as CALCULATION_MODES,Ml as CHAIN_IDS,rl as COMPOSITE_POOL_FETCH_CONCURRENCY,xh as CONTENT_REACTION_TYPES,oh as CONTENT_TYPE_LABELS,fu as CROSS_RATE_TYPED_DATA_TYPES,Uh as ChatMessagesService,se as ConfigurationError,Zd as ContentType,Wl as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Kl as DEFAULT_ETHEREUM_RPC_URL,Zl as DEFAULT_ETHEREUM_TOKENS,Ol as DEFAULT_POLL_INTERVAL_MS,$l as DEFAULT_POLL_TIMEOUT_MS,rr as DEFAULT_PRICING_CONCURRENCY,Ul as DEFAULT_RATE_LIMIT_RPS,zl as DEFAULT_SOLANA_BRIDGE_PROGRAM,Gl as DEFAULT_SOLANA_RPC_URL,Yl as DEFAULT_SOLANA_TOKENS,or as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,fe as DexPoolNotFoundError,ge as DexQuoteError,tu as ERC20_ABI,ie as ERROR_CODES,Hl as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,Vl as ETHEREUM_TOKENS_PROD,Xl as ETHEREUM_TOKENS_STAGE,Pu as EXTENDED_STREAM_ROLE,nI as EthereumBridgeStrategy,sC as EventBufferWithAutoCleanup,rh as FLAG_ACTION_LABELS,sh as FLAG_DETAILS_MAX_LENGTH,nh as FLAG_REASON_LABELS,ih as FLAG_STATUS_LABELS,ba as FileValidationError,th as FlagAction,Yd as FlagReason,eh as FlagStatus,Ll as GALACHAIN_CHANNELS,jl as GALACONNECT_PRODUCTION_URL,cu as GALA_BRIDGE_TYPED_DATA_DOMAIN,wC as GALA_DECIMALS,bC as GALA_TOKEN_CLASS_KEY,de as GSwapAssetError,MC as GSwapAssetService,FC as GSwapLiquidityMutationService,LC as GSwapLiquidityQueryService,DC as GSwapPoolCalculationService,ue as GSwapPoolError,RC as GSwapPoolQueryService,ce as GSwapQuoteError,le as GSwapSwapError,UC as GSwapSwapService,YE as GalaConnectClient,zE as GalaConnectHttpError,iC as GlobalAndRoomCallbackDispatcher,Hr as IMAGE_EXTENSIONS,Od as INVITE_STATUS,$d as INVITE_STATUSES,tn as JWT_CONSTANTS,kC as LAUNCHPAD_TOKEN_DECIMALS,gu as LEGACY_TYPED_DATA_TYPES,xI as LaunchpadSDK,oC as ListenerCleanupManager,cc as LockError,sc as LockErrorType,wc as MAX_BURN_BATCH_SIZE,$s as MAX_CONCURRENT_POOL_FETCHES,rc as MAX_LOCK_BATCH_SIZE,oc as MAX_UNLOCK_BATCH_SIZE,Md as MODERATOR_ROLE,Ld as MODERATOR_ROLES,Oh as NFT_FEES,oe as NetworkError,zh as NftCollectionService,ph as OVERSEER_INVITE_STATUS,mh as OVERSEER_STATUS,Cs as PAGINATION_DEFAULTS,Ns as POOL_FETCH_CONFIG,ig as POOL_TYPES,tC as PayloadWalkerWithDeduplication,nC as PendingSubscriptionTracker,_C as PoolStateManager,vC as QUERY_FIELD_NAMES,_h as REACTION_EMOJI_MAP,vu as RECORDING_STATUS,_u as ROLE_SOURCE,eC as RoomSubscriptionManager,Oc as SDKTransactionStatus,CI as SDK_VERSION,$u as SIMULATE_EVENT_TYPE,Au as SIMULCAST_PLATFORM,Su as SIMULCAST_STATUS,ql as SOLANA_COMPUTE,iu as SOLANA_DISCRIMINATORS,od as STREAM_EVENTS,Bu as STREAM_PERMISSION,xu as STREAM_ROLE,bu as STREAM_STATUS,rC as SelectiveEventForwarding,mI as SolanaBridgeStrategy,sd as StreamWebSocketService,ad as StreamingEventService,$C as TIME_CONSTANTS,ia as TRADES_QUERY_CONSTRAINTS,ng as TRADING_TYPES,PC as TokenMetadataService,ae as TransactionError,TI as TransactionFailedError,aC as TypingIndicatorDebouncer,re as ValidationError,SI as WebSocketError,AI as WebSocketTimeoutError,hr as addressFormatSchema,CC as aggregateMultipleApiSources,Kr as amountMethodSchema,qr as amountTypeSchema,Qt as assertValidWalletAddress,ha as bidirectionalTokenMatch,jr as browserFileSchema,Vr as bufferFileSchema,SC as buildConcurrentBatchRequests,TC as buildQueryParametersWithValidation,yo as buyTokensDataSchema,$I as calculateLinearFeeInterpolation,To as calculatePreMintDataSchema,jI as calculateScaledFeeAmount,Ps as calculateTotalPages,pe as capitalize,la as caseInsensitiveTokenComparison,$r as checkPoolOptionsSchema,Ut as commonValidators,dg as compareAmounts,YI as conditionalSpreadBuilder,ca as conditionalTrimAndValidateString,MI as createLaunchpadSDK,vr as createLimitSchema,Ot as createOptionsValidator,oo as createPaginatedResultSchema,xs as createPaginationQuery,BC as createPoolStateManager,RI as createSolanaWallet,mo as createTradeDataSchema,BI as createWallet,WI as decimalRoundingUp,ZI as deduplicateByKey,ua as errorMessageCaseNormalization,gr as ethereumAddressSchema,QI as extractFieldWithFallbackPath,AC as extractPaginationMetadata,co as fetchGalaBalanceOptionsSchema,Eo as fetchPoolDetailsDataSchema,go as fetchTokenBalanceOptionsSchema,Er as fileSizeSchema,zr as fileUploadSchema,Ir as filenameSchema,gC as filterByFeeTier,cC as filterByLiquidity,lC as filterByMinLiquidity,mC as filterByPoolKey,hC as filterByToken,dC as filterByTokenPair,fr as flexibleAddressSchema,Xr as flexibleFileSchema,yt as formatGalaForDTO,wt as formatLaunchpadTokenForDTO,ug as formatTokenAmount,au as formatTokenDescriptor,jt as fromBackendAddressFormat,lg as fromBaseUnits,dr as fullNameSchema,Qa as generateUniqueKey,Ao as getAmountOptionsSchema,UI as getEnv,FI as getEnvOrThrow,DI as getEthereumAddressFromPrivateKey,Jl as getEthereumBridgeContractByEnvironment,ou as getEthereumTokenConfig,Ql as getEthereumTokensByEnvironment,pu as getGalaBridgeTypedDataTypes,Vh as getLaunchTokenDataValidationErrors,$h as getNftFeeAsNumber,PI as getPublicKeyFromPrivateKey,su as getSolanaTokenConfig,ru as getStaticTokenMetadata,ko as getTradeOptionsSchema,Wr as graduateTokenOptionsSchema,Gr as graphDataOptionsSchema,pC as groupByFeeTier,VI as groupByKey,yC as groupByPoolKey,fC as groupByTokenPair,Ds as hasMorePages,ga as hexStringExtractionAndNormalization,Qr as imageExtensionSchema,Jr as imageFilenameSchema,Cr as imageMimeTypeSchema,Ur as imageUploadOptionsSchema,Lu as isAccessSource,ud as isActiveUserType,dd as isBanData,fd as isBanEnforcementEvent,mc as isBurnTokenEntry,yc as isBurnTokensData,Ku as isChatDisabledReason,Fh as isChatMessageItem,Qu as isChatStatusResponse,kh as isClaimableInvite,ah as isContentType,Ct as isEmptyValue,Mu as isExtendedStreamRole,uh as isFlagAction,dh as isFlagData,ch as isFlagReason,lh as isFlagStatus,ec as isLockTokenEntry,nc as isLockTokensData,Hd as isModeratedToken,Wd as isModeratorInvite,It as isNonEmptyString,yh as isOverseerInviteStatus,wh as isOverseerStatus,ju as isPinnedMessage,zd as isPublicInviteInfo,td as isReactionErrorCode,Eu as isRecordingStatus,Iu as isSimulcastPlatform,zu as isStreamChatDeletedEvent,Hu as isStreamChatErrorEvent,Gu as isStreamChatMessage,Wu as isStreamChatMessageEvent,Vu as isStreamChatPinnedEvent,Xu as isStreamChatUnpinnedEvent,ed as isStreamReactionErrorEvent,Yu as isStreamReactionEvent,Tu as isStreamStatus,Cu as isStreamStatusEvent,OC as isStreamingEvent,Ru as isTokenAccessPermissions,Fu as isTokenAccessResult,wd as isTokenBanData,id as isTypingIndicatorEvent,nd as isTypingUser,tc as isUnlockTokenEntry,ic as isUnlockTokensData,hd as isUserBannedEvent,gd as isUserUnbannedEvent,Xt as isValidAddress,Nd as isValidApiKeyRole,md as isValidBanDuration,pd as isValidBanReason,Ju as isValidChatContent,Zu as isValidChatTokenName,Fl as isValidGalaChainChannel,Gd as isValidInviteCode,Kd as isValidInviteStatus,jh as isValidLaunchTokenData,qd as isValidModeratorRole,kd as isValidTokenBanReason,Mt as isValidTokenName,Nu as isViewerCountEvent,Nr as isoDateStringSchema,Fr as launchTokenDataSchema,LI as loadEnvWithFallback,yr as nonNegativeDecimalStringSchema,Vt as normalizeAddressInput,JI as normalizeDataWithMapping,da as normalizeErrorMessage,Bs as normalizeLimit,Ks as normalizeTokenKey,qs as normalizeTokenName,Gs as normalizeTokenSymbol,kr as optionalUrlSchema,br as pageNumberSchema,ro as paginationResultMetaSchema,IC as parseHttpErrorResponse,GI as percentileIndexCalculation,Or as poolFetchTypeSchema,to as poolPaginationSchema,mr as positiveDecimalStringSchema,KI as priceTickRangeMapping,_r as privateKeySchema,ms as requireNonNegative,ps as requirePositive,ys as requirePositiveWithContext,EC as retryableHttpRequest,Lr as reverseBondingCurveConfigSchema,Io as reverseBondingCurveConfigurationSchema,Dd as roleHasSufficientPermission,qI as roundTickBoundaries,zI as roundTickToSpacing,HI as safeDivideWithMinimum,ur as searchQuerySchema,wo as sellTokensDataSchema,uC as sortByLiquidity,Sr as standardLimitSchema,Zr as standardPaginationSchema,qt as stripHexPrefix,xr as timestampSchema,zt as toBackendAddressFormat,Jt as toBackendAddressFromEthers,cg as toBaseUnits,Rr as tokenCategorySchema,Mr as tokenCollectionSchema,cr as tokenDescriptionSchema,ho as tokenHoldSchema,ao as tokenListOptionsSchema,sr as tokenNameSchema,ar as tokenSymbolSchema,Dr as tokenUrlsSchema,So as tradeCalculationMethodSchema,vo as tradeCalculationTypeSchema,Tr as tradeLimitSchema,bo as tradeListParamsSchema,eo as tradePaginationSchema,io as tradePaginationWithFiltersSchema,po as tradeTypeBackendSchema,fo as tradeTypeSchema,Br as transactionIdSchema,XI as transformRawApiTokenToDomainModel,fa as trimmedLengthValidation,Pr as uniqueKeySchema,lo as updateProfileDataSchema,uo as uploadProfileImageOptionsSchema,wr as urlSchema,Ar as userLimitSchema,Yr as userPaginationSchema,lr as userTokenNameSchema,so as userTokenTypeSchema,no as userTokensPaginationSchema,Bo as validateAddress,Do as validateAmountString,bd as validateBanTokenOptions,jo as validateBuyTokensData,Zo as validateCalculatePreMintData,Lh as validateChatMessageId,$o as validateCheckPoolOptions,qe as validateConstrainedEnumVariant,xd as validateCreateApiKeyOptions,Rh as validateCreateChatMessageOptions,KC as validateCreateCommentOptions,Vd as validateCreateModeratorInviteOptions,bh as validateCreateOverseerInviteOptions,zo as validateCreateTradeData,Ue as validateDecimalRangeStrict,Oe as validateFeePortionConstraints,Ko as validateFetchGalaBalanceOptions,Yo as validateFetchPoolDetailsData,Ho as validateFetchTokenBalanceOptions,Ro as validateFullName,Jo as validateGetAmountOptions,Dh as validateGetChatMessagesOptions,qC as validateGetCommentsOptions,Ad as validateGetTokenBanOptions,Xo as validateGetTradeOptions,ra as validateGetTradesOptions,Oo as validateImageUploadOptions,Xd as validateInviteCode,Xh as validateLaunchTokenData,Bd as validateListApiKeysOptions,Qd as validateListModeratorInvitesOptions,vh as validateListOverseerInvitesOptions,Sh as validateListOverseersOptions,Sd as validateListTokenBansOptions,Ih as validateListUsersOptions,$e as validateMinMaxRelationship,Rt as validateOptionalTokenName,Ah as validateOverseerInviteCode,Eh as validateOverseerInviteId,Th as validateOverseerWalletAddress,_s as validatePaginationParams,Mo as validateSearchQuery,Vo as validateSellTokensData,Fe as validateSortOrderDirection,_o as validateTokenDescription,qo as validateTokenListOptions,Lt as validateTokenName,xo as validateTokenSymbol,Uo as validateTokenUrls,Qo as validateTradeListParams,vd as validateUnbanTokenOptions,_d as validateUpdateApiKeyOptions,Mh as validateUpdateChatMessageOptions,GC as validateUpdateCommentOptions,Go as validateUpdateProfileData,Wo as validateUploadProfileImageOptions,Lo as validateUserTokenName,Po as validateVaultAddress,pr as vaultAddressSchema};
1
+ import{getAddress as e,Wallet as t,isAddress as n,JsonRpcProvider as r,Contract as i,Signature as o,keccak256 as s,toUtf8Bytes as a,ethers as c,Mnemonic as l,HDNodeWallet as u,computeAddress as d,SigningKey as h}from"ethers";import{ChainCallDTO as g,SigningType as f,calculatePersonalSignPrefix as p,SigningClient as m}from"@gala-chain/connect";import*as y from"uuid";import{v4 as w}from"uuid";import{z as b}from"zod";import k from"bignumber.js";import{TokenClassKey as v,TokenBalance as S}from"@gala-chain/api";import{Pool as A,TickData as E,CompositePoolDto as T,GetCompositePoolDto as I,QuoteExactAmountDto as C,quoteExactAmount as N,tickToSqrtPrice as _,getLiquidityForAmounts as x,getAmountsForLiquidity as D,liquidity0 as P,liquidity1 as B,getAmount0Delta as R,getAmount1Delta as M,sqrtPriceToTick as O,computeSwapStep as L}from"@gala-chain/dex";import U from"axios";import{io as F}from"socket.io-client";import*as $ from"dotenv";import*as q from"fs";import*as K from"path";const G={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"},H="/v1/users/referrals/url",W="/v1/users/referrals",z="/v1/users/referrals/summary",j="/v1/tokens/:tokenName/start-stream",V="/v1/tokens/:tokenName/stop-stream",X="/v1/tokens/:tokenName/stream/disable",Q="/v1/tokens/:tokenName/stream/enable",Y="/v1/tokens/:tokenName/reset-key",J="/v1/tokens/:tokenName/recordings",Z="/v1/tokens/:tokenName/recordings/:assetId/download",ee="/v1/tokens/:tokenName/recordings/:assetId",te="/v1/tokens/:tokenName/stream/simulcast",ne="/v1/tokens/:tokenName/stream/simulcast",re="/v1/tokens/:tokenName/stream/simulcast/:targetId",ie="/v1/config",oe="/v1/config",se="/v1/config",ae="/v1/tokens/:tokenName/role",ce="/v1/roles",le="/v1/tokens/:tokenName/access",ue="/v1/tokens/:tokenName/credentials",de="/auth/login",he="/auth/logout",ge="/auth/refresh",fe="/auth/session",pe="/v1/tokens/:tokenName/bans",me="/v1/tokens/:tokenName/bans",ye="/v1/tokens/:tokenName/bans/:userAddress",we="/v1/tokens/:tokenName/bans/:userAddress",be="/v1/tokens/:tokenName/active-users",ke="/v1/user-bans",ve="/v1/user-bans",Se="/v1/user-bans/:userAddress",Ae="/v1/user-bans/:userAddress",Ee={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Te="/v1/moderator-invites",Ie="/v1/moderator-invites/claim",Ce="/v1/moderated-tokens",Ne="/v1/moderator-invites",_e="/v1/moderator-invites/:id",xe="/v1/moderator-invites/:id/role",De="/v1/moderator-invites/:id",Pe="/v1/moderator-invites/code/:code",Be={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Re="/v1/overseer-invites",Me="/v1/overseer-invites",Oe="/v1/overseer-invites/code/:code",Le="/v1/overseer-invites/claim",Ue="/v1/overseer-invites/:id",Fe="/v1/overseers",$e="/v1/overseers",qe="/v1/overseers/:address",Ke="/v1/overseers/me",Ge="/v1/overseer-summary",He="/v1/overseer-summary/bans",We="/v1/overseer-summary/token-bans",ze="/v1/overseer-summary/invites",je="/v1/overseer-summary/flags",Ve="/v1/overseer-summary/users",Xe="/v1/users",Qe="/v1/users/:address/summary",Ye="/v1/cache/flush/address/:address",Je="/v1/cache/flush/token/:tokenName",Ze="/v1/cache/flush/all",et="/v1/cache/flush/wallet-aliases/:address",tt="/v1/cache/flush/wallet-aliases",nt="/v1/token-bans",rt="/v1/token-bans",it="/v1/token-bans/:tokenName",ot="/v1/token-bans/:tokenName",st="/v1/reactions",at="/v1/reactions",ct="/v1/trades",lt={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"},ut="/v1/restricted-token-names",dt="/v1/restricted-token-names",ht="/live/:tokenName/chat",gt="/live/:tokenName/chat",ft="/live/:tokenName/chat",pt="/live/chat",mt="/live/chat",yt="/live/chat",wt="/live/:tokenName/chat/slow-mode",bt="/live/:tokenName/engagement-stats",kt={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"},vt="/v1/stats",St="/v1/trading/fee",At="/v1/trading/sale-details",Et="/v1/trading/quote",Tt="/v1/trading/premint-quote",It={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},Ct={NATIVE:"native",EXACT:"exact"},Nt={RECENT:"recent",POPULAR:"popular"},_t={LOCAL:"local",EXTERNAL:"external"};function xt(e){return e instanceof Error}function Dt(e){return xt(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 Pt(e){return xt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Bt(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 Rt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Mt(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 Ot(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function Lt(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 Ut="Token name is required and must be a string",Ft=e=>`Could not find vault address for token: ${e}`,$t={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 qt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class Kt extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class Gt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Ht extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class Wt extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class zt extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.transactionHash=n,this.code=r,this.name="GSwapSwapError"}}class jt extends Error{constructor(e,t,n,r,i){super(e),this.originalError=t,this.tokenA=n,this.tokenB=r,this.code=i,this.name="GSwapPoolError"}}class Vt extends Error{constructor(e,t,n,r){super(e),this.originalError=t,this.walletAddress=n,this.code=r,this.name="GSwapAssetError"}}class Xt extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class Qt extends qt{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class Yt extends qt{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function Jt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Zt(e,t){return new qt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function en(e,t){const n=Jt(e,t);return new qt(`${n} is required`,e,"REQUIRED")}function tn(e,t,n){const r=Jt(e,n);return new qt(`${r} must be ${t}`,e,"INVALID_FORMAT")}function nn(e,t,n){return new Kt(e,t,n)}function rn(e,t){return new Gt(e,t)}function on(e,t,n){return new Ht(e,t,n)}function sn(e,t,n,r){n&&n.error(`${t}:`,e);const i=Rt(e)?e.response?.status:void 0;return nn(`${t}: ${Dt(e)}`,i,xt(e)?e:void 0)}function an(e,t,n,r,i){const o=Jt(e,i);return new qt(`${o} must be between ${t} and ${n}${void 0!==r?`, received: ${r}`:""}`,e,"OUT_OF_RANGE")}function cn(e,t,n,r){const i=Jt(e,r);return new qt(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function ln(e,t,n,r){const i=Jt(e,r);return new qt(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function un(e,t,n,r){const i=Jt(e,r),o=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new qt(`${i} must be ${t}${o}`,e,"INVALID_TYPE")}function dn(e,t,n){const r=Jt(e,n);return new qt(`${r} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function hn(e){return new qt(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function gn(e,t,n,r){const i=Jt(e,r);return new qt(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function fn(e,t){if(e.length<2)return en(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 qt(`At least one of ${n} must be provided`,e[0],"REQUIRED")}function pn(e,t,n,r){const i=Jt(e,r);return new qt(`${i} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}function mn(e,t){const n=Jt(e,t);return new qt(`${n} cannot be empty`,e,"EMPTY_STRING")}function yn(e){return null!=e&&"object"==typeof e&&"data"in e}function wn(e,t,n=!1){const r=!0===e.error,i=n&&(null===e.data||void 0===e.data);if(r||i){const n=e?.statusCode??e.status??void 0;throw nn(e?.message??t,n)}}function bn(e){if(yn(e))return e.data}function kn(e,t="No data found in response"){if(!yn(e))throw nn(t);const n=e.data;if(null==n)throw nn(t);return n}async function vn(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new qt(`${n}: No response from server`,"response","NO_RESPONSE");if(wn(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),void 0===t.data)throw new qt(`${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:i=!1}=t;i&&r&&r.debug(`${n}: starting operation`);try{const t=await e();return i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}async function An(e,t={}){const{errorContext:n="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new qt(`${n}: No response from server`,"response","NO_RESPONSE");return wn(t,n,!0),i&&r&&r.debug(`${n}: completed successfully`),t}catch(e){throw r&&r.error(n,{error:e}),e}}class En{}function Tn(e){return e.trim().toLowerCase()}function In(e){return e.trim().toUpperCase()}function Cn(e){return e.trim().toUpperCase()}var Nn;En.BASE_PRICE=1650667151e-14,En.PRICE_SCALING_FACTOR=1166069e-12,En.TRADING_FEE_FACTOR=.001,En.GAS_FEE="1",En.MIN_UNBONDING_FEE_FACTOR=0,En.MAX_UNBONDING_FEE_FACTOR=.5,En.NET_UNBONDING_FEE_FACTOR=.5,En.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7,function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Nn||(Nn={}));class _n{constructor(e){this.levelPriority={[Nn.DEBUG]:0,[Nn.INFO]:1,[Nn.WARN]:2,[Nn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Nn.DEBUG:Nn.INFO)}debug(e,t){this.log(Nn.DEBUG,e,t)}info(e,t){this.log(Nn.INFO,e,t)}warn(e,t){this.log(Nn.WARN,e,t)}error(e,t){this.log(Nn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Nn.DEBUG&&!this.debugEnabled)return;const r=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?xt(n)?i(`${r} ${t}`,n.message,Pt(n)??""):i(`${r} ${t}`,n):i(`${r} ${t}`)}getConsoleMethod(e){switch(e){case Nn.DEBUG:return console.debug;case Nn.INFO:return console.info;case Nn.WARN:return console.warn;case Nn.ERROR:return console.error;default:return console.log}}child(e){return new _n({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Nn.DEBUG]>=this.levelPriority[this.minLevel]}}function xn(e){return"string"==typeof e&&e.trim().length>0}function Dn(e){return null==e||""===e}function Pn(e){return null==e}const Bn=new _n({debug:!1,context:"DateUtils"});function Rn(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())?(Bn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return Bn.warn(`Date parsing error for "${e}":`,t),new Date}}function Mn(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 On(e){return Date.now()-e}const Ln={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},Un={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},Fn={MIN_LENGTH:1,MAX_LENGTH:50},$n=100,qn=20,Kn={MAX_LIMIT:50,DEFAULT_OFFSET:0,DEFAULT_LIMIT:20},Gn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},Hn={MAX_LENGTH:100},Wn={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}},zn={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})$/}},jn=60,Vn=31536e3,Xn={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Qn={PATTERN:/^[a-fA-F0-9]{64}$/},Yn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Jn=50,Zn=1,er=100,tr={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function nr(e,t){if(Dn(e))return t;try{return JSON.parse(e)}catch{return t}}function rr(e,t=0){if(Dn(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 ir(e,t,n){if(Pn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const r=Number(e);return isNaN(r)?t:r}function or(e,t=0){if(Dn(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 sr(e,t,n){if(Pn(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const r=parseInt(String(e),10);return isNaN(r)?t:r}function ar(e,t="0"){if(Dn(e))return new k(t);if(k.isBigNumber(e))return e.isNaN()?new k(t):e;try{const n=new k(e);return n.isNaN()||!n.isFinite()?new k(t):n}catch{return new k(t)}}function cr(e,t){if(Pn(e)||""===e)throw en(t);if(k.isBigNumber(e)){if(e.isNaN())throw dn(t,"NaN");return e}try{const n=new k(e);if(n.isNaN())throw dn(t,e);if(!n.isFinite())throw dn(t,e);return n}catch(n){if(n instanceof qt)throw n;throw dn(t,e)}}function lr(e,t=0){if(Pn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return rr(String(e).replace("%","").trim(),t)}function ur(e,t=18){const n=rr(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function dr(e){return ur(e,8)}function hr(e){return ur(e,18)}function gr(e,t,n,r){if("number"!=typeof e)throw un(r,"a number",e,r);if(e<t||e>n)throw an(r,t,n,e)}function fr(e,t,n){if("string"!=typeof e)throw un(n,"a string",e,n);if(e.length>t)throw ln(n,t,e.length)}function pr(e,t){if("number"!=typeof e)throw un(t,"a number",e,t);if(!Number.isInteger(e))throw un(t,"an integer",e,t);if(e<=0)throw cn(t,1,e,t)}function mr(e,t,n="range"){const r="number"==typeof e?e:Number(e),i="number"==typeof t?t:Number(t);if(isNaN(r)||isNaN(i))throw un(n,"numeric values",void 0,n);if(r>i)throw new qt(`Minimum value (${r}) must be less than or equal to maximum value (${i}) for ${n}`,n,$t.INVALID_RANGE)}function yr(e,t,n=!1){if("string"!=typeof e)throw un(t,"a string",e,t);if(!n&&0===e.trim().length)throw en(t,`${t} (non-empty string)`)}function wr(e,t){if("ASC"!==e&&"DESC"!==e)throw new qt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}function br(e,t,n,r){const i="string"==typeof e?parseFloat(e):e;if(!isFinite(i))throw new qt(`${r} must be a valid finite number between ${t} and ${n}`,r,"INVALID_NUMBER");if(i<t||i>n)throw an(r,t,n,i,r)}function kr(e,t,n){const r="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(r))throw new qt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new qt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(r<.1)throw new qt(`${n} minFee must be >= 0.1, received ${r}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new qt(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(r>i)throw new qt(`${n} minFee (${r}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}function vr(e,t,n,r){const i="string"==typeof e?parseFloat(e):e,o="string"==typeof t?parseFloat(t):t;if(!isFinite(i))throw new qt(`${n} must be a valid finite number`,n,"INVALID_MIN_VALUE");if(!isFinite(o))throw new qt(`${r} must be a valid finite number`,r,"INVALID_MAX_VALUE");if(i>o)throw new qt(`${n} (${i}) must be less than or equal to ${r} (${o})`,n,"INVALID_RANGE")}function Sr(e,t,n){if(!t.includes(e))throw new qt(`${n} must be one of [${t.map(e=>String(e)).join(", ")}], received "${e}"`,n,"INVALID_ENUM_VALUE")}const Ar={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Er=xn,Tr=Dn,Ir=Pn;function Cr(e,t,n=100,r,i){if(void 0!==i&&"string"!=typeof i)throw new qt("cursor must be a string","cursor",$t.INVALID_TYPE);const o=r??t,s=void 0!==r?"pageSize":"limit";if(void 0!==o&&(pr(o,s),o>n))throw new qt(`${s} must be at most ${n}`,s,$t.TOO_LARGE)}function Nr(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function _r(e){return Object.values(e)}function xr(e,t,n,r={}){const{description:i="parameter",treatEmptyAsNull:o=!0}=r,s=e[t],a=e[n],c=null!=s&&(!o||""!==s),l=null!=a&&(!o||""!==a);if(!c&&!l)throw rn(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&l)throw rn(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function Dr(e,t="tokenName",n=Ln){if(!Er(e))throw en(t);const r=e.trim();if(0===r.length)throw en(t);if(r.length<n.MIN_LENGTH)throw an(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(r.length>n.MAX_LENGTH)throw an(t,n.MIN_LENGTH,n.MAX_LENGTH,r.length,`${t} length`);if(!n.PATTERN.test(r))throw new qt(`${t} must contain only alphanumeric characters`,t,$t.INVALID_FORMAT)}function Pr(e,t="tokenName",n=Ln){if(null==e)return;if("string"!=typeof e)throw un(t,"a string",e);const r=e.trim();if(0!==r.length&&!n.PATTERN.test(r))throw new qt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,$t.INVALID_FORMAT)}function Br(e,t=Ln){if("string"!=typeof e)return!1;const n=e.trim();return 0!==n.length&&t.PATTERN.test(n)}function Rr(e,t="tokenName",n=Ln){if(null==e)throw en(t,t);if("string"!=typeof e)throw un(t,"a string",e);const r=e.trim();if(0===r.length)throw en(t,t);if(!n.PATTERN.test(r))throw new qt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,$t.INVALID_FORMAT)}function Mr(e){return t=>{if(null==t||"object"!=typeof t)return!1;const n=t;for(const{field:t,type:r,nullable:i=!1,optional:o=!1,validator:s}of e){const e=n[t];if((!o||void 0!==e)&&(!i||null!==e)){if(typeof e!==r)return!1;if(s&&!s(e))return!1}}return!0}}const Or={requiredString:e=>t=>Ir(t)?`${e} is required`:"string"!=typeof t?`${e} must be a string`:0===t.trim().length?`${e} cannot be empty`:void 0,maxLength:(e,t)=>n=>{if(!Tr(n))return"string"!=typeof n?`${e} must be a string`:n.length>t?`${e} must be at most ${t} characters`:void 0},positiveInteger:e=>t=>{if(!Ir(t))return"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`},requiredPositiveInteger:e=>t=>Ir(t)?`${e} is required`:"number"==typeof t&&Number.isInteger(t)?t<1?`${e} must be a positive integer`:void 0:`${e} must be an integer`,enumValue:(e,t)=>n=>{if(!Ir(n))return t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`},requiredEnumValue:(e,t)=>n=>Ir(n)?`${e} is required`:t.includes(n)?void 0:`${e} must be one of: ${t.join(", ")}`,isoDate:e=>t=>{if(!Ir(t))return"string"!=typeof t?`${e} must be a string`:Mn(t)?void 0:`${e} must be a valid ISO 8601 date string`},walletAddress:(e,t=!1)=>n=>{if(Ir(n))return t?`${e} is required`:void 0;if("string"!=typeof n)return`${e} must be a string`;return Ar.ETH_ADDRESS.test(n)||Ar.BACKEND_ADDRESS.test(n)||Ar.CLIENT_ADDRESS.test(n)?void 0:`${e} must be a valid wallet address`}};function Lr(e){return t=>{const n=[],r=t;for(const t of e){const{field:e,required:i,type:o,validator:s}=t,a=r[e];if(i){if(Ir(a)){n.push(`${e} is required`);continue}if("string"===o){if("string"!=typeof a){n.push(`${e} must be a string`);continue}if(0===a.trim().length){n.push(`${e} is required`);continue}}}if(!Ir(a))if(void 0===o||typeof a===o){if(void 0!==s){const e=s(a,r);null!=e&&""!==e&&n.push(e)}}else n.push(`${e} must be a ${o}`)}return n}}function Ur(e){return""===e||0===e.trim().length}function Fr(e,t,n){if(!Ir(e)){if("string"!=typeof e)throw un(t,"a string",e,t);if(e.length>n)throw new qt(`${t} must be at most ${n} characters`,t,$t.TOO_LARGE)}}function $r(e,t){if(Ir(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 un(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new qt(`${t} must be a valid date`,t,$t.INVALID_FORMAT)}function qr(e,t,n){try{pr(e,t)}catch{throw function(e,t,n,r="OPERATION_FAILED"){return new qt(`${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 qt(`${n} must be one of: ${r.join(", ")}`,n,$t.INVALID_FORMAT)}(e,t,n)}class Gr{constructor(e,t=!1,n){this.http=e,this.logger=new _n({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 Gt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Pt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){qr(e,t,n)}}class Hr{constructor(e=!1,t){this.logger=t||new _n({debug:e,context:this.constructor.name})}}class Wr extends Hr{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 zr extends Wr{constructor(e=!1){super(e)}normalizeKey(e){return Tn(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>=zr.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??En.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY.toString()}has(e){const t=this.normalizeKey(e);return this.cache.has(t)}clear(e){if(void 0!==e&&""!==e){const t=this.normalizeKey(e);this.cache.delete(t)}else super.clear()}dumpAsObject(){const e={};return this.cache.forEach((t,n)=>{e[n]=t}),e}getStats(){const e=this.buildBaseStats(),{cacheSize:t,oldestEntry:n}=this.calculateCacheSizeAndAge();return{...e,totalTokens:e.totalItems,cacheSize:t,oldestEntry:n}}calculateCacheSizeAndAge(){let e=Date.now(),t=0;return this.cache.forEach((n,r)=>{n.lastUpdated<e&&(e=n.lastUpdated);let i=0;i+=2*r.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(i+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(i+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(i+=2*n.symbol.length),i+=32,t+=i}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${Tn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${Tn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${Tn(e)}`;return this.cache.has(t)}}zr.MAX_CACHE_SIZE=1e4;class jr extends g{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 Vr(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}const Xr={ETHEREUM:Ar.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Ar.BACKEND_ADDRESS,CLIENT:Ar.CLIENT_ADDRESS};class Qr{toBackendFormat(t){if(!Er(t))throw new qt("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 qt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${t}"`,"address","INVALID_FORMAT");return t}if(n=Vr(t),!/^[a-fA-F0-9]{40}$/.test(n))throw new qt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${t}"`,"address","INVALID_FORMAT");return`eth|${e(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!Er(e))throw new qt("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 qt(`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(!Xr.CLIENT.test(e))throw new qt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!Xr.BACKEND.test(e))throw new qt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Er(e)&&(!!Xr.ETHEREUM.test(e)||(!!Xr.ETHEREUM_NO_PREFIX.test(e)||(!!Xr.BACKEND.test(e)||!!Xr.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new qt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Er(e)?Xr.ETHEREUM.test(e)||Xr.ETHEREUM_NO_PREFIX.test(e)?"ethereum":Xr.BACKEND.test(e)?"backend":Xr.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 Vr(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new qt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Yr=new Qr,Jr=Vr;function Zr(e){return Yr.toBackendFormat(e)}function ei(e){return Yr.toEthereumFormat(e)}function ti(e){return Yr.normalizeInput(e)}function ni(e){return Yr.isValid(e)}function ri(e,t="address"){Yr.assertValid(e,t)}function ii(e){const t="string"==typeof e?e:e.address;return Yr.toBackendFormat(t)}function oi(e){return Yr.detectFormat(e)}var si=Object.freeze({__proto__:null,AddressFormatter:Qr,assertValidWalletAddress:ri,detectFormat:oi,fromBackendAddressFormat:ei,isValidAddress:ni,normalizeAddressInput:ti,stripHexPrefix:Jr,toBackendAddressFormat:Zr,toBackendAddressFromEthers:ii});const ai=b.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"),ci=b.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"),li=b.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),ui=b.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),di=b.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),hi=b.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"),gi=b.string().regex(Ar.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),fi=b.string().regex(Ar.ETH_ADDRESS,"Invalid Ethereum address format"),pi=b.string().refine(e=>Ar.BACKEND_ADDRESS.test(e)||Ar.ETH_ADDRESS.test(e)||Ar.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Qr).normalizeInput(e)??e),mi=b.string().refine(e=>Ar.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),yi=b.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>rr(e,0)>0,"Amount must be greater than zero"),wi=b.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>rr(e,0)>=0,"Amount must be zero or greater"),bi=b.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://"),ki=b.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided"),vi=b.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 Si(e=100){return b.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 Ai=Si(100),Ei=Si(20),Ti=Si(20),Ii=b.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"),Ci=b.string().max(255,"Filename must be at most 255 characters"),Ni=b.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]),_i=b.string().datetime("Must be a valid ISO 8601 date string"),xi=b.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative"),Di=b.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters"),Pi=b.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"),Bi=b.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}"),Ri=[".png",".jpg",".jpeg",".gif",".webp",".svg"],Mi=b.object({file:b.union([b.instanceof(File),b.instanceof(Buffer)]),name:Ci,size:Ii,type:Ni}),Oi=b.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"),Li=b.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB"),Ui=b.union([Oi,Li]),Fi=b.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),$i=Ci.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Ri.includes(t)},`Filename must end with one of: ${Ri.join(", ")}`),qi=b.object({websiteUrl:ki,telegramUrl:ki,twitterUrl:ki,instagramUrl:ki,facebookUrl:ki,redditUrl:ki,tiktokUrl:ki}).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"),Ki=b.string().min(1,"Token category must not be empty").default("Unit"),Gi=b.string().min(1,"Token collection must not be empty").default("Token"),Hi=b.object({minFeePortion:b.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>rr(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>rr(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:b.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>rr(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>rr(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>rr(e.maxFeePortion,0)>=rr(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Wi=b.object({tokenName:ai,tokenSymbol:ci,tokenDescription:li,tokenImage:b.union([b.instanceof(File),b.instanceof(Buffer),b.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:wi.default("0"),websiteUrl:ki,telegramUrl:ki,twitterUrl:ki,instagramUrl:ki,facebookUrl:ki,redditUrl:ki,tiktokUrl:ki,tokenCategory:Ki,tokenCollection:Gi,reverseBondingCurveConfiguration:Hi.optional(),saleStartTime:b.number().int().positive().optional(),privateKey:Di.optional()}),zi=b.object({file:b.union([b.instanceof(File),b.instanceof(Buffer)]),tokenName:ai}),ji=b.enum(["RECENT","POPULAR"]),Vi=b.object({tokenName:ai.optional(),symbol:ci.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required"),Xi=b.enum(["NATIVE","MEME"]),Qi=b.enum(["IN","OUT"]),Yi=b.object({from:b.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:b.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:b.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ai}),Ji=b.object({tokenName:ai,slippageToleranceFactor:b.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:b.number().min(0).max(1).optional(),privateKey:Di.optional()}),Zi=b.object({offset:b.number().int().min(0).default(0),pageSize:b.number().int().min(1).max(100).default(10)}),eo=b.object({offset:b.number().int().min(0).default(0),pageSize:b.number().int().min(1).max(20).default(10)}),to=b.object({offset:b.number().int().min(0).default(0),pageSize:b.number().int().min(1).max(20).default(10)}),no=Zi.extend({type:b.enum(["RECENT","POPULAR"]).optional(),tokenName:b.string().min(1).max(50).optional(),search:b.string().min(1).max(100).optional()}),ro=eo.extend({tokenName:b.string().min(1).max(50).optional(),search:b.string().min(1).max(100).optional()}),io=to.extend({tradeType:b.enum(["BUY","SELL"]).optional(),tokenName:b.string().min(1).max(50).optional(),userAddress:b.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:b.string().datetime().optional(),endDate:b.string().datetime().optional(),sortOrder:b.enum(["ASC","DESC"]).default("DESC")}),oo=b.object({page:b.number().int().min(1),limit:b.number().int().min(1),total:b.number().int().min(0),totalPages:b.number().int().min(0),hasNext:b.boolean(),hasPrevious:b.boolean()});function so(e){return b.object({data:b.array(e),page:b.number().int().min(1),limit:b.number().int().min(1),total:b.number().int().min(0),totalPages:b.number().int().min(0),hasNext:b.boolean(),hasPrevious:b.boolean()})}const ao=b.enum(["buy","sell"]),co=b.enum(["BUY","SELL"]),lo=b.object({tradeType:ao,tokenAmount:yi,vaultAddress:mi,userAddress:pi,slippageTolerance:yi.optional(),deadline:b.number().int().positive().optional()}),uo=b.object({tokenSymbol:ci,nativeTokenQuantity:yi,expectedToken:yi,maxAcceptableReverseBondingCurveFee:wi.default("0").optional()}),ho=b.object({tokenSymbol:ci,tokenQuantity:yi,expectedNativeToken:yi,maxAcceptableReverseBondingCurveFee:wi.default("0").optional()}),go=to.extend({tokenName:ui.optional()}),fo=b.object({page:b.number().int().min(1).max(1e3).default(1).optional(),limit:b.number().int().min(1).max(20).default(10).optional()}),po=b.enum(["NATIVE","MEME"]),mo=b.enum(["IN","OUT"]),yo=b.object({type:po,method:mo,vaultAddress:mi,amount:yi}),wo=b.object({nativeTokenQuantity:yi}),bo=b.object({vaultAddress:mi}),ko=b.object({minFeePortion:yi,maxFeePortion:yi}),vo=b.enum(["all","DEFI","ASSET"]),So=eo.extend({type:vo.optional(),address:pi.optional(),search:di.optional(),tokenName:ui.optional()}),Ao=b.object({address:pi.optional(),refresh:b.boolean().optional()}),Eo=b.object({profileImage:b.string(),fullName:hi,address:pi,privateKey:Di.optional()}),To=b.object({file:b.union([b.instanceof(File),b.instanceof(Buffer)]),address:pi.optional(),privateKey:Di.optional()}),Io=b.object({created:b.number(),createdBy:b.string(),expires:b.number(),instanceId:b.string(),lockAuthority:b.string(),name:b.string(),quantity:b.string(),vestingPeriodStart:b.number()}),Co=b.object({address:pi,tokenId:b.union([b.string(),b.object({collection:b.string(),category:b.string(),type:b.string(),additionalKey:b.string()}),b.object({collection:b.string(),category:b.string(),type:b.string(),additionalKey:b.string(),instance:b.string()})]).optional(),tokenName:ui.optional(),withExpired:b.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");function No(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 _o=No(ai),xo=No(ci),Do=No(li),Po=No(pi),Bo=No(mi),Ro=No(yi),Mo=No(hi),Oo=No(di),Lo=No(ui),Uo=No(Wi),Fo=No(qi),$o=No(zi),qo=No(Vi),Ko=No(So),Go=No(Ao),Ho=No(Eo),Wo=No(To),zo=No(Co),jo=No(lo),Vo=No(uo),Xo=No(ho),Qo=No(go),Yo=No(fo),Jo=No(yo),Zo=No(wo),es=No(bo);function ts(e){return Uo(e).success}function ns(e){const t=Uo(e);return t.success?[]:t.errors??["Unknown validation error"]}function rs(e){const t=ns(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function is(e,t){return"string"==typeof e[t]}function os(e,t){return void 0===e[t]||"string"==typeof e[t]}function ss(e,t){return void 0===e[t]||"number"==typeof e[t]}function as(e){if(null==e||"object"!=typeof e)return!1;const t=e;return is(t,"tokenName")&&ss(t,"from")&&ss(t,"to")&&ss(t,"resolution")}function cs(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 ls(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(!cs(n[t],r))return!1}return!0}}Nr({BUY:"buy",SELL:"sell"});const us=ls({vaultAddress:"string"}),ds=ls({nativeTokenQuantity:"string"});function hs(e){if(Ir(e)||"object"!=typeof e)return{};const t={};for(const[n,r]of Object.entries(e))Ir(r)||(Er(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 gs=Object.freeze({__proto__:null,adaptQueryParams:hs});function fs(e,t="0"){return ar(e,t)}function ps(e,t){return void 0!==t?fs(e).toFixed(t):fs(e).toFixed()}function ms(e,t=.01){const n=fs(e),r=new k(1).minus(t);return n.multipliedBy(r)}function ys(e=.01){return new k(1).minus(e)}function ws(e=.01){return new k(1).plus(e)}function bs(e){const t=fs(e),n=Math.log(1.0001),r=t.toNumber();return Math.log(r)/n}function ks(e,t=!1){const n=fs(e),r=new k(1).dividedBy(n);return t?r.toFixed():r}function vs(){return new k(2).pow(96)}function Ss(e,t){return k.min(fs(e),fs(t))}function As(e,t){return k.max(fs(e),fs(t))}function Es(e){return fs(e).isZero()}function Ts(e){return fs(e).isGreaterThan(0)}function Is(e){return fs(e).isLessThan(0)}function Cs(e,t){return fs(e).isLessThan(fs(t))}function Ns(e,t){return fs(e).multipliedBy(t).dividedBy(100)}function _s(...e){e.forEach(e=>{if(e.isNaN())throw dn("value","NaN");if(!e.isFinite())throw ln("value","finite");if(e.isLessThanOrEqualTo(0))throw cn("value","0",e.toString())})}function xs(...e){e.forEach(e=>{if(e.isNaN())throw dn("value","NaN");if(!e.isFinite())throw ln("value","finite");if(e.isLessThan(0))throw cn("value","0",e.toString())})}function Ds(e,t,n){if(e.isNaN())throw dn(t,"NaN");if(!e.isFinite())throw ln(t,"finite");if(e.isLessThanOrEqualTo(0))throw cn(t,"0",e.toString())}function Ps(e,t,n="0"){const r=fs(t);return Es(r)?fs(n):fs(e).dividedBy(r)}function Bs(e,t){return Math.floor(e/t)*t}class Rs{static calculateBuyWithExact(e,t){const n=rr(e),r=rr(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=En,c=this.roundUp(i*(Math.exp((r+n)*o)-Math.exp(r*o))/o,8),l=ps(fs(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateBuyWithNative(e,t){const n=rr(e),r=rr(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:o,TRADING_FEE_FACTOR:s,GAS_FEE:a}=En,c=Math.log(n*o/i+Math.exp(r*o))/o-r,l=ps(fs(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateSellWithExact(e,t,n,r,i){const o=rr(e),s=rr(t),a=rr(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=En,h=c*(Math.exp(s*l)-Math.exp((s-o)*l))/l,g=fs(h),f=r+s/a*(i-r),p=ps(g.multipliedBy(f),8),m=ps(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}}static calculateSellWithNative(e,t,n,r,i){const o=rr(e),s=rr(t),a=rr(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:u,GAS_FEE:d}=En;if(o>=c*(Math.exp(s*l)-1)/l){const e=fs(o),t=r+s/a*(i-r),n=ps(e.multipliedBy(t),8),c=ps(e.multipliedBy(u));return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:d}}const h=s-Math.log(Math.exp(s*l)-o*l/c)/l,g=fs(o),f=r+s/a*(i-r),p=ps(g.multipliedBy(f),8),m=ps(g.multipliedBy(u));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:m,gasFee:d}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class Ms extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Os(e,t,n){if(null==e)throw new Ms("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Oi.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Ms(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Ms("Filename is required when uploading Buffer objects",t,n);const r=Li.safeParse(e);if(!r.success){const e=r.error.issues.map(e=>e.message).join("; ");throw new Ms(e,t,n)}try{fr(t,255,"filename")}catch(e){throw new Ms(e.message,t,n)}const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(n))throw new Ms(`Invalid file type "${n}" is not allowed. Allowed types: ${i.join(", ")}`,t,n);const o=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(o))throw new Ms(`File extension "${o}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(o);if(a!==n&&"application/octet-stream"!==a)throw new Ms(`File extension "${o}" does not match MIME type "${n}"`,t,n);return}throw new Ms("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Ls(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 Us(e,t){return e.toLowerCase()===t.toLowerCase()}function Fs(e){return e.toLowerCase()}function $s(e,t){return e.toLowerCase().includes(t.toLowerCase())}function qs(e,t,n,r){return e===n&&t===r||e===r&&t===n}function Ks(e){if(""===e||"string"!=typeof e)return null;if(e.includes("|")){const t=e.split("|");if(t.length>=2){const e=t[1];if(Hs(e))return Ws(e)}return null}return Hs(e)?Ws(e):null}function Gs(e){return null==e||"string"!=typeof e||0===e.trim().length}function Hs(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 zs{validate(e,t={}){const{allowZero:n=!0,minimum:r,maximum:i,maxDecimals:o=zs.MAX_DECIMAL_PLACES,fieldName:s="amount"}=t;if(!Er(e))throw new qt(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new qt(`${s} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,s,"INVALID_NUMERIC_STRING");const a=rr(e,NaN);if(isNaN(a))throw new qt(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new qt(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new qt(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new qt(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=fs(e),l=c.decimalPlaces()??0;if(l>o)throw new qt(`${s} cannot exceed ${o} decimal places. Received: ${l} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==r&&Cs(c,r))throw new qt(`${s} must be at least ${r}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==i&&(u=i,fs(c).isGreaterThan(fs(u))))throw new qt(`${s} cannot exceed ${i}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var u}parseAmount(e,t="0"){return fs(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 ps(e,t)}clampAmount(e,t,n){const r=fs(e),i=fs(t),o=fs(n);return function(e,t,n){const r=fs(e),i=fs(t),o=fs(n);return r.isGreaterThanOrEqualTo(i)&&r.isLessThanOrEqualTo(o)}(r,i,o)?ps(r):Cs(r,i)?ps(i):ps(o)}}function js(e,t){throw new qt(e.join("; "),t,"VALIDATION_ERROR")}function Vs(e){const t=_o(e);!t.success&&t.errors&&js(t.errors,"tokenName")}function Xs(e){const t=qo(e);!t.success&&t.errors&&js(t.errors,"options")}function Qs(e){const t=Yi.safeParse(e);var n;t.success||js((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 Ys(e,t,n=!0){Js.validate(e,{fieldName:t,allowZero:n})}zs.MAX_DECIMAL_PLACES=18,zs.MIN_POSITIVE="0.00000000000000001";const Js=new zs;class Zs{constructor(e,t,n,r,i,o,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=r,this.galaChainHttp=i,this.dexApiHttp=o,this.defaultCalculateAmountMode=s,this.metadataCache=new zr}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`;Os(n.file,r,"image/png");try{const e=new FormData;if("undefined"!=typeof File&&n.file instanceof File)e.append("image",n.file);else{if(!Buffer.isBuffer(n.file))throw tn("file","a File object (browser) or Buffer (Node.js)");{const r=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,i=new Blob([n.file],{type:"image/png"});e.append("image",i,r)}}const r=await this.http.request({method:"POST",url:`/launchpad/upload-image?tokenName=${encodeURIComponent(void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t)}`,data:e,headers:{}});if(!0===r.error||200!==r.status)throw nn(void 0!==r.message&&""!==r.message?r.message:"Image upload failed - no URL returned",r.status);const i=bn(r);if(!i?.imageUrl)throw nn("Image upload failed - no URL returned",r.status);return i.imageUrl}catch(e){if(xt(e)&&e.message.includes("FormData"))throw rn("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=hs(t),r=await this.http.get("/launchpad/fetch-pool",n);if(!0===r.error||200!==r.status)throw nn(void 0!==r.message&&""!==r.message?r.message:"Failed to fetch pools",r.status);const i=bn(r);if(null==i)throw nn("Failed to fetch pools - no data returned",r.status);let o=[];if(i.tokens)if(Array.isArray(i.tokens))o=i.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!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=i.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",r=!Es(t)||!Es(n);o=[{...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 i.pools&&Array.isArray(i.pools)&&(o=i.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 B_});o.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=i.count??i.total??0,l={hasNextPage:i.hasNextPage??!1};return void 0!==i.hasPrevPage&&(l.hasPrevPage=i.hasPrevPage),void 0!==i.nextCursor&&(l.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(l.prevCursor=i.prevCursor),c>0&&(l.totalCount=c),{items:o,pageInfo:l}}async checkPool(e){Xs(e),void 0!==e.tokenName&&""!==e.tokenName&&Vs(e.tokenName);const t=hs(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw nn(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(!as(e))throw tn("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:r,resolution:i}=e;if(Vs(t),null==n||null==r||null==i)throw en("graphOptions","Graph options (from, to, resolution)");const o={tokenName:t,from:n,to:r,resolution:i};Qs(o);const s=hs(o),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw nn(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch graph data",a.status);const c=bn(a);if(!c)throw nn("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 tn("options","an options object");const{tokenName:t,amount:n,type:r,currentSupply:i}=e,o=e.mode??this.defaultCalculateAmountMode;if("local"!==o&&"external"!==o)throw un("mode",'"local" or "external"',o);if(!Er(t))throw en("tokenName","Token name");if(!Er(n))throw en("amount","Amount");if(r!==Ct.NATIVE&&r!==Ct.EXACT)throw un("type",'"native" or "exact"',r);return"external"===o?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:r}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:r},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;if("string"!=typeof t||""===t)throw new qt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof n||""===n)throw new qt("Amount must be a non-empty string","amount","INVALID_AMOUNT");return"exact"===r?vn(()=>this.http.get(Et,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):vn(()=>this.http.get(Et,{tokenName:t,amount:n,type:"NATIVE",method:"IN"}),{errorContext:`Failed to calculate buy amount for ${t} (native/GALA budget)`})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw un("mode",'"local" or "external"',c);if(!Er(t))throw en("tokenName","Token name");if(!Er(n))throw en("amount","Amount");if(r!==Ct.EXACT&&r!==Ct.NATIVE)throw un("type",'"exact" or "native"',r);if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:r});{const e={tokenName:t,amount:n,type:r,...void 0!==i&&{currentSupply:i},...void 0!==o&&{maxSupply:o},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:r}=e;if("string"!=typeof t||""===t)throw new qt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof n||""===n)throw new qt("Amount must be a non-empty string","amount","INVALID_AMOUNT");return"exact"===r?vn(()=>this.http.get(Et,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):vn(()=>this.http.get(Et,{tokenName:t,amount:n,type:"NATIVE",method:"OUT"}),{errorContext:`Failed to calculate sell amount for ${t} (native/GALA target)`})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i}=e;if(!Er(n))throw en("amount","Amount");if(r!==Ct.NATIVE&&r!==Ct.EXACT)throw un("type",'"native" or "exact"',r);void 0!==i&&Ys(i,"currentSupply");const o=null==i||""===i;if(o&&(null==t||""===t))throw en("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Vs(t);let s=i;if(o){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return r===Ct.EXACT?Rs.calculateBuyWithExact(n,s):Rs.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:r,currentSupply:i,maxSupply:o,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!Er(n))throw en("amount","Amount");if(r!==Ct.EXACT&&r!==Ct.NATIVE)throw un("type",'"exact" or "native"',r);void 0!==i&&Ys(i,"currentSupply");const c=null==i||""===i||null==o||""===o||void 0===s||void 0===a;if(c&&(null==t||""===t))throw en("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Vs(t);let l=i,u=o,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===Ct.EXACT?Rs.calculateSellWithExact(n,l,u,h,d):Rs.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 is(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&os(t,"currentSupply")}(e))throw un("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:r,currentSupply:i}=t;Vs(n);const o=await this.tokenResolver.resolveTokenToVault(n);if(null==o||""===o)throw new qt(Ft(n),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw rn("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:o});if(1!==s.Status)throw nn(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=i??ps(fs(a.maxSupply).minus(a.sellingTokenQuantity)),l=a.sellingTokenQuantity;if("0"===l)throw en("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 rn("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");rs(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=rr(t);if(0===n&&"0"!==t)throw dn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw dn("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;kr(t,n,"reverseBondingCurve")}let r="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 nn("Image upload failed: No URL returned");r=t}else"string"==typeof e.tokenImage&&(r=e.tokenImage);const i=`galaswap - operation - ${w()}-${Date.now()}-${this.http.getAddress()}`,o=(void 0!==t&&""!==t?t:"0").toString(),s=void 0!==e.tokenCategory&&""!==e.tokenCategory?e.tokenCategory:"Unit",a=void 0!==e.tokenCollection&&""!==e.tokenCollection?e.tokenCollection:"Token",c={tokenName:e.tokenName.trim(),tokenSymbol:Cn(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:r.trim(),preBuyQuantity:o,tokenCategory:s,tokenCollection:a,uniqueKey:i},l=Ls(e.websiteUrl);null!==l&&(c.websiteUrl=l);const u=Ls(e.telegramUrl);null!==u&&(c.telegramUrl=u);const d=Ls(e.twitterUrl);null!==d&&(c.twitterUrl=d);const h=Ls(e.instagramUrl);null!==h&&(c.instagramUrl=h);const g=Ls(e.facebookUrl);null!==g&&(c.facebookUrl=g);const p=Ls(e.redditUrl);null!==p&&(c.redditUrl=p);const m=Ls(e.tiktokUrl);null!==m&&(c.tiktokUrl=m);const y=e.reverseBondingCurveConfiguration?.minFeePortion?.toString()??"0.1",b=e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()??"0.5";c.reverseBondingCurveConfiguration={minFeePortion:y,maxFeePortion:b},void 0!==e.saleStartTime&&null!==e.saleStartTime&&(c.saleStartTime=e.saleStartTime);const k=Object.fromEntries(Object.entries(c).filter(([e,t])=>void 0!==t)),v=new jr(k),S=await this.http.signWithGalaChain("CreateSale",v,f.SIGN_TYPED_DATA),{signature:A,types:E,domain:T,prefix:I}=S,C=null!=I?{prefix:I}:{},N=void 0!==v.reverseBondingCurveConfiguration&&null!==v.reverseBondingCurveConfiguration?{reverseBondingCurveConfiguration:v.reverseBondingCurveConfiguration}:{},_=void 0!==v.saleStartTime&&null!==v.saleStartTime?{saleStartTime:v.saleStartTime}:{},x={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,...N,..._},D=`${e.tokenName.trim()}$Unit$none$none`,P="GALA$Unit$none$none";let B;if(rr(t,0)>0){const e=`$service$${D}$launchpad`;B=[e,`$token$${D}$${e}`,`$tokenBalance$${D}$${e}`,`$tokenBalance$${D}$${e}`,`$tokenBalance$${P}$${e}`,`$tokenBalance$${P}$${e}`]}else{const e=`$service$${D}$launchpad`;B=[e,`$token$${D}$${e}`,`$tokenBalance$${D}$${e}`]}const R={signedDto:x,stringsInstructions:B,method:"CreateSale"},M=await this.bundleHttp.post("/bundle",R);if(M.error)throw nn(void 0!==M.message&&""!==M.message?M.message:"Token launch failed");const O=bn(M);if(null==O||""===O)throw nn("Token launch failed - no transaction ID returned");return O}async fetchTokenDistribution(e){if(null==e||""===e)throw en("tokenName","Token name");Vs(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw nn(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=bn(t);if(null==n)throw nn("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw nn("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 nn("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 nn("Invalid holder data: missing or invalid quantity field",t.status);const n=rr(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw nn(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),fs(0));return{holders:n.map(e=>{const t=Ps(fs(e.quantity),r,fs(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:ps(r),totalHolders:n.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(null==e||""===e)throw en("tokenName","Token name");Vs(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw nn(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token badges");const n=bn(t);if(null==n)throw nn("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 i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return i?.isActive??!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!ds(e))throw tn("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw rn("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 nn("Malformed response data from GalaChain gateway");try{Mt(n,"Pre-mint calculation")}catch(e){throw nn(Dt(e),500)}const{calculatedQuantity:r,extraFees:i}=n.Data;return{amount:r,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(xt(e)&&e instanceof Kt)throw e;throw nn(Dt(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new qt(Ft(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw rn("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw nn(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=ps(fs(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity,s=r.maxSupply;let a=.5,c=.1;const l=r.reverseBondingCurveConfiguration;null!=l?.maxFeePortion&&(a=lr(l.maxFeePortion,.5)),null!=l?.minFeePortion&&(c=lr(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:i,remainingTokens:o,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 qt(Ft(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw rn("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw nn(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const r=n.Data,i=ps(fs(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.maxSupply;return this.metadataCache.set(e,{maxSupply:o}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Zr(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 rn("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw en("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 nn(`Failed to fetch token prices: ${Dt(e)}`,void 0,xt(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const ea={REFRESH_THRESHOLD_MS:3e5,DEFAULT_EXPIRY_S:86400,LOGIN_MESSAGE_PREFIX:"Sign in to Launchpad t:",AUTH_HEADER:"Authorization",BEARER_PREFIX:"Bearer "};class ta{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 na,ra;!function(e){e.WALLET_NOT_CONNECTED="WALLET_NOT_CONNECTED",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.INVALID_ADDRESS="INVALID_ADDRESS",e.MESSAGE_GENERATION_FAILED="MESSAGE_GENERATION_FAILED"}(na||(na={}));class ia extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class oa{constructor(e,t=ea.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 ta,this.refreshThresholdMs=t}setToken(e,t){if(!Er(e))throw new ia(na.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new ia(na.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new ia(na.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new ia(na.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 ia(na.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:`${ea.BEARER_PREFIX}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new ia(na.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[ea.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 i=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),o=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(i&&o){const e=Number(o);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=i,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function sa(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),sn(e,t,n))}}function aa(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),sn(e,t,n))}}class ca{constructor(e,t,n,r=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new _n({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 ia(na.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 sa(async()=>{const e=Date.now(),t=`${ea.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();ri(r,"address");const i={address:r,message:t,signature:n.signature};let o;try{this.logger.debug("Sending login request with refresh token support",{address:r,message:t}),o=await this.http.post(de,{...i,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),o=await this.http.post(de,i)}const s=this.extractLoginData(o);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 ia)throw e;throw new ia(na.SIGNATURE_FAILED,`Login failed: ${Dt(e)}`,xt(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 ia(na.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 sa(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(ge,{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(ge,{},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 ia)throw e;throw new ia(na.SIGNATURE_FAILED,`Token refresh failed: ${Dt(e)}`,xt(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(he,{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): ${Dt(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 ia(na.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return sa(async()=>{const e=await this.http.get(fe,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(e,t,n)=>{if(e instanceof ia)throw e;throw new ia(na.SIGNATURE_FAILED,`Failed to get session: ${Dt(e)}`,xt(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 ia(na.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: ${Dt(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 ia(na.SIGNATURE_FAILED,""!==Dt(e)?Dt(e):"Authentication failed");const t=kn(e,"No data in authentication response"),{accessToken:n,expiresIn:r,address:i,refreshToken:o,refreshExpiresIn:s}=t;if(!Er(n))throw new ia(na.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof r||r<=0)throw new ia(na.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:r,address:i,...void 0!==o&&{refreshToken:o},...void 0!==s&&{refreshExpiresIn:s}}}extractSessionData(e){if(e.error)throw new ia(na.SIGNATURE_FAILED,""!==Dt(e)?Dt(e):"Failed to get session");return kn(e,"No data in session response")}}class la 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"}(ra||(ra={}));class ua{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new t(e)}catch(e){throw new la("Invalid private key provided",ra.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new ua(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new la("Failed to sign message",ra.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 la("Failed to sign typed data",ra.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(e(this.wallet.address))}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async connect(){return this.connected=!0,this.getAddress()}disconnect(){return this.connected=!1,Promise.resolve()}isConnected(){return this.connected}getPrivateKey(){return Promise.resolve(this.wallet.privateKey)}getWallet(){return this.wallet}}class da{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{yr(e.messagePrefix,"messagePrefix",!1)}catch{throw new ia(na.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=ua.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Zr(this.wallet.address)}catch(e){if(e instanceof ia)throw e;if(e instanceof qt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new ia(na.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new ia(na.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new ia(na.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new ia(na.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=ua.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Zr(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 ia)throw e;throw new ia(na.SIGNATURE_FAILED,"Failed to generate signature for authentication",xt(e)?e:new Error(Dt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new ia(na.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 ia(na.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 ia(na.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 ia(na.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 ia(na.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new ia(na.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",xt(e)?e:void 0)}}formatAddress(e){try{return Zr(e)}catch{throw new ia(na.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 ia)throw e;throw new ia(na.SIGNATURE_FAILED,Dt(e),xt(e)?e:new Error(Dt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),r=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,i=await this.walletProvider.signMessage(r);return{"x-signature":i,"x-address":await this.walletProvider.getGalaAddress(),"x-message":r,"x-timestamp":n.toString()}}catch(e){if(e instanceof ia)throw e;throw new ia(na.SIGNATURE_FAILED,"Failed to generate authentication headers",xt(e)?e:new Error(Dt(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 ia)throw e;throw new ia(na.SIGNATURE_FAILED,"Failed to sign typed data",xt(e)?e:new Error(Dt(e)))}}async generateCustomSignature(e){if(!Er(e))throw new ia(na.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 ia)throw e;throw new ia(na.SIGNATURE_FAILED,"Failed to generate custom message signature",xt(e)?e:new Error(Dt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new ia(na.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new ia(na.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new ia(na.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ha={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://galachain-gateway-chain-platform-stage-chain-platform-eks.stage.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"},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",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-dev1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-qa1.defi.gala.com"}};function ga(e){return ha[e]}function fa(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function pa(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function ma(e){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const ya={GALA_CHAIN:1,ETHEREUM:2,SOLANA:1002},wa={ASSET:1,MUSIC:3};function ba(e){return Object.values(wa).includes(e)}const ka=12,va=15e3,Sa=27e5,Aa={UNIT_LIMIT:2e5,UNIT_PRICE_MICROLAMPORTS:375e3},Ea="https://ethereum.publicnode.com",Ta="https://api.mainnet-beta.solana.com",Ia="0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9",Ca="0x6a1734E09f3099a3675645D214ce547080ea67e0",Na="AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",_a="https://dex-api-platform-dex-prod-gala.gala.com",xa=[{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}],Da=[{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 Pa(e){return"PROD"===e?xa:Da}function Ba(e){return"PROD"===e?Ia:Ca}const Ra=xa,Ma=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],Oa={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"}},La=["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)"],Ua=["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"],Fa={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 $a(e){const t=Cn(e),n=Oa[t];if(void 0!==n)return n;if(!t.startsWith("G")){const e=Oa[`G${t}`];if(void 0!==e)return e}}function qa(e){const t=Cn(e);return Ra.find(e=>Cn(e.symbol)===t||Cn(e.symbol)===`G${t}`)}function Ka(e){const t=Cn(e);return Ma.find(e=>Cn(e.symbol)===t||Cn(e.symbol)===`G${t}`)}function Ga(e){return fa(e)}function Ha(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Wa(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 za,ja={},Va={};function Xa(){if(za)return Va;za=1,Va.byteLength=function(e){var t=o(e),n=t[0],r=t[1];return 3*(n+r)/4-r},Va.toByteArray=function(e){var r,i,s=o(e),a=s[0],c=s[1],l=new n(function(e,t,n){return 3*(t+n)/4-n}(0,a,c)),u=0,d=c>0?a-4:a;for(i=0;i<d;i+=4)r=t[e.charCodeAt(i)]<<18|t[e.charCodeAt(i+1)]<<12|t[e.charCodeAt(i+2)]<<6|t[e.charCodeAt(i+3)],l[u++]=r>>16&255,l[u++]=r>>8&255,l[u++]=255&r;2===c&&(r=t[e.charCodeAt(i)]<<2|t[e.charCodeAt(i+1)]>>4,l[u++]=255&r);1===c&&(r=t[e.charCodeAt(i)]<<10|t[e.charCodeAt(i+1)]<<4|t[e.charCodeAt(i+2)]>>2,l[u++]=r>>8&255,l[u++]=255&r);return l},Va.fromByteArray=function(t){for(var n,r=t.length,i=r%3,o=[],s=16383,c=0,l=r-i;c<l;c+=s)o.push(a(t,c,c+s>l?l:c+s));1===i?(n=t[r-1],o.push(e[n>>2]+e[n<<4&63]+"==")):2===i&&(n=(t[r-2]<<8)+t[r-1],o.push(e[n>>10]+e[n>>4&63]+e[n<<2&63]+"="));return o.join("")};for(var e=[],t=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)e[i]=r[i],t[r.charCodeAt(i)]=i;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function s(t){return e[t>>18&63]+e[t>>12&63]+e[t>>6&63]+e[63&t]}function a(e,t,n){for(var r,i=[],o=t;o<n;o+=3)r=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(s(r));return i.join("")}return t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63,Va}var Qa,Ya,Ja={};function Za(){return Qa||(Qa=1,Ja.read=function(e,t,n,r,i){var o,s,a=8*i-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?i-1:0,h=n?-1:1,g=e[t+d];for(d+=h,o=g&(1<<-u)-1,g>>=-u,u+=a;u>0;o=256*o+e[t+d],d+=h,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=r;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(g?-1:1);s+=Math.pow(2,r),o-=l}return(g?-1:1)*s*Math.pow(2,o-r)},Ja.write=function(e,t,n,r,i,o){var s,a,c,l=8*o-i-1,u=(1<<l)-1,d=u>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:o-1,f=r?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(t*c-1)*Math.pow(2,i),s+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;e[n+g]=255&a,g+=f,a/=256,i-=8);for(s=s<<i|a,l+=i;l>0;e[n+g]=255&s,g+=f,s/=256,l-=8);e[n+g-f]|=128*p}),Ja}function ec(){return Ya||(Ya=1,function(e){const t=Xa(),n=Za(),r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let r=o(n);const i=r.write(e,t);i!==n&&(r=r.slice(0,i));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(j(e,Uint8Array)){const t=new Uint8Array(e);return d(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer))return d(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return d(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return s.from(r,t,n);const i=function(e){if(s.isBuffer(e)){const t=0|h(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?o(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),o(e<0?0:0|h(e))}function u(e){const t=e.length<0?0:0|h(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,s.prototype),r}function h(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function g(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return 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(i)return r?-1:H(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return N(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 _(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function m(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),V(n=+n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=s.from(t,r)),s.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,i){let o,s=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,n/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let r=-1;for(o=n;o<a;o++)if(l(e,o)===l(t,-1===r?0:o-r)){if(-1===r&&(r=o),o-r+1===c)return r*s}else-1!==r&&(o-=o-r),r=-1}else for(n+c>a&&(n=a-c),o=n;o>=0;o--){let n=!0;for(let r=0;r<c;r++)if(l(e,o+r)!==l(t,r)){n=!1;break}if(n)return o}return-1}function w(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const o=t.length;let s;for(r>o/2&&(r=o/2),s=0;s<r;++s){const r=parseInt(t.substr(2*s,2),16);if(V(r))return s;e[n+s]=r}return s}function 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,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function E(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=n){let n,r,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(o=c));break;case 3:n=e[i+1],r=e[i+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:n=e[i+1],r=e[i+2],a=e[i+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=s}return function(e){const t=e.length;if(t<=T)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=T));return n}(r)}e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!s.TYPED_ARRAY_SUPPORT&&"undefined"!=typeof console&&console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,n){return function(e,t,n){return c(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,o=Math.min(n,r);i<o;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=s.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(j(t,Uint8Array))i+t.length>r.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},s.byteLength=g,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)p(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)p(this,t,t+3),p(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?E(this,0,e):f.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(s.prototype[r]=s.prototype.inspect),s.prototype.compare=function(e,t,n,r,i){if(j(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;let o=(i>>>=0)-(r>>>=0),a=(n>>>=0)-(t>>>=0);const c=Math.min(o,a),l=this.slice(r,i),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){o=l[e],a=u[e];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return m(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return m(this,e,t,n,!1)},s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let o=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return v(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const T=4096;function I(e,t,n){let r="";n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function C(e,t,n){let r="";n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function N(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i="";for(let r=t;r<n;++r)i+=X[e[r]];return i}function _(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}function x(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,n}function B(e,t,n,r,i){$(t,r,i,e,n,7);let o=Number(t&BigInt(4294967295));e[n+7]=o,o>>=8,e[n+6]=o,o>>=8,e[n+5]=o,o>>=8,e[n+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=s,s>>=8,e[n+2]=s,s>>=8,e[n+1]=s,s>>=8,e[n]=s,n+8}function R(e,t,n,r,i,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,r,i,o){return t=+t,r>>>=0,o||R(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function O(e,t,r,i,o){return t=+t,r>>>=0,o||R(e,0,r,8),n.write(e,t,r,i,52,8),r+8}s.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,s.prototype),r},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||x(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=this[e],i=1,o=0;for(;++o<t&&(i*=256);)r+=this[e+o]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},s.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||x(e,t,this.length);let r=t,i=1,o=this[e+--r];for(;r>0&&(i*=256);)o+=this[e+--r]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||x(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||x(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||x(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||K(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||x(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||x(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<n&&(i*=256);)this[t+o]=e/i&255;return t+n},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}let i=n-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+n},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||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 B(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 i=0,o=1,s=0;for(this[t]=255&e;++i<n&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}let i=n-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+n},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||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 B(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 i=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!s.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{const o=s.isBuffer(e)?e:s.from(e,r),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=o[i%a]}return this};const 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,i,o){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`,new 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,i,o)}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.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=F(String(n)):"bigint"==typeof n&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=F(i)),i+="n"),r+=` It must be ${t}. Received ${i}`,r},RangeError);const G=/[^+/0-9A-Za-z-_]/g;function H(e,t){let n;t=t||1/0;const r=e.length;let i=null;const o=[];for(let s=0;s<r;++s){if(n=e.charCodeAt(s),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function W(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function z(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const X=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t}();function Q(e){return"undefined"==typeof BigInt?Y:e}function Y(){throw new Error("BigInt not supported")}}(ja)),ja}var tc=ec();const nc="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function rc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ic(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function oc(e,...t){if(!rc(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 sc(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ic(e.outputLen),ic(e.blockLen)}function ac(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 cc(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function lc(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function uc(e,t){return e<<32-t|e>>>t}const dc=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),hc=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function gc(e){if(oc(e),dc)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=hc[e[n]];return t}const fc=48,pc=57,mc=65,yc=70,wc=97,bc=102;function kc(e){return e>=fc&&e<=pc?e-fc:e>=mc&&e<=yc?e-(mc-10):e>=wc&&e<=bc?e-(wc-10):void 0}function vc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(dc)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=kc(e.charCodeAt(i)),o=kc(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+o}return r}function Sc(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)),oc(e),e}function Ac(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];oc(r),t+=r.length}const n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return n}class Ec{}function Tc(e){const t=t=>e().update(Sc(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Ic(e=32){if(nc&&"function"==typeof nc.getRandomValues)return nc.getRandomValues(new Uint8Array(e));if(nc&&"function"==typeof nc.randomBytes)return Uint8Array.from(nc.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Cc(e,t,n){return e&t^~e&n}function Nc(e,t,n){return e&t^e&n^t&n}class _c extends Ec{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=lc(this.buffer)}update(e){ac(this),oc(e=Sc(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);if(s===r){const t=lc(e);for(;r<=i-o;o+=r)this.process(t,o);continue}n.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ac(this),function(e,t){oc(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;t[o++]=128,cc(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let e=o;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),a=Number(n&o),c=r?4:0,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const s=lc(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)s.setUint32(4*e,l[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=s,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const xc=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Dc=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Pc=BigInt(2**32-1),Bc=BigInt(32);function Rc(e,t=!1){return t?{h:Number(e&Pc),l:Number(e>>Bc&Pc)}:{h:0|Number(e>>Bc&Pc),l:0|Number(e&Pc)}}const Mc=(e,t,n)=>e>>>n,Oc=(e,t,n)=>e<<32-n|t>>>n,Lc=(e,t,n)=>e>>>n|t<<32-n,Uc=(e,t,n)=>e<<32-n|t>>>n,Fc=(e,t,n)=>e<<64-n|t>>>n-32,$c=(e,t,n)=>e>>>n-32|t<<64-n;function qc(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const Kc=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Gc=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Hc=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Wc=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,zc=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),jc=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0,Vc=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]),Xc=new Uint32Array(64);class Qc extends _c{constructor(e=32){super(64,e,8,!1),this.A=0|xc[0],this.B=0|xc[1],this.C=0|xc[2],this.D=0|xc[3],this.E=0|xc[4],this.F=0|xc[5],this.G=0|xc[6],this.H=0|xc[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:o,G:s,H:a}=this;return[e,t,n,r,i,o,s,a]}set(e,t,n,r,i,o,s,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)Xc[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=Xc[e-15],n=Xc[e-2],r=uc(t,7)^uc(t,18)^t>>>3,i=uc(n,17)^uc(n,19)^n>>>10;Xc[e]=i+Xc[e-7]+r+Xc[e-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(uc(s,6)^uc(s,11)^uc(s,25))+Cc(s,a,c)+Vc[e]+Xc[e]|0,u=(uc(n,2)^uc(n,13)^uc(n,22))+Nc(n,r,i)|0;l=c,c=a,a=s,s=o+t|0,o=i,i=r,r=n,n=t+u|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,o,s,a,c,l)}roundClean(){cc(Xc)}destroy(){this.set(0,0,0,0,0,0,0,0),cc(this.buffer)}}const Yc=(()=>function(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=Rc(e[o],t);[r[o],i[o]]=[n,s]}return[r,i]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Jc=(()=>Yc[0])(),Zc=(()=>Yc[1])(),el=new Uint32Array(80),tl=new Uint32Array(80);class nl extends _c{constructor(e=64){super(128,e,16,!1),this.Ah=0|Dc[0],this.Al=0|Dc[1],this.Bh=0|Dc[2],this.Bl=0|Dc[3],this.Ch=0|Dc[4],this.Cl=0|Dc[5],this.Dh=0|Dc[6],this.Dl=0|Dc[7],this.Eh=0|Dc[8],this.El=0|Dc[9],this.Fh=0|Dc[10],this.Fl=0|Dc[11],this.Gh=0|Dc[12],this.Gl=0|Dc[13],this.Hh=0|Dc[14],this.Hl=0|Dc[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:d,Gh:h,Gl:g,Hh:f,Hl:p}=this;return[e,t,n,r,i,o,s,a,c,l,u,d,h,g,f,p]}set(e,t,n,r,i,o,s,a,c,l,u,d,h,g,f,p){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|g,this.Hh=0|f,this.Hl=0|p}process(e,t){for(let n=0;n<16;n++,t+=4)el[n]=e.getUint32(t),tl[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|el[e-15],n=0|tl[e-15],r=Lc(t,n,1)^Lc(t,n,8)^Mc(t,0,7),i=Uc(t,n,1)^Uc(t,n,8)^Oc(t,n,7),o=0|el[e-2],s=0|tl[e-2],a=Lc(o,s,19)^Fc(o,s,61)^Mc(o,0,6),c=Uc(o,s,19)^$c(o,s,61)^Oc(o,s,6),l=Hc(i,c,tl[e-7],tl[e-16]),u=Wc(l,r,a,el[e-7],el[e-16]);el[e]=0|u,tl[e]=0|l}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:d,Fh:h,Fl:g,Gh:f,Gl:p,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Lc(u,d,14)^Lc(u,d,18)^Fc(u,d,41),w=Uc(u,d,14)^Uc(u,d,18)^$c(u,d,41),b=u&h^~u&f,k=zc(y,w,d&g^~d&p,Zc[e],tl[e]),v=jc(k,m,t,b,Jc[e],el[e]),S=0|k,A=Lc(n,r,28)^Fc(n,r,34)^Fc(n,r,39),E=Uc(n,r,28)^$c(n,r,34)^$c(n,r,39),T=n&i^n&s^i&s,I=r&o^r&a^o&a;m=0|f,y=0|p,f=0|h,p=0|g,h=0|u,g=0|d,({h:u,l:d}=qc(0|c,0|l,0|v,0|S)),c=0|s,l=0|a,s=0|i,a=0|o,i=0|n,o=0|r;const C=Kc(S,E,I);n=Gc(C,v,A,T),r=0|C}({h:n,l:r}=qc(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=qc(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:a}=qc(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:l}=qc(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:d}=qc(0|this.Eh,0|this.El,0|u,0|d)),({h:h,l:g}=qc(0|this.Fh,0|this.Fl,0|h,0|g)),({h:f,l:p}=qc(0|this.Gh,0|this.Gl,0|f,0|p)),({h:m,l:y}=qc(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(n,r,i,o,s,a,c,l,u,d,h,g,f,p,m,y)}roundClean(){cc(el,tl)}destroy(){cc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const rl=Tc(()=>new Qc),il=Tc(()=>new nl),ol=BigInt(0),sl=BigInt(1);function al(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function cl(e,t,n=""){const r=rc(e),i=e?.length,o=void 0!==t;if(!r||o&&i!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${t}`:"")+", got "+(r?`length=${i}`:"type="+typeof e))}return e}function ll(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function ul(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?ol:BigInt("0x"+e)}function dl(e){return ul(gc(e))}function hl(e){return oc(e),ul(gc(Uint8Array.from(e).reverse()))}function gl(e,t){return vc(e.toString(16).padStart(2*t,"0"))}function fl(e,t){return gl(e,t).reverse()}function pl(e,t,n){let r;if("string"==typeof t)try{r=vc(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!rc(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function ml(e){return Uint8Array.from(e)}const yl=e=>"bigint"==typeof e&&ol<=e;function wl(e,t,n,r){if(!function(e,t,n){return yl(e)&&yl(t)&&yl(n)&&t<=e&&e<n}(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function bl(e){let t;for(t=0;e>ol;e>>=sl,t+=1);return t}const kl=e=>(sl<<BigInt(e))-sl;function vl(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const i=e[t];if(r&&void 0===i)return;const o=typeof i;if(o!==n||null===i)throw new Error(`param "${t}" is invalid: expected ${n}, got ${o}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function Sl(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(void 0!==i)return i;const o=e(n,...r);return t.set(n,o),o}}const Al=BigInt(0),El=BigInt(1),Tl=BigInt(2),Il=BigInt(3),Cl=BigInt(4),Nl=BigInt(5),_l=BigInt(7),xl=BigInt(8),Dl=BigInt(9),Pl=BigInt(16);function Bl(e,t){const n=e%t;return n>=Al?n:t+n}function Rl(e,t,n){let r=e;for(;t-- >Al;)r*=r,r%=n;return r}function Ml(e,t){if(e===Al)throw new Error("invert: expected non-zero number");if(t<=Al)throw new Error("invert: expected positive modulus, got "+t);let n=Bl(e,t),r=t,i=Al,o=El;for(;n!==Al;){const e=r%n,t=i-o*(r/n);r=n,n=e,i=o,o=t}if(r!==El)throw new Error("invert: does not exist");return Bl(i,t)}function Ol(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function Ll(e,t){const n=(e.ORDER+El)/Cl,r=e.pow(t,n);return Ol(e,r,t),r}function Ul(e,t){const n=(e.ORDER-Nl)/xl,r=e.mul(t,Tl),i=e.pow(r,n),o=e.mul(t,i),s=e.mul(e.mul(o,Tl),i),a=e.mul(o,e.sub(s,e.ONE));return Ol(e,a,t),a}function Fl(e){if(e<Il)throw new Error("sqrt is not defined for small field");let t=e-El,n=0;for(;t%Tl===Al;)t/=Tl,n++;let r=Tl;const i=Wl(e);for(;1===Gl(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return Ll;let o=i.pow(r,t);const s=(t+El)/Tl;return function(e,r){if(e.is0(r))return r;if(1!==Gl(e,r))throw new Error("Cannot find square root");let i=n,a=e.mul(e.ONE,o),c=e.pow(r,t),l=e.pow(r,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw new Error("Cannot find square root");const r=El<<BigInt(i-t-1),o=e.pow(a,r);i=t,a=e.sqr(o),c=e.mul(c,a),l=e.mul(l,o)}return l}}function $l(e){return e%Cl===Il?Ll:e%xl===Nl?Ul:e%Pl===Dl?function(e){const t=Wl(e),n=Fl(e),r=n(t,t.neg(t.ONE)),i=n(t,r),o=n(t,t.neg(r)),s=(e+_l)/Pl;return(e,t)=>{let n=e.pow(t,s),a=e.mul(n,r);const c=e.mul(n,i),l=e.mul(n,o),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),g=e.cmov(n,a,h);return Ol(e,g,t),g}}(e):Fl(e)}const ql=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kl(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),o=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),o),r}function Gl(e,t){const n=(e.ORDER-El)/Tl,r=e.pow(t,n),i=e.eql(r,e.ONE),o=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Hl(e,t){void 0!==t&&ic(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Wl(e,t,n=!1,r={}){if(e<=Al)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,o,s,a=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(i=e.BITS),e.sqrt&&(o=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(i=t),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:l}=Hl(e,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:kl(c),ZERO:Al,ONE:El,allowedLengths:s,create:t=>Bl(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Al<=t&&t<e},is0:e=>e===Al,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&El)===El,neg:t=>Bl(-t,e),eql:(e,t)=>e===t,sqr:t=>Bl(t*t,e),add:(t,n)=>Bl(t+n,e),sub:(t,n)=>Bl(t-n,e),mul:(t,n)=>Bl(t*n,e),pow:(e,t)=>function(e,t,n){if(n<Al)throw new Error("invalid exponent, negatives unsupported");if(n===Al)return e.ONE;if(n===El)return t;let r=e.ONE,i=t;for(;n>Al;)n&El&&(r=e.mul(r,i)),i=e.sqr(i),n>>=El;return r}(d,e,t),div:(t,n)=>Bl(t*Ml(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Ml(t,e),sqrt:o||(t=>(u||(u=$l(e)),u(d,t))),toBytes:e=>n?fl(e,l):gl(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let i=n?hl(t):dl(t);if(a&&(i=Bl(i,e)),!r&&!d.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>Kl(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function zl(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 jl(e){const t=zl(e);return t+Math.ceil(t/2)}const Vl=BigInt(0),Xl=BigInt(1);function Ql(e,t){const n=t.negate();return e?n:t}function Yl(e,t){const n=Kl(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Jl(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Zl(e,t){Jl(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:kl(e),maxNumber:n,shiftBy:BigInt(e)}}function eu(e,t,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let a=Number(e&i),c=e>>s;a>r&&(a-=o,c+=Xl);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 tu=new WeakMap,nu=new WeakMap;function ru(e){return nu.get(e)||1}function iu(e){if(e!==Vl)throw new Error("invalid wNAF")}class ou{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>Vl;)t&Xl&&(n=n.add(r)),r=r.double(),t>>=Xl;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=Zl(t,this.bits),i=[];let o=e,s=o;for(let e=0;e<n;e++){s=o,i.push(s);for(let e=1;e<r;e++)s=s.add(o),i.push(s);o=s.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Zl(e,this.bits);for(let e=0;e<o.windows;e++){const{nextN:s,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=eu(n,e,o);n=s,c?i=i.add(Ql(u,t[d])):r=r.add(Ql(l,t[a]))}return iu(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){const i=Zl(e,this.bits);for(let e=0;e<i.windows&&n!==Vl;e++){const{nextN:o,offset:s,isZero:a,isNeg:c}=eu(n,e,i);if(n=o,!a){const e=t[s];r=r.add(c?e.negate():e)}}return iu(n),r}getPrecomputes(e,t,n){let r=tu.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),tu.set(t,r))),r}cached(e,t,n){const r=ru(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const i=ru(e);return 1===i?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){Jl(t,this.bits),nu.set(e,t),tu.delete(e)}hasCache(e){return 1!==ru(e)}}function su(e,t,n,r){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}(n,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}(r,t);const i=n.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=bl(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=kl(c),u=new Array(Number(l)+1).fill(s);let d=s;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(s);for(let t=0;t<o;t++){const i=r[t],o=Number(i>>BigInt(e)&l);u[o]=u[o].add(n[t])}let t=s;for(let e=u.length-1,n=s;e>0;e--)n=n.add(u[e]),t=t.add(n);if(d=d.add(t),0!==e)for(let e=0;e<c;e++)d=d.double()}return d}function au(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){vl(e,ql.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Wl(e,{isLE:n})}function cu(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>Vl))throw new Error(`CURVE.${e} must be positive bigint`)}const i=au(t.p,n.Fp,r),o=au(t.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of s)if(!i.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:o}}const lu=BigInt(0),uu=BigInt(1),du=BigInt(2),hu=BigInt(8);function gu(e,t,n={}){if("function"!=typeof t)throw new Error('"hash" function param is required');vl(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=e,a=n.randomBytes||Ic,c=n.adjustScalarBytes||(e=>e),l=n.domain||((e,t,n)=>{if(al(n,"phflag"),t.length||n)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return s.create(hl(e))}function d(e){const{head:n,prefix:r,scalar:o}=function(e){const n=m.secretKey;e=pl("private key",e,n);const r=pl("hashed private key",t(e),2*n),i=c(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:u(i)}}(e),s=i.multiply(o),a=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:a}}function h(e){return d(e).pointBytes}function g(e=Uint8Array.of(),...n){const i=Ac(...n);return u(t(l(i,pl("context",e),!!r)))}const f={zip215:!0};const p=o.BYTES,m={secretKey:p,publicKey:p,signature:2*p,seed:p};function y(e=a(m.seed)){return cl(e,m.seed,"seed")}const w={getExtendedPublicKey:d,randomSecretKey:y,isValidSecretKey:function(e){return rc(e)&&e.length===s.BYTES},isValidPublicKey:function(t,n){try{return!!e.fromBytes(t,n)}catch(e){return!1}},toMontgomery(t){const{y:n}=e.fromBytes(t),r=m.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const s=i?o.div(uu+n,uu-n):o.div(n-uu,n+uu);return o.toBytes(s)},toMontgomerySecret(e){const n=m.secretKey;cl(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=pl("message",e),r&&(e=r(e));const{prefix:o,scalar:a,pointBytes:c}=d(t),l=g(n.context,o,e),u=i.multiply(l).toBytes(),h=g(n.context,u,c,e),f=s.create(l+h*a);if(!s.isValid(f))throw new Error("sign failed: invalid s");return cl(Ac(u,s.toBytes(f)),m.signature,"result")},verify:function(t,n,o,s=f){const{context:a,zip215:c}=s,l=m.signature;t=pl("signature",t,l),n=pl("message",n),o=pl("publicKey",o,m.publicKey),void 0!==c&&al(c,"zip215"),r&&(n=r(n));const u=l/2,d=t.subarray(0,u),h=hl(t.subarray(u,l));let p,y,w;try{p=e.fromBytes(o,c),y=e.fromBytes(d,c),w=i.multiplyUnsafe(h)}catch(e){return!1}if(!c&&p.isSmallOrder())return!1;const b=g(a,y.toBytes(),p.toBytes(),n);return y.add(p.multiplyUnsafe(b)).subtract(w).clearCofactor().is0()},utils:w,Point:e,lengths:m})}function fu(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n={Fp:e.Fp,Fn:Wl(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:n,hash:e.hash,eddsaOpts:r}}(e),o=function(e,t={}){const n=cu("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;vl(t,{},{uvRatio:"function"});const a=du<<BigInt(8*i.BYTES)-uu,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:lu}}});if(!function(e,t,n,r){const i=e.sqr(n),o=e.sqr(r),s=e.add(e.mul(t.a,i),o),a=e.add(e.ONE,e.mul(t.d,e.mul(i,o)));return e.eql(s,a)}(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(e,t,n=!1){return wl("coordinate "+e,t,n?uu:lu,a),t}function d(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const h=Sl((e,t)=>{const{X:n,Y:i,Z:o}=e,s=e.is0();null==t&&(t=s?hu:r.inv(o));const a=c(n*t),l=c(i*t),u=r.mul(o,t);if(s)return{x:lu,y:uu};if(u!==uu)throw new Error("invZ was invalid");return{x:a,y:l}}),g=Sl(e=>{const{a:t,d:n}=o;if(e.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:s,T:a}=e,l=c(r*r),u=c(i*i),d=c(s*s),h=c(d*d),g=c(l*t);if(c(d*c(g+u))!==c(h+c(n*c(l*u))))throw new Error("bad point: equation left != right (1)");if(c(r*i)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class f{constructor(e,t,n,r){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",n,!0),this.T=u("t",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:n}=e||{};return u("x",t),u("y",n),new f(t,n,uu,c(t*n))}static fromBytes(e,t=!1){const n=r.BYTES,{a:i,d:s}=o;e=ml(cl(e,n,"point")),al(t,"zip215");const u=ml(e),d=e[n-1];u[n-1]=-129&d;const h=hl(u),g=t?a:r.ORDER;wl("point.y",h,lu,g);const p=c(h*h),m=c(p-uu),y=c(s*p-i);let{isValid:w,value:b}=l(m,y);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&uu)===uu,v=!!(128&d);if(!t&&b===lu&&v)throw new Error("bad point: x=0 and x_0=1");return v!==k&&(b=c(-b)),f.fromAffine({x:b,y:h})}static fromHex(e,t=!1){return f.fromBytes(pl("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return p.createCache(this,e),t||this.multiply(du),this}assertValidity(){g(this)}equals(e){d(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=e,a=c(t*s),l=c(i*r),u=c(n*s),h=c(o*r);return a===l&&u===h}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=o,{X:t,Y:n,Z:r}=this,i=c(t*t),s=c(n*n),a=c(du*c(r*r)),l=c(e*i),u=t+n,d=c(c(u*u)-i-s),h=l+s,g=h-a,p=l-s,m=c(d*g),y=c(h*p),w=c(d*p),b=c(g*h);return new f(m,y,b,w)}add(e){d(e);const{a:t,d:n}=o,{X:r,Y:i,Z:s,T:a}=this,{X:l,Y:u,Z:h,T:g}=e,p=c(r*l),m=c(i*u),y=c(a*n*g),w=c(s*h),b=c((r+i)*(l+u)-p-m),k=w-y,v=w+y,S=c(m-t*p),A=c(b*k),E=c(v*S),T=c(b*S),I=c(k*v);return new f(A,E,I,T)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:n}=p.cached(this,e,e=>Yl(f,e));return Yl(f,[t,n])[0]}multiplyUnsafe(e,t=f.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===lu?f.ZERO:this.is0()||e===uu?this:p.unsafe(this,e,e=>Yl(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return s===uu?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),n=r.toBytes(t);return n[n.length-1]|=e&uu?128:0,n}toHex(){return gc(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 Yl(f,e)}static msm(e,t){return su(f,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(o.Gx,o.Gy,uu,c(o.Gx*o.Gy)),f.ZERO=new f(lu,uu,uu,lu),f.Fp=r,f.Fn=i;const p=new ou(f,i.BITS);return f.BASE.precompute(8),f}(t,n);return function(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(e,gu(o,r,i))}const pu=BigInt(1),mu=BigInt(2);BigInt(3);const yu=BigInt(5),wu=BigInt(8),bu=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ku=(()=>({p:bu,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:wu,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function vu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Su=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Au(e,t){const n=bu,r=Bl(t*t*t,n),i=function(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=bu,s=e*e%o*e%o,a=Rl(s,mu,o)*s%o,c=Rl(a,pu,o)*e%o,l=Rl(c,yu,o)*c%o,u=Rl(l,t,o)*l%o,d=Rl(u,n,o)*u%o,h=Rl(d,r,o)*d%o,g=Rl(h,i,o)*h%o,f=Rl(g,i,o)*h%o,p=Rl(f,t,o)*l%o;return{pow_p_5_8:Rl(p,mu,o)*e%o,b2:s}}(e*Bl(r*r*t,n)).pow_p_5_8;let o=Bl(e*r*i,n);const s=Bl(t*o*o,n),a=o,c=Bl(o*Su,n),l=s===e,u=s===Bl(-e,n),d=s===Bl(-e*Su,n);return l&&(o=a),(u||d)&&(o=c),(Bl(o,n)&El)===El&&(o=Bl(-o,n)),{isValid:l||u,value:o}}const Eu=(()=>Wl(ku.p,{isLE:!0}))(),Tu=(()=>({...ku,Fp:Eu,hash:il,adjustScalarBytes:vu,uvRatio:Au}))(),Iu=(()=>fu(Tu))();var Cu,Nu={exports:{}},_u=Wa(Object.freeze({__proto__:null,default:{}})),xu=Nu.exports;function Du(){return Cu||(Cu=1,function(e,t){function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}function i(e,t,n){if(i.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(n=t,t=10),this._init(e||0,t||10,n||"be"))}var o;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:_u.Buffer}catch(e){}function s(e,t){var r=e.charCodeAt(t);return r>=48&&r<=57?r-48:r>=65&&r<=70?r-55:r>=97&&r<=102?r-87:void n(!1,"Invalid character in "+e)}function a(e,t,n){var r=s(e,n);return n-1>=t&&(r|=s(e,n-1)<<4),r}function c(e,t,r,i){for(var o=0,s=0,a=Math.min(e.length,r),c=t;c<a;c++){var l=e.charCodeAt(c)-48;o*=i,s=l>=49?l-49+10:l>=17?l-17+10:l,n(l>=0&&s<i,"Invalid character"),o+=s}return o}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,r):(this._parseBase(e,t,i),"le"===r&&this._initArray(this.toArray(),t,r)))},i.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},i.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var o,s,a=0;if("be"===r)for(i=e.length-1,o=0;i>=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===r)for(i=0,o=0;i<e.length;i+=3)s=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},i.prototype._parseHex=function(e,t,n){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;var i,o=0,s=0;if("be"===n)for(r=e.length-1;r>=t;r-=2)i=a(e,t,r)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(r=(e.length-t)%2==0?t+1:t;r<e.length;r+=2)i=a(e,t,r)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this._strip()},i.prototype._parseBase=function(e,t,n){this.words=[0],this.length=1;for(var r=0,i=1;i<=67108863;i*=t)r++;r--,i=i/t|0;for(var o=e.length-n,s=o%r,a=Math.min(o,o-s)+n,l=0,u=n;u<a;u+=r)l=c(e,u,u+r,t),this.imuln(i),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(0!==s){var d=1;for(l=c(e,u,e.length,t),u=0;u<s;u++)d*=t;this.imuln(d),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},i.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},i.prototype._move=function(e){l(e,this)},i.prototype.clone=function(){var e=new i(null);return this.copy(e),e},i.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){i.prototype.inspect=u}else i.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],h=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],g=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,n){n.negative=t.negative^e.negative;var r=e.length+t.length|0;n.length=r,r=r-1|0;var i=0|e.words[0],o=0|t.words[0],s=i*o,a=67108863&s,c=s/67108864|0;n.words[0]=a;for(var l=1;l<r;l++){for(var u=c>>>26,d=67108863&c,h=Math.min(l,t.length-1),g=Math.max(0,l-e.length+1);g<=h;g++){var f=l-g|0;u+=(s=(i=0|e.words[f])*(o=0|t.words[g])+d)/67108864|0,d=67108863&s}n.words[l]=0|d,c=0|u}return 0!==c?n.words[l]=0|c:n.length--,n._strip()}i.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<i|o)).toString(16);o=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,s--),r=0!==o||s!==this.length-1?d[6-c.length]+c+r:c+r}for(0!==o&&(r=o.toString(16)+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=h[e],u=g[e];r="";var f=this.clone();for(f.negative=0;!f.isZero();){var p=f.modrn(u).toString(e);r=(f=f.idivn(u)).isZero()?p+r:d[l-p.length]+p+r}for(this.isZero()&&(r="0"+r);r.length%t!==0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},i.prototype.toJSON=function(){return this.toString(16,2)},o&&(i.prototype.toBuffer=function(e,t){return this.toArrayLike(o,e,t)}),i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,r){this._strip();var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,i),s},i.prototype._toArrayLikeLE=function(e,t){for(var n=0,r=0,i=0,o=0;i<this.length;i++){var s=this.words[i]<<o|r;e[n++]=255&s,n<e.length&&(e[n++]=s>>8&255),n<e.length&&(e[n++]=s>>16&255),6===o?(n<e.length&&(e[n++]=s>>24&255),r=0,o=0):(r=s>>>24,o+=2)}if(n<e.length)for(e[n++]=r;n<e.length;)e[n++]=0},i.prototype._toArrayLikeBE=function(e,t){for(var n=e.length-1,r=0,i=0,o=0;i<this.length;i++){var s=this.words[i]<<o|r;e[n--]=255&s,n>=0&&(e[n--]=s>>8&255),n>=0&&(e[n--]=s>>16&255),6===o?(n>=0&&(e[n--]=s>>24&255),r=0,o=0):(r=s>>>24,o+=2)}if(n>=0)for(e[n--]=r;n>=0;)e[n--]=0},Math.clz32?i.prototype._countBits=function(e){return 32-Math.clz32(e)}:i.prototype._countBits=function(e){var t=e,n=0;return t>=4096&&(n+=13,t>>>=13),t>=64&&(n+=7,t>>>=7),t>=8&&(n+=4,t>>>=4),t>=2&&(n+=2,t>>>=2),n+t},i.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,n=0;return 8191&t||(n+=13,t>>>=13),127&t||(n+=7,t>>>=7),15&t||(n+=4,t>>>=4),3&t||(n+=2,t>>>=2),1&t||n++,n},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var n=this._zeroBits(this.words[t]);if(e+=n,26!==n)break}return e},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},i.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return 0!==this.negative},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},i.prototype.ior=function(e){return n(0===(this.negative|e.negative)),this.iuor(e)},i.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var n=0;n<t.length;n++)this.words[n]=this.words[n]&e.words[n];return this.length=t.length,this._strip()},i.prototype.iand=function(e){return n(0===(this.negative|e.negative)),this.iuand(e)},i.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.prototype.iuxor=function(e){var t,n;this.length>e.length?(t=this,n=e):(t=e,n=this);for(var r=0;r<n.length;r++)this.words[r]=t.words[r]^n.words[r];if(this!==t)for(;r<t.length;r++)this.words[r]=t.words[r];return this.length=t.length,this._strip()},i.prototype.ixor=function(e){return n(0===(this.negative|e.negative)),this.iuxor(e)},i.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i<t;i++)this.words[i]=67108863&~this.words[i];return r>0&&(this.words[i]=~this.words[i]&67108863>>26-r),this._strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<<i:this.words[r]&~(1<<i),this._strip()},i.prototype.iadd=function(e){var t,n,r;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(n=this,r=e):(n=e,r=this);for(var i=0,o=0;o<r.length;o++)t=(0|n.words[o])+(0|r.words[o])+i,this.words[o]=67108863&t,i=t>>>26;for(;0!==i&&o<n.length;o++)t=(0|n.words[o])+i,this.words[o]=67108863&t,i=t>>>26;if(this.length=n.length,0!==i)this.words[this.length]=i,this.length++;else if(n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this},i.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},i.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var n,r,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(n=this,r=e):(n=e,r=this);for(var o=0,s=0;s<r.length;s++)o=(t=(0|n.words[s])-(0|r.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<n.length;s++)o=(t=(0|n.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<n.length&&n!==this)for(;s<n.length;s++)this.words[s]=n.words[s];return this.length=Math.max(this.length,s),n!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(e){return this.clone().isub(e)};var p=function(e,t,n){var r,i,o,s=e.words,a=t.words,c=n.words,l=0,u=0|s[0],d=8191&u,h=u>>>13,g=0|s[1],f=8191&g,p=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,N=0|s[6],_=8191&N,x=N>>>13,D=0|s[7],P=8191&D,B=D>>>13,R=0|s[8],M=8191&R,O=R>>>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],j=8191&z,V=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,ie=0|a[6],oe=8191&ie,se=ie>>>13,ae=0|a[7],ce=8191&ae,le=ae>>>13,ue=0|a[8],de=8191&ue,he=ue>>>13,ge=0|a[9],fe=8191&ge,pe=ge>>>13;n.negative=e.negative^t.negative,n.length=19;var me=(l+(r=Math.imul(d,q))|0)+((8191&(i=(i=Math.imul(d,K))+Math.imul(h,q)|0))<<13)|0;l=((o=Math.imul(h,K))+(i>>>13)|0)+(me>>>26)|0,me&=67108863,r=Math.imul(f,q),i=(i=Math.imul(f,K))+Math.imul(p,q)|0,o=Math.imul(p,K);var ye=(l+(r=r+Math.imul(d,H)|0)|0)+((8191&(i=(i=i+Math.imul(d,W)|0)+Math.imul(h,H)|0))<<13)|0;l=((o=o+Math.imul(h,W)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,r=Math.imul(y,q),i=(i=Math.imul(y,K))+Math.imul(w,q)|0,o=Math.imul(w,K),r=r+Math.imul(f,H)|0,i=(i=i+Math.imul(f,W)|0)+Math.imul(p,H)|0,o=o+Math.imul(p,W)|0;var we=(l+(r=r+Math.imul(d,j)|0)|0)+((8191&(i=(i=i+Math.imul(d,V)|0)+Math.imul(h,j)|0))<<13)|0;l=((o=o+Math.imul(h,V)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,r=Math.imul(k,q),i=(i=Math.imul(k,K))+Math.imul(v,q)|0,o=Math.imul(v,K),r=r+Math.imul(y,H)|0,i=(i=i+Math.imul(y,W)|0)+Math.imul(w,H)|0,o=o+Math.imul(w,W)|0,r=r+Math.imul(f,j)|0,i=(i=i+Math.imul(f,V)|0)+Math.imul(p,j)|0,o=o+Math.imul(p,V)|0;var be=(l+(r=r+Math.imul(d,Q)|0)|0)+((8191&(i=(i=i+Math.imul(d,Y)|0)+Math.imul(h,Q)|0))<<13)|0;l=((o=o+Math.imul(h,Y)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,r=Math.imul(A,q),i=(i=Math.imul(A,K))+Math.imul(E,q)|0,o=Math.imul(E,K),r=r+Math.imul(k,H)|0,i=(i=i+Math.imul(k,W)|0)+Math.imul(v,H)|0,o=o+Math.imul(v,W)|0,r=r+Math.imul(y,j)|0,i=(i=i+Math.imul(y,V)|0)+Math.imul(w,j)|0,o=o+Math.imul(w,V)|0,r=r+Math.imul(f,Q)|0,i=(i=i+Math.imul(f,Y)|0)+Math.imul(p,Q)|0,o=o+Math.imul(p,Y)|0;var ke=(l+(r=r+Math.imul(d,Z)|0)|0)+((8191&(i=(i=i+Math.imul(d,ee)|0)+Math.imul(h,Z)|0))<<13)|0;l=((o=o+Math.imul(h,ee)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,r=Math.imul(I,q),i=(i=Math.imul(I,K))+Math.imul(C,q)|0,o=Math.imul(C,K),r=r+Math.imul(A,H)|0,i=(i=i+Math.imul(A,W)|0)+Math.imul(E,H)|0,o=o+Math.imul(E,W)|0,r=r+Math.imul(k,j)|0,i=(i=i+Math.imul(k,V)|0)+Math.imul(v,j)|0,o=o+Math.imul(v,V)|0,r=r+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,Y)|0)+Math.imul(w,Q)|0,o=o+Math.imul(w,Y)|0,r=r+Math.imul(f,Z)|0,i=(i=i+Math.imul(f,ee)|0)+Math.imul(p,Z)|0,o=o+Math.imul(p,ee)|0;var ve=(l+(r=r+Math.imul(d,ne)|0)|0)+((8191&(i=(i=i+Math.imul(d,re)|0)+Math.imul(h,ne)|0))<<13)|0;l=((o=o+Math.imul(h,re)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,r=Math.imul(_,q),i=(i=Math.imul(_,K))+Math.imul(x,q)|0,o=Math.imul(x,K),r=r+Math.imul(I,H)|0,i=(i=i+Math.imul(I,W)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,W)|0,r=r+Math.imul(A,j)|0,i=(i=i+Math.imul(A,V)|0)+Math.imul(E,j)|0,o=o+Math.imul(E,V)|0,r=r+Math.imul(k,Q)|0,i=(i=i+Math.imul(k,Y)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,Y)|0,r=r+Math.imul(y,Z)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(w,Z)|0,o=o+Math.imul(w,ee)|0,r=r+Math.imul(f,ne)|0,i=(i=i+Math.imul(f,re)|0)+Math.imul(p,ne)|0,o=o+Math.imul(p,re)|0;var Se=(l+(r=r+Math.imul(d,oe)|0)|0)+((8191&(i=(i=i+Math.imul(d,se)|0)+Math.imul(h,oe)|0))<<13)|0;l=((o=o+Math.imul(h,se)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,r=Math.imul(P,q),i=(i=Math.imul(P,K))+Math.imul(B,q)|0,o=Math.imul(B,K),r=r+Math.imul(_,H)|0,i=(i=i+Math.imul(_,W)|0)+Math.imul(x,H)|0,o=o+Math.imul(x,W)|0,r=r+Math.imul(I,j)|0,i=(i=i+Math.imul(I,V)|0)+Math.imul(C,j)|0,o=o+Math.imul(C,V)|0,r=r+Math.imul(A,Q)|0,i=(i=i+Math.imul(A,Y)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,Y)|0,r=r+Math.imul(k,Z)|0,i=(i=i+Math.imul(k,ee)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,ee)|0,r=r+Math.imul(y,ne)|0,i=(i=i+Math.imul(y,re)|0)+Math.imul(w,ne)|0,o=o+Math.imul(w,re)|0,r=r+Math.imul(f,oe)|0,i=(i=i+Math.imul(f,se)|0)+Math.imul(p,oe)|0,o=o+Math.imul(p,se)|0;var Ae=(l+(r=r+Math.imul(d,ce)|0)|0)+((8191&(i=(i=i+Math.imul(d,le)|0)+Math.imul(h,ce)|0))<<13)|0;l=((o=o+Math.imul(h,le)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,r=Math.imul(M,q),i=(i=Math.imul(M,K))+Math.imul(O,q)|0,o=Math.imul(O,K),r=r+Math.imul(P,H)|0,i=(i=i+Math.imul(P,W)|0)+Math.imul(B,H)|0,o=o+Math.imul(B,W)|0,r=r+Math.imul(_,j)|0,i=(i=i+Math.imul(_,V)|0)+Math.imul(x,j)|0,o=o+Math.imul(x,V)|0,r=r+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,Y)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,Y)|0,r=r+Math.imul(A,Z)|0,i=(i=i+Math.imul(A,ee)|0)+Math.imul(E,Z)|0,o=o+Math.imul(E,ee)|0,r=r+Math.imul(k,ne)|0,i=(i=i+Math.imul(k,re)|0)+Math.imul(v,ne)|0,o=o+Math.imul(v,re)|0,r=r+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,se)|0)+Math.imul(w,oe)|0,o=o+Math.imul(w,se)|0,r=r+Math.imul(f,ce)|0,i=(i=i+Math.imul(f,le)|0)+Math.imul(p,ce)|0,o=o+Math.imul(p,le)|0;var Ee=(l+(r=r+Math.imul(d,de)|0)|0)+((8191&(i=(i=i+Math.imul(d,he)|0)+Math.imul(h,de)|0))<<13)|0;l=((o=o+Math.imul(h,he)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,r=Math.imul(U,q),i=(i=Math.imul(U,K))+Math.imul(F,q)|0,o=Math.imul(F,K),r=r+Math.imul(M,H)|0,i=(i=i+Math.imul(M,W)|0)+Math.imul(O,H)|0,o=o+Math.imul(O,W)|0,r=r+Math.imul(P,j)|0,i=(i=i+Math.imul(P,V)|0)+Math.imul(B,j)|0,o=o+Math.imul(B,V)|0,r=r+Math.imul(_,Q)|0,i=(i=i+Math.imul(_,Y)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,Y)|0,r=r+Math.imul(I,Z)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(C,Z)|0,o=o+Math.imul(C,ee)|0,r=r+Math.imul(A,ne)|0,i=(i=i+Math.imul(A,re)|0)+Math.imul(E,ne)|0,o=o+Math.imul(E,re)|0,r=r+Math.imul(k,oe)|0,i=(i=i+Math.imul(k,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0,r=r+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,le)|0)+Math.imul(w,ce)|0,o=o+Math.imul(w,le)|0,r=r+Math.imul(f,de)|0,i=(i=i+Math.imul(f,he)|0)+Math.imul(p,de)|0,o=o+Math.imul(p,he)|0;var Te=(l+(r=r+Math.imul(d,fe)|0)|0)+((8191&(i=(i=i+Math.imul(d,pe)|0)+Math.imul(h,fe)|0))<<13)|0;l=((o=o+Math.imul(h,pe)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,r=Math.imul(U,H),i=(i=Math.imul(U,W))+Math.imul(F,H)|0,o=Math.imul(F,W),r=r+Math.imul(M,j)|0,i=(i=i+Math.imul(M,V)|0)+Math.imul(O,j)|0,o=o+Math.imul(O,V)|0,r=r+Math.imul(P,Q)|0,i=(i=i+Math.imul(P,Y)|0)+Math.imul(B,Q)|0,o=o+Math.imul(B,Y)|0,r=r+Math.imul(_,Z)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,ee)|0,r=r+Math.imul(I,ne)|0,i=(i=i+Math.imul(I,re)|0)+Math.imul(C,ne)|0,o=o+Math.imul(C,re)|0,r=r+Math.imul(A,oe)|0,i=(i=i+Math.imul(A,se)|0)+Math.imul(E,oe)|0,o=o+Math.imul(E,se)|0,r=r+Math.imul(k,ce)|0,i=(i=i+Math.imul(k,le)|0)+Math.imul(v,ce)|0,o=o+Math.imul(v,le)|0,r=r+Math.imul(y,de)|0,i=(i=i+Math.imul(y,he)|0)+Math.imul(w,de)|0,o=o+Math.imul(w,he)|0;var Ie=(l+(r=r+Math.imul(f,fe)|0)|0)+((8191&(i=(i=i+Math.imul(f,pe)|0)+Math.imul(p,fe)|0))<<13)|0;l=((o=o+Math.imul(p,pe)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,r=Math.imul(U,j),i=(i=Math.imul(U,V))+Math.imul(F,j)|0,o=Math.imul(F,V),r=r+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,Y)|0)+Math.imul(O,Q)|0,o=o+Math.imul(O,Y)|0,r=r+Math.imul(P,Z)|0,i=(i=i+Math.imul(P,ee)|0)+Math.imul(B,Z)|0,o=o+Math.imul(B,ee)|0,r=r+Math.imul(_,ne)|0,i=(i=i+Math.imul(_,re)|0)+Math.imul(x,ne)|0,o=o+Math.imul(x,re)|0,r=r+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,se)|0,r=r+Math.imul(A,ce)|0,i=(i=i+Math.imul(A,le)|0)+Math.imul(E,ce)|0,o=o+Math.imul(E,le)|0,r=r+Math.imul(k,de)|0,i=(i=i+Math.imul(k,he)|0)+Math.imul(v,de)|0,o=o+Math.imul(v,he)|0;var Ce=(l+(r=r+Math.imul(y,fe)|0)|0)+((8191&(i=(i=i+Math.imul(y,pe)|0)+Math.imul(w,fe)|0))<<13)|0;l=((o=o+Math.imul(w,pe)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,r=Math.imul(U,Q),i=(i=Math.imul(U,Y))+Math.imul(F,Q)|0,o=Math.imul(F,Y),r=r+Math.imul(M,Z)|0,i=(i=i+Math.imul(M,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,r=r+Math.imul(P,ne)|0,i=(i=i+Math.imul(P,re)|0)+Math.imul(B,ne)|0,o=o+Math.imul(B,re)|0,r=r+Math.imul(_,oe)|0,i=(i=i+Math.imul(_,se)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,se)|0,r=r+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,le)|0)+Math.imul(C,ce)|0,o=o+Math.imul(C,le)|0,r=r+Math.imul(A,de)|0,i=(i=i+Math.imul(A,he)|0)+Math.imul(E,de)|0,o=o+Math.imul(E,he)|0;var Ne=(l+(r=r+Math.imul(k,fe)|0)|0)+((8191&(i=(i=i+Math.imul(k,pe)|0)+Math.imul(v,fe)|0))<<13)|0;l=((o=o+Math.imul(v,pe)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,r=Math.imul(U,Z),i=(i=Math.imul(U,ee))+Math.imul(F,Z)|0,o=Math.imul(F,ee),r=r+Math.imul(M,ne)|0,i=(i=i+Math.imul(M,re)|0)+Math.imul(O,ne)|0,o=o+Math.imul(O,re)|0,r=r+Math.imul(P,oe)|0,i=(i=i+Math.imul(P,se)|0)+Math.imul(B,oe)|0,o=o+Math.imul(B,se)|0,r=r+Math.imul(_,ce)|0,i=(i=i+Math.imul(_,le)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,le)|0,r=r+Math.imul(I,de)|0,i=(i=i+Math.imul(I,he)|0)+Math.imul(C,de)|0,o=o+Math.imul(C,he)|0;var _e=(l+(r=r+Math.imul(A,fe)|0)|0)+((8191&(i=(i=i+Math.imul(A,pe)|0)+Math.imul(E,fe)|0))<<13)|0;l=((o=o+Math.imul(E,pe)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,r=Math.imul(U,ne),i=(i=Math.imul(U,re))+Math.imul(F,ne)|0,o=Math.imul(F,re),r=r+Math.imul(M,oe)|0,i=(i=i+Math.imul(M,se)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,se)|0,r=r+Math.imul(P,ce)|0,i=(i=i+Math.imul(P,le)|0)+Math.imul(B,ce)|0,o=o+Math.imul(B,le)|0,r=r+Math.imul(_,de)|0,i=(i=i+Math.imul(_,he)|0)+Math.imul(x,de)|0,o=o+Math.imul(x,he)|0;var xe=(l+(r=r+Math.imul(I,fe)|0)|0)+((8191&(i=(i=i+Math.imul(I,pe)|0)+Math.imul(C,fe)|0))<<13)|0;l=((o=o+Math.imul(C,pe)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,r=Math.imul(U,oe),i=(i=Math.imul(U,se))+Math.imul(F,oe)|0,o=Math.imul(F,se),r=r+Math.imul(M,ce)|0,i=(i=i+Math.imul(M,le)|0)+Math.imul(O,ce)|0,o=o+Math.imul(O,le)|0,r=r+Math.imul(P,de)|0,i=(i=i+Math.imul(P,he)|0)+Math.imul(B,de)|0,o=o+Math.imul(B,he)|0;var De=(l+(r=r+Math.imul(_,fe)|0)|0)+((8191&(i=(i=i+Math.imul(_,pe)|0)+Math.imul(x,fe)|0))<<13)|0;l=((o=o+Math.imul(x,pe)|0)+(i>>>13)|0)+(De>>>26)|0,De&=67108863,r=Math.imul(U,ce),i=(i=Math.imul(U,le))+Math.imul(F,ce)|0,o=Math.imul(F,le),r=r+Math.imul(M,de)|0,i=(i=i+Math.imul(M,he)|0)+Math.imul(O,de)|0,o=o+Math.imul(O,he)|0;var Pe=(l+(r=r+Math.imul(P,fe)|0)|0)+((8191&(i=(i=i+Math.imul(P,pe)|0)+Math.imul(B,fe)|0))<<13)|0;l=((o=o+Math.imul(B,pe)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,r=Math.imul(U,de),i=(i=Math.imul(U,he))+Math.imul(F,de)|0,o=Math.imul(F,he);var Be=(l+(r=r+Math.imul(M,fe)|0)|0)+((8191&(i=(i=i+Math.imul(M,pe)|0)+Math.imul(O,fe)|0))<<13)|0;l=((o=o+Math.imul(O,pe)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863;var Re=(l+(r=Math.imul(U,fe))|0)+((8191&(i=(i=Math.imul(U,pe))+Math.imul(F,fe)|0))<<13)|0;return l=((o=Math.imul(F,pe))+(i>>>13)|0)+(Re>>>26)|0,Re&=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]=Ne,c[13]=_e,c[14]=xe,c[15]=De,c[16]=Pe,c[17]=Be,c[18]=Re,0!==l&&(c[19]=l,n.length++),n};function m(e,t,n){n.negative=t.negative^e.negative,n.length=e.length+t.length;for(var r=0,i=0,o=0;o<n.length-1;o++){var s=i;i=0;for(var a=67108863&r,c=Math.min(o,t.length-1),l=Math.max(0,o-e.length+1);l<=c;l++){var u=o-l,d=(0|e.words[u])*(0|t.words[l]),h=67108863&d;a=67108863&(h=h+a|0),i+=(s=(s=s+(d/67108864|0)|0)+(h>>>26)|0)>>>26,s&=67108863}n.words[o]=a,r=s,s=i}return 0!==r?n.words[o]=r:n.length--,n._strip()}function y(e,t,n){return m(e,t,n)}Math.imul||(p=f),i.prototype.mulTo=function(e,t){var n=this.length+e.length;return 10===this.length&&10===e.length?p(this,e,t):n<63?f(this,e,t):n<1024?m(this,e,t):y(this,e,t)},i.prototype.mul=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},i.prototype.mulf=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),y(this,e,t)},i.prototype.imul=function(e){return this.clone().mulTo(e,this)},i.prototype.imuln=function(e){var t=e<0;t&&(e=-e),n("number"==typeof e),n(e<67108864);for(var r=0,i=0;i<this.length;i++){var o=(0|this.words[i])*e,s=(67108863&o)+(67108863&r);r>>=26,r+=o/67108864|0,r+=s>>>26,this.words[i]=67108863&s}return 0!==r&&(this.words[i]=r,this.length++),this.length=0===e?1:this.length,t?this.ineg():this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),n=0;n<t.length;n++){var r=n/26|0,i=n%26;t[n]=e.words[r]>>>i&1}return t}(e);if(0===t.length)return new i(1);for(var n=this,r=0;r<t.length&&0===t[r];r++,n=n.sqr());if(++r<t.length)for(var o=n.sqr();r<t.length;r++,o=o.sqr())0!==t[r]&&(n=n.mul(o));return n},i.prototype.iushln=function(e){n("number"==typeof e&&e>=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<r;this.words[t]=c|s,s=a>>>26-r}s&&(this.words[t]=s,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this._strip()},i.prototype.ishln=function(e){return n(0===this.negative),this.iushln(e)},i.prototype.iushrn=function(e,t,r){var i;n("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=r;if(i-=s,i=Math.max(0,i),c){for(var l=0;l<s;l++)c.words[l]=this.words[l];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,l=0;l<this.length;l++)this.words[l]=this.words[l+s];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=i);l--){var d=0|this.words[l];this.words[l]=u<<26-o|d>>>o,u=d&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<<t;return!(this.length<=r||!(this.words[r]&i))},i.prototype.imaskn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return this._strip()},i.prototype.maskn=function(e){return this.clone().imaskn(e)},i.prototype.iaddn=function(e){return n("number"==typeof e),n(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},i.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},i.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},i.prototype.addn=function(e){return this.clone().iaddn(e)},i.prototype.subn=function(e){return this.clone().isubn(e)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(e,t,r){var i,o,s=e.length+r;this._expand(s);var a=0;for(i=0;i<e.length;i++){o=(0|this.words[i+r])+a;var c=(0|e.words[i])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[i+r]=67108863&o}for(;i<this.length-r;i++)a=(o=(0|this.words[i+r])+a)>>26,this.words[i+r]=67108863&o;if(0===a)return this._strip();for(n(-1===a),a=0,i=0;i<this.length;i++)a=(o=-(0|this.words[i])+a)>>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},i.prototype._wordDiv=function(e,t){var n=(this.length,e.length),r=this.clone(),o=e,s=0|o.words[o.length-1];0!=(n=26-this._countBits(s))&&(o=o.ushln(n),r.iushln(n),s=0|o.words[o.length-1]);var a,c=r.length-o.length;if("mod"!==t){(a=new i(null)).length=c+1,a.words=new Array(a.length);for(var l=0;l<a.length;l++)a.words[l]=0}var u=r.clone()._ishlnsubmul(o,1,c);0===u.negative&&(r=u,a&&(a.words[c]=1));for(var d=c-1;d>=0;d--){var h=67108864*(0|r.words[o.length+d])+(0|r.words[o.length+d-1]);for(h=Math.min(h/s|0,67108863),r._ishlnsubmul(o,h,d);0!==r.negative;)h--,r.negative=0,r._ishlnsubmul(o,1,d),r.isZero()||(r.negative^=1);a&&(a.words[d]=h)}return a&&a._strip(),r._strip(),"div"!==t&&0!==n&&r.iushrn(n),{div:a||null,mod:r}},i.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(o=a.div.neg()),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.iadd(e)),{div:o,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(o=a.div.neg()),{div:o,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),r&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modrn(e.words[0]))}:this._wordDiv(e,t);var o,s,a},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var n=0!==t.div.negative?t.mod.isub(e):t.mod,r=e.ushrn(1),i=e.andln(1),o=n.cmp(r);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(r*i+(0|this.words[o]))%e;return t?-i:i},i.prototype.modn=function(e){return this.modrn(e)},i.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var r=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*r;this.words[i]=o/e|0,r=o%e}return this._strip(),t?this.ineg():this},i.prototype.divn=function(e){return this.clone().idivn(e)},i.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o=new i(1),s=new i(0),a=new i(0),c=new i(1),l=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++l;for(var u=r.clone(),d=t.clone();!t.isZero();){for(var h=0,g=1;0===(t.words[0]&g)&&h<26;++h,g<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(u),s.isub(d)),o.iushrn(1),s.iushrn(1);for(var f=0,p=1;0===(r.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(r.iushrn(f);f-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(d)),a.iushrn(1),c.iushrn(1);t.cmp(r)>=0?(t.isub(r),o.isub(a),s.isub(c)):(r.isub(t),a.isub(o),c.isub(s))}return{a:a,b:c,gcd:r.iushln(l)}},i.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o,s=new i(1),a=new i(0),c=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var l=0,u=1;0===(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var d=0,h=1;0===(r.words[0]&h)&&d<26;++d,h<<=1);if(d>0)for(r.iushrn(d);d-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(r)>=0?(t.isub(r),s.isub(a)):(r.isub(t),a.isub(s))}return(o=0===t.cmpn(1)?s:a).cmpn(0)<0&&o.iadd(e),o},i.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),n=e.clone();t.negative=0,n.negative=0;for(var r=0;t.isEven()&&n.isEven();r++)t.iushrn(1),n.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;n.isEven();)n.iushrn(1);var i=t.cmp(n);if(i<0){var o=t;t=n,n=o}else if(0===i||0===n.cmpn(1))break;t.isub(n)}return n.iushln(r)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return!(1&this.words[0])},i.prototype.isOdd=function(){return!(1&~this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<<t;if(this.length<=r)return this._expand(r+1),this.words[r]|=i,this;for(var o=i,s=r;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this._strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},i.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},i.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,n=this.length-1;n>=0;n--){var r=0|this.words[n],i=0|e.words[n];if(r!==i){r<i?t=-1:r>i&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new E(e)},i.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},i.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function b(e,t){this.name=e,this.p=new i(t,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function k(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function v(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function S(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function A(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function E(e){if("string"==typeof e){var t=i._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){E.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}b.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},b.prototype.ireduce=function(e){var t,n=e;do{this.split(n,this.tmp),t=(n=(n=this.imulK(n)).iadd(this.tmp)).bitLength()}while(t>this.n);var r=t<this.n?-1:n.ucmp(this.p);return 0===r?(n.words[0]=0,n.length=1):r>0?n.isub(this.p):void 0!==n.strip?n.strip():n._strip(),n},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},r(k,b),k.prototype.split=function(e,t){for(var n=4194303,r=Math.min(e.length,9),i=0;i<r;i++)t.words[i]=e.words[i];if(t.length=r,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&n,i=10;i<e.length;i++){var s=0|e.words[i];e.words[i-10]=(s&n)<<4|o>>>22,o=s}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},k.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,n=0;n<e.length;n++){var r=0|e.words[n];t+=977*r,e.words[n]=67108863&t,t=64*r+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},r(v,b),r(S,b),r(A,b),A.prototype.imulK=function(e){for(var t=0,n=0;n<e.length;n++){var r=19*(0|e.words[n])+t,i=67108863&r;r>>>=26,e.words[n]=i,t=r}return 0!==t&&(e.words[e.length++]=t),e},i._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new k;else if("p224"===e)t=new v;else if("p192"===e)t=new S;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new A}return w[e]=t,t},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 i(1)).iushrn(2);return this.pow(e,r)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);n(!o.isZero());var a=new i(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new i(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var d=this.pow(u,o),h=this.pow(e,o.addn(1).iushrn(1)),g=this.pow(e,o),f=s;0!==g.cmp(a);){for(var p=g,m=0;0!==p.cmp(a);m++)p=p.redSqr();n(m<f);var y=this.pow(d,new i(1).iushln(f-m-1));h=h.redMul(y),d=y.redSqr(),g=g.redMul(d),f=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 i(1).toRed(this);if(0===t.cmpn(1))return e.clone();var n=new Array(16);n[0]=new i(1).toRed(this),n[1]=e;for(var r=2;r<n.length;r++)n[r]=this.mul(n[r-1],e);var o=n[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),r=t.length-1;r>=0;r--){for(var l=t.words[r],u=c-1;u>=0;u--){var d=l>>u&1;o!==n[0]&&(o=this.sqr(o)),0!==d||0!==s?(s<<=1,s|=d,(4===++a||0===r&&0===u)&&(o=this.mul(o,n[s]),a=0,s=0)):a=0}c=26}return o},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},i.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),i=n.isub(r).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=n.isub(r).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(Nu,xu)),Nu.exports}var Pu,Bu,Ru,Mu,Ou,Lu=Ha(Du()),Uu={exports:{}};function Fu(){return Pu||(Pu=1,function(e,t){var n=ec(),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=o),o.prototype=Object.create(r.prototype),i(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(Uu,Uu.exports)),Uu.exports}function $u(){if(Ru)return Bu;Ru=1;var e=Fu().Buffer;return Bu=function(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(255!==n[s])throw new TypeError(o+" is ambiguous");n[s]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(t){if("string"!=typeof t)throw new TypeError("Expected String");if(0===t.length)return e.alloc(0);for(var r=0,i=0,o=0;t[r]===c;)i++,r++;for(var s=(t.length-r)*l+1>>>0,u=new Uint8Array(s);r<t.length;){var d=t.charCodeAt(r);if(d>255)return;var h=n[d];if(255===h)return;for(var g=0,f=s-1;(0!==h||g<o)&&-1!==f;f--,g++)h+=a*u[f]>>>0,u[f]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");o=g,r++}for(var p=s-o;p!==s&&0===u[p];)p++;var m=e.allocUnsafe(i+(s-p));m.fill(0,0,i);for(var y=i;p!==s;)m[y++]=u[p++];return m}return{encode:function(n){if((Array.isArray(n)||n instanceof Uint8Array)&&(n=e.from(n)),!e.isBuffer(n))throw new TypeError("Expected Buffer");if(0===n.length)return"";for(var r=0,i=0,o=0,s=n.length;o!==s&&0===n[o];)o++,r++;for(var l=(s-o)*u+1>>>0,d=new Uint8Array(l);o!==s;){for(var h=n[o],g=0,f=l-1;(0!==h||g<i)&&-1!==f;f--,g++)h+=256*d[f]>>>0,d[f]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");i=g,o++}for(var p=l-i;p!==l&&0===d[p];)p++;for(var m=c.repeat(r);p<l;++p)m+=t.charAt(d[p]);return m},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+a+" character")}}},Bu}function qu(){if(Ou)return Mu;Ou=1;return Mu=$u()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")}var Ku=Ha(qu());const Gu=rl;var Hu={};function Wu(e,t,n){return t<=e&&e<=n}function zu(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function ju(e){this.tokens=[].slice.call(e)}ju.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 Vu=-1;function Xu(e,t){if(e)throw TypeError("Decoder error");return t||65533}var Qu="utf-8";function Yu(e,t){if(!(this instanceof Yu))return new Yu(e,t);if((e=void 0!==e?String(e).toLowerCase():Qu)!==Qu)throw new Error("Encoding not supported. Only utf-8 is supported");t=zu(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 Ju(e,t){if(!(this instanceof Ju))return new Ju(e,t);if((e=void 0!==e?String(e).toLowerCase():Qu)!==Qu)throw new Error("Encoding not supported. Only utf-8 is supported");t=zu(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function Zu(e){var t=e.fatal,n=0,r=0,i=0,o=128,s=191;this.handler=function(e,a){if(-1===a&&0!==i)return i=0,Xu(t);if(-1===a)return Vu;if(0===i){if(Wu(a,0,127))return a;if(Wu(a,194,223))i=1,n=a-192;else if(Wu(a,224,239))224===a&&(o=160),237===a&&(s=159),i=2,n=a-224;else{if(!Wu(a,240,244))return Xu(t);240===a&&(o=144),244===a&&(s=143),i=3,n=a-240}return n<<=6*i,null}if(!Wu(a,o,s))return n=i=r=0,o=128,s=191,e.prepend(a),Xu(t);if(o=128,s=191,n+=a-128<<6*(i-(r+=1)),r!==i)return null;var c=n;return n=i=r=0,c}}function ed(e){e.fatal,this.handler=function(e,t){if(-1===t)return Vu;if(Wu(t,0,127))return t;var n,r;Wu(t,128,2047)?(n=1,r=192):Wu(t,2048,65535)?(n=2,r=224):Wu(t,65536,1114111)&&(n=3,r=240);for(var i=[(t>>6*n)+r];n>0;){var o=t>>6*(n-1);i.push(128|63&o),n-=1}return i}}Yu.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=zu(t),this._streaming||(this._decoder=new Zu({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var r,i=new ju(n),o=[];!i.endOfStream()&&(r=this._decoder.handler(i,i.read()))!==Vu;)null!==r&&(Array.isArray(r)?o.push.apply(o,r):o.push(r));if(!this._streaming){do{if((r=this._decoder.handler(i,i.read()))===Vu)break;null!==r&&(Array.isArray(r)?o.push.apply(o,r):o.push(r))}while(!i.endOfStream());this._decoder=null}return o.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===o[0]?(this._BOMseen=!0,o.shift()):this._BOMseen=!0)),function(e){for(var t="",n=0;n<e.length;++n){var r=e[n];r<=65535?t+=String.fromCharCode(r):(r-=65536,t+=String.fromCharCode(55296+(r>>10),56320+(1023&r)))}return t}(o)}},Ju.prototype={encode:function(e,t){e=e?String(e):"",t=zu(t),this._streaming||(this._encoder=new ed(this._options)),this._streaming=Boolean(t.stream);for(var n,r=[],i=new ju(function(e){for(var t=String(e),n=t.length,r=0,i=[];r<n;){var o=t.charCodeAt(r);if(o<55296||o>57343)i.push(o);else if(56320<=o&&o<=57343)i.push(65533);else if(55296<=o&&o<=56319)if(r===n-1)i.push(65533);else{var s=e.charCodeAt(r+1);if(56320<=s&&s<=57343){var a=1023&o,c=1023&s;i.push(65536+(a<<10)+c),r+=1}else i.push(65533)}r+=1}return i}(e));!i.endOfStream()&&(n=this._encoder.handler(i,i.read()))!==Vu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);if(!this._streaming){for(;(n=this._encoder.handler(i,i.read()))!==Vu;)Array.isArray(n)?r.push.apply(r,n):r.push(n);this._encoder=null}return new Uint8Array(r)}};var td,nd=Wa(Object.freeze({__proto__:null,TextDecoder:Yu,TextEncoder:Ju}));function rd(){if(td)return Hu;td=1;var e=Hu&&Hu.__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=Hu&&Hu.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=Hu&&Hu.__decorate||function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s},r=Hu&&Hu.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(null!=n)for(var i in n)"default"!==i&&Object.hasOwnProperty.call(n,i)&&e(r,n,i);return t(r,n),r},i=Hu&&Hu.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Hu,"__esModule",{value:!0}),Hu.deserializeUnchecked=Hu.deserialize=Hu.serialize=Hu.BinaryReader=Hu.BinaryWriter=Hu.BorshError=Hu.baseDecode=Hu.baseEncode=void 0;const o=i(Du()),s=i(qu()),a=r(nd),c=new("function"!=typeof TextDecoder?a.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Hu.baseEncode=function(e){return"string"==typeof e&&(e=Buffer.from(e,"utf8")),s.default.encode(Buffer.from(e))},Hu.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(".")}}Hu.BorshError=u;class d{constructor(){this.buf=Buffer.alloc(l),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=Buffer.concat([this.buf,Buffer.alloc(l)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(Buffer.from(new o.default(e).toArray("le",64)))}writeBuffer(e){this.buf=Buffer.concat([Buffer.from(this.buf.subarray(0,this.length)),e,Buffer.alloc(l)]),this.length+=e.length}writeString(e){this.maybeResize();const t=Buffer.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(Buffer.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const n of e)this.maybeResize(),t(n)}toArray(){return this.buf.subarray(0,this.length)}}function h(e,t,n){const r=n.value;n.value=function(...e){try{return r.apply(this,e)}catch(e){if(e instanceof RangeError){const t=e.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(t)>=0)throw new u("Reached the end of buffer when deserializing")}throw e}}}Hu.BinaryWriter=d;class g{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new o.default(e,"le")}readU128(){const e=this.readBuffer(16);return new o.default(e,"le")}readU256(){const e=this.readBuffer(32);return new o.default(e,"le")}readU512(){const e=this.readBuffer(64);return new o.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new u(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return c.decode(t)}catch(e){throw new u(`Error decoding UTF-8 string: ${e}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),n=Array();for(let r=0;r<t;++r)n.push(e());return n}}function f(e){return e.charAt(0).toUpperCase()+e.slice(1)}function p(e,t,n,r,i){try{if("string"==typeof r)i[`write${f(r)}`](n);else if(r instanceof Array)if("number"==typeof r[0]){if(n.length!==r[0])throw new u(`Expecting byte array of length ${r[0]}, but got ${n.length} bytes`);i.writeFixedArray(n)}else if(2===r.length&&"number"==typeof r[1]){if(n.length!==r[1])throw new u(`Expecting byte array of length ${r[1]}, but got ${n.length} bytes`);for(let t=0;t<r[1];t++)p(e,null,n[t],r[0],i)}else i.writeArray(n,n=>{p(e,t,n,r[0],i)});else if(void 0!==r.kind)switch(r.kind){case"option":null==n?i.writeU8(0):(i.writeU8(1),p(e,t,n,r.type,i));break;case"map":i.writeU32(n.size),n.forEach((n,o)=>{p(e,t,o,r.key,i),p(e,t,n,r.value,i)});break;default:throw new u(`FieldType ${r} unrecognized`)}else m(e,n,i)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function m(e,t,n){if("function"==typeof t.borshSerialize)return void t.borshSerialize(n);const r=e.get(t.constructor);if(!r)throw new u(`Class ${t.constructor.name} is missing in schema`);if("struct"===r.kind)r.fields.map(([r,i])=>{p(e,r,t[r],i,n)});else{if("enum"!==r.kind)throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`);{const i=t[r.field];for(let o=0;o<r.values.length;++o){const[s,a]=r.values[o];if(s===i){n.writeU8(o),p(e,s,t[s],a,n);break}}}}}function y(e,t,n,r){try{if("string"==typeof n)return r[`read${f(n)}`]();if(n instanceof Array){if("number"==typeof n[0])return r.readFixedArray(n[0]);if("number"==typeof n[1]){const t=[];for(let i=0;i<n[1];i++)t.push(y(e,null,n[0],r));return t}return r.readArray(()=>y(e,t,n[0],r))}if("option"===n.kind){return r.readU8()?y(e,t,n.type,r):void 0}if("map"===n.kind){let i=new Map;const o=r.readU32();for(let s=0;s<o;s++){const o=y(e,t,n.key,r),s=y(e,t,n.value,r);i.set(o,s)}return i}return w(e,n,r)}catch(e){throw e instanceof u&&e.addToFieldPath(t),e}}function w(e,t,n){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(n);const r=e.get(t);if(!r)throw new u(`Class ${t.name} is missing in schema`);if("struct"===r.kind){const r={};for(const[i,o]of e.get(t).fields)r[i]=y(e,i,o,n);return new t(r)}if("enum"===r.kind){const i=n.readU8();if(i>=r.values.length)throw new u(`Enum index: ${i} is out of range`);const[o,s]=r.values[i],a=y(e,o,s,n);return new t({[o]:a})}throw new u(`Unexpected schema kind: ${r.kind} for ${t.constructor.name}`)}return n([h],g.prototype,"readU8",null),n([h],g.prototype,"readU16",null),n([h],g.prototype,"readU32",null),n([h],g.prototype,"readU64",null),n([h],g.prototype,"readU128",null),n([h],g.prototype,"readU256",null),n([h],g.prototype,"readU512",null),n([h],g.prototype,"readString",null),n([h],g.prototype,"readFixedArray",null),n([h],g.prototype,"readArray",null),Hu.BinaryReader=g,Hu.serialize=function(e,t,n=d){const r=new n;return m(e,t,r),r.toArray()},Hu.deserialize=function(e,t,n,r=g){const i=new r(n),o=w(e,t,i);if(i.offset<n.length)throw new u(`Unexpected ${n.length-i.offset} bytes after deserialized data`);return o},Hu.deserializeUnchecked=function(e,t,n,r=g){return w(e,t,new r(n))},Hu}var id,od=rd(),sd={};function ad(){if(id)return sd;id=1,Object.defineProperty(sd,"__esModule",{value:!0}),sd.s16=sd.s8=sd.nu64be=sd.u48be=sd.u40be=sd.u32be=sd.u24be=sd.u16be=sd.nu64=sd.u48=sd.u40=sd.u32=sd.u24=sd.u16=sd.u8=sd.offset=sd.greedy=sd.Constant=sd.UTF8=sd.CString=sd.Blob=sd.Boolean=sd.BitField=sd.BitStructure=sd.VariantLayout=sd.Union=sd.UnionLayoutDiscriminator=sd.UnionDiscriminator=sd.Structure=sd.Sequence=sd.DoubleBE=sd.Double=sd.FloatBE=sd.Float=sd.NearInt64BE=sd.NearInt64=sd.NearUInt64BE=sd.NearUInt64=sd.IntBE=sd.Int=sd.UIntBE=sd.UInt=sd.OffsetLayout=sd.GreedyCount=sd.ExternalLayout=sd.bindConstructorLayout=sd.nameWithProperty=sd.Layout=sd.uint8ArrayToBuffer=sd.checkUint8Array=void 0,sd.constant=sd.utf8=sd.cstr=sd.blob=sd.unionLayoutDiscriminator=sd.union=sd.seq=sd.bits=sd.struct=sd.f64be=sd.f64=sd.f32be=sd.f32=sd.ns64be=sd.s48be=sd.s40be=sd.s32be=sd.s24be=sd.s16be=sd.ns64=sd.s48=sd.s40=sd.s32=sd.s24=void 0;const e=ec();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)}sd.checkUint8Array=t,sd.uint8ArrayToBuffer=n;let r=class{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(e){const t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}};function i(e,t){return t.property?e+"["+t.property+"]":e}sd.Layout=r,sd.nameWithProperty=i,sd.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof r))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,n){return t.encode(this,e,n)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,n)=>t.decode(e,n),writable:!0})};class o extends r{isCount(){throw new Error("ExternalLayout is abstract")}}sd.ExternalLayout=o;class s extends o{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,n=0){t(e);const r=e.length-n;return Math.floor(r/this.elementSpan)}encode(e,t,n){return 0}}sd.GreedyCount=s;class a extends o{constructor(e,t=0,n){if(!(e instanceof r))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,n||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof c||this.layout instanceof l}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,n=0){return this.layout.encode(e,t,n+this.offset)}}sd.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}}sd.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}}sd.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}}sd.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}}sd.IntBE=d;const h=Math.pow(2,32);function g(e){const t=Math.floor(e/h);return{hi32:t,lo32:e-t*h}}function f(e,t){return e*h+t}class p extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return f(r.readUInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeUInt32LE(i.lo32,r),o.writeUInt32LE(i.hi32,r+4),8}}sd.NearUInt64=p;class m extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return f(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeUInt32BE(i.hi32,r),o.writeUInt32BE(i.lo32,r+4),8}}sd.NearUInt64BE=m;class y extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e),i=r.readUInt32LE(t);return f(r.readInt32LE(t+4),i)}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeUInt32LE(i.lo32,r),o.writeInt32LE(i.hi32,r+4),8}}sd.NearInt64=y;class w extends r{constructor(e){super(8,e)}decode(e,t=0){const r=n(e);return f(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const i=g(e),o=n(t);return o.writeInt32BE(i.hi32,r),o.writeUInt32BE(i.lo32,r+4),8}}sd.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}}sd.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}}sd.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}}sd.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}}sd.DoubleBE=S;class A extends r{constructor(e,t,n){if(!(e instanceof r))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof o&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let i=-1;!(t instanceof o)&&0<e.span&&(i=t*e.span),super(i,n),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0,r=this.count;if(r instanceof o&&(r=r.decode(e,t)),0<this.elementLayout.span)n=r*this.elementLayout.span;else{let i=0;for(;i<r;)n+=this.elementLayout.getSpan(e,t+n),++i}return n}decode(e,t=0){const n=[];let r=0,i=this.count;for(i instanceof o&&(i=i.decode(e,t));r<i;)n.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),r+=1;return n}encode(e,t,n=0){const r=this.elementLayout,i=e.reduce((e,i)=>e+r.encode(i,t,n+e),0);return this.count instanceof o&&this.count.encode(e.length,t,n),i}}sd.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 i=-1;try{i=e.reduce((e,t)=>e+t.getSpan(),0)}catch(e){}super(i,t),this.fields=e,this.decodePrefixes=!!n}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;try{n=this.fields.reduce((n,r)=>{const i=r.getSpan(e,t);return t+=i,n+i},0)}catch(e){throw new RangeError("indeterminate span")}return n}decode(e,n=0){t(e);const r=this.makeDestinationObject();for(const t of this.fields)if(void 0!==t.property&&(r[t.property]=t.decode(e,n)),n+=t.getSpan(e,n),this.decodePrefixes&&e.length===n)break;return r}encode(e,t,n=0){const r=n;let i=0,o=0;for(const r of this.fields){let s=r.span;if(o=0<s?s:0,void 0!==r.property){const i=e[r.property];void 0!==i&&(o=r.encode(i,t,n),0>s&&(s=r.getSpan(t,n)))}i=n,n+=s}return i+o-r}fromArray(e){const t=this.makeDestinationObject();for(const n of this.fields)void 0!==n.property&&0<e.length&&(t[n.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const n of this.fields){if(n.property===e)return t;0>n.span?t=-1:0<=t&&(t+=n.span)}}}sd.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")}}sd.UnionDiscriminator=T;class I extends T{constructor(e,t){if(!(e instanceof o&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,n){return this.layout.encode(e,t,n)}}sd.UnionLayoutDiscriminator=I;class C extends r{constructor(e,t,n){let i;if(e instanceof c||e instanceof l)i=new I(new a(e));else if(e instanceof o&&e.isCount())i=new I(e);else{if(!(e instanceof T))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");i=e}if(void 0===t&&(t=null),!(null===t||t instanceof r))throw new TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw new Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let s=-1;t&&(s=t.span,0<=s&&(e instanceof c||e instanceof l)&&(s+=i.layout.span)),super(s,n),this.discriminator=i,this.usesPrefixDiscriminator=e instanceof c||e instanceof l,this.defaultLayout=t,this.registry={};let u=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return u(e)},this.configGetSourceVariant=function(e){u=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const n=this.getVariant(e,t);if(!n)throw new Error("unable to determine span for unrecognized variant");return n.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const n=this.registry[t];if(n.property&&Object.prototype.hasOwnProperty.call(e,n.property))return n}throw new Error("unable to infer src variant")}decode(e,t=0){let n;const r=this.discriminator,i=r.decode(e,t),o=this.registry[i];if(void 0===o){const o=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=r.layout.span),n=this.makeDestinationObject(),n[r.property]=i,n[o.property]=o.decode(e,t+s)}else n=o.decode(e,t);return n}encode(e,t,n=0){const r=this.getSourceVariant(e);if(void 0===r){const r=this.discriminator,i=this.defaultLayout;let o=0;return this.usesPrefixDiscriminator&&(o=r.layout.span),r.encode(e[r.property],t,n),o+i.encode(e[i.property],t,n+o)}return r.encode(e,t,n)}addVariant(e,t,n){const r=new N(this,e,t,n);return this.registry[e]=r,r}getVariant(e,t=0){let n;return n=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[n]}}sd.Union=C;class N extends r{constructor(e,t,n,i){if(!(e instanceof C))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof n&&void 0===i&&(i=n,n=null),n){if(!(n instanceof r))throw new TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=n.span&&n.span>e.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof i)throw new TypeError("variant must have a String property")}let o=e.span;0>e.span&&(o=n?n.span:0,0<=o&&e.usesPrefixDiscriminator&&(o+=e.discriminator.layout.span)),super(o,i),this.union=e,this.variant=t,this.layout=n||null}getSpan(e,t=0){if(0<=this.span)return this.span;let n=0;this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span);let r=0;return this.layout&&(r=this.layout.getSpan(e,t+n)),n+r}decode(e,t=0){const n=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let r=0;return this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout?n[this.property]=this.layout.decode(e,t+r):this.property?n[this.property]=!0:this.union.usesPrefixDiscriminator&&(n[this.union.discriminator.property]=this.variant),n}encode(e,t,n=0){let r=0;if(this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,n);let i=r;if(this.layout&&(this.layout.encode(e[this.property],t,n+r),i+=this.layout.getSpan(t,n+r),0<=this.union.span&&i>this.union.span))throw new Error("encoded variant overruns containing union");return i}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function _(e){return 0>e&&(e+=4294967296),e}sd.VariantLayout=N;class x extends r{constructor(e,t,n){if(!(e instanceof c||e instanceof l))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===n&&(n=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,n),this.word=e,this.msb=!!t,this.fields=[];let r=0;this._packedSetValue=function(e){return r=_(e),this},this._packedGetValue=function(){return r}}decode(e,t=0){const n=this.makeDestinationObject(),r=this.word.decode(e,t);this._packedSetValue(r);for(const t of this.fields)void 0!==t.property&&(n[t.property]=t.decode(e));return n}encode(e,t,n=0){const r=this.word.decode(t,n);this._packedSetValue(r);for(const t of this.fields)if(void 0!==t.property){const n=e[t.property];void 0!==n&&t.encode(n)}return this.word.encode(this._packedGetValue(),t,n)}addField(e,t){const n=new 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}}sd.BitStructure=x;class D{constructor(e,t,n){if(!(e instanceof x))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const r=8*e.span,i=e.fields.reduce((e,t)=>e+t.bits,0);if(t+i>r)throw new Error("bits too long for span remainder ("+(r-i)+" of "+r+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=i,this.container.msb&&(this.start=r-i-t),this.wordMask=_(this.valueMask<<this.start),this.property=n}decode(e,t){return _(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==_(e&this.valueMask))throw new TypeError(i("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),n=_(e<<this.start);this.container._packedSetValue(_(t&~this.wordMask)|n)}}sd.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)}}sd.Boolean=P;class B extends r{constructor(e,t){if(!(e instanceof o&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let n=-1;e instanceof o||(n=e),super(n,t),this.length=e}getSpan(e,t){let n=this.span;return 0>n&&(n=this.length.decode(e,t)),n}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),n(e).slice(t,t+r)}encode(e,t,r){let s=this.length;if(this.length instanceof o&&(s=e.length),!(e instanceof Uint8Array&&s===e.length))throw new TypeError(i("Blob.encode",this)+" requires (length "+s+") Uint8Array as src");if(r+s>t.length)throw new RangeError("encoding overruns Uint8Array");const a=n(e);return n(t).write(a.toString("hex"),r,s,"hex"),this.length instanceof o&&this.length.encode(s,t,r),s}}sd.Blob=B;class R extends r{constructor(e){super(-1,e)}getSpan(e,n=0){t(e);let r=n;for(;r<e.length&&0!==e[r];)r+=1;return 1+r-n}decode(e,t=0){const r=this.getSpan(e,t);return n(e).slice(t,t+r-1).toString("utf-8")}encode(t,r,i=0){"string"!=typeof t&&(t=String(t));const o=e.Buffer.from(t,"utf8"),s=o.length;if(i+s>r.length)throw new RangeError("encoding overruns Buffer");const a=n(r);return o.copy(a,i),a[i+s]=0,s+1}}sd.CString=R;class M extends r{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,n=0){return t(e),e.length-n}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return n(e).slice(t,t+r).toString("utf-8")}encode(t,r,i=0){"string"!=typeof t&&(t=String(t));const o=e.Buffer.from(t,"utf8"),s=o.length;if(0<=this.maxSpan&&this.maxSpan<s)throw new RangeError("text length exceeds maxSpan");if(i+s>r.length)throw new RangeError("encoding overruns Buffer");return o.copy(n(r),i),s}}sd.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 sd.Constant=O,sd.greedy=(e,t)=>new s(e,t),sd.offset=(e,t,n)=>new a(e,t,n),sd.u8=e=>new c(1,e),sd.u16=e=>new c(2,e),sd.u24=e=>new c(3,e),sd.u32=e=>new c(4,e),sd.u40=e=>new c(5,e),sd.u48=e=>new c(6,e),sd.nu64=e=>new p(e),sd.u16be=e=>new l(2,e),sd.u24be=e=>new l(3,e),sd.u32be=e=>new l(4,e),sd.u40be=e=>new l(5,e),sd.u48be=e=>new l(6,e),sd.nu64be=e=>new m(e),sd.s8=e=>new u(1,e),sd.s16=e=>new u(2,e),sd.s24=e=>new u(3,e),sd.s32=e=>new u(4,e),sd.s40=e=>new u(5,e),sd.s48=e=>new u(6,e),sd.ns64=e=>new y(e),sd.s16be=e=>new d(2,e),sd.s24be=e=>new d(3,e),sd.s32be=e=>new d(4,e),sd.s40be=e=>new d(5,e),sd.s48be=e=>new d(6,e),sd.ns64be=e=>new w(e),sd.f32=e=>new b(e),sd.f32be=e=>new k(e),sd.f64=e=>new v(e),sd.f64be=e=>new S(e),sd.struct=(e,t,n)=>new E(e,t,n),sd.bits=(e,t,n)=>new x(e,t,n),sd.seq=(e,t,n)=>new A(e,t,n),sd.union=(e,t,n)=>new C(e,t,n),sd.unionLayoutDiscriminator=(e,t)=>new I(e,t),sd.blob=(e,t)=>new B(e,t),sd.cstr=e=>new R(e),sd.utf8=(e,t)=>new M(e,t),sd.constant=(e,t)=>new O(e,t),sd}var cd=ad(),ld=1,ud=2,dd=3,hd=4,gd=5,fd=6,pd=7,md=8,yd=9,wd=10,bd=-32700,kd=-32603,vd=-32602,Sd=-32601,Ad=-32600,Ed=-32016,Td=-32015,Id=-32014,Cd=-32013,Nd=-32012,_d=-32011,xd=-32010,Dd=-32009,Pd=-32008,Bd=-32007,Rd=-32006,Md=-32005,Od=-32004,Ld=-32003,Ud=-32002,Fd=-32001,$d=28e5,qd=2800001,Kd=2800002,Gd=2800003,Hd=2800004,Wd=2800005,zd=2800006,jd=2800007,Vd=2800008,Xd=2800009,Qd=2800010,Yd=2800011,Jd=323e4,Zd=32300001,eh=3230002,th=3230003,nh=3230004,rh=361e4,ih=3610001,oh=3610002,sh=3610003,ah=3610004,ch=3610005,lh=3610006,uh=3610007,dh=3611e3,hh=3704e3,gh=3704001,fh=3704002,ph=3704003,mh=3704004,yh=4128e3,wh=4128001,bh=4128002,kh=4615e3,vh=4615001,Sh=4615002,Ah=4615003,Eh=4615004,Th=4615005,Ih=4615006,Ch=4615007,Nh=4615008,_h=4615009,xh=4615010,Dh=4615011,Ph=4615012,Bh=4615013,Rh=4615014,Mh=4615015,Oh=4615016,Lh=4615017,Uh=4615018,Fh=4615019,$h=4615020,qh=4615021,Kh=4615022,Gh=4615023,Hh=4615024,Wh=4615025,zh=4615026,jh=4615027,Vh=4615028,Xh=4615029,Qh=4615030,Yh=4615031,Jh=4615032,Zh=4615033,eg=4615034,tg=4615035,ng=4615036,rg=4615037,ig=4615038,og=4615039,sg=4615040,ag=4615041,cg=4615042,lg=4615043,ug=4615044,dg=4615045,hg=4615046,gg=4615047,fg=4615048,pg=4615049,mg=4615050,yg=4615051,wg=4615052,bg=4615053,kg=4615054,vg=5508e3,Sg=5508001,Ag=5508002,Eg=5508003,Tg=5508004,Ig=5508005,Cg=5508006,Ng=5508007,_g=5508008,xg=5508009,Dg=5508010,Pg=5508011,Bg=5663e3,Rg=5663001,Mg=5663002,Og=5663003,Lg=5663004,Ug=5663005,Fg=5663006,$g=5663007,qg=5663008,Kg=5663009,Gg=5663010,Hg=5663011,Wg=5663012,zg=5663013,jg=5663014,Vg=5663015,Xg=5663016,Qg=5663017,Yg=5663018,Jg=5663019,Zg=5663020,ef=705e4,tf=7050001,nf=7050002,rf=7050003,of=7050004,sf=7050005,af=7050006,cf=7050007,lf=7050008,uf=7050009,df=7050010,hf=7050011,gf=7050012,ff=7050013,pf=7050014,mf=7050015,yf=7050016,wf=7050017,bf=7050018,kf=7050019,vf=7050020,Sf=7050021,Af=7050022,Ef=7050023,Tf=7050024,If=7050025,Cf=7050026,Nf=7050027,_f=7050028,xf=7050029,Df=7050030,Pf=7050031,Bf=7050032,Rf=7050033,Mf=7050034,Of=7050035,Lf=7050036,Uf=8078e3,Ff=8078001,$f=8078002,qf=8078003,Kf=8078004,Gf=8078005,Hf=8078006,Wf=8078007,zf=8078008,jf=8078009,Vf=8078010,Xf=8078011,Qf=8078012,Yf=8078013,Jf=8078014,Zf=8078015,ep=8078016,tp=8078017,np=8078018,rp=8078019,ip=8078020,op=8078021,sp=8078022,ap=81e5,cp=8100001,lp=8100002,up=8100003,dp=819e4,hp=8190001,gp=8190002,fp=8190003,pp=8190004,mp=99e5,yp=9900001,wp=9900002,bp=9900003,kp=9900004;function vp(e){if(Array.isArray(e)){return"%5B"+e.map(vp).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Sp([e,t]){return`${e}=${vp(t)}`}var Ap={[Jd]:"Account not found at address: $address",[nh]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[th]:"Expected decoded account at address: $address",[eh]:"Failed to decode account data at address: $address",[Zd]:"Accounts not found at addresses: $addresses",[Xd]:"Unable to find a viable program address bump seed.",[Kd]:"$putativeAddress is not a base58-encoded address.",[$d]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Gd]:"The `CryptoKey` must be an `Ed25519` public key.",[Yd]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Vd]:"Invalid seeds; point must fall off the Ed25519 curve.",[Hd]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[zd]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[jd]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Wd]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Qd]:"Program address cannot end with PDA marker.",[qd]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[hd]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[ld]:"The network has progressed past the last block for which this transaction could have been committed.",[Uf]:"Codec [$codecDescription] cannot decode empty byte arrays.",[sp]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[ip]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Gf]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Hf]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Kf]:"Encoder and decoder must either both be fixed-size or variable-size.",[zf]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[$f]:"Expected a fixed-size codec, got a variable-size one.",[Yf]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[qf]:"Expected a variable-size codec, got a fixed-size one.",[rp]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Ff]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[np]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[jf]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Vf]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Zf]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Wf]:"Expected [$codecDescription] to have $expected items, got $actual.",[Qf]:"Invalid value $value for base $base with alphabet $alphabet.",[ep]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Xf]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Jf]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[op]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[tp]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[dh]:"No random values implementation could be found.",[_h]:"instruction requires an uninitialized account",[Gh]:"instruction tries to borrow reference for an account which is already borrowed",[Hh]:"instruction left account with an outstanding borrowed reference",[qh]:"program other than the account's owner changed the size of the account data",[Th]:"account data too small for instruction",[Kh]:"instruction expected an executable account",[hg]:"An account does not have enough lamports to be rent-exempt",[fg]:"Program arithmetic overflowed",[dg]:"Failed to serialize or deserialize account data: $encodedData",[kg]:"Builtin programs must consume compute units",[Jh]:"Cross-program invocation call depth too deep",[ig]:"Computational budget exceeded",[zh]:"custom program error: #$code",[Lh]:"instruction contains duplicate accounts",[Wh]:"instruction modifications of multiply-passed account differ",[Qh]:"executable accounts must be rent exempt",[Vh]:"instruction changed executable accounts data",[Xh]:"instruction changed the balance of an executable account",[Uh]:"instruction changed executable bit of an account",[Rh]:"instruction modified data of an account it does not own",[Bh]:"instruction spent from the balance of an account it does not own",[vh]:"generic instruction error",[mg]:"Provided owner is not allowed",[lg]:"Account is immutable",[ug]:"Incorrect authority provided",[Ch]:"incorrect program id for instruction",[Ih]:"insufficient funds for instruction",[Eh]:"invalid account data for instruction",[gg]:"Invalid account owner",[Sh]:"invalid program argument",[jh]:"program returned invalid error code",[Ah]:"invalid instruction data",[rg]:"Failed to reallocate account data",[ng]:"Provided seeds do not result in a valid address",[yg]:"Accounts data allocations exceeded the maximum allowed per transaction",[wg]:"Max accounts exceeded",[bg]:"Max instruction trace length exceeded",[tg]:"Length of the seed is too long for address generation",[Zh]:"An account required by the instruction is missing",[Nh]:"missing required signature for instruction",[Ph]:"instruction illegally modified the program id of an account",[$h]:"insufficient account keys for instruction",[og]:"Cross-program invocation with unauthorized signer or writable account",[sg]:"Failed to create program execution environment",[cg]:"Program failed to compile",[ag]:"Program failed to complete",[Oh]:"instruction modified data of a read-only account",[Mh]:"instruction changed the balance of a read-only account",[eg]:"Cross-program invocation reentrancy not allowed for this instruction",[Fh]:"instruction modified rent epoch of an account",[Dh]:"sum of account balances before and after instruction do not match",[xh]:"instruction requires an initialized account",[kh]:"",[Yh]:"Unsupported program id",[pg]:"Unsupported sysvar",[yh]:"The instruction does not have any accounts.",[wh]:"The instruction does not have any data.",[bh]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[gd]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[ud]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[wp]:"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",[kp]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[yp]:"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",[mp]:"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",[bp]:"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",[kd]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[vd]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Ad]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Sd]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[bd]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Nd]:"$__serverMessage",[Fd]:"$__serverMessage",[Od]:"$__serverMessage",[Id]:"$__serverMessage",[xd]:"$__serverMessage",[Dd]:"$__serverMessage",[Ed]:"Minimum context slot has not been reached",[Md]:"Node is unhealthy; behind by $numSlotsBehind slots",[Pd]:"No snapshot",[Ud]:"Transaction simulation failed",[Bd]:"$__serverMessage",[_d]:"Transaction history is not available from this node",[Rd]:"$__serverMessage",[Cd]:"Transaction signature length mismatch",[Ld]:"Transaction signature verification failure",[Td]:"$__serverMessage",[hh]:"Key pair bytes must be of length 64, got $byteLength.",[gh]:"Expected private key bytes with length 32. Actual length: $actualLength.",[fh]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[mh]:"The provided private key does not match the provided public key.",[ph]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[fd]:"Lamports value must be in the range [0, 2e64-1]",[pd]:"`$value` cannot be parsed as a `BigInt`",[wd]:"$message",[md]:"`$value` cannot be parsed as a `Number`",[dd]:"No nonce account could be found at address `$nonceAccountAddress`",[dp]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[gp]:"WebSocket was closed before payload could be added to the send buffer",[fp]:"WebSocket connection closed",[pp]:"WebSocket failed to connect",[hp]:"Failed to obtain a subscription id from the server",[up]:"Could not find an API plan for RPC method: `$method`",[ap]:"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`.",[lp]:"HTTP error ($statusCode): $message",[cp]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[vg]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Sg]:"The provided value does not implement the `KeyPairSigner` interface",[Eg]:"The provided value does not implement the `MessageModifyingSigner` interface",[Tg]:"The provided value does not implement the `MessagePartialSigner` interface",[Ag]:"The provided value does not implement any of the `MessageSigner` interfaces",[Cg]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Ng]:"The provided value does not implement the `TransactionPartialSigner` interface",[_g]:"The provided value does not implement the `TransactionSendingSigner` interface",[Ig]:"The provided value does not implement any of the `TransactionSigner` interfaces",[xg]:"More than one `TransactionSendingSigner` was identified.",[Dg]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Pg]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[uh]:"Cannot export a non-extractable key.",[ih]:"No digest implementation could be found.",[rh]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[oh]:"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.",[sh]:"No signature verification implementation could be found.",[ah]:"No key generation implementation could be found.",[ch]:"No signing implementation could be found.",[lh]:"No key export implementation could be found.",[yd]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[yf]:"Transaction processing left an account with an outstanding borrowed reference",[tf]:"Account in use",[nf]:"Account loaded twice",[rf]:"Attempt to debit an account but found no record of a prior credit.",[Ef]:"Transaction loads an address table account that doesn't exist",[cf]:"This transaction has already been processed",[lf]:"Blockhash not found",[uf]:"Loader call chain is too deep",[mf]:"Transactions are currently disabled due to cluster maintenance",[Df]:"Transaction contains a duplicate instruction ($index) that is not allowed",[sf]:"Insufficient funds for fee",[Pf]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[af]:"This account may not be used to pay transaction fees",[hf]:"Transaction contains an invalid account reference",[If]:"Transaction loads an address table account with invalid data",[Cf]:"Transaction address table lookup uses an invalid index",[Tf]:"Transaction loads an address table account with an invalid owner",[Rf]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[ff]:"This program may not be used for executing instructions",[Nf]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[kf]:"Transaction loads a writable account that cannot be written",[Bf]:"Transaction exceeded max loaded accounts data size cap",[df]:"Transaction requires a fee but has no signature present",[of]:"Attempt to load a program that does not exist",[Of]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Mf]:"ResanitizationNeeded",[pf]:"Transaction failed to sanitize accounts offsets correctly",[gf]:"Transaction did not pass signature verification",[Af]:"Transaction locked too many accounts",[Lf]:"Sum of account balances before and after transaction do not match",[ef]:"The transaction failed with the error `$errorName`",[bf]:"Transaction version is unsupported",[Sf]:"Transaction would exceed account data limit within the block",[xf]:"Transaction would exceed total account data limit",[vf]:"Transaction would exceed max account limit within the block",[wf]:"Transaction would exceed max Block Cost Limit",[_f]:"Transaction would exceed max Vote Cost Limit",[Vg]:"Attempted to sign a transaction with an address that is not a signer for it",[Gg]:"Transaction is missing an address at index: $index.",[Xg]:"Transaction has no expected signers therefore it cannot be encoded",[Zg]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Mg]:"Transaction does not have a blockhash lifetime",[Og]:"Transaction is not a durable nonce transaction",[Ug]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Fg]:"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",[qg]:"No fee payer set in CompiledTransaction",[$g]:"Could not find program address at index $index",[Yg]:"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",[Jg]:"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",[Hg]:"Transaction is missing a fee payer.",[Wg]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[jg]:"Transaction first instruction is not advance nonce account instruction.",[zg]:"Transaction with no instructions cannot be durable nonce transaction.",[Bg]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Rg]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Qg]:"The transaction message expected the transaction to have $signerAddressesLength signatures, got $signaturesLength.",[Kg]:"Transaction is missing signatures for addresses: $addresses.",[Lg]:"Transaction version must be in the range [0, 127]. `$actualVersion` given"},Ep="i",Tp="t";function Ip(e,t={}){if("production"!==process.env.NODE_ENV)return function(e,t={}){const n=Ap[e];if(0===n.length)return"";let r;function i(e){if(2===r[Tp]){const i=n.slice(r[Ep]+1,e);o.push(i in t?`${t[i]}`:`$${i}`)}else 1===r[Tp]&&o.push(n.slice(r[Ep],e))}const o=[];return n.split("").forEach((e,t)=>{if(0===t)return void(r={[Ep]:0,[Tp]:"\\"===n[0]?0:"$"===n[0]?2:1});let o;switch(r[Tp]){case 0:o={[Ep]:t,[Tp]:1};break;case 1:"\\"===e?o={[Ep]:t,[Tp]:0}:"$"===e&&(o={[Ep]:t,[Tp]:2});break;case 2:"\\"===e?o={[Ep]:t,[Tp]:0}:"$"===e?o={[Ep]:t,[Tp]:2}:e.match(/\w/)||(o={[Ep]:t,[Tp]:1})}o&&(r!==o&&i(t),r=o)}),i(),o.join("")}(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${function(e){const t=Object.entries(e).map(Sp).join("&");return btoa(t)}(t)}'`),`${n}\``}}var Cp=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;if(t){const{cause:e,...i}=t;e&&(r={cause:e}),Object.keys(i).length>0&&(n=i)}super(Ip(e,n),r),this.context={__code:e,...n},this.name="SolanaError"}};function Np(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function _p(e){return 1!==e?.endian}function xp(e){return t={fixedSize:e.size,write(t,n,r){e.range&&function(e,t,n,r){if(r<t||r>n)throw new Cp(Xf,{codecDescription:e,max:n,min:t,value:r})}(e.name,e.range[0],e.range[1],t);const i=new ArrayBuffer(e.size);return e.set(new DataView(i),t,_p(e.config)),n.set(new Uint8Array(i),r),r+e.size}},Object.freeze({...t,encode:e=>{const n=new Uint8Array(function(e,t){return"fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}(e,t));return t.write(e,n,0),n}});var t}function Dp(e){return t={fixedSize:e.size,read(t,n=0){!function(e,t,n=0){if(t.length-n<=0)throw new Cp(Uf,{codecDescription:e})}(e.name,t,n),function(e,t,n,r=0){const i=n.length-r;if(i<t)throw new Cp(Ff,{bytesLength:i,codecDescription:e,expected:t})}(e.name,e.size,t,n);const r=new DataView(function(e,t,n){const r=e.byteOffset+(t??0),i=n??e.byteLength;return e.buffer.slice(r,r+i)}(t,n,e.size));return[e.get(r,_p(e.config)),n+e.size]}},Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]});var t}var Pp=(e={})=>function(e,t){if(Np(e)!==Np(t))throw new Cp(Kf);if(Np(e)&&Np(t)&&e.fixedSize!==t.fixedSize)throw new Cp(Gf,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Np(e)&&!Np(t)&&e.maxSize!==t.maxSize)throw new Cp(Hf,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>xp({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,n)=>e.setBigUint64(0,BigInt(t),n),size:8}))(e),((e={})=>Dp({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Bp extends TypeError{constructor(e,t){let n;const{message:r,explanation:i,...o}=e,{path:s}=e,a=0===s.length?r:`At path: ${s.join(".")} -- ${r}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>n??(n=[e,...t()])}}function Rp(e){return"object"==typeof e&&null!=e}function Mp(e){return Rp(e)&&!Array.isArray(e)}function Op(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function Lp(e,t,n,r){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:i,branch:o}=t,{type:s}=n,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Op(r)}\``}=e;return{value:r,type:s,refinement:a,key:i[i.length-1],path:i,branch:o,...e,message:c}}function*Up(e,t,n,r){var i;Rp(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const i of e){const e=Lp(i,t,n,r);e&&(yield e)}}function*Fp(e,t,n={}){const{path:r=[],branch:i=[e],coerce:o=!1,mask:s=!1}=n,a={path:r,branch:i,mask:s};o&&(e=t.coercer(e,a));let c="valid";for(const r of t.validator(e,a))r.explanation=n.message,c="not_valid",yield[r,void 0];for(let[l,u,d]of t.entries(e,a)){const t=Fp(u,d,{path:void 0===l?r:[...r,l],branch:void 0===l?i:[...i,u],coerce:o,mask:s,message:n.message});for(const n of t)n[0]?(c=null!=n[0].refinement?"not_refined":"not_valid",yield[n[0],void 0]):o&&(u=n[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Rp(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 $p=class{constructor(e){const{type:t,schema:n,validator:r,refiner:i,coercer:o=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=n,this.entries=s,this.coercer=o,this.validator=r?(e,t)=>Up(r(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Up(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,n){const r=Gp(e,t,{message:n});if(r[0])throw r[0]}(e,this,t)}create(e,t){return qp(e,this,t)}is(e){return Kp(e,this)}mask(e,t){return function(e,t,n){const r=Gp(e,t,{coerce:!0,mask:!0,message:n});if(r[0])throw r[0];return r[1]}(e,this,t)}validate(e,t={}){return Gp(e,this,t)}};function qp(e,t,n){const r=Gp(e,t,{coerce:!0,message:n});if(r[0])throw r[0];return r[1]}function Kp(e,t){return!Gp(e,t)[0]}function Gp(e,t,n={}){const r=Fp(e,t,n),i=function(e){const{done:t,value:n}=e.next();return t?void 0:n}(r);if(i[0]){return[new Bp(i[0],function*(){for(const e of r)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Hp(e,t){return new $p({type:e,schema:null,validator:t})}function Wp(e){return new $p({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: ${Op(e)}`})}function zp(){return Hp("boolean",e=>"boolean"==typeof e)}function jp(e){return Hp("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Op(t)}`)}function Vp(e){const t=Op(e),n=typeof e;return new $p({type:"literal",schema:"string"===n||"number"===n||"boolean"===n?e:null,validator:n=>n===e||`Expected the literal \`${t}\`, but received: ${Op(n)}`})}function Xp(e){return new $p({...e,validator:(t,n)=>null===t||e.validator(t,n),refiner:(t,n)=>null===t||e.refiner(t,n)})}function Qp(){return Hp("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Op(e)}`)}function Yp(e){return new $p({...e,validator:(t,n)=>void 0===t||e.validator(t,n),refiner:(t,n)=>void 0===t||e.refiner(t,n)})}function Jp(e,t){return new $p({type:"record",schema:null,*entries(n){if(Rp(n))for(const r in n){const i=n[r];yield[r,r,e],yield[r,i,t]}},validator:e=>Mp(e)||`Expected an object, but received: ${Op(e)}`,coercer:e=>Mp(e)?{...e}:e})}function Zp(){return Hp("string",e=>"string"==typeof e||`Expected a string, but received: ${Op(e)}`)}function em(e){const t=Hp("never",()=>!1);return new $p({type:"tuple",schema:null,*entries(n){if(Array.isArray(n)){const r=Math.max(e.length,n.length);for(let i=0;i<r;i++)yield[i,n[i],e[i]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Op(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function tm(e){const t=Object.keys(e);return new $p({type:"type",schema:e,*entries(n){if(Rp(n))for(const r of t)yield[r,n[r],e[r]]},validator:e=>Mp(e)||`Expected an object, but received: ${Op(e)}`,coercer:e=>Mp(e)?{...e}:e})}function nm(e){const t=e.map(e=>e.type).join(" | ");return new $p({type:"union",schema:null,coercer(t,n){for(const r of e){const[e,i]=r.validate(t,{coerce:!0,mask:n.mask});if(!e)return i}return t},validator(n,r){const i=[];for(const t of e){const[...e]=Fp(n,t,r),[o]=e;if(!o[0])return[];for(const[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Op(n)}`,...i]}})}function rm(){return Hp("unknown",()=>!0)}function im(e,t,n){return new $p({...e,coercer:(r,i)=>Kp(r,t)?e.coercer(n(r,i),i):e.coercer(r,i)})}var om,sm,am,cm,lm=Wa(y);function um(){if(sm)return om;sm=1;const e=lm.v4;return om=function(t,n,r,i){if("string"!=typeof t)throw new TypeError(t+" must be a string");const o="number"==typeof(i=i||{}).version?i.version:2;if(1!==o&&2!==o)throw new TypeError(o+" must be 1 or 2");const s={method:t};if(2===o&&(s.jsonrpc="2.0"),n){if("object"!=typeof n&&!Array.isArray(n))throw new TypeError(n+" must be an object, array or omitted");s.params=n}if(void 0===r){const t="function"==typeof i.generator?i.generator:function(){return e()};s.id=t(s,i)}else 2===o&&null===r?i.notificationIdNull&&(s.id=null):s.id=r;return s}}function dm(){if(cm)return am;cm=1;const e=lm.v4,t=um(),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 am=n,n.prototype.request=function(e,n,r,i){const o=this;let s=null;const a=Array.isArray(e)&&"function"==typeof n;if(1===this.options.version&&a)throw new TypeError("JSON-RPC 1.0 does not support batching");if(a||!a&&e&&"object"==typeof e&&"function"==typeof n)i=n,s=e;else{"function"==typeof r&&(i=r,r=void 0);const o="function"==typeof i;try{s=t(e,n,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(e){if(o)return void i(e);throw e}if(!o)return s}let c;try{c=JSON.stringify(s,this.options.replacer)}catch(e){return void i(e)}return this.callServer(c,function(e,t){o._parseResponse(e,t,i)}),s},n.prototype._parseResponse=function(e,t,n){if(e)return void n(e);if(!t)return void n();let r;try{r=JSON.parse(t,this.options.reviver)}catch(e){return void n(e)}if(3!==n.length)n(null,r);else{if(Array.isArray(r)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return void n(null,r.filter(e),r.filter(t))}n(null,r.error,r.result)}},am}var hm,gm=Ha(dm()),fm={exports:{}};function pm(){return hm||(hm=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,r,o,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new i(r,o||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,o=r.length,s=new Array(o);i<o;i++)s[i]=r[i].fn;return s},a.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},a.prototype.emit=function(e,t,r,i,o,s){var a=n?n+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,i),!0;case 5:return u.fn.call(u.context,t,r,i,o),!0;case 6:return u.fn.call(u.context,t,r,i,o,s),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var h,g=u.length;for(l=0;l<g;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),d){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,r);break;case 4:u[l].fn.call(u[l].context,t,r,i);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,i){var o=n?n+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||i&&!a.once||r&&a.context!==r||s(this,o);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||i&&!a[c].once||r&&a[c].context!==r)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(fm)),fm.exports}var mm=Ha(pm()),ym=class extends mm{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 wm=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},bm=class extends mm{address;rpc_id;queue;options;autoconnect;ready;reconnect;reconnect_timer_id;reconnect_interval;max_reconnects;rest_options;current_reconnects;generate_request_id;socket;webSocketFactory;dataPack;constructor(e,t="ws://localhost:8080",{autoconnect:n=!0,reconnect:r=!0,reconnect_interval:i=1e3,max_reconnects:o=5,...s}={},a,c){super(),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=n,this.ready=!1,this.reconnect=r,this.reconnect_timer_id=void 0,this.reconnect_interval=i,this.max_reconnects=o,this.rest_options=s,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new wm,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(e,t,n,r){return r||"object"!=typeof n||(r=n,n=null),new Promise((i,o)=>{if(!this.ready)return o(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),r,e=>{if(e)return o(e);this.queue[s]={promise:[i,o]},n&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],o(new Error("reply timeout"))},n))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((n,r)=>{if(!this.ready)return r(new Error("socket not ready"));const i={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(i),e=>{if(e)return r(e);n()})})}async subscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket&&this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}getCurrentReconnects(){return this.current_reconnects}getMaxReconnects(){return this.max_reconnects}isReconnecting(){return void 0!==this.reconnect_timer_id}willReconnect(){return this.reconnect&&(0===this.max_reconnects||this.current_reconnects<this.max_reconnects)}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=tc.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 km extends Ec{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,sc(e);const n=Sc(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),cc(i)}update(e){return ac(this),this.iHash.update(e),this}digestInto(e){ac(this),oc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:s}=this;return e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const vm=(e,t,n)=>new km(e,t).update(n).digest();vm.create=(e,t)=>new km(e,t);const Sm=(e,t)=>(e+(e>=0?t:-t)/_m)/t;function Am(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Em(e,t){const n={};for(let r of Object.keys(t))n[r]=void 0===e[r]?t[r]:e[r];return al(n.lowS,"lowS"),al(n.prehash,"prehash"),void 0!==n.format&&Am(n.format),n}class Tm extends Error{constructor(e=""){super(e)}}const Im={Err:Tm,_tlv:{encode:(e,t)=>{const{Err:n}=Im;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const r=t.length/2,i=ll(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?ll(i.length/2|128):"";return ll(e)+o+i+t},decode(e,t){const{Err:n}=Im;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const i=t[r++];let o=0;if(!!(128&i)){const e=127&i;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const s=t.subarray(r,r+e);if(s.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===s[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of s)o=o<<8|e;if(r+=e,o<128)throw new n("tlv.decode(long): not minimal encoding")}else o=i;const s=t.subarray(r,r+o);if(s.length!==o)throw new n("tlv.decode: wrong value length");return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){const{Err:t}=Im;if(e<Cm)throw new t("integer: negative integers are not allowed");let n=ll(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}=Im;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 dl(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=Im,i=pl("signature",e),{v:o,l:s}=r.decode(48,i);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,o),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=Im,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},Cm=BigInt(0),Nm=BigInt(1),_m=BigInt(2),xm=BigInt(3),Dm=BigInt(4);function Pm(e,t){const{BYTES:n}=e;let r;if("bigint"==typeof t)r=t;else{let i=pl("private key",t);try{r=e.fromBytes(i)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Bm(e,t={}){const n=cu("weierstrass",e,t),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s,n:a}=o;vl(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(o.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Mm(r,i);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,n){const{x:i,y:o}=t.toAffine(),s=r.toBytes(i);if(al(n,"isCompressed"),n){u();return Ac(Rm(!r.isOdd(o)),s)}return Ac(Uint8Array.of(4),s,r.toBytes(o))},h=t.fromBytes||function(e){cl(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,o=e[0],s=e.subarray(1);if(i!==t||2!==o&&3!==o){if(i===n&&4===o){const e=r.BYTES,t=r.fromBytes(s.subarray(0,e)),n=r.fromBytes(s.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}{const e=r.fromBytes(s);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=g(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}u();return!(1&~o)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}};function g(e){const t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,o.a)),o.b)}function f(e,t){const n=r.sqr(t),i=g(e);return r.eql(n,i)}if(!f(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const p=r.mul(r.pow(o.a,xm),Dm),m=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(p,m)))throw new Error("bad curve params: a or b");function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function w(e){if(!(e instanceof A))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,n){const[[r,i],[o,s]]=t,a=Sm(s*e,n),c=Sm(-i*e,n);let l=e-a*r-c*o,u=-a*i-c*s;const d=l<Cm,h=u<Cm;d&&(l=-l),h&&(u=-u);const g=kl(Math.ceil(bl(n)/2))+Nm;if(l<Cm||l>=g||u<Cm||u>=g)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}(e,c.basises,i.ORDER)}const k=Sl((e,t)=>{const{X:n,Y:i,Z:o}=e;if(r.eql(o,r.ONE))return{x:n,y:i};const s=e.is0();null==t&&(t=s?r.ONE:r.inv(o));const a=r.mul(n,t),c=r.mul(i,t),l=r.mul(o,t);if(s)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),v=Sl(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(n,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(e,t,n,i,o){return n=new A(r.mul(n.X,e),n.Y,n.Z),t=Ql(i,t),n=Ql(o,n),t.add(n)}class A{constructor(e,t,n){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",n),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof A)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?A.ZERO:new A(t,n,r.ONE)}static fromBytes(e){const t=A.fromAffine(h(cl(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(pl("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(xm),this}assertValidity(){v(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){w(e);const{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(o,i)),l=r.eql(r.mul(n,a),r.mul(s,i));return c&&l}negate(){return new A(this.X,r.neg(this.Y),this.Z)}double(){const{a:e,b:t}=o,n=r.mul(t,xm),{X:i,Y:s,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),h=r.mul(s,s),g=r.mul(a,a),f=r.mul(i,s);return f=r.add(f,f),u=r.mul(i,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,g),l=r.add(c,l),c=r.sub(h,l),l=r.add(h,l),l=r.mul(c,l),c=r.mul(f,c),u=r.mul(n,u),g=r.mul(e,g),f=r.sub(d,g),f=r.mul(e,f),f=r.add(f,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,g),d=r.mul(d,f),l=r.add(l,d),g=r.mul(s,a),g=r.add(g,g),d=r.mul(g,f),c=r.sub(c,d),u=r.mul(g,h),u=r.add(u,u),u=r.add(u,u),new A(c,l,u)}add(e){w(e);const{X:t,Y:n,Z:i}=this,{X:s,Y:a,Z:c}=e;let l=r.ZERO,u=r.ZERO,d=r.ZERO;const h=o.a,g=r.mul(o.b,xm);let f=r.mul(t,s),p=r.mul(n,a),m=r.mul(i,c),y=r.add(t,n),b=r.add(s,a);y=r.mul(y,b),b=r.add(f,p),y=r.sub(y,b),b=r.add(t,i);let k=r.add(s,c);return b=r.mul(b,k),k=r.add(f,m),b=r.sub(b,k),k=r.add(n,i),l=r.add(a,c),k=r.mul(k,l),l=r.add(p,m),k=r.sub(k,l),d=r.mul(h,b),l=r.mul(g,m),d=r.add(l,d),l=r.sub(p,d),d=r.add(p,d),u=r.mul(l,d),p=r.add(f,f),p=r.add(p,f),m=r.mul(h,m),b=r.mul(g,b),p=r.add(p,m),m=r.sub(f,m),m=r.mul(h,m),b=r.add(b,m),f=r.mul(p,b),u=r.add(u,f),f=r.mul(k,b),l=r.mul(y,l),l=r.sub(l,f),f=r.mul(y,p),d=r.mul(k,d),d=r.add(d,f),new A(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:n}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let r,o;const s=e=>T.cached(this,e,e=>Yl(A,e));if(n){const{k1neg:t,k1:i,k2neg:a,k2:c}=b(e),{p:l,f:u}=s(i),{p:d,f:h}=s(c);o=u.add(h),r=S(n.beta,l,d,t,a)}else{const{p:t,f:n}=s(e);r=t,o=n}return Yl(A,[r,o])[0]}multiplyUnsafe(e){const{endo:n}=t,r=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Cm||r.is0())return A.ZERO;if(e===Nm)return r;if(T.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:i,k2neg:o,k2:s}=b(e),{p1:a,p2:c}=function(e,t,n,r){let i=t,o=e.ZERO,s=e.ZERO;for(;n>Vl||r>Vl;)n&Xl&&(o=o.add(i)),r&Xl&&(s=s.add(i)),i=i.double(),n>>=Xl,r>>=Xl;return{p1:o,p2:s}}(A,r,i,s);return S(n.beta,a,c,t,o)}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===Nm||(e?e(A,this):T.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Nm?this:e?e(A,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return al(e,"isCompressed"),this.assertValidity(),d(A,this,e)}toHex(e=!0){return gc(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 Yl(A,e)}static msm(e,t){return su(A,i,e,t)}static fromPrivateKey(e){return A.BASE.multiply(Pm(i,e))}}A.BASE=new A(o.Gx,o.Gy,r.ONE),A.ZERO=new A(r.ZERO,r.ONE,r.ZERO),A.Fp=r,A.Fn=i;const E=i.BITS,T=new ou(A,t.endo?Math.ceil(E/2):E);return A.BASE.precompute(8),A}function Rm(e){return Uint8Array.of(e?2:3)}function Mm(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Om(e,t={}){const{Fn:n}=e,r=t.randomBytes||Ic,i=Object.assign(Mm(e.Fp,n),{seed:jl(n.ORDER)});function o(e){try{return!!Pm(n,e)}catch(e){return!1}}function s(e=r(i.seed)){return function(e,t,n=!1){const r=e.length,i=zl(t),o=jl(t);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const s=Bl(n?hl(e):dl(e),t-El)+El;return n?fl(s,i):gl(s,i)}(cl(e,i.seed,"seed"),n.ORDER)}function a(t,r=!0){return e.BASE.multiply(Pm(n,t)).toBytes(r)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:r,publicKey:o,publicKeyUncompressed:s}=i;if(n.allowedLengths||r===o)return;const a=pl("key",t).length;return a===o||a===s}const l={isValidSecretKey:o,isValidPublicKey:function(t,n){const{publicKey:r,publicKeyUncompressed:o}=i;try{const i=t.length;return(!0!==n||i===r)&&((!1!==n||i===o)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:s,isValidPrivateKey:o,randomPrivateKey:s,normPrivateKeyToScalar:e=>Pm(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,r,i=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(r))throw new Error("second arg must be public key");const o=Pm(n,t);return e.fromHex(r).multiply(o).toBytes(i)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:i})}function Lm(e,t,n={}){sc(t),vl(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Ic,i=n.hmac||((e,...n)=>vm(t,e,Ac(...n))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g}=Om(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},p="compact";function m(e){return e>a>>Nm}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class w{constructor(e,t,n){this.r=y("r",e),this.s=y("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=p){let n;if(function(e,t){Am(t);const n=g.signature;cl(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=Im.toSig(cl(e));return new w(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const r=s.BYTES,i=e.subarray(0,r),o=e.subarray(r,2*r);return new w(s.fromBytes(i),s.fromBytes(o),n)}static fromHex(e,t){return this.fromBytes(vc(e),t)}addRecoveryBit(e){return new w(this.r,this.s,e)}recoverPublicKey(t){const n=o.ORDER,{r:r,s:i,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*_m<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?r+a:r;if(!o.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=o.toBytes(l),d=e.fromBytes(Ac(Rm(!(1&c)),u)),h=s.inv(l),g=k(pl("msgHash",t)),f=s.create(-g*h),p=s.create(i*h),m=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(p));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return m(this.s)}toBytes(e=p){if(Am(e),"der"===e)return vc(Im.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 Ac(Uint8Array.of(this.recovery),t,n)}return Ac(t,n)}toHex(e){return gc(this.toBytes(e))}assertValidity(){}static fromCompact(e){return w.fromBytes(pl("sig",e),"compact")}static fromDER(e){return w.fromBytes(pl("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 gc(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return gc(this.toBytes("compact"))}}const b=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=dl(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=kl(c);function S(e){return wl("num < 2^"+c,e,Cm,v),s.toBytes(e)}function A(e,n){return cl(e,void 0,"message"),n?cl(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:g,Point:e,sign:function(n,o,a={}){n=pl("message",n);const{seed:c,k2sig:l}=function(t,n,i){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");const{lowS:o,prehash:a,extraEntropy:c}=Em(i,f);t=A(t,a);const l=k(t),u=Pm(s,n),d=[S(u),S(l)];if(null!=c&&!1!==c){const e=!0===c?r(g.secretKey):c;d.push(pl("extraEntropy",e))}const h=Ac(...d),p=l;return{seed:h,k2sig:function(t){const n=b(t);if(!s.isValidNot0(n))return;const r=s.inv(n),i=e.BASE.multiply(n).toAffine(),a=s.create(i.x);if(a===Cm)return;const c=s.create(r*s.create(p+a*u));if(c===Cm)return;let l=(i.x===a?0:2)|Number(i.y&Nm),d=c;return o&&m(c)&&(d=s.neg(c),l^=1),new w(a,d,l)}}}(n,o,a);return function(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),i=e=>Uint8Array.of(e);let o=r(e),s=r(e),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},l=(...e)=>n(s,o,...e),u=(e=r(0))=>{s=l(i(0),e),o=l(),0!==e.length&&(s=l(i(1),e),o=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){o=l();const t=o.slice();n.push(t),e+=o.length}return Ac(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}(t.outputLen,s.BYTES,i)(c,l)},verify:function(t,n,r,i={}){const{lowS:o,prehash:a,format:c}=Em(i,f);if(r=pl("publicKey",r),n=A(pl("message",n),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||rc(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(pl("sig",e),"der")}catch(e){if(!(e instanceof Im.Err))throw e}if(!t)try{t=w.fromBytes(pl("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):w.fromBytes(pl("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(r);if(o&&l.hasHighS())return!1;const{r:i,s:a}=l,c=k(n),u=s.inv(a),d=s.create(c*u),h=s.create(i*u),g=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(g.is0())return!1;return s.create(g.x)===i}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:r}=Em(n,f);return t=A(t,r),w.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:w,hash:t})}function Um(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:Wl(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 Fm(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=Um(e);return function(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Hl(n.Fn.ORDER,n.Fn.BITS))})}(e,Lm(Bm(t,n),r,i))}const $m={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Km=BigInt(2);const Gm=Wl($m.p,{sqrt:function(e){const t=$m.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=Rl(u,n,t)*u%t,h=Rl(d,n,t)*u%t,g=Rl(h,Km,t)*l%t,f=Rl(g,i,t)*g%t,p=Rl(f,o,t)*f%t,m=Rl(p,a,t)*p%t,y=Rl(m,c,t)*m%t,w=Rl(y,a,t)*p%t,b=Rl(w,n,t)*u%t,k=Rl(b,s,t)*f%t,v=Rl(k,r,t)*l%t,S=Rl(v,Km,t);if(!Gm.eql(Gm.sqr(S),e))throw new Error("Cannot find square root");return S}}),Hm=function(e,t){const n=t=>Fm({...e,hash:t});return{...n(t),create:n}}({...$m,Fp:Gm,lowS:!0,endo:qm},rl);Iu.utils.randomPrivateKey;const Wm=()=>{const e=Iu.utils.randomPrivateKey(),t=zm(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),{publicKey:t,secretKey:n}},zm=Iu.getPublicKey;function jm(e){try{return Iu.ExtendedPoint.fromHex(e),!0}catch{return!1}}const Vm=Iu.verify,Xm=e=>tc.Buffer.isBuffer(e)?e:e instanceof Uint8Array?tc.Buffer.from(e.buffer,e.byteOffset,e.byteLength):tc.Buffer.from(e);class Qm{constructor(e){Object.assign(this,e)}encode(){return tc.Buffer.from(od.serialize(Ym,this))}static decode(e){return od.deserialize(Ym,this,e)}static decodeUnchecked(e){return od.deserializeUnchecked(Ym,this,e)}}const Ym=new Map;var Jm;const Zm=32;let ey=1;class ty extends Qm{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=Ku.decode(e);if(t.length!=Zm)throw new Error("Invalid public key input");this._bn=new Lu(t)}else this._bn=new Lu(e);if(this._bn.byteLength()>Zm)throw new Error("Invalid public key input")}}static unique(){const e=new ty(ey);return ey+=1,new ty(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Ku.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(tc.Buffer);if(e.length===Zm)return e;const t=tc.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=tc.Buffer.concat([e.toBuffer(),tc.Buffer.from(t),n.toBuffer()]),i=Gu(r);return new ty(i)}static createProgramAddressSync(e,t){let n=tc.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");n=tc.Buffer.concat([n,Xm(e)])}),n=tc.Buffer.concat([n,t.toBuffer(),tc.Buffer.from("ProgramDerivedAddress")]);const r=Gu(n);if(jm(r))throw new Error("Invalid seeds, address must fall off the curve");return new ty(r)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let n,r=255;for(;0!=r;){try{const i=e.concat(tc.Buffer.from([r]));n=this.createProgramAddressSync(i,t)}catch(e){if(e instanceof TypeError)throw e;r--;continue}return[n,r]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return jm(new ty(e).toBytes())}}Jm=ty,ty.default=new Jm("11111111111111111111111111111111"),Ym.set(ty,{kind:"struct",fields:[["_bn","u256"]]}),new ty("BPFLoader1111111111111111111111111111111111");const ny=1232;class ry extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(ry.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class iy 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(iy.prototype,"name",{value:"TransactionExpiredTimeoutError"});class oy extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(oy.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class sy{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 ay=(e="publicKey")=>cd.blob(32,e),cy=(e="string")=>{const t=cd.struct([cd.u32("length"),cd.u32("lengthPadding"),cd.blob(cd.offset(cd.u32(),-8),"chars")],e),n=t.decode.bind(t),r=t.encode.bind(t),i=t;return i.decode=(e,t)=>n(e,t).chars.toString(),i.encode=(e,t,n)=>{const i={chars:tc.Buffer.from(e,"utf8")};return r(i,t,n)},i.alloc=e=>cd.u32().span+cd.u32().span+tc.Buffer.from(e,"utf8").length,i};function ly(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 ly({layout:e},t[e.property]);return 0};let r=0;return e.layout.fields.forEach(e=>{r+=n(e)}),r}function uy(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 dy(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 hy(e,t){if(!e)throw new Error(t||"Assertion failed")}class gy{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const n=new Map,r=e=>{const t=e.toBase58();let r=n.get(t);return void 0===r&&(r={isSigner:!1,isWritable:!1,isInvoked:!1},n.set(t,r)),r},i=r(t);i.isSigner=!0,i.isWritable=!0;for(const t of e){r(t.programId).isInvoked=!0;for(const e of t.keys){const t=r(e.pubkey);t.isSigner||=e.isSigner,t.isWritable||=e.isWritable}}return new gy(t,n)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];hy(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),n=e.filter(([,e])=>e.isSigner&&!e.isWritable),r=e.filter(([,e])=>!e.isSigner&&e.isWritable),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),o={numRequiredSignatures:t.length+n.length,numReadonlySignedAccounts:n.length,numReadonlyUnsignedAccounts:i.length};{hy(t.length>0,"Expected at least one writable signer key");const[e]=t[0];hy(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new ty(e)),...n.map(([e])=>new ty(e)),...r.map(([e])=>new ty(e)),...i.map(([e])=>new ty(e))]]}extractTableLookup(e){const[t,n]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[r,i]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==r.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:r},{writable:n,readonly:i}]}drainKeysFoundInLookupTable(e,t){const n=new Array,r=new Array;for(const[i,o]of this.keyMetaMap.entries())if(t(o)){const t=new ty(i),o=e.findIndex(e=>e.equals(t));o>=0&&(hy(o<256,"Max lookup table index exceeded"),n.push(o),r.push(t),this.keyMetaMap.delete(i))}return[n,r]}}const fy="Reached end of buffer unexpectedly";function py(e){if(0===e.length)throw new Error(fy);return e.shift()}function my(e,...t){const[n]=t;if(2===t.length?n+(t[1]??0)>e.length:n>=e.length)throw new Error(fy);return e.splice(...t)}class yy{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 ty(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:Ku.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new sy(this.staticAccountKeys)}static compile(e){const t=gy.compile(e.instructions,e.payerKey),[n,r]=t.getMessageComponents(),i=new sy(r).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Ku.encode(e.data)}));return new yy({header:n,accountKeys:r,recentBlockhash:e.recentBlockhash,instructions:i})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];dy(t,e);const n=this.instructions.map(e=>{const{accounts:t,programIdIndex:n}=e,r=Array.from(Ku.decode(e.data));let i=[];dy(i,t.length);let o=[];return dy(o,r.length),{programIdIndex:n,keyIndicesCount:tc.Buffer.from(i),keyIndices:t,dataLength:tc.Buffer.from(o),data:r}});let r=[];dy(r,n.length);let i=tc.Buffer.alloc(ny);tc.Buffer.from(r).copy(i);let o=r.length;n.forEach(e=>{const t=cd.struct([cd.u8("programIdIndex"),cd.blob(e.keyIndicesCount.length,"keyIndicesCount"),cd.seq(cd.u8("keyIndex"),e.keyIndices.length,"keyIndices"),cd.blob(e.dataLength.length,"dataLength"),cd.seq(cd.u8("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=cd.struct([cd.blob(1,"numRequiredSignatures"),cd.blob(1,"numReadonlySignedAccounts"),cd.blob(1,"numReadonlyUnsignedAccounts"),cd.blob(t.length,"keyCount"),cd.seq(ay("key"),e,"keys"),ay("recentBlockhash")]),a={numRequiredSignatures:tc.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:tc.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:tc.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:tc.Buffer.from(t),keys:this.accountKeys.map(e=>Xm(e.toBytes())),recentBlockhash:Ku.decode(this.recentBlockhash)};let c=tc.Buffer.alloc(2048);const l=s.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const n=py(t);if(n!==(127&n))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const r=py(t),i=py(t),o=uy(t);let s=[];for(let e=0;e<o;e++){const e=my(t,0,Zm);s.push(new ty(tc.Buffer.from(e)))}const a=my(t,0,Zm),c=uy(t);let l=[];for(let e=0;e<c;e++){const e=py(t),n=my(t,0,uy(t)),r=my(t,0,uy(t)),i=Ku.encode(tc.Buffer.from(r));l.push({programIdIndex:e,accounts:n,data:i})}const u={header:{numRequiredSignatures:n,numReadonlySignedAccounts:r,numReadonlyUnsignedAccounts:i},recentBlockhash:Ku.encode(tc.Buffer.from(a)),accountKeys:s,instructions:l};return new yy(u)}}class wy{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 sy(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=gy.compile(e.instructions,e.payerKey),n=new Array,r={writable:new Array,readonly:new Array},i=e.addressLookupTableAccounts||[];for(const e of i){const i=t.extractTableLookup(e);if(void 0!==i){const[e,{writable:t,readonly:o}]=i;n.push(e),r.writable.push(...t),r.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new sy(s,r).compileInstructions(e.instructions);return new wy({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:n})}serialize(){const e=Array();dy(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),n=Array();dy(n,this.compiledInstructions.length);const r=this.serializeAddressTableLookups(),i=Array();dy(i,this.addressTableLookups.length);const o=cd.struct([cd.u8("prefix"),cd.struct([cd.u8("numRequiredSignatures"),cd.u8("numReadonlySignedAccounts"),cd.u8("numReadonlyUnsignedAccounts")],"header"),cd.blob(e.length,"staticAccountKeysLength"),cd.seq(ay(),this.staticAccountKeys.length,"staticAccountKeys"),ay("recentBlockhash"),cd.blob(n.length,"instructionsLength"),cd.blob(t.length,"serializedInstructions"),cd.blob(i.length,"addressTableLookupsLength"),cd.blob(r.length,"serializedAddressTableLookups")]),s=new Uint8Array(ny),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Ku.decode(this.recentBlockhash),instructionsLength:new Uint8Array(n),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:r},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(ny);for(const n of this.compiledInstructions){const r=Array();dy(r,n.accountKeyIndexes.length);const i=Array();dy(i,n.data.length);e+=cd.struct([cd.u8("programIdIndex"),cd.blob(r.length,"encodedAccountKeyIndexesLength"),cd.seq(cd.u8(),n.accountKeyIndexes.length,"accountKeyIndexes"),cd.blob(i.length,"encodedDataLength"),cd.blob(n.data.length,"data")]).encode({programIdIndex:n.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(r),accountKeyIndexes:n.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:n.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(ny);for(const n of this.addressTableLookups){const r=Array();dy(r,n.writableIndexes.length);const i=Array();dy(i,n.readonlyIndexes.length);e+=cd.struct([ay("accountKey"),cd.blob(r.length,"encodedWritableIndexesLength"),cd.seq(cd.u8(),n.writableIndexes.length,"writableIndexes"),cd.blob(i.length,"encodedReadonlyIndexesLength"),cd.seq(cd.u8(),n.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:n.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(r),writableIndexes:n.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:n.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const n=py(t),r=127&n;hy(n!==r,"Expected versioned message but received legacy message");hy(0===r,`Expected versioned message with version 0 but found version ${r}`);const i={numRequiredSignatures:py(t),numReadonlySignedAccounts:py(t),numReadonlyUnsignedAccounts:py(t)},o=[],s=uy(t);for(let e=0;e<s;e++)o.push(new ty(my(t,0,Zm)));const a=Ku.encode(my(t,0,Zm)),c=uy(t),l=[];for(let e=0;e<c;e++){const e=py(t),n=my(t,0,uy(t)),r=uy(t),i=new Uint8Array(my(t,0,r));l.push({programIdIndex:e,accountKeyIndexes:n,data:i})}const u=uy(t),d=[];for(let e=0;e<u;e++){const e=new ty(my(t,0,Zm)),n=my(t,0,uy(t)),r=my(t,0,uy(t));d.push({accountKey:e,writableIndexes:n,readonlyIndexes:r})}return new wy({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:l,addressTableLookups:d})}}let by=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const ky=tc.Buffer.alloc(64).fill(0);class vy{constructor(e){this.keys=void 0,this.programId=void 0,this.data=tc.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 Sy{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 vy(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,n;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length,this.feePayer)n=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");n=this.signatures[0].publicKey}for(let e=0;e<t.length;e++)if(void 0===t[e].programId)throw new Error(`Transaction instruction index ${e} has undefined program id`);const r=[],i=[];t.forEach(e=>{e.keys.forEach(e=>{i.push({...e})});const t=e.programId.toString();r.includes(t)||r.push(t)}),r.forEach(e=>{i.push({pubkey:new ty(e),isSigner:!1,isWritable:!1})});const o=[];i.forEach(e=>{const t=e.pubkey.toString(),n=o.findIndex(e=>e.pubkey.toString()===t);n>-1?(o[n].isWritable=o[n].isWritable||e.isWritable,o[n].isSigner=o[n].isSigner||e.isSigner):o.push(e)}),o.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=o.findIndex(e=>e.pubkey.equals(n));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:n,isSigner:!0,isWritable:!0});for(const e of this.signatures){const t=o.findIndex(t=>t.pubkey.equals(e.publicKey));if(!(t>-1))throw new Error(`unknown signer: ${e.publicKey.toString()}`);o[t].isSigner||(o[t].isSigner=!0)}let a=0,c=0,l=0;const u=[],d=[];o.forEach(({pubkey:e,isSigner:t,isWritable:n})=>{t?(u.push(e.toString()),a+=1,n||(c+=1)):(d.push(e.toString()),n||(l+=1))});const h=u.concat(d),g=t.map(e=>{const{data:t,programId:n}=e;return{programIdIndex:h.indexOf(n.toString()),accounts:e.keys.map(e=>h.indexOf(e.pubkey.toString())),data:Ku.encode(t)}});return g.forEach(e=>{hy(e.programIdIndex>=0),e.accounts.forEach(e=>hy(e>=0))}),new yy({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)=>Iu.sign(e,t.slice(0,32)))(n,e.secretKey);this._addSignature(e.publicKey,Xm(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){hy(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=tc.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const n={};for(const{signature:r,publicKey:i}of this.signatures)null===r?t&&(n.missing||=[]).push(i):Vm(r,e,i.toBytes())||(n.invalid||=[]).push(i);return n.invalid||n.missing?n:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:n}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),r=this.serializeMessage();if(n){const e=this._getMessageSignednessErrors(r,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(r)}_serialize(e){const{signatures:t}=this,n=[];dy(n,t.length);const r=n.length+64*t.length+e.length,i=tc.Buffer.alloc(r);return hy(t.length<256),tc.Buffer.from(n).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(hy(64===e.length,"signature has invalid length"),tc.Buffer.from(e).copy(i,n.length+64*t))}),e.copy(i,n.length+64*t.length),hy(i.length<=ny,`Transaction too large: ${i.length} > 1232`),i}get keys(){return hy(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return hy(1===this.instructions.length),this.instructions[0].programId}get data(){return hy(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const n=uy(t);let r=[];for(let e=0;e<n;e++){const e=my(t,0,64);r.push(Ku.encode(tc.Buffer.from(e)))}return Sy.populate(yy.from(t),r)}static populate(e,t=[]){const n=new Sy;return n.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(n.feePayer=e.accountKeys[0]),t.forEach((t,r)=>{const i={signature:t==Ku.encode(ky)?null:Ku.decode(t),publicKey:e.accountKeys[r]};n.signatures.push(i)}),e.instructions.forEach(t=>{const r=t.accounts.map(t=>{const r=e.accountKeys[t];return{pubkey:r,isSigner:n.signatures.some(e=>e.publicKey.toString()===r.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});n.instructions.push(new vy({keys:r,programId:e.accountKeys[t.programIdIndex],data:Ku.decode(t.data)}))}),n._message=e,n._json=n.toJSON(),n}}new ty("SysvarC1ock11111111111111111111111111111111"),new ty("SysvarEpochSchedu1e111111111111111111111111"),new ty("Sysvar1nstructions1111111111111111111111111");const Ay=new ty("SysvarRecentB1ockHashes11111111111111111111"),Ey=new ty("SysvarRent111111111111111111111111111111111");new ty("SysvarRewards111111111111111111111111111111"),new ty("SysvarS1otHashes111111111111111111111111111"),new ty("SysvarS1otHistory11111111111111111111111111"),new ty("SysvarStakeHistory1111111111111111111111111");class Ty extends Error{constructor({action:e,signature:t,transactionMessage:n,logs:r}){const i=r?`Logs: \n${JSON.stringify(r.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${n}. `+i+o;break;case"simulate":s=`Simulation failed. \nMessage: ${n}. \n`+i+o;break;default:s=`Unknown action '${e}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=n,this.transactionLogs=r||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,n)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const n=e.meta.logMessages;this.transactionLogs=n,t(n)}else n(new Error("Log messages not found"))}).catch(n)})),await this.transactionLogs}}class Iy 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 Cy(e){return new Promise(t=>setTimeout(t,e))}function Ny(e,t){const n=e.layout.span>=0?e.layout.span:ly(e,t),r=tc.Buffer.alloc(n),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,r),r}const _y=cd.nu64("lamportsPerSignature"),xy=cd.struct([cd.u32("version"),cd.u32("state"),ay("authorizedPubkey"),ay("nonce"),cd.struct([_y],"feeCalculator")]),Dy=xy.span;class Py{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=xy.decode(Xm(e),0);return new Py({authorizedPubkey:new ty(t.authorizedPubkey),nonce:new ty(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function By(e){const t=cd.blob(8,e),n=t.decode.bind(t),r=t.encode.bind(t),i=t,o=Pp();return i.decode=(e,t)=>{const r=n(e,t);return o.decode(r)},i.encode=(e,t,n)=>{const i=o.encode(e);return r(i,t,n)},i}const Ry=Object.freeze({Create:{index:0,layout:cd.struct([cd.u32("instruction"),cd.ns64("lamports"),cd.ns64("space"),ay("programId")])},Assign:{index:1,layout:cd.struct([cd.u32("instruction"),ay("programId")])},Transfer:{index:2,layout:cd.struct([cd.u32("instruction"),By("lamports")])},CreateWithSeed:{index:3,layout:cd.struct([cd.u32("instruction"),ay("base"),cy("seed"),cd.ns64("lamports"),cd.ns64("space"),ay("programId")])},AdvanceNonceAccount:{index:4,layout:cd.struct([cd.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:cd.struct([cd.u32("instruction"),cd.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:cd.struct([cd.u32("instruction"),ay("authorized")])},AuthorizeNonceAccount:{index:7,layout:cd.struct([cd.u32("instruction"),ay("authorized")])},Allocate:{index:8,layout:cd.struct([cd.u32("instruction"),cd.ns64("space")])},AllocateWithSeed:{index:9,layout:cd.struct([cd.u32("instruction"),ay("base"),cy("seed"),cd.ns64("space"),ay("programId")])},AssignWithSeed:{index:10,layout:cd.struct([cd.u32("instruction"),ay("base"),cy("seed"),ay("programId")])},TransferWithSeed:{index:11,layout:cd.struct([cd.u32("instruction"),By("lamports"),cy("seed"),ay("programId")])},UpgradeNonceAccount:{index:12,layout:cd.struct([cd.u32("instruction")])}});class My{constructor(){}static createAccount(e){const t=Ny(Ry.Create,{lamports:e.lamports,space:e.space,programId:Xm(e.programId.toBuffer())});return new vy({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,n;if("basePubkey"in e){t=Ny(Ry.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:Xm(e.programId.toBuffer())}),n=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=Ny(Ry.Transfer,{lamports:BigInt(e.lamports)}),n=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new vy({keys:n,programId:this.programId,data:t})}static assign(e){let t,n;if("basePubkey"in e){t=Ny(Ry.AssignWithSeed,{base:Xm(e.basePubkey.toBuffer()),seed:e.seed,programId:Xm(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Ny(Ry.Assign,{programId:Xm(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new vy({keys:n,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Ny(Ry.CreateWithSeed,{base:Xm(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:Xm(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 vy({keys:n,programId:this.programId,data:t})}static createNonceAccount(e){const t=new Sy;"basePubkey"in e&&"seed"in e?t.add(My.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Dy,programId:this.programId})):t.add(My.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Dy,programId:this.programId}));const n={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(n)),t}static nonceInitialize(e){const t=Ny(Ry.InitializeNonceAccount,{authorized:Xm(e.authorizedPubkey.toBuffer())}),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Ay,isSigner:!1,isWritable:!1},{pubkey:Ey,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new vy(n)}static nonceAdvance(e){const t=Ny(Ry.AdvanceNonceAccount),n={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:Ay,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new vy(n)}static nonceWithdraw(e){const t=Ny(Ry.WithdrawNonceAccount,{lamports:e.lamports});return new vy({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:Ay,isSigner:!1,isWritable:!1},{pubkey:Ey,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Ny(Ry.AuthorizeNonceAccount,{authorized:Xm(e.newAuthorizedPubkey.toBuffer())});return new vy({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,n;if("basePubkey"in e){t=Ny(Ry.AllocateWithSeed,{base:Xm(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:Xm(e.programId.toBuffer())}),n=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Ny(Ry.Allocate,{space:e.space}),n=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new vy({keys:n,programId:this.programId,data:t})}}function Oy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ly,Uy;function Fy(){if(Uy)return Ly;Uy=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};function n(r,i){var o,s,a,c,l,u,d;if(!0===r)return"true";if(!1===r)return"false";switch(typeof r){case"object":if(null===r)return null;if(r.toJSON&&"function"==typeof r.toJSON)return n(r.toJSON(),i);if("[object Array]"===(d=e.call(r))){for(a="[",s=r.length-1,o=0;o<s;o++)a+=n(r[o],!0)+",";return s>-1&&(a+=n(r[o],!0)),a+"]"}if("[object Object]"===d){for(s=(c=t(r).sort()).length,a="",o=0;o<s;)void 0!==(u=n(r[l=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),o++;return"{"+a+"}"}return JSON.stringify(r);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return Ly=function(e){var t=n(e,!1);if(void 0!==t)return""+t}}My.programId=new ty("11111111111111111111111111111111"),new ty("BPFLoader2111111111111111111111111111111111");var $y=Oy(Fy());function qy(e){let t=0;for(;e>1;)e/=2,t++;return t}class Ky{constructor(e,t,n,r,i){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=n,this.firstNormalEpoch=r,this.firstNormalSlot=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=qy(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)))-qy(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+qy(32)):this.slotsPerEpoch}}var Gy=globalThis.fetch;class Hy extends bm{constructor(e,t,n){super(e=>{const n=function(e,t){return new ym(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in n?n.socket:n,n},e,t,n),this.underlyingSocket=void 0}call(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}notify(...e){const t=this.underlyingSocket?.readyState;return 1===t?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+t+")"))}}class Wy{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let n;try{n=e.layout.decode(t)}catch(e){throw new Error("invalid instruction; "+e)}if(n.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${n.typeIndex} != ${e.index}`);return n}(zy,e),n=e.length-56;hy(n>=0,"lookup table is invalid"),hy(n%32==0,"lookup table is invalid");const r=n/32,{addresses:i}=cd.struct([cd.seq(ay(),r,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new ty(t.authority[0]):void 0,addresses:i.map(e=>new ty(e))}}}const zy={index:1,layout:cd.struct([cd.u32("typeIndex"),By("deactivationSlot"),cd.nu64("lastExtendedSlot"),cd.u8("lastExtendedStartIndex"),cd.u8(),cd.seq(ay(),cd.offset(cd.u8(),-1),"authority")])},jy=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const Vy=im(jp(ty),Zp(),e=>new ty(e)),Xy=em([Zp(),Vp("base64")]),Qy=im(jp(tc.Buffer),Xy,e=>tc.Buffer.from(e[0],"base64"));function Yy(e){let t,n;if("string"==typeof e)t=e;else if(e){const{commitment:r,...i}=e;t=r,n=i}return{commitment:t,config:n}}function Jy(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function Zy(e){return nm([tm({jsonrpc:Vp("2.0"),id:Zp(),result:e}),tm({jsonrpc:Vp("2.0"),id:Zp(),error:tm({code:rm(),message:Zp(),data:Yp(Hp("any",()=>!0))})})])}const ew=Zy(rm());function tw(e){return im(Zy(e),ew,t=>"error"in t?t:{...t,result:qp(t.result,e)})}function nw(e){return tw(tm({context:tm({slot:Qp()}),value:e}))}function rw(e){return tm({context:tm({slot:Qp()}),value:e})}function iw(e,t){return 0===e?new wy({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new ty(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Ku.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new yy(t)}const ow=tm({foundation:Qp(),foundationTerm:Qp(),initial:Qp(),taper:Qp(),terminal:Qp()}),sw=tw(Wp(Xp(tm({epoch:Qp(),effectiveSlot:Qp(),amount:Qp(),postBalance:Qp(),commission:Yp(Xp(Qp()))})))),aw=Wp(tm({slot:Qp(),prioritizationFee:Qp()})),cw=tm({total:Qp(),validator:Qp(),foundation:Qp(),epoch:Qp()}),lw=tm({epoch:Qp(),slotIndex:Qp(),slotsInEpoch:Qp(),absoluteSlot:Qp(),blockHeight:Yp(Qp()),transactionCount:Yp(Qp())}),uw=tm({slotsPerEpoch:Qp(),leaderScheduleSlotOffset:Qp(),warmup:zp(),firstNormalEpoch:Qp(),firstNormalSlot:Qp()}),dw=Jp(Zp(),Wp(Qp())),hw=Xp(nm([tm({}),Zp()])),gw=tm({err:hw}),fw=Vp("receivedSignature"),pw=tm({"solana-core":Zp(),"feature-set":Yp(Qp())}),mw=tm({program:Zp(),programId:Vy,parsed:rm()}),yw=tm({programId:Vy,accounts:Wp(Vy),data:Zp()}),ww=nw(tm({err:Xp(nm([tm({}),Zp()])),logs:Xp(Wp(Zp())),accounts:Yp(Xp(Wp(Xp(tm({executable:zp(),owner:Zp(),lamports:Qp(),data:Wp(Zp()),rentEpoch:Yp(Qp())}))))),unitsConsumed:Yp(Qp()),returnData:Yp(Xp(tm({programId:Zp(),data:em([Zp(),Vp("base64")])}))),innerInstructions:Yp(Xp(Wp(tm({index:Qp(),instructions:Wp(nm([mw,yw]))}))))})),bw=nw(tm({byIdentity:Jp(Zp(),Wp(Qp())),range:tm({firstSlot:Qp(),lastSlot:Qp()})}));const kw=tw(ow),vw=tw(cw),Sw=tw(aw),Aw=tw(lw),Ew=tw(uw),Tw=tw(dw),Iw=tw(Qp()),Cw=nw(tm({total:Qp(),circulating:Qp(),nonCirculating:Qp(),nonCirculatingAccounts:Wp(Vy)})),Nw=tm({amount:Zp(),uiAmount:Xp(Qp()),decimals:Qp(),uiAmountString:Yp(Zp())}),_w=nw(Wp(tm({address:Vy,amount:Zp(),uiAmount:Xp(Qp()),decimals:Qp(),uiAmountString:Yp(Zp())}))),xw=nw(Wp(tm({pubkey:Vy,account:tm({executable:zp(),owner:Vy,lamports:Qp(),data:Qy,rentEpoch:Qp()})}))),Dw=tm({program:Zp(),parsed:rm(),space:Qp()}),Pw=nw(Wp(tm({pubkey:Vy,account:tm({executable:zp(),owner:Vy,lamports:Qp(),data:Dw,rentEpoch:Qp()})}))),Bw=nw(Wp(tm({lamports:Qp(),address:Vy}))),Rw=tm({executable:zp(),owner:Vy,lamports:Qp(),data:Qy,rentEpoch:Qp()}),Mw=tm({pubkey:Vy,account:Rw}),Ow=im(nm([jp(tc.Buffer),Dw]),nm([Xy,Dw]),e=>Array.isArray(e)?qp(e,Qy):e),Lw=tm({executable:zp(),owner:Vy,lamports:Qp(),data:Ow,rentEpoch:Qp()}),Uw=tm({pubkey:Vy,account:Lw}),Fw=tm({state:nm([Vp("active"),Vp("inactive"),Vp("activating"),Vp("deactivating")]),active:Qp(),inactive:Qp()}),$w=tw(Wp(tm({signature:Zp(),slot:Qp(),err:hw,memo:Xp(Zp()),blockTime:Yp(Xp(Qp()))}))),qw=tw(Wp(tm({signature:Zp(),slot:Qp(),err:hw,memo:Xp(Zp()),blockTime:Yp(Xp(Qp()))}))),Kw=tm({subscription:Qp(),result:rw(Rw)}),Gw=tm({pubkey:Vy,account:Rw}),Hw=tm({subscription:Qp(),result:rw(Gw)}),Ww=tm({parent:Qp(),slot:Qp(),root:Qp()}),zw=tm({subscription:Qp(),result:Ww}),jw=nm([tm({type:nm([Vp("firstShredReceived"),Vp("completed"),Vp("optimisticConfirmation"),Vp("root")]),slot:Qp(),timestamp:Qp()}),tm({type:Vp("createdBank"),parent:Qp(),slot:Qp(),timestamp:Qp()}),tm({type:Vp("frozen"),slot:Qp(),timestamp:Qp(),stats:tm({numTransactionEntries:Qp(),numSuccessfulTransactions:Qp(),numFailedTransactions:Qp(),maxTransactionsPerEntry:Qp()})}),tm({type:Vp("dead"),slot:Qp(),timestamp:Qp(),err:Zp()})]),Vw=tm({subscription:Qp(),result:jw}),Xw=tm({subscription:Qp(),result:rw(nm([gw,fw]))}),Qw=tm({subscription:Qp(),result:Qp()}),Yw=tm({pubkey:Zp(),gossip:Xp(Zp()),tpu:Xp(Zp()),rpc:Xp(Zp()),version:Xp(Zp())}),Jw=tm({votePubkey:Zp(),nodePubkey:Zp(),activatedStake:Qp(),epochVoteAccount:zp(),epochCredits:Wp(em([Qp(),Qp(),Qp()])),commission:Qp(),lastVote:Qp(),rootSlot:Xp(Qp())}),Zw=tw(tm({current:Wp(Jw),delinquent:Wp(Jw)})),eb=nm([Vp("processed"),Vp("confirmed"),Vp("finalized")]),tb=tm({slot:Qp(),confirmations:Xp(Qp()),err:hw,confirmationStatus:Yp(eb)}),nb=nw(Wp(Xp(tb))),rb=tw(Qp()),ib=tm({accountKey:Vy,writableIndexes:Wp(Qp()),readonlyIndexes:Wp(Qp())}),ob=tm({signatures:Wp(Zp()),message:tm({accountKeys:Wp(Zp()),header:tm({numRequiredSignatures:Qp(),numReadonlySignedAccounts:Qp(),numReadonlyUnsignedAccounts:Qp()}),instructions:Wp(tm({accounts:Wp(Qp()),data:Zp(),programIdIndex:Qp()})),recentBlockhash:Zp(),addressTableLookups:Yp(Wp(ib))})}),sb=tm({pubkey:Vy,signer:zp(),writable:zp(),source:Yp(nm([Vp("transaction"),Vp("lookupTable")]))}),ab=tm({accountKeys:Wp(sb),signatures:Wp(Zp())}),cb=tm({parsed:rm(),program:Zp(),programId:Vy}),lb=tm({accounts:Wp(Vy),data:Zp(),programId:Vy}),ub=im(nm([lb,cb]),nm([tm({parsed:rm(),program:Zp(),programId:Zp()}),tm({accounts:Wp(Zp()),data:Zp(),programId:Zp()})]),e=>qp(e,"accounts"in e?lb:cb)),db=tm({signatures:Wp(Zp()),message:tm({accountKeys:Wp(sb),instructions:Wp(ub),recentBlockhash:Zp(),addressTableLookups:Yp(Xp(Wp(ib)))})}),hb=tm({accountIndex:Qp(),mint:Zp(),owner:Yp(Zp()),programId:Yp(Zp()),uiTokenAmount:Nw}),gb=tm({writable:Wp(Vy),readonly:Wp(Vy)}),fb=tm({err:hw,fee:Qp(),innerInstructions:Yp(Xp(Wp(tm({index:Qp(),instructions:Wp(tm({accounts:Wp(Qp()),data:Zp(),programIdIndex:Qp()}))})))),preBalances:Wp(Qp()),postBalances:Wp(Qp()),logMessages:Yp(Xp(Wp(Zp()))),preTokenBalances:Yp(Xp(Wp(hb))),postTokenBalances:Yp(Xp(Wp(hb))),loadedAddresses:Yp(gb),computeUnitsConsumed:Yp(Qp()),costUnits:Yp(Qp())}),pb=tm({err:hw,fee:Qp(),innerInstructions:Yp(Xp(Wp(tm({index:Qp(),instructions:Wp(ub)})))),preBalances:Wp(Qp()),postBalances:Wp(Qp()),logMessages:Yp(Xp(Wp(Zp()))),preTokenBalances:Yp(Xp(Wp(hb))),postTokenBalances:Yp(Xp(Wp(hb))),loadedAddresses:Yp(gb),computeUnitsConsumed:Yp(Qp()),costUnits:Yp(Qp())}),mb=nm([Vp(0),Vp("legacy")]),yb=tm({pubkey:Zp(),lamports:Qp(),postBalance:Xp(Qp()),rewardType:Xp(Zp()),commission:Yp(Xp(Qp()))}),wb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),transactions:Wp(tm({transaction:ob,meta:Xp(fb),version:Yp(mb)})),rewards:Yp(Wp(yb)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),bb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),rewards:Yp(Wp(yb)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),kb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),transactions:Wp(tm({transaction:ab,meta:Xp(fb),version:Yp(mb)})),rewards:Yp(Wp(yb)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),vb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),transactions:Wp(tm({transaction:db,meta:Xp(pb),version:Yp(mb)})),rewards:Yp(Wp(yb)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Sb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),transactions:Wp(tm({transaction:ab,meta:Xp(pb),version:Yp(mb)})),rewards:Yp(Wp(yb)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Ab=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),rewards:Yp(Wp(yb)),blockTime:Xp(Qp()),blockHeight:Xp(Qp())}))),Eb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),transactions:Wp(tm({transaction:ob,meta:Xp(fb)})),rewards:Yp(Wp(yb)),blockTime:Xp(Qp())}))),Tb=tw(Xp(tm({blockhash:Zp(),previousBlockhash:Zp(),parentSlot:Qp(),signatures:Wp(Zp()),blockTime:Xp(Qp())}))),Ib=tw(Xp(tm({slot:Qp(),meta:Xp(fb),blockTime:Yp(Xp(Qp())),transaction:ob,version:Yp(mb)}))),Cb=tw(Xp(tm({slot:Qp(),transaction:db,meta:Xp(pb),blockTime:Yp(Xp(Qp())),version:Yp(mb)}))),Nb=nw(tm({blockhash:Zp(),lastValidBlockHeight:Qp()})),_b=nw(zp()),xb=tw(Wp(tm({slot:Qp(),numTransactions:Qp(),numSlots:Qp(),samplePeriodSecs:Qp()}))),Db=nw(Xp(tm({feeCalculator:tm({lamportsPerSignature:Qp()})}))),Pb=tw(Zp()),Bb=tw(Zp()),Rb=tm({err:hw,logs:Wp(Zp()),signature:Zp()}),Mb=tm({result:rw(Rb),subscription:Qp()}),Ob={"solana-client":"js/1.0.0-maintenance"};class Lb{constructor(e,t){let n,r,i,o,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:n,config:r}=Yy(t),i=this._buildArgs([],n,void 0,r),o=$y(i);return e[o]=e[o]??(async()=>{try{const e=qp(await this._rpcRequest("getBlockHeight",i),tw(Qp()));if("error"in e)throw new Iy(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,n=t.wsEndpoint,r=t.httpHeaders,i=t.fetch,o=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=n||function(e){const t=e.match(jy);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[n,r,i,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${s}//${r}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,n,r,i){const o=n||Gy;let s;return r&&(s=async(e,t)=>{const n=await new Promise((n,i)=>{try{r(e,t,(e,t)=>n([e,t]))}catch(e){i(e)}});return await o(...n)}),new gm(async(n,r)=>{const a={method:"POST",body:n,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},Ob)};try{let t,n=5,c=500;for(;t=s?await s(e,a):await o(e,a),429===t.status&&!0!==i&&(n-=1,0!==n);)await Cy(c),c*=2;const l=await t.text();t.ok?r(null,l):r(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(e){e instanceof Error&&r(e)}},{})}(e,r,i,o,s),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((n,r)=>{c.request(e,t,(e,t)=>{e?r(e):n(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((n,r)=>{0===t.length&&n([]);const i=t.map(t=>e.request(t.methodName,t.args));e.request(i,(e,t)=>{e?r(e):n(t)})})}(this._rpcClient),this._rpcWebSocket=new Hy(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgs([e.toBase58()],n,void 0,r),o=qp(await this._rpcRequest("getBalance",i),nw(Qp()));if("error"in o)throw new Iy(o.error,`failed to get balance for ${e.toBase58()}`);return o.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=qp(await this._rpcRequest("getBlockTime",[e]),tw(Xp(Qp())));if("error"in t)throw new Iy(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=qp(await this._rpcRequest("minimumLedgerSlot",[]),tw(Qp()));if("error"in e)throw new Iy(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=qp(await this._rpcRequest("getFirstAvailableBlock",[]),Iw);if("error"in e)throw new Iy(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=qp(await this._rpcRequest("getSupply",[t]),Cw);if("error"in n)throw new Iy(n.error,"failed to get supply");return n.result}async getTokenSupply(e,t){const n=this._buildArgs([e.toBase58()],t),r=qp(await this._rpcRequest("getTokenSupply",n),nw(Nw));if("error"in r)throw new Iy(r.error,"failed to get token supply");return r.result}async getTokenAccountBalance(e,t){const n=this._buildArgs([e.toBase58()],t),r=qp(await this._rpcRequest("getTokenAccountBalance",n),nw(Nw));if("error"in r)throw new Iy(r.error,"failed to get token account balance");return r.result}async getTokenAccountsByOwner(e,t,n){const{commitment:r,config:i}=Yy(n);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,r,"base64",i),a=qp(await this._rpcRequest("getTokenAccountsByOwner",s),xw);if("error"in a)throw new Iy(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,n){let r=[e.toBase58()];"mint"in t?r.push({mint:t.mint.toBase58()}):r.push({programId:t.programId.toBase58()});const i=this._buildArgs(r,n,"jsonParsed"),o=qp(await this._rpcRequest("getTokenAccountsByOwner",i),Pw);if("error"in o)throw new Iy(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},n=t.filter||t.commitment?[t]:[],r=qp(await this._rpcRequest("getLargestAccounts",n),Bw);if("error"in r)throw new Iy(r.error,"failed to get largest accounts");return r.result}async getTokenLargestAccounts(e,t){const n=this._buildArgs([e.toBase58()],t),r=qp(await this._rpcRequest("getTokenLargestAccounts",n),_w);if("error"in r)throw new Iy(r.error,"failed to get token largest accounts");return r.result}async getAccountInfoAndContext(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgs([e.toBase58()],n,"base64",r),o=qp(await this._rpcRequest("getAccountInfo",i),nw(Xp(Rw)));if("error"in o)throw new Iy(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=qp(await this._rpcRequest("getAccountInfo",i),nw(Xp(Lw)));if("error"in o)throw new Iy(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(t){throw new Error("failed to get info about account "+e.toBase58()+": "+t)}}async getMultipleParsedAccounts(e,t){const{commitment:n,config:r}=Yy(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"jsonParsed",r),s=qp(await this._rpcRequest("getMultipleAccounts",o),nw(Wp(Xp(Lw))));if("error"in s)throw new Iy(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:n,config:r}=Yy(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],n,"base64",r),s=qp(await this._rpcRequest("getMultipleAccounts",o),nw(Wp(Xp(Rw))));if("error"in s)throw new Iy(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,n){const{commitment:r,config:i}=Yy(t),o=this._buildArgs([e.toBase58()],r,void 0,{...i,epoch:null!=n?n:i?.epoch}),s=qp(await this._rpcRequest("getStakeActivation",o),tw(Fw));if("error"in s)throw new Iy(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:n,config:r}=Yy(t),{encoding:i,...o}=r||{},s=this._buildArgs([e.toBase58()],n,i||"base64",{...o,...o.filters?{filters:Jy(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Wp(Mw),l=!0===o.withContext?qp(a,nw(c)):qp(a,tw(c));if("error"in l)throw new Iy(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgs([e.toBase58()],n,"jsonParsed",r),o=qp(await this._rpcRequest("getProgramAccounts",i),tw(Wp(Uw)));if("error"in o)throw new Iy(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.result}async confirmTransaction(e,t){let n,r;if("string"==typeof e)n=e;else{const t=e;if(t.abortSignal?.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{r=Ku.decode(n)}catch(e){throw new Error("signature must be base58 encoded: "+n)}return hy(64===r.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,n)=>{null!=e&&(e.aborted?n(e.reason):e.addEventListener("abort",()=>{n(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let n,r,i=!1;return{abortConfirmation:()=>{r&&(r(),r=void 0),null!=n&&(this.removeSignatureListener(n),n=void 0)},confirmationPromise:new Promise((o,s)=>{try{n=this.onSignature(t,(e,t)=>{n=void 0;const r={context:t,value:e};o({__type:by.PROCESSED,response:r})},e);const a=new Promise(e=>{null==n?e():r=this._onSubscriptionStateChange(n,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,i)return;const n=await this.getSignatureStatus(t);if(i)return;if(null==n)return;const{context:r,value:c}=n;if(null!=c)if(c?.err)s(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}i=!0,o({__type:by.PROCESSED,response:{context:r,value:c}})}})()}catch(e){s(e)}})}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:n,signature:r}}){let i=!1;const o=new Promise(t=>{const r=async()=>{try{return await this.getBlockHeight(e)}catch(e){return-1}};(async()=>{let e=await r();if(!i){for(;e<=n;){if(await Cy(1e3),i)return;if(e=await r(),i)return}t({__type:by.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:r}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,o]);if(e.__type!==by.PROCESSED)throw new ry(r);l=e.response}finally{i=!0,s()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:n,nonceAccountPubkey:r,nonceValue:i,signature:o}}){let s=!1;const a=new Promise(t=>{let o=i,a=null;const c=async()=>{try{const{context:t,value:i}=await this.getNonceAndContext(r,{commitment:e,minContextSlot:n});return a=t.slot,i?.nonce}catch(e){return o}};(async()=>{if(o=await c(),!s)for(;;){if(i!==o)return void t({__type:by.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Cy(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),u=this.getCancellationPromise(t);let d;try{const t=await Promise.race([u,l,a]);if(t.__type===by.PROCESSED)d=t.response;else{let r;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??n))){r=e;break}await Cy(400)}if(!r?.value)throw new oy(o);{const t=e||"finalized",{confirmationStatus:n}=r.value;switch(t){case"processed":case"recent":if("processed"!==n&&"confirmed"!==n&&"finalized"!==n)throw new oy(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==n&&"finalized"!==n)throw new oy(o);break;case"finalized":case"max":case"root":if("finalized"!==n)throw new oy(o)}d={context:r.context,value:{err:r.value.err}}}}}finally{s=!0,c()}return d}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let n;const r=new Promise(t=>{let r=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":r=this._confirmTransactionInitialTimeout||3e4}n=setTimeout(()=>t({__type:by.TIMED_OUT,timeoutMs:r}),r)}),{abortConfirmation:i,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,r]);if(e.__type!==by.PROCESSED)throw new iy(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(n),i()}return s}async getClusterNodes(){const e=qp(await this._rpcRequest("getClusterNodes",[]),tw(Wp(Yw)));if("error"in e)throw new Iy(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),n=qp(await this._rpcRequest("getVoteAccounts",t),Zw);if("error"in n)throw new Iy(n.error,"failed to get vote accounts");return n.result}async getSlot(e){const{commitment:t,config:n}=Yy(e),r=this._buildArgs([],t,void 0,n),i=qp(await this._rpcRequest("getSlot",r),tw(Qp()));if("error"in i)throw new Iy(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:n}=Yy(e),r=this._buildArgs([],t,void 0,n),i=qp(await this._rpcRequest("getSlotLeader",r),tw(Zp()));if("error"in i)throw new Iy(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const n=[e,t],r=qp(await this._rpcRequest("getSlotLeaders",n),tw(Wp(Vy)));if("error"in r)throw new Iy(r.error,"failed to get slot leaders");return r.result}async getSignatureStatus(e,t){const{context:n,value:r}=await this.getSignatureStatuses([e],t);hy(1===r.length);return{context:n,value:r[0]}}async getSignatureStatuses(e,t){const n=[e];t&&n.push(t);const r=qp(await this._rpcRequest("getSignatureStatuses",n),nb);if("error"in r)throw new Iy(r.error,"failed to get signature status");return r.result}async getTransactionCount(e){const{commitment:t,config:n}=Yy(e),r=this._buildArgs([],t,void 0,n),i=qp(await this._rpcRequest("getTransactionCount",r),tw(Qp()));if("error"in i)throw new Iy(i.error,"failed to get transaction count");return i.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),n=qp(await this._rpcRequest("getInflationGovernor",t),kw);if("error"in n)throw new Iy(n.error,"failed to get inflation");return n.result}async getInflationReward(e,t,n){const{commitment:r,config:i}=Yy(n),o=this._buildArgs([e.map(e=>e.toBase58())],r,void 0,{...i,epoch:null!=t?t:i?.epoch}),s=qp(await this._rpcRequest("getInflationReward",o),sw);if("error"in s)throw new Iy(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=qp(await this._rpcRequest("getInflationRate",[]),vw);if("error"in e)throw new Iy(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:n}=Yy(e),r=this._buildArgs([],t,void 0,n),i=qp(await this._rpcRequest("getEpochInfo",r),Aw);if("error"in i)throw new Iy(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=qp(await this._rpcRequest("getEpochSchedule",[]),Ew);if("error"in e)throw new Iy(e.error,"failed to get epoch schedule");const t=e.result;return new Ky(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=qp(await this._rpcRequest("getLeaderSchedule",[]),Tw);if("error"in e)throw new Iy(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const n=this._buildArgs([e],t),r=qp(await this._rpcRequest("getMinimumBalanceForRentExemption",n),rb);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=qp(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),xb);if("error"in t)throw new Iy(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const n=this._buildArgs([e],t),r=qp(await this._rpcRequest("getFeeCalculatorForBlockhash",n),Db);if("error"in r)throw new Iy(r.error,"failed to get fee calculator");const{context:i,value:o}=r.result;return{context:i,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const n=Xm(e.serialize()).toString("base64"),r=this._buildArgs([n],t),i=qp(await this._rpcRequest("getFeeForMessage",r),nw(Xp(Qp())));if("error"in i)throw new Iy(i.error,"failed to get fee for message");if(null===i.result)throw new Error("invalid blockhash");return i.result}async getRecentPrioritizationFees(e){const t=e?.lockedWritableAccounts?.map(e=>e.toBase58()),n=t?.length?[t]:[],r=qp(await this._rpcRequest("getRecentPrioritizationFees",n),Sw);if("error"in r)throw new Iy(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}=Yy(e),r=this._buildArgs([],t,void 0,n),i=qp(await this._rpcRequest("getLatestBlockhash",r),Nb);if("error"in i)throw new Iy(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgs([e],n,void 0,r),o=qp(await this._rpcRequest("isBlockhashValid",i),_b);if("error"in o)throw new Iy(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=qp(await this._rpcRequest("getVersion",[]),tw(pw));if("error"in e)throw new Iy(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=qp(await this._rpcRequest("getGenesisHash",[]),tw(Zp()));if("error"in e)throw new Iy(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=qp(o,kb);if("error"in e)throw e.error;return e.result}case"none":{const e=qp(o,bb);if("error"in e)throw e.error;return e.result}default:{const e=qp(o,wb);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:iw(n,e.message)},version:n}))}:null}}}catch(e){throw new Iy(e,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=await this._rpcRequest("getBlock",i);try{switch(r?.transactionDetails){case"accounts":{const e=qp(o,Sb);if("error"in e)throw e.error;return e.result}case"none":{const e=qp(o,Ab);if("error"in e)throw e.error;return e.result}default:{const e=qp(o,vb);if("error"in e)throw e.error;return e.result}}}catch(e){throw new Iy(e,"failed to get block")}}async getBlockProduction(e){let t,n;if("string"==typeof e)n=e;else if(e){const{commitment:r,...i}=e;n=r,t=i}const r=this._buildArgs([],n,"base64",t),i=qp(await this._rpcRequest("getBlockProduction",r),bw);if("error"in i)throw new Iy(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgsAtLeastConfirmed([e],n,void 0,r),o=qp(await this._rpcRequest("getTransaction",i),Ib);if("error"in o)throw new Iy(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:iw(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:n,config:r}=Yy(t),i=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r),o=qp(await this._rpcRequest("getTransaction",i),Cb);if("error"in o)throw new Iy(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:n,config:r}=Yy(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,"jsonParsed",r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=qp(e,Cb);if("error"in t)throw new Iy(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:n,config:r}=Yy(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],n,void 0,r)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=qp(e,Ib);if("error"in t)throw new Iy(t.error,"failed to get transactions");const n=t.result;return n?{...n,transaction:{...n.transaction,message:iw(n.version,n.transaction.message)}}:n})}async getConfirmedBlock(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=qp(await this._rpcRequest("getBlock",n),Eb);if("error"in r)throw new Iy(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");const o={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const n=new yy(e.message);return{meta:t,transaction:{...e,message:n}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:Sy.populate(e.message,e.signatures)}))}}async getBlocks(e,t,n){const r=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],n),i=qp(await this._rpcRequest("getBlocks",r),tw(Wp(Qp())));if("error"in i)throw new Iy(i.error,"failed to get blocks");return i.result}async getBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=qp(await this._rpcRequest("getBlock",n),Tb);if("error"in r)throw new Iy(r.error,"failed to get block");const i=r.result;if(!i)throw new Error("Block "+e+" not found");return i}async getConfirmedBlockSignatures(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),r=qp(await this._rpcRequest("getBlock",n),Tb);if("error"in r)throw new Iy(r.error,"failed to get confirmed block");const i=r.result;if(!i)throw new Error("Confirmed block "+e+" not found");return i}async getConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t),r=qp(await this._rpcRequest("getTransaction",n),Ib);if("error"in r)throw new Iy(r.error,"failed to get transaction");const i=r.result;if(!i)return i;const o=new yy(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:Sy.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const n=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),r=qp(await this._rpcRequest("getTransaction",n),Cb);if("error"in r)throw new Iy(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=qp(e,Cb);if("error"in t)throw new Iy(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,n){let r={},i=await this.getFirstAvailableBlock();for(;!("until"in r)&&!(--t<=0||t<i);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(r.until=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}let o=await this.getSlot("finalized");for(;!("before"in r||++n>o);)try{const e=await this.getConfirmedBlockSignatures(n);e.signatures.length>0&&(r.before=e.signatures[e.signatures.length-1].toString())}catch(e){if(e instanceof Error&&e.message.includes("skipped"))continue;throw e}return(await this.getConfirmedSignaturesForAddress2(e,r)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),i=qp(await this._rpcRequest("getConfirmedSignaturesForAddress2",r),$w);if("error"in i)throw new Iy(i.error,"failed to get confirmed signatures for address");return i.result}async getSignaturesForAddress(e,t,n){const r=this._buildArgsAtLeastConfirmed([e.toBase58()],n,void 0,t),i=qp(await this._rpcRequest("getSignaturesForAddress",r),qw);if("error"in i)throw new Iy(i.error,"failed to get signatures for address");return i.result}async getAddressLookupTable(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==r&&(i=new Wy({key:e,state:Wy.deserialize(r.data)})),{context:n,value:i}}async getNonceAndContext(e,t){const{context:n,value:r}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==r&&(i=Py.fromAccountData(r.data)),{context:n,value:i}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const n=qp(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),Pb);if("error"in n)throw new Iy(n.error,`airdrop to ${e.toBase58()} failed`);return n.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Cy(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 Cy(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}=Yy(e),r=this._buildArgs([],t,"base64",n),i=qp(await this._rpcRequest("getStakeMinimumDelegation",r),nw(Qp()));if("error"in i)throw new Iy(i.error,"failed to get stake minimum delegation");return i.result}async simulateTransaction(e,t,n){if("message"in e){const r=e.serialize(),i=tc.Buffer.from(r).toString("base64");if(Array.isArray(t)||void 0!==n)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[i,o],a=qp(await this._rpcRequest("simulateTransaction",s),ww);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let r;if(e instanceof Sy){let t=e;r=new Sy,r.feePayer=t.feePayer,r.instructions=e.instructions,r.nonceInfo=t.nonceInfo,r.signatures=t.signatures}else r=Sy.populate(e),r._message=r._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const i=t;if(r.nonceInfo&&i)r.sign(...i);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(r.lastValidBlockHeight=t.lastValidBlockHeight,r.recentBlockhash=t.blockhash,!i)break;if(r.sign(...i),!r.signature)throw new Error("!signature");const n=r.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(n)&&!this._blockhashInfo.transactionSignatures.includes(n)){this._blockhashInfo.simulatedSignatures.push(n);break}e=!0}}const o=r._compile(),s=o.serialize(),a=r._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(n){const e=(Array.isArray(n)?n:o.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}i&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=qp(await this._rpcRequest("simulateTransaction",l),ww);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 Ty({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,n){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const n=e.serialize();return await this.sendRawTransaction(n,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const r=t;if(e.nonceInfo)e.sign(...r);else{let t=this._disableBlockhashCaching;for(;;){const n=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=n.lastValidBlockHeight,e.recentBlockhash=n.blockhash,e.sign(...r),!e.signature)throw new Error("!signature");const i=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(i)){this._blockhashInfo.transactionSignatures.push(i);break}t=!0}}const i=e.serialize();return await this.sendRawTransaction(i,n)}async sendRawTransaction(e,t){const n=Xm(e).toString("base64");return await this.sendEncodedTransaction(n,t)}async sendEncodedTransaction(e,t){const n={encoding:"base64"},r=t&&t.skipPreflight,i=!0===r?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(n.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(n.minContextSlot=t.minContextSlot),r&&(n.skipPreflight=r),i&&(n.preflightCommitment=i);const o=[e,n],s=qp(await this._rpcRequest("sendTransaction",o),Bb);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new Ty({action:r?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){const n=this._subscriptionsByHash[e]?.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const n=this._subscriptionStateChangeCallbacksByHash[e];n&&n.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const r=this._subscriptionStateChangeCallbacksByHash[n]||=new Set;return r.add(t),()=>{r.delete(t),0===r.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(e){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const n=this._subscriptionsByHash[e];if(void 0!==n)switch(n.state){case"pending":case"unsubscribed":if(0===n.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===n.state&&delete this._subscriptionCallbacksByServerSubscriptionId[n.serverSubscriptionId],void await this._updateSubscriptions();await(async()=>{const{args:r,method:i}=n;try{this._setSubscription(e,{...n,state:"subscribing"});const t=await this._rpcWebSocket.call(i,r);this._setSubscription(e,{...n,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=n.callbacks,await this._updateSubscriptions()}catch(r){if(!t())return;this._setSubscription(e,{...n,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===n.callbacks.size&&await(async()=>{const{serverSubscriptionId:r,unsubscribeMethod:i}=n;if(this._subscriptionsAutoDisposedByRpc.has(r))this._subscriptionsAutoDisposedByRpc.delete(r);else{this._setSubscription(e,{...n,state:"unsubscribing"}),this._setSubscription(e,{...n,state:"unsubscribing"});try{await this._rpcWebSocket.call(i,[r])}catch(r){if(Error,!t())return;return this._setSubscription(e,{...n,state:"subscribed"}),void await this._updateSubscriptions()}}this._setSubscription(e,{...n,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const n=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==n&&n.forEach(e=>{try{e(...t)}catch(e){}})}_wsOnAccountNotification(e){const{result:t,subscription:n}=qp(e,Kw);this._handleServerNotification(n,[t.value,t.context])}_makeSubscription(e,t){const n=this._nextClientSubscriptionId++,r=$y([e.method,t]),i=this._subscriptionsByHash[r];return void 0===i?this._subscriptionsByHash[r]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[n]=r,this._subscriptionDisposeFunctionsByClientSubscriptionId[n]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[n],delete this._subscriptionHashByClientSubscriptionId[n];const t=this._subscriptionsByHash[r];hy(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${n}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),n}onAccountChange(e,t,n){const{commitment:r,config:i}=Yy(n),o=this._buildArgs([e.toBase58()],r||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:n}=qp(e,Hw);this._handleServerNotification(n,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,n,r){const{commitment:i,config:o}=Yy(n),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(r?{filters:Jy(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}=qp(e,Mb);this._handleServerNotification(n,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:n}=qp(e,zw);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}=qp(e,Vw);this._handleServerNotification(n,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const n=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];n&&await n()}_buildArgs(e,t,n,r){const i=t||this._commitment;if(i||n||r){let t={};n&&(t.encoding=n),i&&(t.commitment=i),r&&(t=Object.assign(t,r)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,n,r){const i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,n,r)}_wsOnSignatureNotification(e){const{result:t,subscription:n}=qp(e,Xw);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(n),this._handleServerNotification(n,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,n){const r=this._buildArgs([e],n||this._commitment||"finalized"),i=this._makeSubscription({callback:(e,n)=>{if("status"===e.type){t(e.result,n);try{this.removeSignatureListener(i)}catch(e){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},r);return i}onSignatureWithOptions(e,t,n){const{commitment:r,...i}={...n,commitment:n&&n.commitment||this._commitment||"finalized"},o=this._buildArgs([e],r,void 0,i),s=this._makeSubscription({callback:(e,n)=>{t(e,n);try{this.removeSignatureListener(s)}catch(e){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:n}=qp(e,Qw);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 Ub{constructor(e){this._keypair=void 0,this._keypair=e??Wm()}static generate(){return new Ub(Wm())}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=zm(t);for(let e=0;e<32;e++)if(n[e]!==r[e])throw new Error("provided secretKey is invalid")}return new Ub({publicKey:n,secretKey:e})}static fromSeed(e){const t=zm(e),n=new Uint8Array(64);return n.set(e),n.set(t,32),new Ub({publicKey:t,secretKey:n})}get publicKey(){return new ty(this._keypair.publicKey)}get secretKey(){return new Uint8Array(this._keypair.secretKey)}}Object.freeze({CreateLookupTable:{index:0,layout:cd.struct([cd.u32("instruction"),By("recentSlot"),cd.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:cd.struct([cd.u32("instruction")])},ExtendLookupTable:{index:2,layout:cd.struct([cd.u32("instruction"),By(),cd.seq(ay(),cd.offset(cd.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:cd.struct([cd.u32("instruction")])},CloseLookupTable:{index:4,layout:cd.struct([cd.u32("instruction")])}}),new ty("AddressLookupTab1e1111111111111111111111111");const Fb=Object.freeze({RequestUnits:{index:0,layout:cd.struct([cd.u8("instruction"),cd.u32("units"),cd.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:cd.struct([cd.u8("instruction"),cd.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:cd.struct([cd.u8("instruction"),cd.u32("units")])},SetComputeUnitPrice:{index:3,layout:cd.struct([cd.u8("instruction"),By("microLamports")])}});class $b{constructor(){}static requestUnits(e){const t=Ny(Fb.RequestUnits,e);return new vy({keys:[],programId:this.programId,data:t})}static requestHeapFrame(e){const t=Ny(Fb.RequestHeapFrame,e);return new vy({keys:[],programId:this.programId,data:t})}static setComputeUnitLimit(e){const t=Ny(Fb.SetComputeUnitLimit,e);return new vy({keys:[],programId:this.programId,data:t})}static setComputeUnitPrice(e){const t=Ny(Fb.SetComputeUnitPrice,{microLamports:BigInt(e.microLamports)});return new vy({keys:[],programId:this.programId,data:t})}}var qb;$b.programId=new ty("ComputeBudget111111111111111111111111111111"),cd.struct([cd.u8("numSignatures"),cd.u8("padding"),cd.u16("signatureOffset"),cd.u16("signatureInstructionIndex"),cd.u16("publicKeyOffset"),cd.u16("publicKeyInstructionIndex"),cd.u16("messageDataOffset"),cd.u16("messageDataSize"),cd.u16("messageInstructionIndex")]),new ty("Ed25519SigVerify111111111111111111111111111"),Hm.utils.isValidPrivateKey,cd.struct([cd.u8("numSignatures"),cd.u16("signatureOffset"),cd.u8("signatureInstructionIndex"),cd.u16("ethAddressOffset"),cd.u8("ethAddressInstructionIndex"),cd.u16("messageDataOffset"),cd.u16("messageDataSize"),cd.u8("messageInstructionIndex"),cd.blob(20,"ethAddress"),cd.blob(64,"signature"),cd.u8("recoveryId")]),new ty("KeccakSecp256k11111111111111111111111111111"),new ty("StakeConfig11111111111111111111111111111111");class Kb{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}}qb=Kb,Kb.default=new qb(0,0,ty.default),Object.freeze({Initialize:{index:0,layout:cd.struct([cd.u32("instruction"),((e="authorized")=>cd.struct([ay("staker"),ay("withdrawer")],e))(),((e="lockup")=>cd.struct([cd.ns64("unixTimestamp"),cd.ns64("epoch"),ay("custodian")],e))()])},Authorize:{index:1,layout:cd.struct([cd.u32("instruction"),ay("newAuthorized"),cd.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:cd.struct([cd.u32("instruction")])},Split:{index:3,layout:cd.struct([cd.u32("instruction"),cd.ns64("lamports")])},Withdraw:{index:4,layout:cd.struct([cd.u32("instruction"),cd.ns64("lamports")])},Deactivate:{index:5,layout:cd.struct([cd.u32("instruction")])},Merge:{index:7,layout:cd.struct([cd.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:cd.struct([cd.u32("instruction"),ay("newAuthorized"),cd.u32("stakeAuthorizationType"),cy("authoritySeed"),ay("authorityOwner")])}}),new ty("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:cd.struct([cd.u32("instruction"),((e="voteInit")=>cd.struct([ay("nodePubkey"),ay("authorizedVoter"),ay("authorizedWithdrawer"),cd.u8("commission")],e))()])},Authorize:{index:1,layout:cd.struct([cd.u32("instruction"),ay("newAuthorized"),cd.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:cd.struct([cd.u32("instruction"),cd.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:cd.struct([cd.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:cd.struct([cd.u32("instruction"),((e="voteAuthorizeWithSeedArgs")=>cd.struct([cd.u32("voteAuthorizationType"),ay("currentAuthorityDerivedKeyOwnerPubkey"),cy("currentAuthorityDerivedKeySeed"),ay("newAuthorized")],e))()])}}),new ty("Vote111111111111111111111111111111111111111"),new ty("Va1idator1nfo111111111111111111111111111111"),tm({name:Zp(),website:Yp(Zp()),details:Yp(Zp()),iconUrl:Yp(Zp()),keybaseUsername:Yp(Zp())}),new ty("Vote111111111111111111111111111111111111111"),cd.struct([ay("nodePubkey"),ay("authorizedWithdrawer"),cd.u8("commission"),cd.nu64(),cd.seq(cd.struct([cd.nu64("slot"),cd.u32("confirmationCount")]),cd.offset(cd.u32(),-8),"votes"),cd.u8("rootSlotValid"),cd.nu64("rootSlot"),cd.nu64(),cd.seq(cd.struct([cd.nu64("epoch"),ay("authorizedVoter")]),cd.offset(cd.u32(),-8),"authorizedVoters"),cd.struct([cd.seq(cd.struct([ay("authorizedPubkey"),cd.nu64("epochOfLastAuthorizedSwitch"),cd.nu64("targetEpoch")]),32,"buf"),cd.nu64("idx"),cd.u8("isEmpty")],"priorVoters"),cd.nu64(),cd.seq(cd.struct([cd.nu64("epoch"),cd.nu64("credits"),cd.nu64("prevCredits")]),cd.offset(cd.u32(),-8),"epochCredits"),cd.struct([cd.nu64("slot"),cd.nu64("timestamp")],"lastTimestamp")]);function Gb(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Hb(e){const t=new Map;for(const n of e)t.set(In(n.symbol),n);return t}function Wb(e,t,n){const r=function(e,t){return e.get(In(t))}(e,t);if(!r){throw rn(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return r}function zb(e){if(null==e||!Gb(e))throw tn("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function jb(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function Vb(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function Xb(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function Qb(e,t,n){const r=e.find(e=>e.symbol===t);if(!r){const r=e.map(e=>e.symbol).join(", ");throw en("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${r}`)}return r}const Yb={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function Jb(e,t,n){if(void 0===e)throw rn(n??Yb[t],`${t.toLowerCase()}Strategy`);return e}function Zb(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 ek="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",tk="Bridge request ID missing from RequestTokenBridgeOut response",nk="BridgeTokenOut response missing transaction hash";function rk(e){if(void 0===e||""===e)throw rn(ek,"tokenSymbol");return e}function ik(e,t){if(!n(e)){throw tn(t??"address","a valid 0x-prefixed Ethereum address",e)}}function ok(e,t){try{return new ty(e)}catch{throw tn(t??"address","a valid Solana address (base58)",e)}}function sk(e){try{return new ty(e)}catch{throw tn("address","a valid Solana address (base58)",e)}}function ak(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(r&&"object"==typeof r&&!Array.isArray(r)?t[n]=ak(r):t[n]=r);return t}function ck(e,t){const n=rr(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}function lk(e){const t="string"==typeof e.timestamp?sr(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 uk,dk,hk,gk,fk,pk;function mk(){return dk?uk:(dk=1,uk={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify})}function yk(){return gk?hk:(gk=1,hk={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 wk(){if(pk)return fk;pk=1;const e=mk(),t=yk().isFunction,n=yk().isBoolean,r=yk().isObject,i=yk().isArray,o=yk().isRegex,s=yk().assign,a=yk().keys;return fk=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,f=l.compare&&(p=l.compare,function(e){return function(t,n){const r={key:t,value:e[t]},i={key:n,value:e[n]};return p(r,i)}});var p;d||g(c);const m=[];return function e(t,n,s,c){const l=u?"\n"+new Array(c+1).join(u):"",p=u?": ":":";if(s=function(e){return null==e?e:o(e)?e.toString():e.toJSON?e.toJSON():e}(s),void 0!==(s=h.call(t,n,s))){if(!r(s)||null===s)return g(s);if(i(s)){const t=[];for(let n=0;n<s.length;n++){const r=e(s,n,s[n],c+1)||g(null);t.push(l+u+r)}return"["+t.join(",")+l+"]"}{if(d){if(-1!==m.indexOf(s))return g("[Circular]");m.push(s)}const t=a(s).sort(f&&f(s)),n=[];for(let r=0;r<t.length;r++){const i=t[r],o=e(s,i,s[i],c+1);if(!o)continue;const a=g(i)+p+o;n.push(l+u+a)}return m.splice(m.indexOf(s),1),"{"+n.join(",")+l+"}"}}}({"":c},"",c,0)},fk}var bk=Ha(wk());let kk=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{kk=require("crypto")}catch{}function vk(){if(void 0!==kk?.randomUUID)try{return kk.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 Sk(e){if(void 0!==kk?.createHash)try{const t=kk.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 Ak={name:"GalaConnect",chainId:1},Ek=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Tk=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Ik=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Ck=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Nk={GalaTransaction:Ek,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:Tk,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:Ik,externalQuoteToken:Ck,tokenInstance:Ik},_k={GalaTransaction:Ek,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:Tk,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:Ck,externalQuoteToken:Ck,externalCrossRateToken:Ck,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:Ik,tokenInstance:Ik};function xk(e){return e?_k:Nk}const Dk={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:Ik};async function Pk(e,t){const{wallet:n}=t,r=e.uniqueKey??`galaconnect-operation-${vk()}`,i="string"==typeof e.destinationChainId?sr(e.destinationChainId,1):e.destinationChainId,o=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?sr(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?sr(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?sr(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?sr(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?sr(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?sr(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(o.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:ak(s?{...o,galaExchangeRate:void 0}:{...o,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:r},c=xk(s),l=await n.signTypedData(Ak,c,a),u=`Ethereum Signed Message:\n${bk({domain:Ak,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:u,types:c,domain:Ak}}async function Bk(e,t){const{amount:n,recipientAddress:r,tokenSymbol:i}=e,{galaConnectClient:o,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:u}=t,d=rk(i);ck(n,d),u(r,"recipient");const h=await s.getTokenMetadata(d),g=await o.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),f=function(e){return{destinationChainId:e.destinationChainId,destinationChainTxFee:e.bridgeFee,quantity:e.amount,recipient:e.recipientAddress,tokenInstance:{...e.tokenDescriptor,instance:"0"}}}({destinationChainId:c,bridgeFee:g,amount:n,recipientAddress:r,tokenDescriptor:h.descriptor}),p=await Pk(f,{wallet:a}),m=function(e){if(void 0===e||""===e)throw rn(tk,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}(await o.requestBridgeOut(p)));return function(e){return{direction:"outbound",fromChain:"GalaChain",toChain:e.toChain,transactionHash:e.transactionHash,tokenSymbol:e.tokenSymbol,amount:e.amount,feePaid:e.feePaid,timestamp:Date.now(),statusUrl:`${e.baseUrl}/v1/bridge/transaction?hash=${e.transactionHash}`}}({toChain:l,transactionHash:function(e){const t=e.Hash??e.hash??"";if(""===t)throw rn(nk,"transactionHash");return t}(await o.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:m})),tokenSymbol:d,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:o.getBaseUrl()})}const Rk=5,Mk=6,Ok=7;function Lk(e){const t=sr(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===Rk,isFailed:t===Mk||t===Ok}}class Uk{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw cn("requestsPerSecond","1",e,"Requests per second");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const r=new Promise((e,r)=>{t=e,n=r});if(this.pendingPromise=this.pendingPromise.then(async()=>{const r=Date.now()-this.lastTimestamp,i=Math.max(0,this.minIntervalMs-r);i>0&&await new Promise(e=>setTimeout(e,i)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(xt(e)?e:new Error(Dt(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return r}}const Fk={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},$k=new Set([408,429,500,502,503,504]),qk=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function Kk(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return $k.has(t.status);if("number"==typeof t.statusCode)return $k.has(t.statusCode);const n=Bt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=Dt(e);return qk.some(e=>e.test(t))}function Gk(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),r=Math.min(n,t.maxDelayMs),i=r*t.jitterFactor*Math.random();return Math.floor(r+i)}function Hk(e){return new Promise(t=>setTimeout(t,e))}function Wk(e,t){return Jb(e.get("Ethereum"),"Ethereum",t)}function zk(e,t){return Jb(e.get("Solana"),"Solana",t)}function jk(e,t){return e??t.getWalletAddress()}function Vk(e,t,n){const r=void 0!==n?` (${n})`:"";try{if(!Er(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);const[r,i,o,...s]=n;if(""===r||""===i||""===o)throw new Error("Collection, category, and type must be non-empty");const a=s.join(t);if(""===a)throw new Error("AdditionalKey must be non-empty");return{collection:r,category:i,type:o,additionalKey:a}}catch(n){const i=e?.split?.(t)??[];throw new qt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${i.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${Dt(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function Xk(e){if("object"==typeof e&&null!==e)return function(e){if(null===e||"object"!=typeof e)throw new qt("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:r,additionalKey:i}=e;if(!Er(t))throw new qt("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!Er(n))throw new qt("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!Er(r))throw new qt("Token.type must be a non-empty string, got "+typeof r,"token.type","MISSING_OR_INVALID_TYPE");if(!Er(i))throw new qt("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:r,additionalKey:i}}(e);if(null==e)throw new qt(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new qt("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(Yk(e))return Qk(e);if(Jk(e))return function(e){return function(e,t,n){const r=` (${n})`;try{if(!Er(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],i=n[n.length-2],o=n[n.length-3],s=n.slice(0,n.length-3).join(t);if(""===s||""===o||""===i||""===r)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:s,category:o,type:i,additionalKey:r}}catch(n){const i=e?.split?.(t)??[];throw new qt(`Invalid dollar-delimited token: "${e}" (${i.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${Dt(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new qt(`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 Qk(e){return Vk(e,"|","pipe-delimited token")}function Yk(e){return Er(e)&&e.includes("|")}function Jk(e){return"string"==typeof e&&e.includes("$")}function Zk(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,r=t.category,i=t.type,o=t.additionalKey;return"string"==typeof n&&"string"==typeof r&&"string"==typeof i&&"string"==typeof o&&n.length>0&&r.length>0&&i.length>0&&o.length>0}function ev(e){let t;if("string"==typeof e)t=Qk(e);else{if(!Zk(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:fa(t)}}function tv(e,t){let n;try{n=cr(e,"amount")}catch(t){throw dn("amount",`${e} (${Dt(t)})`)}if(!n.isFinite())throw dn("amount",e);const r=n.multipliedBy(fs(10).pow(t));if(!r.isInteger())throw dn("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(r.toFixed(0))}function nv(e,t){return fs(e.toString()).dividedBy(fs(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}function rv(e,t=6){const n=fs(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+$/,"")}function iv(e,t){const n=fs(e),r=fs(t);return n.comparedTo(r)}class ov{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=Cn(e),n=this.cache.get(t);if(n)return n;const r=Oa[t];if(void 0!==r)return this.cache.set(t,r),r;const i=await this.fetchFromApi(e);return this.cache.set(t,i),i}hasMetadata(e){const t=Cn(e);return this.cache.has(t)||t in Oa}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>Cn(e.symbol)===Cn(t)&&e.verified);if(r||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),r=n.find(e=>Cn(e.symbol)===Cn(t)&&e.verified)),!r)throw new Error(`Unable to locate token metadata for ${e}`);return i={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey},o=r.decimals,s=r.channel,{descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:o,...void 0!==s?{channel:s}:{}};var i,o,s}}class sv 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 av=_a,cv="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",lv=12,uv=!0,dv=3,hv=1e3;class gv{constructor(e){this.baseUrl=e.baseUrl??av,this.galachainBaseUrl=e.galachainBaseUrl??cv,this.walletAddress=e.walletAddress,this.rateLimiter=new Uk(e.requestsPerSecond??lv),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??uv;this.retryOptions=t?{maxRetries:e.maxRetries??dv,initialDelayMs:e.retryInitialDelayMs??hv,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>Kk(e instanceof sv?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return sa(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?nr(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new sv(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof sv)throw e;throw sn(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 sa(async()=>{const r=n.baseUrl??this.baseUrl,i=new URL(e,r),o=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(i.toString(),{method:"POST",headers:o,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!s.ok){const t=await s.text(),n=500,r=nr(t,{rawBody:t.slice(0,n)});throw new sv(s.status,e,r)}const a=await s.text();if(""!==a){const t=function(e){if(Dn(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: ${Dt(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 sv)throw e;throw sn(e,t)})}async request(e,t){const n=async()=>this.rateLimiter.schedule(async()=>{const n={...this.defaultHeaders,...t.headers};""===n["X-Wallet-Address"]?delete n["X-Wallet-Address"]:n["X-Wallet-Address"]??(n["X-Wallet-Address"]=this.walletAddress);const r=await fetch(e,{...t,headers:n});if(this.retryOptions&&!r.ok){const t=r.status;if(429===t||t>=500){const n=r.clone(),i=await this.safeParseJson(n);throw new sv(t,e,i)}}return r});return this.retryOptions?async function(e,t={}){const n={...Fk,...t},r=t.shouldRetry??(e=>Kk(e));let i;for(let o=1;o<=n.maxRetries+1;o++)try{return await e()}catch(e){if(i=e,o>n.maxRetries)break;if(!r(e,o))break;const s=Gk(o,n);t.onRetry&&t.onRetry(e,o,s),await new Promise(e=>setTimeout(e,s))}throw i}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var fv;!function(e){e[e.PENDING=0]="PENDING",e[e.SUBMITTED=1]="SUBMITTED",e[e.CONFIRMED=2]="CONFIRMED",e[e.PROCESSING=3]="PROCESSING",e[e.FINALIZING=4]="FINALIZING",e[e.COMPLETED=5]="COMPLETED",e[e.FAILED=6]="FAILED",e[e.DELIVERY_FAILED=7]="DELIVERY_FAILED"}(fv||(fv={}));class pv{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:r=27e5,onStatusUpdate:i}=t,o=Date.now();for(;;){const t=await this.getStatus(e);if(i&&i(t),t.status===fv.COMPLETED||t.status===fv.FAILED||t.status===fv.DELIVERY_FAILED)return t;if(On(o)>r)throw on(`Bridge transaction timed out after ${r}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class mv extends pv{constructor(e){super(),this.network="Ethereum",this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,zb(e.ethereumPrivateKey);const n=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new r(n),this.ethereumWallet=new t(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const i=e.tokenConfigs??Ra;this.tokenConfigs=Hb(i),this.tokenMetadataResolver=new ov({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return lk(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return Bk(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ya.ETHEREUM,destinationChain:"Ethereum",validateRecipientAddress:ik})}async bridgeIn(n){const{amount:r,sourcePrivateKey:o,recipientAddress:s,tokenSymbol:a}=n,c=rk(a);if(ck(r,c),void 0!==o&&""!==o&&!Gb(o))throw tn("sourcePrivateKey","0x-prefixed 64-character hex string",o.slice(0,10)+"...");const l=void 0!==o&&""!==o?new t(o,this.ethereumProvider):this.ethereumWallet,u=Wb(this.tokenConfigs,c,"Ethereum bridge"),d=await this.tokenMetadataResolver.getTokenMetadata(c),h=new i(u.contractAddress,La,l),g=sr(await h.decimals(),18),f=tv(r,g),p=BigInt(await h.balanceOf(l.address));if(p<f){throw rn(`Insufficient ${c} balance on Ethereum. Needed ${nv(f,g)}, have ${nv(p,g)}`,"amount")}const m=function(t){const n=new Qr;if("client"===n.detectFormat(t))return t;const r=n.normalizeInput(t);if(null==r)throw tn("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const i=n.extractHex(r);return`eth|${e("0x"+i).slice(2)}`}(s??this.galaChainWalletAddress);return Zb({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:l,tokenContract:h,tokenConfig:u,amountBaseUnits:f,decimals:g,recipient:m,metadata:d})).txHash,tokenSymbol:c,amount:r,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return Lk(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(In(e))}isValidAddress(e){return Ar.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=Wb(this.tokenConfigs,e,"Ethereum"),r=t??this.ethereumWalletAddress;ik(r);const o=new i(n.contractAddress,La,this.ethereumProvider);return nv(await o.balanceOf(r),n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;ik(t);return nv(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 tn("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>=mv.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: ${Dt(e)}`}}}async executeBridgeDeposit(e){const t=new i(this.ethereumBridgeContract,Ua,e.wallet),n=(new TextEncoder).encode(e.recipient);let r;r=e.tokenConfig.bridgeUsesPermit?await this.bridgeWithPermit(e.wallet,e.tokenContract,e.tokenConfig,t,e.amountBaseUnits,n):await this.bridgeWithApproval(e.wallet,e.tokenContract,t,e.tokenConfig,e.amountBaseUnits,n);if(!await r.wait())throw rn("Bridge transaction receipt not available","ethereumRpcUrl");await Hk(3e4);const o={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:nv(e.amountBaseUnits,e.decimals),tokenInstance:o,fromChain:"Ethereum",toChain:"GC",hash:r.hash}),{txHash:r.hash}}async bridgeWithPermit(e,t,n,r,i,s){const a=await this.ethereumProvider.getNetwork(),c=await t.name(),l=await t.nonces(e.address),u=BigInt(Math.floor(Date.now()/1e3)+3600),d=await e.signTypedData({name:c,version:"1",chainId:sr(a.chainId,1),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:i,nonce:l,deadline:u}),h=o.from(d);return await r.bridgeOutWithPermit(n.contractAddress,i,ya.GALA_CHAIN,s,u,h.v,h.r,h.s)}async bridgeWithApproval(e,t,n,r,i,o){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<i){const e=await t.approve(this.ethereumBridgeContract,i);await e.wait()}return await n.bridgeOut(r.contractAddress,i,0,ya.GALA_CHAIN,o)}}mv.ETHEREUM_FINALITY_THRESHOLD=12;const yv=new ty("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new ty("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const wv=new ty("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new ty("So11111111111111111111111111111111111111112"),new ty("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const bv=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var kv,vv={};function Sv(){if(kv)return vv;return kv=1,Object.defineProperty(vv,"__esModule",{value:!0}),vv.toBigIntLE=function(e){{const t=Buffer.from(e);t.reverse();const n=t.toString("hex");return 0===n.length?BigInt(0):BigInt(`0x${n}`)}},vv.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}},vv.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}},vv.toBufferBE=function(e,t){{const n=e.toString(16);return Buffer.from(n.padStart(2*t,"0").slice(0,2*t),"hex")}},vv}var Av=Sv();const Ev=(Tv=8,e=>{const t=cd.blob(Tv,e),{encode:n,decode:r}=bv(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return Av.toBigIntLE(Buffer.from(n))},i.encode=(e,t,r)=>{const i=Av.toBufferLE(e,Tv);return n(i,t,r)},i});var Tv;const Iv=e=>{const t=cd.blob(32,e),{encode:n,decode:r}=bv(t),i=t;return i.decode=(e,t)=>{const n=r(e,t);return new ty(n)},i.encode=(e,t,r)=>{const i=e.toBuffer();return n(i,t,r)},i};var Cv;!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initialized=1]="Initialized",e[e.Frozen=2]="Frozen"}(Cv||(Cv={}));const Nv=cd.struct([Iv("mint"),Iv("owner"),Ev("amount"),cd.u32("delegateOption"),Iv("delegate"),cd.u8("state"),cd.u32("isNativeOption"),Ev("isNative"),Ev("delegatedAmount"),cd.u32("closeAuthorityOption"),Iv("closeAuthority")]);Nv.span;var _v=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let e=0;e<t.length;e++)t[e]=255;for(let n=0;n<e.length;n++){const r=e.charAt(n),i=r.charCodeAt(0);if(255!==t[i])throw new TypeError(r+" is ambiguous");t[i]=n}const n=e.length,r=e.charAt(0),i=Math.log(n)/Math.log(256),o=Math.log(256)/Math.log(n);function s(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;let o=0,s=0,a=0;for(;e[o]===r;)s++,o++;const c=(e.length-o)*i+1>>>0,l=new Uint8Array(c);for(;o<e.length;){const r=e.charCodeAt(o);if(r>255)return;let i=t[r];if(255===i)return;let s=0;for(let e=c-1;(0!==i||s<a)&&-1!==e;e--,s++)i+=n*l[e]>>>0,l[e]=i%256>>>0,i=i/256>>>0;if(0!==i)throw new Error("Non-zero carry");a=s,o++}let u=c-a;for(;u!==c&&0===l[u];)u++;const d=new Uint8Array(s+(c-u));let h=s;for(;u!==c;)d[h++]=l[u++];return d}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";let i=0,s=0,a=0;const c=t.length;for(;a!==c&&0===t[a];)a++,i++;const l=(c-a)*o+1>>>0,u=new Uint8Array(l);for(;a!==c;){let e=t[a],r=0;for(let t=l-1;(0!==e||r<s)&&-1!==t;t--,r++)e+=256*u[t]>>>0,u[t]=e%n>>>0,e=e/n>>>0;if(0!==e)throw new Error("Non-zero carry");s=r,a++}let d=l-s;for(;d!==l&&0===u[d];)d++;let h=r.repeat(i);for(;d<l;++d)h+=e.charAt(u[d]);return h},decodeUnsafe:s,decode:function(e){const t=s(e);if(t)return t;throw new Error("Non-base"+n+" character")}}}("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function xv(e,t,n,r,i){const[o]=ty.findProgramAddressSync([t.toBuffer(),r.toBuffer(),e.toBuffer()],i);return o}class Dv extends pv{constructor(e){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,zb(e.ethereumPrivateKey);const n=new r("https://ethereum.publicnode.com");this.ethereumWallet=new t(e.ethereumPrivateKey,n);const i=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let o;this.solanaConnection=new Lb(i,"confirmed");try{o=_v.decode(e.solanaPrivateKeyBase58)}catch{throw tn("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==o.length)throw tn("solanaPrivateKeyBase58","64 bytes when decoded",`${o.length} bytes`);this.solanaKeypair=Ub.fromSecretKey(o);const s=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new ty(s),[this.solanaBridgeTokenAuthority]=ty.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=ty.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=ty.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const a=e.tokenConfigs??Ma;this.tokenConfigs=Hb(a),this.tokenMetadataResolver=new ov({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return lk(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return Bk(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ya.SOLANA,destinationChain:"Solana",validateRecipientAddress:ok})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:r,tokenSymbol:i}=e,o=rk(i);ck(t,o);let s=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=_v.decode(n)}catch{throw tn("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw tn("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=Ub.fromSecretKey(e)}const a=Wb(this.tokenConfigs,o,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(o),l=tv(t,c.decimals),u=r??this.galaChainWalletAddress;return Zb({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:u,amount:t}),tokenSymbol:o,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return Lk(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(In(e))}isValidAddress(e){try{return new ty(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=Wb(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const r=t??this.solanaKeypair.publicKey.toBase58(),i=sk(r),o=xv(new ty(n.mintAddress),i,0,yv,wv);try{const e=await async function(e,t,n,r){const i=await e.getAccountInfo(t);if(!i)throw new Error(`could not find account ${t.toBase58()}`);if(!i.owner.equals(r))throw new Error(`account owner mismatch: expected ${r.toBase58()}, got ${i.owner.toBase58()}`);return{amount:Nv.decode(i.data).amount,decimals:0}}(this.solanaConnection,o,0,yv),t=n.decimals??8;return nv(e.amount,t)}catch(t){if(xt(t)&&t.message.includes("could not find")){return nv(0n,n.decimals??8)}throw rn(`Failed to fetch ${e} balance for ${r}: ${Dt(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=sk(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return nv(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){gr(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?sk(t):this.solanaKeypair.publicKey,r=this.solanaConnection.rpcEndpoint;if(!r.includes("devnet"))throw rn(`Solana devnet faucet only available on devnet. Current RPC: ${r}. Ensure SDK is configured with environment='STAGE' for devnet access.`,"solanaRpcUrl");const i=Math.floor(1e9*e);return await this.solanaConnection.requestAirdrop(n,i)}async getSolanaTransactionStatus(e){if(!Er(e))throw tn("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw tn("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 ty(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),r=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:xv(t,e.keypair.publicKey,0,yv,wv),o=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(o.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,o):this.buildTokenBridgeInstruction(e.keypair.publicKey,i,t,r,s,a,o),l=new Sy;l.add($b.setComputeUnitPrice({microLamports:375e3}),$b.setComputeUnitLimit({units:2e5}),c),l.feePayer=e.keypair.publicKey;const u=await this.sendAndConfirmWithFallback(l,e.keypair),d={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:e.amount,tokenInstance:d,fromChain:"Solana",toChain:"GC",hash:u}),u}async sendAndConfirmWithFallback(e,t,n=3){let r=null;for(let i=1;i<=n;i++){try{const o=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=o.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:o.blockhash,lastValidBlockHeight:o.lastValidBlockHeight},"confirmed"),s}catch(e){const t=xt(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const o=await this.solanaConnection.getSignatureStatuses([s]);if("confirmed"===o.value[0]?.confirmationStatus||"finalized"===o.value[0]?.confirmationStatus)return s;r=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${i}/${n})`)}}catch(e){r=xt(e)?e:new Error(Dt(e));const t=r.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||i===n)throw r}const o=Math.min(1e3*Math.pow(2,i-1),5e3);await Hk(o)}throw r??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,r){const i=Buffer.concat([Fa.BRIDGE_OUT_NATIVE,t,n,r]);return new vy({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!0},{pubkey:this.solanaNativeBridgePda,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:My.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,r,i,o,s){const a=Buffer.concat([Fa.BRIDGE_OUT,i,o,s]);return new vy({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:r.mintLookup,isSigner:!1,isWritable:!1},{pubkey:r.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:r.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:My.programId,isSigner:!1,isWritable:!1},{pubkey:yv,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[r]=ty.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(r,"confirmed");if(!i)throw rn(`Mint lookup account not found for ${r.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw rn("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw rn("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const o={mintLookup:r,tokenBridge:new ty(i.data.slice(8,40)),bridgeTokenAccount:xv(e,this.solanaBridgeTokenAuthority,0,yv,wv)};return this.solanaBridgeAccountCache.set(t,o),o}}const Pv={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"}},Bv={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class Rv{static normalizeGalaChainAddress(e){const t=new Qr;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 rn(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(r);return`eth|${Rv.checksumAddress(i)}`}static checksumAddress(e){const t=e.toLowerCase(),n=Vr(s(a(t)));let r="";for(let e=0;e<t.length;e++){const i=t[e];parseInt(n[e],16)>=8?r+=i.toUpperCase():r+=i}return r}constructor(e){const t=Rv.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"STAGE",r=ha[n],i=Pv[n],o={galaConnectBaseUrl:e.galaConnectBaseUrl??r.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??r.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??i.ethereum,solanaRpcUrl:e.solanaRpcUrl??i.solana,ethereumBridgeContract:e.ethereumBridgeContract??Ba(n),solanaBridgeProgram:e.solanaBridgeProgram??Bv.solanaBridgeProgram,rateLimit:e.rateLimit??Bv.rateLimit,pollInterval:e.pollInterval??Bv.pollInterval,pollTimeout:e.pollTimeout??Bv.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...o,solanaPrivateKey:e.solanaPrivateKey}:o,this.galaConnectClient=new gv({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=Pa(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 mv(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:Ma};this.strategies.set("Solana",new Dv(e))}}async resolveTokenSymbol(e,t){return sa(async()=>{if(!this.bridgeableTokenService)throw rn("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=ev(e).stringified,r="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,r);if(!i){throw rn([`Token "${n}" was not found in the list of tokens bridgeable to ${t}.`,"","Troubleshooting suggestions:",' 1. Verify the tokenId format is correct (e.g., "GALA|Unit|none|none")'," 2. Check if the token supports bridging to this network:",` - Use sdk.fetchAllBridgeableTokensByNetwork('${r}')`," - Or use sdk.isTokenBridgeableToNetwork({ tokenSymbol, network })"," 3. Common tokenId formats for bridge tokens:",' - GALA: "GALA|Unit|none|none"',' - GUSDC: "GUSDC|Unit|none|eth:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"'," 4. Use sdk.getSupportedBridgeTokens() to list all available tokens"].join("\n"),"tokenId")}return i.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return sa(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 sa(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw rn(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw rn(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return sa(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw rn(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return sa(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=xt(e)?e:new Error(Dt(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){r=xt(e)?e:new Error(Dt(e))}const o=r?` (last error: ${r.message})`:"";throw on(`Unable to get status for transaction ${e}${o}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return sa(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},r=this.strategies.get("Ethereum");if(r)try{return await r.getStatus(e),r.waitForCompletion(e,n)}catch{}const i=this.strategies.get("Solana");if(i)return i.waitForCompletion(e,n);throw on(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=Pa(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 Ma){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 sa(async()=>Wk(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return sa(async()=>Wk(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return sa(async()=>zk(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return sa(async()=>zk(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return sa(async()=>{const n=Wk(this.strategies),r=Qb(Pa(this.config.environment),e,"Ethereum"),i=jk(t,n);return Vb(r,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return sa(async()=>{const t=Wk(this.strategies),n=jk(e,t);return jb("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return sa(async()=>{const n=zk(this.strategies),r=Qb(Ma,e,"Solana"),i=jk(t,n);return Xb(r,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return sa(async()=>{const t=zk(this.strategies),n=jk(e,t);return jb("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return sa(async()=>zk(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return sa(async()=>zk(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 sa(async()=>Wk(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 sa(async()=>{const t=Wk(this.strategies),n=jk(e,t),r=Pa(this.config.environment),[i,...o]=await Promise.all([t.getEthereumNativeBalance(n),...r.map(async e=>Vb(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:jb("ETH",i,18),tokens:o,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return sa(async()=>{const t=zk(this.strategies),n=jk(e,t),[r,...i]=await Promise.all([t.getSolanaNativeBalance(n),...Ma.map(async e=>Xb(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:jb("SOL",r,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw rn(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}const Mv=5,Ov=5,Lv="5.0.4-beta.60",Uv={DEFAULT_PAGE_SIZE:50,MAX_PAGE_SIZE:1e3,SAFETY_MAX_PAGES:1e4,DEFAULT_OFFSET:0,DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20},Fv={MAX_CONCURRENT_FETCHES:5,PAGE_SIZE:50,BACKEND_PAGE_SIZE:20};function $v(e,t=Uv.DEFAULT_LIMIT){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw un("offset","a non-negative integer",e);return pr(t,"limit"),{offset:e,limit:t}}function qv(e,t,n){if("number"!=typeof e||!Number.isInteger(e)||e<0)throw un("offset","a non-negative integer",e);pr(t,"limit")}function Kv(e,t=1,n=Uv.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Gv(e,t){if("number"!=typeof e||!Number.isInteger(e))throw un("total","a non-negative integer",e);if(e<0)throw an("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw un("limit","a non-negative integer",t);if(t<0)throw an("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Hv(e,t,n){if("number"!=typeof e||!Number.isInteger(e))throw un("offset","a non-negative integer",e);if(e<0)throw an("offset",0,1/0,e);return e+t<n}function Wv(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 zv(e,t,n){for(const r of n){const n=t[r];null!=n&&""!==n&&(e[r]=String(n))}return e}const jv="x-api-key";class Vv extends Gr{constructor(e,t,n,r=!1,i){super(e,r),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=i??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Er(e))throw en("tokenName","Token name");const n=Tn(e);if(!t.PATTERN.test(n))throw tn("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Er(e))throw en(t,n)}(e,t,n)}validateOptionalString(e,t,n,r){!function(e,t,n,r){if(null!=e){if("string"!=typeof e)throw un(t,"string",typeof e,n);if(e.length>r)throw ln(t,r,e.length,n)}}(e,t,n,r)}validateOptionalNumber(e,t,n,r,i,o,s){!function(e,t,n,r,i){if(null!=e){if("number"!=typeof e)throw un(t,"number",typeof e,n);if(e<r||e>i)throw an(t,r,i,e,n)}}(e,t,n,r,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Mn(e))throw tn(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){qr(e,t,n)}validateStatusFilter(e,t,n="status"){Kr(e,t,n)}buildPaginationParams(e,t){return Wv(e,t)}addOptionalFilterParams(e,t,n){return zv(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 Gt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[jv]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Gt("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?{[jv]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return wn(e,"Backend request failed",!0),kn(e,"No data in backend response")}extractDataOrNull(e){return wn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const r=this.buildEndpoint(t,{tokenName:e}),i=await this.http.post(r,{},this.getAdminHeaders()),o=this.extractData(i);return{enabled:o.enabled,tokenName:o.tokenName??Tn(e)}}}class Xv extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async getSettings(){return{settings:(await this.http.get(kt.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(kt.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=kt.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=kt.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(kt.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Qv={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"},Yv=_r(Qv),Jv={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"},Zv={MANAGE_COMMUNITY:"MANAGE_COMMUNITY",MANAGE_STREAM:"MANAGE_STREAM",MANAGE_SETTINGS:"MANAGE_SETTINGS",MANAGE_RECORDINGS:"MANAGE_RECORDINGS",VIEW_ANALYTICS:"VIEW_ANALYTICS"},eS=Object.values(Zv);function tS(e){return Yv.includes(e)}function nS(e){const t=[];void 0===e.role||null===e.role?t.push("Role is required"):tS(e.role)||t.push(`Invalid role. Must be one of: ${Yv.join(", ")}`);const n=t.length;if(Lt(t,()=>{Fr(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Lt(t,()=>{if(!Array.isArray(e.tokenNames))throw un("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw un("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;Lt(t,()=>{$r(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function rS(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||tS(e.role)||t.push(`Invalid role. Must be one of: ${Yv.join(", ")}`);const n=t.length;if(Lt(t,()=>{Fr(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Lt(t,()=>{if(!Array.isArray(e.tokenNames))throw un("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw un("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;Lt(t,()=>{$r(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}function iS(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>$n))throw un("pageSize",`number between 1 and ${$n}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw un("cursor","non-empty string",typeof e.cursor)}const oS={[Qv.MODERATOR]:1,[Qv.TECHNICAL_PRODUCER]:1,[Qv.MANAGER]:2,[Qv.OWNER]:3};function sS(e,t){return e===Qv.MANAGER?t!==Qv.OWNER:e===Qv.OWNER||e===t}class aS extends Gr{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),wn(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=nS(e);if(t.length>0)throw new qt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const r=await this.http.post(Ee.CREATE,n,this.getJwtHeaders()),i=this.extractData(r);return this.logger.debug("API key created",{id:i.id,keyPrefix:i.keyPrefix}),i}async findAll(e={}){iS(e),this.logger.debug("Listing API keys",e);const t=Wv(e,$n),n=await this.http.get(Ee.LIST,t,this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Listed API keys",{count:r.apiKeys.length,total:r.pageInfo.totalCount}),r}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=Ee.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),r=this.extractData(n);return this.logger.debug("Got API key",{id:r.id,keyPrefix:r.keyPrefix}),r}async update(e,t){this.validateApiKeyId(e);const n=rS(t);if(n.length>0)throw new qt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const r={};void 0!==t.role&&(r.role=t.role),void 0!==t.description&&(r.description=t.description),void 0!==t.delegateAllTokens&&(r.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(r.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(r.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(r.tokenPermissions=t.tokenPermissions);const i=Ee.UPDATE.replace(":id",String(e)),o=await this.http.patch(i,r,this.getJwtHeaders()),s=this.extractData(o);return this.logger.debug("Updated API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=Ee.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Yv]}}const cS={ONE_HOUR:3600,ONE_DAY:86400,ONE_WEEK:604800,ONE_MONTH:2592e3},lS={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},uS=Nr(lS),dS=Mr([{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}]),hS=Mr([{field:"userAddress",type:"string"},{field:"isPermanent",type:"boolean"}]),gS=Mr([{field:"userAddress",type:"string"}]),fS=Mr([{field:"tokenName",type:"string"},{field:"action",type:"string",validator:e=>"CHAT_MESSAGE"===e||"COMMENT"===e||"REACTION"===e}]);function pS(e){return null==e||""===e||"string"==typeof e&&(!Ur(e)&&e.length<=Wn.BAN_REASON.MAX_LENGTH)}function mS(e){return!!Ir(e)||"number"==typeof e&&(e>=jn&&e<=Vn)}class yS extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async createBan(e){!function(e){if(Dr(e.tokenName,"tokenName",Ln),!Er(e.userAddress))throw en("userAddress");if(!pS(e.reason))throw new qt(`reason must be at most ${Wn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!mS(e.durationSeconds))throw new qt(`durationSeconds must be between ${jn} and ${Vn} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(pe,{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:Tn(e.tokenName)}}async removeBan(e){!function(e){if(Dr(e.tokenName,"tokenName",Ln),!Er(e.userAddress))throw en("userAddress")}(e);const t=this.buildEndpoint(we,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),r=this.extractDataOrNull(n);return{removed:r?.removed??!0,tokenName:Tn(e.tokenName),userAddress:r?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Dr(e.tokenName,"tokenName",Ln),Cr(0,void 0,$n,e.pageSize)}(e);const t=this.buildEndpoint(me,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,$n);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getBanStatus(e){!function(e){if(Dr(e.tokenName,"tokenName",Ln),!Er(e.userAddress))throw en("userAddress")}(e);const t=this.buildEndpoint(ye,{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:Tn(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Dr(e.tokenName,"tokenName",Ln),void 0!==e.type&&!uS(e.type))throw new qt(`type must be one of: ${Object.values(lS).join(", ")}`,"type",$t.INVALID_VALUE)}(e);const t=this.buildEndpoint(be,{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(!Er(e.userAddress))throw en("userAddress");if(!pS(e.reason))throw new qt(`reason must be at most ${Wn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!mS(e.durationSeconds))throw new qt(`durationSeconds must be between ${jn} and ${Vn} 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(ke,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Er(e.userAddress))throw en("userAddress")}(e);const t=this.buildEndpoint(Ae,{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,$n,e.pageSize)}(t);const n=this.buildPaginationParams(t,$n);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const r=await this.http.get(ve,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getGlobalBan(e){!function(e){if(!Er(e.userAddress))throw en("userAddress")}(e);const t=this.buildEndpoint(Se,{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 wS(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20,concurrency:o=1,startPage:s=1}=t,a=[];let c=s;const l=s+n-1;let u=!0,d=0;if(o<=1)for(;u&&c<=l;){r&&r.debug(`Auto-pagination: fetching page ${c} with limit ${i}`);const t=await e(c,i);if(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=${o}`);u&&c<=l;){const t=[];for(let e=0;e<o&&c+e<=l;e++)t.push(c+e);r&&r.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,i).catch(e=>{const n=e,o=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===o||404===o)return r&&r.debug(`Auto-pagination: page ${t} returned ${o} (end of pagination)`,{statusCode:o}),{items:[],total:0,totalPages:0,page:t,limit:i,hasNext:!1,hasPrevious:!1};throw e})),s=await Promise.all(n);for(const e of s){if(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 bS(e){if("string"==typeof e){if(!Yk(e))throw new qt(`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=Qk(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...Qk(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(!Zk(e))throw new qt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Zk(e))throw new qt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new qt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function kS(e){return function(e){try{if(!Er(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[i,o,s,...a]=r;if(""===i||""===o||""===s)throw new Error("Collection, category, and type must be non-empty");const c=a.slice(0,-1),l=c.length>0?c.join("$"):a[0];if(""===l||void 0===l)throw new Error("AdditionalKey must be non-empty");return{collection:i,category:o,type:s,additionalKey:l}}catch(t){throw new qt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Dt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function vS(e){return{...kS(e),instance:"0"}}function SS(e){return kS(e).type}function AS(e){return fa(bS(e))}var ES=Object.freeze({__proto__:null,extractTokenSymbolFromVault:SS,isTokenClassKeyStrict:Zk,normalizeToTokenInstanceKey:bS,normalizeTokenIdToString:AS,parseVaultAddressToTokenClassKey:kS,parseVaultAddressToTokenInstance:vS});class TS{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new _n({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const r=Math.min(t,this.getMaxLimit()),i=this.buildApiParams(n),o=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...i,pageSize:r,offset:e}});if(Ir(o)||!Array.isArray(o.tokens))throw new qt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(o.tokens),rawCount:o.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:r,maxPages:i=1e4}=t,o=[];let s=0,a=!0,c=0;for(;a&&c<i;){r&&r.debug(`Auto-pagination (offset): fetching at offset ${s} with limit ${n}`);const t=await e(s,n);if(null==t||!Array.isArray(t.items)){r&&r.warn("Auto-pagination (offset): received invalid result structure, stopping");break}o.push(...t.items),a=t.rawCount===n,s+=n,c++,r&&r.debug(`Auto-pagination (offset): fetched ${o.length} items so far (hasMore=${a})`)}return c>=i&&r&&r.warn(`Auto-pagination (offset): exceeded maxPages limit of ${i}, stopping`),r&&r.debug(`Auto-pagination (offset): completed with total items: ${o.length}`),o}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw sn(e,t,this.logger)}}class IS extends Hr{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return In(e)}has(e){const t=this.primaryIndex.get(e);return void 0!==t&&t.size>0}getAll(e){const t=this.primaryIndex.get(e);return t?Array.from(t.values()):[]}getByPrimaryKey(e,t){const n=this.normalizeKey(t);return this.primaryIndex.get(e)?.get(n)}getBySecondaryKey(e,t){const n=this.normalizeKey(t);return this.secondaryIndex.get(e)?.get(n)}set(e,t){const n=new Map,r=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const i=this.normalizeKey(this.extractSecondaryKey(e));r.set(i,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,r),this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Cached ${t.length} items for ${e}`)}merge(e,t){let n=this.primaryIndex.get(e);n||(n=new Map,this.primaryIndex.set(e,n));let r=this.secondaryIndex.get(e);r||(r=new Map,this.secondaryIndex.set(e,r));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const i=this.normalizeKey(this.extractSecondaryKey(e));r.set(i,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} items for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}buildBaseStats(e){const t=[];let n=0;const r={},i={};for(const t of e)r[t]=0;for(const[e,o]of this.primaryIndex){t.push(e),n+=o.size,r[e]=o.size;const s=this.fetchTimestamps.get(e);void 0!==s&&(i[e]=s)}return{networks:t,totalItems:n,itemsByNetwork:r,fetchTimestamps:i}}clear(e){void 0!==e&&""!==e?(this.primaryIndex.delete(e),this.secondaryIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared cache for ${e}`)):(this.primaryIndex.clear(),this.secondaryIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all caches"))}size(e){return this.primaryIndex.get(e)?.size??0}hasByPrimaryKey(e,t){return void 0!==this.getByPrimaryKey(e,t)}getCachedNetworks(){return Array.from(this.primaryIndex.keys())}dump(){const e={};for(const t of this.getCachedNetworks())e[t]=this.getAll(t);return e}}const CS=["ETHEREUM","SOLANA"];class NS extends IS{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(CS);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class _S extends TS{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new NS(t)}buildApiParams(e){return{canBridgeTo:(e?.network??"ETHEREUM").toLowerCase()}}transformApiResponse(e){return e.map(e=>{const t=e.otherNetworks?.find(e=>"Ethereum"===e.network),n=e.otherNetworks?.find(e=>"Solana"===e.network),r=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),i={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:r};return void 0!==t?.contractAddress&&(i.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(i.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(i.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(i.solanaSymbol=n.symbol),void 0!==e.image&&(i.image=e.image),void 0!==e.description&&(i.description=e.description),i})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:r=this.getDefaultLimit()}=e,i=Math.min(r,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${i})`),sa(async()=>{const e=(await this.executePaginatedRequest(n,i,{network:t})).items;return 0===n?this.cache.set(t,e):this.cache.merge(t,e),{tokens:e,network:t,fetchedAt:Date.now(),tokenCount:e.length}},`Failed to fetch bridgeable tokens for ${t}`,this.logger)}async fetchAllBridgeableTokensByNetwork(e){return sa(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:r,logger:i,itemTypeName:o="items"}=e;if(n.has(t)){const e=n.getAll(t);return i&&i.debug(`Returning ${e.length} cached ${o} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${o} for ${t} (no cache)`);const s=await r();return n.set(t,s),{items:s,fetchedAt:Date.now(),itemCount:s.length}}({network:e,cache:this.cache,fetchFn:()=>this.autoPaginateFetch({network:e}),logger:this.logger,itemTypeName:"bridgeable tokens"});return{tokens:t.items,network:e,fetchedAt:t.fetchedAt,tokenCount:t.itemCount}},`Failed to fetch bridgeable tokens for ${e}`,this.logger)}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork("ETHEREUM")}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork("SOLANA")}async isTokenBridgeableToNetwork(e){const{tokenId:t,network:n}=e,r=AS(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const i=this.cache.getByTokenId(n,r),o=void 0!==i,s=o?"ETHEREUM"===n?i.ethereumContractAddress:i.solanaContractAddress:void 0,a={isBridgeable:o,tokenSymbol:i?.symbol??Qk(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 xS(e){return{maxAcceptableReverseBondingCurveFee:dr(e.maxAcceptableReverseBondingCurveFee)}}const DS={BuyNativeDto:class extends g{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=dr(t),this.expectedToken=hr(n),this.extraFees=xS(r)}},BuyExactDto:class extends g{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=hr(t),this.expectedNativeToken=dr(n),this.extraFees=xS(r)}},SellExactDto:class extends g{constructor(e,t,n="0",r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=hr(t),this.expectedNativeToken=dr(n),this.extraFees=xS(r)}},SellNativeDto:class extends g{constructor(e,t,n,r={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=dr(t),this.expectedToken=hr(n),this.extraFees=xS(r)}}};function PS(e,t,n){let r;gr(t,0,1,"slippageToleranceFactor");try{r=cr(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const i=r.multipliedBy(t);let o;switch(n){case"buy-native":case"sell-exact":o=r.minus(i);break;case"buy-exact":case"sell-native":o=r.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return Is(o)&&(o=fs(0)),ps(o)}class BS extends Hr{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),r=p(e),i={...e,prefix:r},{signature:o,domain:s}=await this.signWithEthersWallet(n,i),a={...e,signature:o,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(a),signatureLength:o.length}),a}catch(e){this.logger.error("❌ Signature generation failed:",e);throw on(`Failed to sign DTO: ${Dt(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 rn("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();n={name:i.name,chainId:sr(i.chainId,1)},r=await this.walletProvider.signTypedData(n,e,t)}}return{signature:r,domain:n}}catch(e){throw on(`Ethers.js signing failed: ${Dt(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const r=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,r,o=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=i(e,t[0],r,!0);return o||n[r].push({name:e,type:(s??e)+"[]"}),void 0!==s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(void 0!==n[e])throw new qt(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).filter(([e,t])=>null!=t).forEach(([t,n])=>{i(t,n,e)}),o||n[r].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new qt(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return o||n[r].push({name:e,type:i}),i}}};return Object.entries(r).forEach(([t,n])=>{i(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class RS{toLaunchpadFormat(e){if(null==e)throw new qt('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(Yk(e))return e;throw new qt(`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 fa({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=Vk(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return""===e?"":Yk(e)?e:`${e}|Unit|none|none`}normalize(e){return"string"==typeof e&&Yk(e)?e:this.toLaunchpadFormat(e)}}function MS(e){if(!Er(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function OS(e){return Vk(e,"$","dollar-delimited token")}class LS extends Hr{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),r=this.createGalaInstance(),i=`$service$${n.toStringKey()}$launchpad`,o=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${r.toStringKey()}$${e}`,c=[i,o,s,a,`$tokenBalance$${r.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Dt(e);throw new qt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new v;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 v;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(!Er(e))throw en("vaultAddress","Vault address");try{const t=SS(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof qt)throw tn("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Er(e))throw en("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw tn("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw tn("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Er(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 tn("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 tn("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 OS(e)}catch(e){if(e instanceof qt)throw tn("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}class US extends Gr{constructor(e,t,n=!1,r,i,o=.05,s=.01){super(e,n),this.tokenResolver=t,this._walletProvider=r,this.userAddress=i,this.defaultSlippageToleranceFactor=o,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=i&&(this.signatureService=new BS(this._walletProvider,n),this.tokenKeyService=new LS(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:yn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof qt)return{success:!1,error:Dt(e)};throw e}}validateBundleData(e){if(null==e)throw en("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw en("signedDto","Signed DTO");if(!Er(e.method))throw en("method","Method name");if(!Array.isArray(e.stringsInstructions))throw tn("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new qt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw tn("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Er(e))throw new qt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!Jk(e))throw new qt(`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=bn(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(Rt(e)&&null!==e.response&&void 0!==e.response){const t=bn(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 Dt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Er(e))throw en("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 qt)return{success:!1,error:Dt(e)};throw e}}async cancelTransaction(e){try{if(!Er(e))throw en("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 qt)return{success:!1,error:Dt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Sn(()=>this.http.get(`${this.bundleEndpoint}/health`),{errorContext:"Bundle service health check failed",logger:this.logger});return null==e?{success:!1,error:"No response from bundle service health check"}:(this.logger.debug("💚 Bundle service health:",e),{success:!0,data:e})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}}async buyToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:i}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===r){if(null==i||""===i)throw new qt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=PS(i,o,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:o,adjustedMinTokens:e});const t=new DS.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==i||""===i)throw new qt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=PS(i,o,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:o,adjustedMaxGalaCost:e});const t=new DS.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:r,expectedAmount:i}=e,{effectiveSlippageFactor:o,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===r){if(null==i||""===i)throw new qt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=PS(i,o,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:o,adjustedMinGala:e});const t=new DS.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==i||""===i)throw new qt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=PS(i,o,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:o,adjustedMaxTokensToSell:e});const t=new DS.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,r){const{effectiveSlippageFactor:i,effectiveMaxFee:o}=this.calculateEffectiveSlippage(t,n,r),s=await this.resolveTokenNameToVault(e);if(null==s)throw Zt(e);return{effectiveSlippageFactor:i,effectiveMaxFee:o,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const r=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let o=e??"0";return null!=e&&(o=PS(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:o})),{effectiveSlippageFactor:r,effectiveFeeSlippageFactor:i,effectiveMaxFee:o}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw rn("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw en("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${w()}-${Date.now()}-${String(this.userAddress)}`;const r=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(n),o={stringsInstructions:i,method:t,signedDto:r};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(r)});const s=await this.submitTransaction(o);if(s.success){const e=bn(s);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const a="string"==typeof s.error?s.error:"Bundle transaction failed";throw new Ht(a,void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}var FS,$S,qS,KS;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(FS||(FS={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}($S||($S={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(qS||(qS={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(KS||(KS={}));const GS={[$S.INAPPROPRIATE_CONTENT]:"Inappropriate Content",[$S.SPAM]:"Spam",[$S.HARASSMENT]:"Harassment",[$S.SCAM]:"Scam",[$S.OTHER]:"Other"},HS={[qS.PENDING]:"Pending",[qS.DISMISSED]:"Dismissed",[qS.ACTIONED]:"Actioned"},WS={[KS.DELETE_CONTENT]:"Delete Content",[KS.BAN_USER]:"Ban User",[KS.DELETE_AND_BAN]:"Delete & Ban"},zS={[FS.CHAT_MESSAGE]:"Chat Message",[FS.COMMENT]:"Comment",[FS.STREAM]:"Stream",[FS.RECORDING]:"Recording"},jS=500,VS=Nr(FS),XS=Nr($S),QS=Nr(qS),YS=Nr(KS),JS=Mr([{field:"id",type:"number"},{field:"tokenName",type:"string"},{field:"contentType",type:"string",validator:VS},{field:"contentId",type:"string"},{field:"reporterAddress",type:"string"},{field:"reportedUserAddress",type:"string"},{field:"status",type:"string",validator:QS}]),ZS={TOKEN_NAME:Un,CONTENT_ID:Wn.CONTENT_ID,DETAILS:Wn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:$n}};function eA(e,t="tokenName"){Dr(e,t,ZS.TOKEN_NAME)}class tA extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async createFlag(e){!function(e){if(eA(e.tokenName),void 0===e.contentType)throw en("contentType","Content type");if(!VS(e.contentType))throw tn("contentType",`one of: ${Object.values(FS).join(", ")}`,"Content type");if(!Er(e.contentId))throw en("contentId","Content ID");if(e.contentId.length>ZS.CONTENT_ID.MAX_LENGTH)throw ln("contentId",ZS.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Er(e.reportedUserAddress))throw en("reportedUserAddress","Reported user address");if(ri(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==FS.STREAM&&e.contentType!==FS.RECORDING||void 0!==e.reason&&null!==e.reason))throw en("reason","Reason");if(void 0!==e.reason&&!XS(e.reason))throw tn("reason",`one of: ${Object.values($S).join(", ")}`,"Reason");if(void 0!==e.details&&!Er(e.details))throw un("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>ZS.DETAILS.MAX_LENGTH)throw ln("details",ZS.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(Be.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){!function(e){if(eA(e.tokenName),void 0!==e.contentType&&!VS(e.contentType))throw tn("contentType",`one of: ${Object.values(FS).join(", ")}`,"Content type");if(void 0!==e.status&&!QS(e.status))throw tn("status",`one of: ${Object.values(qS).join(", ")}`);if(void 0!==e.reason&&!XS(e.reason))throw tn("reason",`one of: ${Object.values($S).join(", ")}`);if(void 0!==e.reporterAddress&&!Er(e.reporterAddress))throw un("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&ri(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Er(e.reportedUserAddress))throw un("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&ri(e.reportedUserAddress,"reportedUserAddress"),Cr(0,void 0,ZS.PAGINATION.MAX_LIMIT,e.pageSize)}(e);const t=Wv(e,$n);zv(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(Be.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&&eA(e.tokenName),void 0!==e.contentType&&!VS(e.contentType))throw tn("contentType",`one of: ${Object.values(FS).join(", ")}`,"Content type");if(void 0!==e.status&&!QS(e.status))throw tn("status",`one of: ${Object.values(qS).join(", ")}`);if(void 0!==e.reason&&!XS(e.reason))throw tn("reason",`one of: ${Object.values($S).join(", ")}`);if(void 0!==e.reporterAddress&&!Er(e.reporterAddress))throw un("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&ri(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Er(e.reportedUserAddress))throw un("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&ri(e.reportedUserAddress,"reportedUserAddress"),Cr(0,void 0,ZS.PAGINATION.MAX_LIMIT,e.pageSize)}(e);const t=Wv(e,$n);zv(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(Be.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 en("flagId","Flag ID");try{pr(e.flagId,"flagId")}catch{throw tn("flagId","a positive integer","Flag ID")}}(e);const t=Be.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 en("flagId","Flag ID");try{pr(e.flagId,"flagId")}catch{throw tn("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw en("action","Action");if(!YS(e.action))throw tn("action",`one of: ${Object.values(KS).join(", ")}`,"Action")}(e);const t=Be.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}}const nA=["heart","fire","laugh","wow","thumbs_up"],rA={heart:"❤️",fire:"🔥",laugh:"😂",wow:"😮",thumbs_up:"👍"};class iA extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateReactionTokenName(e){this.validateTokenName(e,Un)}validateMessageId(e){if(!Er(e))throw en("messageId","Message ID");if(fr(e,zn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!zn.CONTENT_REACTION.PATTERN.test(e))throw tn("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Er(e))throw en("reactionType","Reaction type");if(!nA.includes(e))throw tn("reactionType",`one of: ${nA.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=st,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=Tn(e.tokenName));const r=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(r),{created:o,...s}=i;return{data:s,created:o}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${at}?${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 oA extends Gr{constructor(e,t,n=void 0,r=5,i=!1){super(e,i),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=r}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const r=e[n];t.push({poolIndex:n,token:r.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:r.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${r.token0}`,{error:Dt(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:Dt(e)})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const r=t.slice(e,e+this.pricingConcurrency),i=await Promise.allSettled(r.map(e=>e.task));for(let e=0;e<r.length;e++){const t=r[e],o=i[e],s=n.get(t.poolIndex)??{};"fulfilled"===o.status&&null!=o.value&&(t.isToken0?s.token0Price=o.value:s.token1Price=o.value),n.set(t.poolIndex,s)}}const r=e.map((e,t)=>{const r=n.get(t)??{},i={...e};return void 0!==r.token0Price&&(i.token0Price=r.token0Price),void 0!==r.token1Price&&(i.token1Price=r.token1Price),i}),i=r.filter(e=>null!=e.token0Price&&null!=e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),r}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:r="desc",page:i=1,limit:o=Uv.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:r,page:i,limit:o,withPrices:s});const a=Math.min(o,20),c=Math.max(i,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 vn(()=>this.http.get(u),{errorContext:"Failed to fetch DEX pools",logger:this.logger});let h=d.pools;const g=d.count??0,f=c*a<g,p=c>1;s&&(h=await this.enrichPoolsWithPricing(h)),this.logger.debug("DEX pools fetched successfully",{poolCount:h.length,totalCount:g,hasNextPage:f,withPrices:s});return{items:h,pageInfo:{hasNextPage:f,hasPrevPage:p,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 sA(e){try{if(!Er(e))throw new Error("Token must be a non-empty string");return Qk(e)}catch(t){throw new qt(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${Dt(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}const aA=5;class cA extends Gr{constructor(e,t,n=!1,r=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.galaChainBaseUrl=t}validateFetchCompositePoolDataInput(e,t,n){if(!Er(e))throw new Qt("token0 must be a non-empty string",{token0:e});if(!Er(t))throw new Qt("token1 must be a non-empty string",{token1:t});try{Qk(e),Qk(t)}catch(n){throw new Qt(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${Dt(n)}`,{token0:e,token1:t})}try{pr(n,"fee")}catch{throw new Qt(`fee must be a positive integer (got ${n})`,{fee:n})}const r=[500,3e3,1e4];if(!r.includes(n))throw new Qt(`fee must be one of: ${r.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!Er(e))throw new Qt("amount must be a non-empty string",{amount:e});const t=fs(e);try{Ds(t,"amount")}catch(t){throw new Qt(t.message,{amount:e})}}convertTokenClassKey(e){const t=new v;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:r,gatewayBaseUrl:i}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:r}),this.validateFetchCompositePoolDataInput(t,n,r);try{const e=sA(t),o=sA(n),s=this.convertTokenClassKey(e),a=this.convertTokenClassKey(o),c=new I(s,a,r),l=`${i??this.galaChainBaseUrl}/api/asset/dexv3-contract/GetCompositePool`,u=await this.http.post(l,c);Mt(u,`Pool not found: ${t}/${n} with fee ${r}`);const d=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 A(t.token0,t.token1,t.token0ClassKey,t.token1ClassKey,t.fee,fs(t.sqrtPrice),t.protocolFees);n.bitmap=t.bitmap,n.grossPoolLiquidity=fs(t.grossPoolLiquidity),n.liquidity=fs(t.liquidity),n.feeGrowthGlobal0=fs(t.feeGrowthGlobal0),n.feeGrowthGlobal1=fs(t.feeGrowthGlobal1),n.protocolFeesToken0=fs(t.protocolFeesToken0),n.protocolFeesToken1=fs(t.protocolFeesToken1),n.tickSpacing=t.tickSpacing,n.maxLiquidityPerTick=fs(t.maxLiquidityPerTick);const r={},i=e.tickDataMap;Object.keys(i).forEach(e=>{const t=i[e],n=t.initialised,o=t.liquidityNet,s=t.liquidityGross,a=t.feeGrowthOutside0,c=t.feeGrowthOutside1,l=new E(t.poolHash,t.tick);l.initialised=n,l.liquidityNet=fs(o),l.liquidityGross=fs(s),l.feeGrowthOutside0=fs(a),l.feeGrowthOutside1=fs(c),r[e]=l});const o=e.token0Balance,s=o.quantity,a={...o},c=new S(a);c.quantity=fs(s),Object.keys(a).forEach(e=>{e in c||(c[e]=a[e])});const l=e.token1Balance,u=l.quantity,d={...l},h=new S(d);return h.quantity=fs(u),Object.keys(d).forEach(e=>{e in h||(h[e]=d[e])}),new T(n,r,c,h,e.token0Decimals,e.token1Decimals)}(u.Data),u.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:r,liquidity:d.pool.liquidity.toString()}),d}catch(e){if(e instanceof Yt)throw e;const i=Dt(e);if(i.includes("status indicates failure")||i.includes("Pool not found"))throw new Yt(i);throw this.logger.error("Failed to fetch composite pool data",e),new Qt(`Failed to fetch composite pool data: ${i}`,{token0:t,token1:n,fee:r})}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:i}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:r,amount:i}),this.validateQuoteAmount(i),null==t)throw new Qt("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=sA(n),s=sA(r),a=this.convertTokenClassKey(o),c=this.convertTokenClassKey(s),[l,u]=n<r?[a,c]:[c,a],d=new C(l,u,t.pool.fee,fs(i),e,t.compositePoolDto),h=await N(null,d);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new Qt(`Local quote calculation failed: ${Dt(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:r,amount:i}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:r,amount:i}),this.validateQuoteAmount(i),null==t)throw new Qt("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),o=sA(n),s=sA(r),a=this.convertTokenClassKey(o),c=this.convertTokenClassKey(s),l=new C(a,c,t.pool.fee,fs(i),e,void 0),u=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/QuoteExactAmount`,d=await this.http.post(u,l);Mt(d,"External quote failed");const h=d.Data,g=h.amount0,f=h.amount1;return this.logger.debug("External quote calculated",{amount0:g,amount1:f}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new Qt(`External quote calculation failed: ${Dt(e)}`,{fromToken:n,toToken:r,amount:i})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class lA extends Hr{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}=xr(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 qt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw en("tokenId","Token ID");try{const t=bS(e),n=fa(t),r=MS(n);if(this.logger.debug(`Fetching DEX spot price for token: ${r}`),!this.dexBackendHttp)throw nn("DEX Backend API client not configured");const i=bn(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:r}}));if(null==i||"string"!=typeof i)throw new qt("Invalid price response: data must be a string, got "+typeof i,"data","INVALID_RESPONSE");const o=function(e,t){if(Pn(e)||""===e)throw en(t);const n="number"==typeof e?e:parseFloat(String(e));if(isNaN(n))throw dn(t,e);if(!isFinite(n))throw dn(t,e);return n}(i,"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): $${o}`),{symbol:a,price:o}}this.logger.debug(`Symbol cache miss for ${s}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(s,{symbol:a}),this.logger.debug(`Cached symbol for ${s}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${xt(e)?e.message:String(e)}`),a=Cn("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${a} (fallback): $${o}`)}return{symbol:a,price:o}}catch(e){if(e instanceof qt)throw e;throw nn(`Failed to fetch DEX spot price: ${Dt(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Er(e))throw new qt(Ut,"tokenName",$t.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=fa(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Dt(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const r=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==i)throw nn("GALA price not available");const o=rr(r.amount,0)/1e18;if(o<=0)throw new qt(`Invalid token amount calculation: ${o}`,"amount","INVALID_CALCULATION");const s=i.price/o;return{symbol:Cn(e),price:s}}catch(t){if(xt(t))throw nn(`Failed to calculate launchpad token spot price for ${e}: ${Dt(t)}`);throw nn(`Failed to calculate launchpad token spot price for ${e}: ${Dt(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw nn("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 qt||xt(t))&&("NetworkError"===t.name||Dt(t).includes("Token not found")))throw t;throw nn(`Failed to fetch token details from GalaChain for ${String(e)}: ${Dt(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw nn("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=bn(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:Rn(t?.start??null),end:Rn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(xt(e)&&Dt(e).includes("not configured"))throw e;if(Rt(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw nn(`Failed to fetch DEX seasons: ${Dt(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{pr(e,"seasonId")}catch{throw en("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw nn("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=bn(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(xt(t)&&Dt(t).includes("must be a positive number"))throw t;throw nn(`Failed to fetch DEX leaderboard for season ${e}: ${Dt(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 nn("DEX Backend API client not configured");const e=bn(await this.dexBackendHttp.request({method:"GET",url:"/explore/volume"}));if(!e)throw nn("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 nn(`Failed to fetch DEX volume summary: ${Dt(e)}`)}}}const uA={BATCH_SIZE:20,FLUSH_INTERVAL_MS:3e3,MAX_QUEUE_SIZE:1e3,FLUSH_ON_PAGE_HIDE:!0,FLUSH_ON_PAGE_UNLOAD:!0,DEBUG:!1},dA={LOGIN:"login",LOGOUT:"logout",TOKEN_BUY:"token_buy",TOKEN_SELL:"token_sell",TOKEN_SWAP:"token_swap",TOKEN_CREATED:"token_created",TOKEN_GRADUATED:"token_graduated",PAGE_VIEW:"page_view",PAGE_LEAVE:"page_leave",STREAM_START:"stream_start",STREAM_END:"stream_end",STREAM_VIEWERS_CHANGED:"stream_viewers_changed",CHAT_MESSAGE_SENT:"chat_message_sent",CHAT_MESSAGE_RECEIVED:"chat_message_received",LIQUIDITY_ADDED:"liquidity_added",LIQUIDITY_REMOVED:"liquidity_removed",BRIDGE_DEPOSIT:"bridge_deposit",BRIDGE_WITHDRAW:"bridge_withdraw",PROFILE_UPDATED:"profile_updated",BALANCE_CHANGED:"balance_changed",ERROR_OCCURRED:"error_occurred"};class hA{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 _n({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??uA.BATCH_SIZE,flushIntervalMs:t.flushIntervalMs??uA.FLUSH_INTERVAL_MS,maxQueueSize:t.maxQueueSize??uA.MAX_QUEUE_SIZE,flushOnPageHide:t.flushOnPageHide??uA.FLUSH_ON_PAGE_HIDE,flushOnPageUnload:t.flushOnPageUnload??uA.FLUSH_ON_PAGE_UNLOAD,debug:t.debug??uA.DEBUG},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const r={eventType:e,payload:t,clientTimestamp:(new Date).toISOString(),...void 0!==n?.userAddress&&""!==n.userAddress&&{userAddress:n.userAddress},...void 0!==n?.tokenName&&""!==n.tokenName&&{tokenName:n.tokenName},...void 0!==n?.sessionId&&""!==n.sessionId&&{sessionId:n.sessionId}};this.buffer(r),n?.immediate&&this.scheduleFlush(0)}async flush(){if(0===this.eventBuffer.length)return;this.cancelFlushTimer();const e=this.eventBuffer.splice(0);this.logger.debug(`Flushing ${e.length} events`);try{const t=await this.submitEvents(e);this.totalFlushed+=t.accepted,this.lastFlushTime=Date.now(),this.lastError=void 0,this.logger.debug(`Flush successful, accepted ${t.accepted} events`)}catch(t){throw this.eventBuffer.unshift(...e),this.lastError=t instanceof Error?t.message:String(t),this.logger.error(`Flush failed: ${this.lastError}`),t}}getStats(){const e={bufferedCount:this.eventBuffer.length,totalQueued:this.totalQueued,totalFlushed:this.totalFlushed,totalDropped:this.totalDropped};return void 0!==this.lastFlushTime&&(e.lastFlushTime=this.lastFlushTime),void 0!==this.lastError&&(e.lastError=this.lastError),e}configure(e){void 0!==e.batchSize&&(this.config.batchSize=e.batchSize),void 0!==e.flushIntervalMs&&(this.config.flushIntervalMs=e.flushIntervalMs),void 0!==e.maxQueueSize&&(this.config.maxQueueSize=e.maxQueueSize),void 0!==e.flushOnPageHide&&(this.config.flushOnPageHide=e.flushOnPageHide),void 0!==e.flushOnPageUnload&&(this.config.flushOnPageUnload=e.flushOnPageUnload)}async shutdown(e=5e3){if(this.isShuttingDown=!0,this.removePageLifecycleListeners(),0!==this.eventBuffer.length)try{await Promise.race([this.flush(),new Promise((t,n)=>setTimeout(()=>n(new Error("Flush timeout during shutdown")),e))])}catch(e){this.logger.error(`Shutdown flush failed: ${e instanceof Error?e.message:String(e)}`)}}buffer(e){this.eventBuffer.length>=this.config.maxQueueSize&&(this.eventBuffer.shift(),this.totalDropped++,this.logger.warn("Event buffer full, dropped oldest event")),this.eventBuffer.push(e),this.totalQueued++,this.eventBuffer.length>=this.config.batchSize?this.scheduleFlush(0):this.scheduleFlush(this.config.flushIntervalMs)}scheduleFlush(e){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush().catch(e=>{this.logger.error(`Scheduled flush failed: ${e instanceof Error?e.message:String(e)}`)})},e))}cancelFlushTimer(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}async submitEvents(e){return await this.httpClient.post("/v1/events",{events:e})}setupPageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.addEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.addEventListener("beforeunload",this.handleBeforeUnload))}removePageLifecycleListeners(){"undefined"!=typeof document&&(this.config.flushOnPageHide&&document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.config.flushOnPageUnload&&window.removeEventListener("beforeunload",this.handleBeforeUnload))}flushWithBeacon(){if("undefined"==typeof navigator||!navigator.sendBeacon)return;const e=this.eventBuffer.splice(0),t=JSON.stringify({events:e});try{const n=this.getBaseUrl();navigator.sendBeacon(`${n}/v1/events`,t)?(this.totalFlushed+=e.length,this.lastFlushTime=Date.now()):(this.eventBuffer.unshift(...e),this.logger.warn("sendBeacon returned false, events re-buffered"))}catch(t){this.eventBuffer.unshift(...e),this.logger.error(`sendBeacon failed: ${t instanceof Error?t.message:String(t)}`)}}getBaseUrl(){const e=this.httpClient.config;return e?.baseUrl??""}}function gA(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>k(e).plus(t.quantity).toString(),"0")}function fA(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 pA extends Gr{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(Jk(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{Mt(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 o=fa(i),s={quantity:i.quantity,collection:i.collection,category:i.category,tokenId:o};if((i.inUseHolds?.length??0)>0){const e=fA(i.inUseHolds??[],t);e.length>0&&(s.inUseHolds=e,s.inUseQuantity=gA(e))}if((i.lockedHolds?.length??0)>0){const e=fA(i.lockedHolds??[],t);e.length>0&&(s.lockedHolds=e,s.lockedQuantity=gA(e))}return void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=function(e,t="0",n="0"){return k(e).minus(t).minus(n).toString()}(s.quantity,s.lockedQuantity,s.inUseQuantity)),s}catch(e){throw nn(`Failed to fetch token balance from GalaChain: ${Dt(e)}`,void 0,xt(e)?e:void 0)}}}function mA(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class yA extends g{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,i){let o;if("string"==typeof r){o={...OS(r),instance:"0"}}else o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new yA({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:o}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey??mA()})}static forGALA(e,t,n,r){return new yA({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??mA()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return pa(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 wA extends g{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 i;if("string"==typeof n){i={...OS(n),instance:"0"}}else i={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new wA({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==r?.name&&{name:r.name},uniqueKey:r?.uniqueKey??mA()})}static forGALA(e,t,n){return new wA({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??mA()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return pa(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function bA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Er(t.amount)&&(void 0!==t.tokenId||Er(t.tokenName))&&(void 0===t.lockAuthority||"string"==typeof t.lockAuthority)&&(void 0===t.expires||"number"==typeof t.expires)&&(void 0===t.name||"string"==typeof t.name)}function kA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Er(t.amount)&&(void 0!==t.tokenId||Er(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}function vA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(bA)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}function SA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(kA)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const AA=100,EA=100;var TA,IA;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(TA||(TA={}));class CA 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"}(IA||(IA={}));class NA extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}class _A{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 Qr).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new Qr).toEthereumFormat(e)}catch{try{return ei(e)}catch{return e}}}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...OS(e),instance:"0"}}}const xA=100,DA=100;class PA extends Gr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new _A(t):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new CA("Wallet required for token lock operations",TA.WALLET_REQUIRED);return sa(async()=>{const t=Zr(this.wallet.address),n=[],r=[];let i=t;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(i=Zr(o.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const o of e.tokens){let e;if(void 0!==o.tokenId)e=bS(o.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",o.tokenId);else{if(void 0===o.tokenName)throw new CA("Must provide either tokenId or tokenName for token identification",TA.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(o.tokenName)}n.push({owner:t,quantity:o.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:o.amount,lockAuthority:void 0!==o.lockAuthority?Zr(o.lockAuthority):i})}const c=new yA({lockAuthority:i,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??mA()}),l=await this.signatureHelper.signLockToken(c.toSigningPayload()),u=new yA({...c.toSigningPayload(),signedPayload:l}),d=await this.http.post("/api/asset/token-contract/LockTokens",u);try{Mt(d,"Token lock failed")}catch(e){const t=Ot(d);throw new CA(`${Dt(e)}${t}`,TA.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 CA("Wallet required for token unlock operations",TA.WALLET_REQUIRED);return sa(async()=>{const t=Zr(this.wallet.address),n=[],r=[],i=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(void 0!==i.tokenId)e=bS(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(void 0===i.tokenName)throw new CA("Must provide either tokenId or tokenName for token identification",TA.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount})}const o=new wA({tokenInstances:n,...void 0!==i?.name&&{name:i.name},uniqueKey:e.uniqueKey??mA()}),s=await this.signatureHelper.signUnlockToken(o.toSigningPayload()),a=new wA({...o.toSigningPayload(),signedPayload:s}),c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);try{Mt(c,"Token unlock failed")}catch(e){const t=Ot(c);throw new CA(`${Dt(e)}${t}`,TA.NETWORK_ERROR)}return this.extractUnlockResult(c,r)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateLockTokensData(e){if(!vA(e))throw new CA("Invalid lock data: missing required fields",TA.VALIDATION_ERROR);if(e.tokens.length>xA)throw new CA(`Batch size exceeds maximum limit of ${xA} tokens per lock operation`,TA.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new CA("Must provide either tokenId or tokenName for token identification",TA.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{Rr(t.tokenName,"tokenName")}catch{throw new CA("Invalid token name format",TA.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=fs(t.amount);try{_s(e)}catch{throw new CA(tn("lockAmount","a positive number","Lock amount").message,TA.INVALID_AMOUNT,{amount:t.amount})}if(void 0!==t.lockAuthority&&!ni(t.lockAuthority))throw new CA("Invalid lock authority address format",TA.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{pr(t.expires,"expires")}catch{throw new CA(tn("expires","a positive integer (epoch milliseconds)","Expires").message,TA.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!SA(e))throw new CA("Invalid unlock data: missing required fields",TA.VALIDATION_ERROR);if(e.tokens.length>DA)throw new CA(`Batch size exceeds maximum limit of ${DA} tokens per unlock operation`,TA.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new CA("Must provide either tokenId or tokenName for token identification",TA.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{Rr(t.tokenName,"tokenName")}catch{throw new CA("Invalid token name format",TA.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=fs(t.amount);try{_s(e)}catch{throw new CA(tn("unlockAmount","a positive number","Unlock amount").message,TA.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 CA)return e;let r=t,i=TA.NETWORK_ERROR;if(Rt(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 o=String(e.Message??"").toLowerCase();o.includes("insufficient")||o.includes("balance")?i=TA.INSUFFICIENT_BALANCE:o.includes("lock")&&o.includes("not found")?i=TA.LOCK_NOT_FOUND:o.includes("not found")||o.includes("token")?i=TA.TOKEN_NOT_FOUND:o.includes("authority")?i=TA.NOT_LOCK_AUTHORITY:o.includes("expired")&&(i=TA.LOCK_EXPIRED)}}else xt(e)&&(r=`${t}: ${Dt(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new CA(r,i,Object.keys(o).length>0?o:void 0)}async resolveTokenInstance(e){return sa(async()=>{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!==t){const n=vS(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:In(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 NA)throw new CA(Dt(t),TA.TOKEN_NOT_FOUND);throw new CA(`Failed to resolve token '${e}': ${Dt(t)}`,TA.TOKEN_NOT_FOUND,{tokenName:e})})}}class BA extends Gr{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?bS(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw en("publicAxios","Public Axios instance");const r=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(Mt(r,"Failed to fetch token class from GalaChain"),null===r.Data||void 0===r.Data||0===r.Data.length)throw nn(`Token not found on GalaChain: ${fa(t)}`,404);return r.Data[0]}catch(e){if(e instanceof qt)throw e;if(Rt(e)&&404===e.response?.status)throw nn("Token not found on GalaChain",404,xt(e)?e:void 0);if(xt(e)&&"Error"===e.name&&Dt(e).includes("status indicates failure"))throw nn(Dt(e),400,xt(e)?e:void 0);const t=Dt(e);if(t.includes("Token not found"))throw e;throw nn(`Failed to fetch token class from GalaChain: ${t}`,void 0,xt(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw en("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw en("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(Mt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw nn("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof qt)throw e;if(Rt(e)&&404===e.response?.status)throw nn("Token supply data not found on GalaChain",404,xt(e)?e:void 0);if(xt(e)&&"Error"===e.name&&Dt(e).includes("status indicates failure"))throw nn(Dt(e),400,xt(e)?e:void 0);const t=Dt(e);if(t.includes("Token not found"))throw e;throw nn(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,xt(e)?e:void 0)}}}class RA extends g{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={...OS(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 RA({tokenInstances:n,uniqueKey:t?.uniqueKey??mA()})}static fromTokenClassKey(e,t,n){return RA.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new RA({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??mA()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return pa(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class MA extends g{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,i){let o;if("string"==typeof r){o={...OS(r),instance:"0"}}else o={collection:r.collection,category:r.category,type:r.type,additionalKey:r.additionalKey,instance:"0"};return new MA({from:e,to:t,quantity:n,tokenInstance:o,uniqueKey:i??mA()})}static forGALA(e,t,n,r){return new MA({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:r??mA()})}getTokenClassKey(){return pa(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function OA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Er(t.amount)&&(void 0!==t.tokenId||Er(t.tokenName))}function LA(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(OA)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}const UA=50;var FA;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR"}(FA||(FA={}));class $A extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}class qA{static validateAmount(e){const t=fs(e);try{Ds(t,"amount")}catch(t){throw new NA(t.message,IA.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!Ir(e)&&Er(e)){if(e.length>Xn.MAX_LENGTH)throw new qt(`Unique key too long. Maximum length: ${Xn.MAX_LENGTH}`);if(!Xn.PATTERN.test(e))throw new NA('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',IA.INVALID_AMOUNT,{uniqueKey:e})}}}const KA="gala-transfer-successful",GA="token-transfer-successful",HA="token-locked-successfully",WA="token-unlocked-successfully",zA="transfer-successful-no-id",jA=50;class VA extends Gr{constructor(e,t,n,r=!1){super(e,r),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new _A(t):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new NA("Wallet required for GALA transfer operations",IA.WALLET_REQUIRED);try{const t=Zr(e.recipientAddress),n=Zr(this.wallet.address),r=MA.forGALA(n,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(r.toSigningPayload()),o=new MA({...r.toSigningPayload(),signedPayload:i}),s=await this.http.post("/api/asset/token-contract/TransferToken",o);if(null==s)throw new NA("No response from GalaChain transfer service",IA.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 NA("Wallet required for token transfer operations",IA.WALLET_REQUIRED);try{const t=Zr(e.to),n=Zr(this.wallet.address);let r;if(null!==e.tokenId&&void 0!==e.tokenId)r=bS(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 NA("Must provide either tokenId or tokenName for token identification",IA.TOKEN_NOT_FOUND);r=await this.resolveTokenInstance(e.tokenName)}const i=new MA({from:n,to:t,quantity:e.amount,tokenInstance:r,uniqueKey:e.uniqueKey??mA()}),o=await this.signatureHelper.signTransferToken(i.toSigningPayload()),s=new MA({...i.toSigningPayload(),signedPayload:o}),a=await this.http.post("/api/asset/token-contract/TransferToken",s);if(null==a)throw new NA("No response from GalaChain transfer service",IA.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 NA)throw t;throw new NA(`Failed to resolve token class key for '${e}': ${Dt(t)}`,IA.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new $A("Wallet required for token burn operations",FA.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=bS(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new $A("Must provide either tokenId or tokenName for token identification",FA.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new RA({tokenInstances:t,uniqueKey:e.uniqueKey??mA()}),r=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),i=new RA({...n.toSigningPayload(),signedPayload:r}),o=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(null==o)throw new $A("No response from GalaChain burn service",FA.NETWORK_ERROR);try{Mt(o,"Token burn operation")}catch(e){throw new Kt(Dt(e),500)}return this.extractBurnResult(o)}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 Er(t.recipientAddress)&&Er(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new qt("Invalid GALA transfer data: missing required fields");if(!ni(e.recipientAddress))throw new NA("Invalid recipient address format",IA.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});qA.validateAmount(e.amount),qA.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Er(t.to)&&Er(t.amount)&&(void 0!==t.tokenId||Er(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new qt("Invalid token transfer data: missing required fields");if(!ni(e.to))throw new NA("Invalid recipient address format",IA.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new NA("Must provide either tokenId or tokenName for token identification",IA.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Rr(e.tokenName,"tokenName")}catch{throw new NA("Invalid token name format",IA.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}qA.validateAmount(e.amount),qA.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!LA(e))throw new $A("Invalid burn data: missing required fields",FA.VALIDATION_ERROR);if(e.tokens.length>jA)throw new $A(`Batch size exceeds maximum limit of ${jA} tokens per burn operation`,FA.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 $A("Must provide either tokenId or tokenName for token identification",FA.TOKEN_NOT_FOUND);const e=fs(t.amount);try{_s(e)}catch{throw new $A("Burn amount must be a positive number",FA.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!=t){const n=vS(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:In(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 NA)throw t;throw new NA(`Failed to resolve token '${e}': ${Dt(t)}`,IA.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransactionIdFromResponse(e,t){if(null!=e&&"object"==typeof e){if("Status"in e&&"Data"in e)try{Mt(e,"Extract transaction ID");const n=e;if(Array.isArray(n.Data)&&n.Data.length>0)switch(t){case"gala":return KA;case"token":return GA;case"lock":return HA;case"unlock":return WA}return zA}catch{}if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return e.transactionId}throw new NA("Operation succeeded but transaction ID could not be extracted",IA.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 NA)return e;if(e instanceof qt)return new NA(Dt(e),IA.INVALID_AMOUNT);if(Rt(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 NA(e??"Invalid transfer request",IA.INVALID_AMOUNT)}if(403===t)return new NA("Insufficient balance for transfer",IA.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new NA("Token not found",IA.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Bt(e)||"ETIMEDOUT"===Bt(e)))return new NA("Transfer request timed out",IA.NETWORK_ERROR);const r=""!==Dt(e)?Dt(e):t;return new NA(r,IA.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof $A)return e;let r=t,i=FA.NETWORK_ERROR;if(Rt(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")?i=FA.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(i=FA.TOKEN_NOT_FOUND)}}else xt(e)&&(r=`${t}: ${Dt(e)}`);const o={};return void 0!==n?.tokens?.[0]?.tokenName&&(o.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(o.amount=n.tokens[0].amount),new $A(r,i,Object.keys(o).length>0?o:void 0)}}class XA extends Gr{constructor(e,t,n,r=!1,i){super(e,r),this.balanceService=new pA(e,r),this.tokenService=new BA(e,r,i),this.lockService=new PA(e,t,n,r),this.transferService=new VA(e,t,n,r)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);aa(()=>Mt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw nn(Dt(e),500)});const n=t.Data.reverseBondingCurveConfiguration,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",o=!Es(r)||!Es(i),s=t.Data;return s.reverseBondingCurveMinFeePortion=r,s.reverseBondingCurveMaxFeePortion=i,s.hasReverseBondingCurveFee=o,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return aa(()=>Mt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw nn(Dt(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!us(e))throw en("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw en("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new qt("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)}}function QA(e,t=3e4){return U.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}class YA{static createClient(e,t=6e4){return QA(e,t)}}class JA extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function ZA(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 eE(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&ZA(t.token0ClassKey)&&ZA(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}class tE{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return sa(async()=>{if(!Er(e))throw en("walletAddress","Wallet address");const r=Math.max(1,Math.floor(n/t)+1),i={};i.address=e,i.page=r,i.pageSize=t;const o=await this.http.get("/user/assets",i);if("object"!=typeof o||null===o)throw new JA(500,"Invalid response format: not an object");const s=bn(o);if(!s||"object"!=typeof s)throw new JA(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new JA(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 JA(500,"Invalid asset in response: asset must be an object");const t=e;if(!Er(t.symbol)||!Er(t.name))throw new JA(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 JA(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 sa(async()=>{const{address:t,search:n,page:r=1,limit:i=20}=e,o={page:r,limit:Kv(i,1,20)};"string"==typeof t&&t.length>0&&(o.address=t),"string"==typeof n&&n.length>0&&(o.search=n);const s=await this.http.get("/user/token-list",o);if("object"!=typeof s||null===s)throw new JA(500,"Invalid response format: not an object");const a=bn(s);if(!a||"object"!=typeof a)throw new JA(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new JA(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 JA(500,"Invalid token in response: must be an object");const t=e;if(!Er(t.symbol))throw new JA(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!Er(t.name))throw new JA(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new JA(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!Er(t.compositeKey))throw new JA(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 JA)return e;if(Rt(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.message??r?.Message??Dt(e),o=r?.Data??r?.data??void 0;return new JA(n,`${t}: ${String(i)}`,o)}return new JA(500,`${t}: ${Dt(e)}`)}}class nE{constructor(e){this.client=QA(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return sa(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new qt(`GalaChain API getPoolData requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getPoolData(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetPoolData",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&ZA(t.token0ClassKey)&&ZA(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(n))throw new JA(t.status,"Invalid pool data response format",n);return n},"GalaChainGatewayClient.getPoolData",void 0,e=>{throw this.handleError(e,"getPoolData")})}async getSlot0(e){return sa(async()=>{if("string"==typeof e.token0||"string"==typeof e.token1)throw new qt(`GalaChain API getSlot0 requires TokenClassKey objects, not strings. Received: token0="${"string"==typeof e.token0?e.token0:"[object]"}", token1="${"string"==typeof e.token1?e.token1:"[object]"}". Convert pipe-delimited tokens using parseToken() before calling getSlot0(). Example: parseToken("GALA|Unit|none|none") → { collection: "GALA", category: "Unit", type: "none", additionalKey: "none" }`,"token","INVALID_TOKEN_FORMAT");const t=await this.client.post("/api/asset/dexv3-contract/GetSlot0",e);this.validateResponse(t.data);const n=t.data.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.liquidity}(n))throw new JA(t.status,"Invalid slot0 data response format",n);return n},"GalaChainGatewayClient.getSlot0",void 0,e=>{throw this.handleError(e,"getSlot0")})}async getPositions(e){return sa(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetPositions",e);this.validateResponse(t.data);const n=t.data.Data;let r;r=null!=n&&"object"==typeof n&&"positions"in n&&Array.isArray(n.positions)?n.positions:null!=n&&"object"==typeof n&&"positionId"in n?[n]:Array.isArray(n)?n:[];for(const e of r)if(!eE(e))throw new JA(t.status,"Invalid position in response",e);return{positions:r,count:r.length}},"GalaChainGatewayClient.getPositions",void 0,e=>{throw this.handleError(e,"getPositions")})}async getPositionById(e,t,n,r,i,o,s){return sa(async()=>{let a,c;if(void 0!==t&&void 0!==n&&void 0!==r&&void 0!==i&&void 0!==o){a={owner:e,token0:"string"==typeof t?{collection:t,category:"Unit",type:"none",additionalKey:"none"}:t,token1:"string"==typeof n?{collection:n,category:"Unit",type:"none",additionalKey:"none"}:n,fee:r,tickLower:i,tickUpper:o},null!=s&&(a.positionId=s),c=`${e}/${String(t)}/${String(n)}/${r}`}else a={positionId:e},c=e;const l=await this.client.post("/api/asset/dexv3-contract/GetPositions",a);this.validateResponse(l.data);const u=l.data.Data;let d;if(null!=u&&"object"==typeof u&&"positionId"in u&&!("positions"in u))d=u;else{if(!(null!=u&&Array.isArray(u.positions)&&u.positions.length>0))throw new JA(404,`Position not found: ${c}`);d=u.positions[0]}const h={Data:d,Status:l.status};return void 0!==l.data.Message&&(h.Message=l.data.Message),h},"GalaChainGatewayClient.getPositionById",void 0,t=>{throw this.handleError(t,`getPositionById(${e})`)})}async getRemoveLiquidityEstimation(e){return sa(async()=>{const t=await this.client.post("/api/asset/dexv3-contract/GetRemoveLiquidityEstimation",e);this.validateResponse(t.data);const n=t.data.Data;if("string"!=typeof n.amount0||"string"!=typeof n.amount1)throw new JA(t.status,"Invalid removal estimation response format",n);return n},"GalaChainGatewayClient.getRemoveLiquidityEstimation",void 0,e=>{throw this.handleError(e,"getRemoveLiquidityEstimation")})}validateResponse(e){if(null==e||"object"!=typeof e)throw new JA(500,"Invalid response format: not an object");if(!("Data"in e)||!("Status"in e))throw new JA(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new JA(e.Status,e.Message??"Gateway error",e.Data)}handleError(e,t){if(e instanceof JA)return e;if(Rt(e)){const n=e.response?.status??500,r=e.response?.data,i=r?.Message??Dt(e);return new JA(n,`${t}: ${i}`,r?.Data??void 0)}return new JA(500,`${t}: ${Dt(e)}`)}}const rE=10;class iE extends Hr{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new RS,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.galaChainBaseUrl=e.galaChainBaseUrl,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.privateKey=e.privateKey,void 0===e.gatewayBaseUrl||null===e.gatewayBaseUrl||""===e.gatewayBaseUrl||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 Gt("GSwapService requires explicit gatewayBaseUrl, bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.","gswapConfig");try{this.gatewayClient=new nE({baseUrl:e.gatewayBaseUrl,timeout:3e4}),this.dexBackendClient=new tE(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{gatewayUrl:e.gatewayBaseUrl,dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new Gt("Failed to initialize GSwapService HTTP clients","httpClients")}}setPricingConcurrency(e){if(e<1)throw cn("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(fs(e.amount).isLessThanOrEqualTo(0))throw new Wt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new Wt("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:i,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=fs(s.currentSqrtPrice),l=fs(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):fs(0),d=fs(s.amount0),h=fs(s.amount1),g=Is(d),f=Is(h);this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":g,"amount1BN.isNegative()":f});const p=g?d:h;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:g,selectedAmount:p.toFixed(),selectedAmountAbs:p.absoluteValue().toFixed()});const m=p.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:m,feeTier:a,priceImpact: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:xt(e)?e.message:"Unknown error"})}throw s??new Wt("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",Wt,e)}}async getSwapQuoteExactOutput(e){try{if(fs(e.amount).isLessThanOrEqualTo(0))throw new Wt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new Wt("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;for(const a of o)try{const o=await this.dexQuoteService.fetchCompositePoolData({token0:r,token1:i,fee:a,gatewayBaseUrl:this.gatewayBaseUrl}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),c=fs(s.currentSqrtPrice),l=fs(s.newSqrtPrice),u=c.gt(l)?c.minus(l).dividedBy(c):fs(0),d=o.pool.token0,h="string"==typeof d?Xk(d).collection:"object"==typeof d&&null!==d&&"tokenName"in d?d.tokenName:String(d),g=Xk(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:xt(e)?e.message:"Unknown error"})}throw s??new Wt("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",Wt,e)}}async executeSwap(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new Gt("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=ms(e.estimatedOutput,e.slippageTolerance??.01),i=this.getWalletAddress();if(null==i||""===i)throw new qt("Wallet address required for swap execution","walletAddress",$t.REQUIRED);let o;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});o=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:o,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:Dt(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:r.toFixed(),feeTier:e.feeTier,walletAddress:i,slippageTolerance:e.slippageTolerance??.01,...!Ir(o)&&{currentSqrtPrice:o}},a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance??.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",zt,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return sa(async()=>{if(!ni(e))throw new Vt(tn("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(Vt,{walletAddress:e,page:t,limit:n}))}async getAllUserAssets(e){return sa(async()=>{if(!ni(e))throw new Vt(tn("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 wS(async(n,r)=>{const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:r}),o=[];for(const e of i.token){if("0"===e.quantity){t=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&o.push(n)}return{items:o,page:n,limit:r,total:o.length,totalPages:1,hasNext:!t&&i.token.length===r,hasPrevious:n>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:n.items.length}),n.items},"Failed to fetch all user assets",this.logger,this.createGSwapErrorHandler(Vt,{walletAddress:e}))}async fetchAvailableDexTokens(e={}){return sa(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 i=await this.dexBackendClient.fetchTokenList({...!Ir(t)&&{search:t},limit:n,page:r}),o=i.token.map(e=>this.transformRawTokenToDexToken(e)),s=r*n<i.count;return{tokens:o,count:i.count,page:r,limit:n,hasMore:s}},"Failed to fetch available DEX tokens",this.logger,this.createGSwapErrorHandler(Vt,{...e}))}async fetchAllAvailableDexTokens(e={}){return sa(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({...!Ir(t)&&{search:t},limit:20,page:r}),i=e.token.map(e=>this.transformRawTokenToDexToken(e));if(n.push(...i),i.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(Vt,e))}async getPoolInfo(e,t){try{if(null==e||""===e)throw en("tokenA","Token A");if(null==t||""===t)throw en("tokenB","Token B");this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let o=fs(0),s=0;for(const a of i)try{const e="string"==typeof n?Xk(n):n,t="string"==typeof r?Xk(r):r,i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});null!=i&&(o=o.plus(fs(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new jt(`Failed to fetch pool info: ${Dt(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const r=Array.from(n.values()),i=this.chunkArray(r,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:i.length,concurrency:t});const o=new Map;for(let e=0;e<i.length;e++){const t=i[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?o.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return o}normalizePositionResponse(e,t){const n=e,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""},i=r(n.token0),o=r(n.tokenA),s=r(n.token1),a=r(n.tokenB),c=n.token0Symbol??(""!==i?i:""!==o?o: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 Xk(e)}catch(t){if(xt(t)&&Dt(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:sr(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?Xk(e.compositeKey.replace(/\$/g,"|")):Xk(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:n,balance:ps(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:Dt(e)}),null}}async getUserLiquidityPositions(e,t=10,n,r){try{if(null==e||""===e)throw en("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:t,bookmark:n});const i=`${this.galaChainBaseUrl}/api/asset/dexv3-contract/GetUserPositions`,o={user:e,limit:t,bookmark:null!=n&&""!==n?n:""};this.logger.debug("Sending position query request",{endpoint:i,payload:o});const s=await U.post(i,o,{headers:{"Content-Type":"application/json",Accept:"application/json"}}),a=bn(s);if(200!==s.status||1!==a?.Status)return this.logger.warn("Unexpected API response status",{httpStatus:s.status,apiStatus:a?.Status}),{items:[]};const c=a?.Data??{},l=c?.positions??[],u=c?.nextBookMark,d=l.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let h;this.logger.debug("Retrieved liquidity positions",{count:d.length,hasNextBookmark:null!=u,nextBookmark:u}),r?.withPrices&&d.length>0&&(h=await this.fetchPositionPrices(d));const g={items:d};return Ir(u)||(g.nextBookmark=u),Ir(h)||(g.prices=h),g}catch(t){Rt(t)&&this.logger.error("Position query failed with HTTP error",{status:t.response?.status,statusText:t.response?.statusText,data:t.response?.data,endpoint:this.galaChainBaseUrl,ownerAddress:e}),this.handleGSwapError("Failed to fetch user liquidity positions",Xt,t)}}async getAllSwapUserLiquidityPositions(e,t){try{if(null==e||""===e)throw en("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,rE,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},r=await async function(e,t={}){const{maxPages:n=1e4,logger:r,pageSize:i=20}=t,o=[];let s,a=0;for(;a<n;){r&&r.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${i}`,{bookmark:s});const t=await e(s,i);let n,c,l;if(!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}o.push(...n),a++,r&&r.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:""!==(c??""),format:l?"BookmarkPaginationResult":"legacy-array"});const u=n.length<i;if(l&&(""===c||void 0===c)){r&&r.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(u){r&&r.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:i,format:l?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&r&&r.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),r&&r.debug(`Auto-pagination (bookmark): completed with total items: ${o.length}`,{pageCount:a}),{items:o,total:o.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:rE}),i=r.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",Xt,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{if(null==e||""===e)throw en("ownerAddress","Owner address");if(void 0===t.token0||null===t.token0||""===t.token0)throw en("token0","Token 0");if(void 0===t.token1||null===t.token1||""===t.token1)throw en("token1","Token 1");this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),i=sA(n),o=sA(r),s=(await this.gatewayClient.getPositions({owner:e,token0:i,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new Xt("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",Xt,e)}}async getLiquidityPositionById(e,t,n,r,i,o,s){try{if(null==e||""===e)throw en("ownerAddress","Owner address");if(null==t||""===t)throw en("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!=i,hasTickLower:!Ir(o),hasTickUpper:!Ir(s)});let c=null;const l=5,u=2e3;for(let d=1;d<=l;d++)try{if(null!=n&&""!==n&&null!=r&&""!==r&&!Ir(i)&&!Ir(o)&&!Ir(s))try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:r,feeTier:i,tickLower:o,tickUpper:s});if(a=(await this.gatewayClient.getPositionById(e,n,r,i,o,s,t)).Data,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 Xt("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:d,error:xt(e)?e.message:e})}try{if(a=(await this.gatewayClient.getPositionById(t)).Data,null!=a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position on attempt",{attempt:d,positionId:t});break}throw new Xt("Invalid position data from direct lookup",null,"INVALID_DATA")}catch(n){this.logger.debug("Direct position lookup failed, trying fallback via GetUserPositions",{attempt:d,positionId:t,error:xt(n)?n.message:n});const r=await this.getAllSwapUserLiquidityPositions(e),i=Array.isArray(r)?r:r.items;if(i.length>0){const e=i.find(e=>Us(null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"",t));if(e){a=e,this.logger.debug("Found position via fallback (GetUserPositions)",{attempt:d,positionId:t,totalPositions:i.length});break}}if(c=hn(t),d<l){this.logger.warn("Fallback query did not find position, retrying",{attempt:d,positionId:t,ownerAddress:e,foundCount:i.length}),await new Promise(e=>setTimeout(e,u));continue}}}catch(e){if(d<l){this.logger.warn("Error fetching position, retrying",{attempt:d,positionId:t,error:Dt(e)}),await new Promise(e=>setTimeout(e,u));continue}c=xt(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??hn(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",Xt,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n="string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1;this.logger.debug("Fetching position via compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const r=await this.gatewayClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(null===r.positions||void 0===r.positions||0===r.positions.length)throw new Xt("Position not found: No position exists for this compound key",null,"NOT_FOUND");const i=r.positions[0],o=this.normalizePositionResponse(i,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:o.positionId,token0:o.token0,token1:o.token1}),o}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",Xt,e)}}async estimateRemoveLiquidity(e){try{if(void 0===e.token0||null===e.token0||""===e.token0)throw en("token0","Token 0");if(void 0===e.token1||null===e.token1||""===e.token1)throw en("token1","Token 1");if(void 0===e.liquidity||null===e.liquidity||""===e.liquidity)throw en("liquidity","Liquidity amount");if(void 0===e.owner||null===e.owner||""===e.owner)throw en("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=sA(t),i=sA(n),o=await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:o}),o}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",Xt,e)}}async addLiquidityByPrice(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new Gt("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=Xk(t),i=Xk(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:o,fee:e.fee});const s=fs(e.minPrice),a=fs(e.maxPrice),c=Math.floor(bs(s)),l=Math.ceil(bs(a)),u=Bs(c,o),d=Bs(l,o);this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:u,tickUpper:d,tickSpacing:o});const h=this.getWalletAddress();if(null==h||""===h)throw new Gt("GSwapService: No wallet address available - cannot create position","walletAddress");const g="string"==typeof e.token0?Xk(e.token0):e.token0,f="string"==typeof e.token1?Xk(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${u}-${d}`,walletAddress:h});const p=await this.sendAddLiquidityToBundler({token0:g,token1:f,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:p};if(null!==m.positionId&&void 0!==m.positionId&&""!==m.positionId&&null!=p&&""!==p){this.logger.debug("Position ID returned directly from backend",{transactionId:p,positionId:m.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(p);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:e.status});const t=this.getWalletAddress();if(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:i,...o}=n,s=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,a={...m,...o,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}};return Ir(s)||(a.createdAt=s),a}catch(t){return this.logger.debug("Could not fetch full position details",{error:Dt(t)}),{...m,positionId:m.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}}if(null!=p&&""!==p){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:p}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(p);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:t.status});let r=null;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 Gt("No wallet address available","walletAddress");this.logger.debug("Fetching positions",{walletAddress:t});const i=(await this.getUserLiquidityPositions(t,10)).items;if(this.logger.debug("Fetched positions",{count:null!=i?i.length:0}),null!=i&&i.length>0){const t=Xk(e.token0).collection.toUpperCase(),o=Xk(e.token1).collection.toUpperCase(),s=[];for(const n of i){if(""===(n?.positionId??""))continue;const r=null!==n.token0&&void 0!==n.token0?n.token0.toUpperCase():void 0,i=null!==n.token1&&void 0!==n.token1?n.token1.toUpperCase():void 0;if(null==r||""===r||null==i||""===i){this.logger.debug("Skipping position with empty tokens",{positionId:n.positionId});continue}const a=qs(r,i,t,o),c=n.feeTier===e.fee;this.logger.debug("Checking position",{positionId:n.positionId,tokens:`${r}/${i}`,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:`${Xk(e.token0).collection}/${Xk(e.token1).collection}`,expectedFee:e.fee,positionCount:i.length,liquidity:r.liquidity,amount0:r.amount0,amount1:r.amount1})):this.logger.debug("No matching position found",{availablePositions:i.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:Dt(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 i=r;if(null!=n&&""!==n)try{i=await this.getLiquidityPositionById(h,n),this.logger.debug("Fetched full position details",{positionId:i.positionId,liquidity:i.liquidity,amount0:i.amount0,amount1:i.amount1,feeAmount0:i.feeAmount0,feeAmount1:i.feeAmount1})}catch(e){this.logger.debug("Could not fetch full position details, using discovered data",{error:Dt(e)})}const o=i?{ownerAddress:i.ownerAddress,token0:i.token0,token1:i.token1,feeTier:i.feeTier,tickLower:i.tickLower,tickUpper:i.tickUpper,liquidity:i.liquidity,amount0:i.amount0,amount1:i.amount1,feeAmount0:i.feeAmount0,feeAmount1:i.feeAmount1}:{};return{...m,...o,...null!=n&&""!==n&&{positionId:n},status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),m}catch(e){this.logger.error("Error in addSwapLiquidityByPrice",{error:Dt(e),stack:xt(e)?Pt(e)?.split("\n").slice(0,3).join(" | "):void 0}),this.handleGSwapError("Failed to add liquidity by price",Xt,e)}}async addSwapLiquidityByTicks(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new Gt("GSwapService not initialized with signing capability (privateKey required)","privateKey");const t=this.getWalletAddress();if(null==t||""===t)throw new Gt("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?Xk(e.token0):e.token0,r="string"==typeof e.token1?Xk(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendAddLiquidityToBundler({token0:n,token1:r,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min: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:i});const o=this.webSocketService.waitForTransaction(i),s={transactionId:i};if(null!==s.positionId&&void 0!==s.positionId&&""!==s.positionId&&null!=i&&""!==i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:s.positionId});const e=await o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:e.status});const t=this.getWalletAddress();if(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:o,...a}=n,c=r instanceof Date?r.getTime():"number"==typeof r?r:void 0,l={...s,...a,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}};return Ir(c)||(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:Dt(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}}if(null!=i&&""!==i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const n=await o;let r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:n.status});let a=null;const c="string"==typeof e.token0?e.token0:e.token0?.type??"unknown",l="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,fee:e.fee});try{const t=this.getWalletAddress();if(null==t||""===t)throw new Gt("No wallet address available","walletAddress");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:rE});const n=3,i=5e3,o=3e3;let s=[];for(let c=1;c<=n;c++){const l=1===c?i:o;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:rE});if(s=(await this.getUserLiquidityPositions(t,rE)).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?Xk(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?Xk(e.token1).collection:e.token1.collection).toUpperCase(),i=[];for(const r of s){if(""===(r?.positionId??""))continue;const o=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==o||""===o||null==s||""===s){this.logger.debug("Skipping position with empty tokens",{positionId:r.positionId});continue}const a=qs(o,s,t,n),c=r.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:r.positionId,tokens:`${o}/${s}`,tokensMatch:a,fee:r.feeTier,feeMatches:c}),a&&c&&i.push(r)}if(i.length>0){a=i[i.length-1],r=a.positionId,this.logger.info("Found newly created position",{positionId:r,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:r,expectedTokens:`${Xk(e.token0).collection}/${Xk(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:Dt(e)}),this.logger.debug("Error waiting for position indexing",{error:Dt(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:Dt(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(i)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),s}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",Xt,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let r;try{const i=await t;r={status:i.status,transactionId:null!==i.transactionId&&void 0!==i.transactionId&&""!==i.transactionId?i.transactionId:e,timestamp:null!==i.timestamp&&void 0!==i.timestamp&&0!==i.timestamp?i.timestamp:Date.now(),data:i.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:r.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:Dt(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 Gt("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=rr(e.liquidity,Number.NaN);if(isNaN(t))throw new qt(`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 qt(`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(xt(e)&&Dt(e).includes("Cannot remove zero liquidity"))throw e;if(xt(e)&&Dt(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?Xk(e.token0):e.token0,n="string"==typeof e.token1?Xk(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 i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",Xt,e)}}async collectPositionFees(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new Gt("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 hn(e.positionId);if(null===t.token0||void 0===t.token0||""===t.token0||null===t.token1||void 0===t.token1||""===t.token1)throw new Xt("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 en("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?Xk(e.token0):e.token0,n="string"==typeof e.token1?Xk(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 i=this.webSocketService.waitForTransaction(r);return this.monitorBundlerTransaction(r,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",Xt,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:i}=this.convertTokenPair(e,t),o=Xk(r),s=Xk(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(fs(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",jt,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),i=fs(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:ks(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",jt,e)}}async calculateOptimalPositionSize(e,t,n,r,i,o,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:r,desiredAmount1:i});const a=(await this.getPoolData(e,t,n)).tick,c=_(o),l=_(a),u=_(s),d=x(fs(r),fs(i),c,l,u),h=D(d,l,c,u),g=h[0],f=h[1],p=fs(r),m=fs(i);return{amount0:g.toFixed(),amount1:f.toFixed(),liquidity:d.toFixed(),ratio:Ps(g,f).toFixed(),utilizationPercent:{amount0:Ns(Ps(g,p),100).toFixed(2),amount1:Ns(Ps(f,m),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",Xt,e)}}async validatePositionParameters(e,t,n,r,i,o,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:r,tickUpper:i});const l=[500,3e3,1e4];l.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${l.join(", ")}`);const u=this.getTickSpacing(n);let d;r%u!==0&&a.push(`tickLower must be multiple of ${u}`),i%u!==0&&a.push(`tickUpper must be multiple of ${u}`),r>=i&&a.push(`tickLower (${r}) must be less than tickUpper (${i})`);try{d=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const h=fs(o),g=fs(s);if(h.isNaN()||g.isNaN())a.push("Amounts must be valid numbers");else try{xs(h,g)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const f=d.tick;(f<r||f>i)&&c.push("Position is out of current price range - will not earn fees until price moves into range");fs(d.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const p=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:p,tickSpacing:u,currentTick:f,poolLiquidity:d.liquidity}}catch(e){const t=Dt(e);return a.includes(t)||a.push(`Validation failed: ${t}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}calculateTicksForPrice(e,t,n,r,i){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:r});const o=this.getTickSpacing(i),s=fs(n),a=fs(r);mr(n,r,"priceRange");const c=Math.floor(bs(s)),l=Math.ceil(bs(a)),u=Bs(c,o),d=Bs(l,o),h=Math.pow(1.0001,u),g=Math.pow(1.0001,d),f=fs(h),p=fs(g);return{tokenA:e,tokenB:t,feeTier:i,tickLower:u,tickUpper:d,tickSpacing:o,requestedMinPrice:n,requestedMaxPrice:r,actualMinPrice:f.toFixed(8),actualMaxPrice:p.toFixed(8),priceDeviation:{minPriceDeviation:Ns(f.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:Ns(p.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",Xt,e)}}async calculatePriceForTicks(e,t,n,r){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:r});const i=Math.pow(1.0001,n),o=Math.pow(1.0001,r);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=fs(i),c=fs(o),l={tokenA:e,tokenB:t,tickLower:n,tickUpper:r,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:r-n};return Ir(s)||(l.currentPrice=s),l}catch(e){throw this.handleGSwapError("Failed to calculate price for ticks",Xt,e),e}}calculateExecutionPrice(e,t){try{const n=fs(e);return Ps(fs(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 tn("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new qt(`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 qt(`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=vs();return Ps(e,t).pow(2)}catch{return fs(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return fs(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?Xk(e):e,i="string"==typeof t?Xk(t):t,o=await this.gatewayClient.getSlot0({token0:r,token1:i,fee:n}),s={sqrtPrice:null!==o.sqrtPrice&&void 0!==o.sqrtPrice&&""!==o.sqrtPrice?o.sqrtPrice:"0",tick:null!==o.tick&&void 0!==o.tick&&0!==o.tick?o.tick:0,liquidity:null!==o.liquidity&&void 0!==o.liquidity&&""!==o.liquidity?o.liquidity:"0",grossPoolLiquidity:null!==o.grossPoolLiquidity&&void 0!==o.grossPoolLiquidity&&""!==o.grossPoolLiquidity?o.grossPoolLiquidity:"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(r){this.handleGSwapError("Failed to fetch pool slot0 data",jt,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=fs(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",jt,t,{token0:e.token0,token1:e.token1})}}_calculateLiquidityFromAmount0(e,t,n){try{const r=_(t),i=_(n);return P(e,r,i)}catch{return fs(0)}}_calculateLiquidityFromAmount1(e,t,n){try{const r=_(t),i=_(n);return B(e,r,i)}catch{return fs(0)}}_calculateAmount0FromLiquidity(e,t,n){try{const r=_(t),i=_(n);return R(r,i,e)}catch{return fs(0)}}_calculateAmount1FromLiquidity(e,t,n){try{const r=_(t),i=_(n);return M(r,i,e)}catch{return fs(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(e){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new Gt("GSwapService: AddLiquidity requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new Gt("GSwapService: Bundler URL not configured","bundlerBaseUrl");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:e.token0?.type??"unknown",token1:e.token1?.type??"unknown",fee:e.fee,tickRange:`${e.tickLower}-${e.tickUpper}`});const t=`galaswap - operation - ${w()}-${Date.now()}-${e.owner}`,n={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:t},r=new c.Wallet(this.privateKey),i={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"}]},o={name:"ethereum",chainId:1},s=this.calculatePersonalSignPrefix(n),a={...n,prefix:s},l=await r.signTypedData(o,i,a),u={...a,signature:l,types:i,domain:o};this.logger.debug("AddLiquidity DTO signed with manual types",{prefix:u.prefix,tickLower:n.tickLower,tickUpper:n.tickUpper});const d=this.buildLiquidityStringsInstructions(e.token0,e.token1,e.fee,e.owner),h=YA.createClient(this.bundlerBaseUrl,3e4),g=await h.post("/bundle",{method:"AddLiquidity",signedDto:u,stringsInstructions:d}),f=bn(g),p=f?.data??f?.transactionId??f?.id;if(null==p)throw this.logger.error("Bundler response structure",{status:g.status,dataType:typeof f}),new Ht("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:p}),p}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(e,t,n,r,i,o,s,a,l){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new Gt("GSwapService: Bundler URL not configured","bundlerBaseUrl");const u=new c.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${w()}-${Date.now()}-${d}`,g={tickLower:e,tickUpper:t,amount:n,token0:r,token1:i,fee:o,amount0Min:s,amount1Min:a,positionId:l,uniqueKey:h},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"}]},p={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},b=await u.signTypedData(p,f,y),k={...y,signature:b,types:f,domain:p},v=this.buildLiquidityStringsInstructions(r,i,o,d);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:e,tickUpper:t,amount:n,fee:o,positionId:l,transactionId:h});const S=YA.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:k,stringsInstructions:v}),E=bn(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 Ht("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(e,t,n,r,i,o,s,a){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new Gt("GSwapService: Bundler URL not configured","bundlerBaseUrl");const l=new c.Wallet(this.privateKey),u=await l.getAddress(),d=`galaswap - operation - ${w()}-${Date.now()}-${u}`,h={token0:e,token1:t,fee:n,amount0Requested:r,amount1Requested:i,tickLower:o,tickUpper:s,positionId:a,uniqueKey:d},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},p=this.calculatePersonalSignPrefix(h),m={...h,prefix:p},y=await l.signTypedData(f,g,m),b={...m,signature:y,types:g,domain:f},k=this.buildLiquidityStringsInstructions(e,t,n,u);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:n,amount0Requested:r,amount1Requested:i,tickLower:o,tickUpper:s,positionId:a,transactionId:d});const v=YA.createClient(this.bundlerBaseUrl,3e4),S=await v.post("/bundle",{method:"CollectPositionFees",signedDto:b,stringsInstructions:k}),A=bn(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 Ht("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(e){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new Gt("GSwapService: Swap requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new Gt("GSwapService: Bundler URL not configured","bundlerBaseUrl");const t=[500,3e3,1e4];if(!t.includes(e.feeTier))throw new qt(`GSwapService: Invalid fee tier ${e.feeTier}. Must be one of: ${t.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken?.type??"unknown",toToken:"string"==typeof e.toToken?e.toToken:e.toToken?.type??"unknown",inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let t=e.fromToken,n=e.toToken;"string"==typeof t&&(t=Xk(t)),"string"==typeof n&&(n=Xk(n));const r=fa(t),i=fa(n),o=r<i?[t,n,r,i]:[n,t,i,r],[s,a,l,u]=o,d=fa("string"==typeof e.fromToken?Xk(e.fromToken):e.fromToken),h=d===l,g=`galaswap - operation - ${w()}-${Date.now()}-${e.walletAddress}`;let f;if(void 0===e.currentSqrtPrice||null===e.currentSqrtPrice||""===e.currentSqrtPrice)throw new qt("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",$t.REQUIRED);const p=fs(e.currentSqrtPrice),m=e.slippageTolerance??.01;if(h){const e=ys(m);f=p.multipliedBy(e).toString()}else{const e=ws(m);f=p.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:e.currentSqrtPrice,slippageTolerance:100*m+"%",zeroForOne:h,sqrtPriceLimit:f,direction:h?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const y={token0:s,token1:a,fee:e.feeTier,amount:fs(e.inputAmount).toFixed(),zeroForOne:h,sqrtPriceLimit:f,recipient:e.walletAddress,amountOutMinimum:fs(e.minOutput).multipliedBy(-1).toFixed(),uniqueKey:g};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:l,orderedToken1String:u,fromTokenStr:d,zeroForOne:h?`TRUE (${l} → ${u})`:`FALSE (${u} → ${l})`,inputAmount:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(null!==e.slippageTolerance&&void 0!==e.slippageTolerance&&0!==e.slippageTolerance?e.slippageTolerance:.01)+"%",currentSqrtPrice:e.currentSqrtPrice,swapDto:{amount:y.amount,zeroForOne:y.zeroForOne,sqrtPriceLimit:y.sqrtPriceLimit,amountOutMinimum:y.amountOutMinimum}});const b=new c.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(y),A={...y,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:y.zeroForOne});const I=this.buildLiquidityStringsInstructions(s,a,e.feeTier,e.walletAddress),C=YA.createClient(this.bundlerBaseUrl,3e4),N=await C.post("/bundle",{method:"Swap",signedDto:T,stringsInstructions:I}),_=bn(N),x=_?.data??_?.transactionId??_?.id;if(null==x)throw this.logger.error("Bundler response structure",{status:N.status,dataType:typeof _}),new Ht("Bundler response does not contain transaction ID. Response type: "+typeof _,void 0,"INVALID_RESPONSE");return this.logger.debug("Swap transaction sent to bundler",{transactionId:x,inputAmount:e.inputAmount,minOutput:e.minOutput}),x}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,r){const i=ma(e),o=ma(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}createGSwapErrorHandler(e,t){return(n,r,i)=>{this.handleGSwapError(r,e,n,t)}}handleGSwapError(e,t,n,r){this.logger.error(e,n);const i=this.extractGSwapErrorCode(n),o=n,s=[`${e}: ${o?.message??Dt(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!=i&&""!==i&&s.push(i),new t(...s)}extractGSwapErrorCode(e){const t=Bt(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 oE(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 tn("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});r.append(t,i,n)}}return r}class sE extends Gr{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Vs(t);const r=`${t}.png`;Os(n.file,r,"image/png");try{const e=`${n.tokenName??t}.png`,r=oE(n.file,"image",e),i=await vn(()=>this.http.request({method:"POST",url:`${G.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof Gt)throw e;if(xt(e)&&Dt(e).includes("FormData"))throw rn("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const aE={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"},cE={PAGINATION:{MAX_LIMIT:Kn.MAX_LIMIT},CONTENT:{CHAT_MAX_LENGTH:Wn.CHAT_MESSAGES_V1.MAX_LENGTH,COMMENT_MAX_LENGTH:Wn.COMMENTS_V1.MAX_LENGTH}};function lE(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 fn(["type","tokenName","userAddress"]);if(void 0!==e.type&&e.type!==aE.CHAT_MESSAGE&&e.type!==aE.COMMENT)throw new qt(`type must be one of: ${Object.values(aE).join(", ")}`,"type",$t.INVALID_VALUE);if(n){if(!Er(e.tokenName))throw un("tokenName","string");if(e.tokenName.length>Fn.MAX_LENGTH)throw new qt(`tokenName must be at most ${Fn.MAX_LENGTH} characters`,"tokenName",$t.TOO_LONG)}if(r){if(!Er(e.userAddress))throw un("userAddress","string");if(e.userAddress.length>Hn.MAX_LENGTH)throw new qt(`userAddress must be at most ${Hn.MAX_LENGTH} characters`,"userAddress",$t.TOO_LONG)}void 0!==e.pageSize&&Cr(0,void 0,Kn.MAX_LIMIT,e.pageSize)}function uE(e){if(void 0===e.type||null===e.type)throw en("type");if(e.type!==aE.CHAT_MESSAGE&&e.type!==aE.COMMENT)throw new qt(`type must be one of: ${Object.values(aE).join(", ")}`,"type",$t.INVALID_VALUE);if(!Er(e.tokenName))throw en("tokenName");if(e.tokenName.length>Fn.MAX_LENGTH)throw new qt(`tokenName must be at most ${Fn.MAX_LENGTH} characters`,"tokenName",$t.TOO_LONG);if(!Er(e.content))throw en("content");if(0===e.content.trim().length)throw mn("content","Content");const t=e.type===aE.CHAT_MESSAGE?cE.CONTENT.CHAT_MAX_LENGTH:cE.CONTENT.COMMENT_MAX_LENGTH;if(e.content.length>t)throw pn("content",t,e.content.length)}function dE(e){if(!Er(e.content))throw en("content");if(0===e.content.trim().length)throw mn("content","Content");const t=Math.max(cE.CONTENT.CHAT_MAX_LENGTH,cE.CONTENT.COMMENT_MAX_LENGTH);if(e.content.length>t)throw pn("content",t,e.content.length)}function hE(e){if(!Er(e))throw en("id","Message ID");const t=zn.CHAT_MESSAGE.PATTERN.test(e),n=/^msg-\d{13}-[a-f0-9]{32}$/.test(e);if(!t&&!n)throw new qt("Invalid message ID format. Expected: chat-{timestamp}-{uuid} or msg-{timestamp}-{uuid}","id",$t.INVALID_FORMAT)}function gE(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 qt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",$t.REQUIRED);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw un("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw un("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw un("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw un("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 un(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw un("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new qt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",$t.INVALID_FORMAT)}}function fE(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&"string"==typeof t.type&&(t.type===aE.CHAT_MESSAGE||t.type===aE.COMMENT)&&"string"==typeof t.tokenName&&"string"==typeof t.userAddress&&"string"==typeof t.content&&"string"==typeof t.createdAt}function pE(e){return e===aE.CHAT_MESSAGE||e===aE.COMMENT}function mE(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class yE extends Gr{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!Ir(e.search)&&{search:e.search},...!Ir(e.tokenName)&&{tokenName:e.tokenName},...!Ir(e.type)&&{type:e.type},...!Ir(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!Ir(e.language)&&{language:e.language},...!Ir(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!Ir(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!Ir(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,r={pageSize:String(t)};void 0!==n&&(r.cursor=n),Ir(e.type)||(r.type=e.type),Ir(e.tokenName)||(r.tokenName=e.tokenName),Ir(e.search)||(r.search=e.search),Ir(e.hasUpcomingShows)||(r.hasUpcomingShows=e.hasUpcomingShows.toString()),Ir(e.language)||(r.language=e.language),Ir(e.recentlyStreamed)||(r.recentlyStreamed=e.recentlyStreamed.toString()),Ir(e.hasRecordings)||(r.hasRecordings=e.hasRecordings.toString()),Ir(e.streamStatus)||(r.streamStatus=e.streamStatus);const i=hs(r),o=bn(await An(()=>this.http.get(G.FETCH_POOLS,i),{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}(o),a={hasNextPage:o.hasNextPage??!1},c=o.count??o.total;return void 0!==c&&(a.totalCount=c),void 0!==o.nextCursor&&null!==o.nextCursor&&(a.nextCursor=o.nextCursor),void 0!==o.prevCursor&&null!==o.prevCursor&&(a.prevCursor=o.prevCursor),void 0!==o.hasPrevPage&&(a.hasPrevPage=o.hasPrevPage),{items:s,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??Uv.DEFAULT_LIMIT;Er(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,i=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,o={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:r,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:i}),pageSize:n,...void 0!==t&&{cursor:t}},s=await this.fetchSinglePage(o);return{items:s.items,pageInfo:s.pageInfo}}async fetchAllPools(e){const t=[];let n;const r=Uv.BACKEND_MAX_PAGE_SIZE;for(;;){const i={...e,pageSize:r,...void 0!==n&&{cursor:n}},o=await this.fetchPools(i);if(t.push(...o.items),!o.pageInfo.hasNextPage)break;n=o.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){Xs(e),Er(e.tokenName)&&Vs(e.tokenName);try{const t=await this.http.post(G.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===Er(e.symbol)){return!n.symbolAvailable}if(!0===Er(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,r="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||r.includes("404")||r.includes("Pool not found"))return!1;const i="number"==typeof n.statusCode?n.statusCode:null;if(404===i)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||r.includes("400")||r.includes("Missing required pool identifier"))return!1;if(400===i&&r.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!as(e))throw new qt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:r,resolution:i}=e;if(Vs(t),null==n||null==r||null==i)throw new qt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const o={tokenName:t,from:n,to:r,resolution:i};Qs(o);const s=hs(o);return{dataPoints:await vn(()=>this.http.get(G.CHART,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw en("tokenName","Token name");let t;Vs(e);try{t=await An(()=>this.http.get(`${G.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Rt(t)&&500===t.response?.status)throw nn(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=bn(t);if(!Array.isArray(n))throw nn("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 nn("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 nn("Invalid holder data: missing or invalid quantity field",t.status);const n=rr(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw nn(`Invalid holder quantity: "${e.quantity}"`,t.status)}const r=n.reduce((e,t)=>e.plus(t.quantity),fs(0));return{holders:n.map(e=>{const t=Ps(fs(e.quantity),r,fs(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 en("tokenName","Token name");if(""===t||null==t)throw en("userAddress","User address");return Vs(e),vn(()=>this.http.get(`${G.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(""===e||null==e)throw en("tokenName","Token name");Vs(e);const t=G.GET_TOKEN_BADGES.replace(":tokenName",e.toLowerCase().trim()),n=await vn(()=>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 i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===r);return i?.isActive??!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(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=G.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=bn(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(G.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(!Er(e))throw en("tokenName","Token name");Vs(e);const t=G.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=bn(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 en("tokenName","Token name");Vs(e),gE(t);const n=G.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 wE={PAGINATION:Kn,TOKEN_NAME:Fn,USER_ADDRESS:Hn};function bE(e){if(void 0!==e.tokenName){if(!Er(e.tokenName))throw un("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>wE.TOKEN_NAME.MAX_LENGTH)throw ln("tokenName",wE.TOKEN_NAME.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Er(e.userAddress))throw un("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>wE.USER_ADDRESS.MAX_LENGTH)throw ln("userAddress",wE.USER_ADDRESS.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw un("search","a string",typeof e.search);if(e.search.length>256)throw ln("search",256,e.search.length)}if(Cr(0,void 0,wE.PAGINATION.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw tn("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Er(e.startDate))throw un("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw tn("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Er(e.endDate))throw un("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw tn("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{gr(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw tn("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{gr(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw tn("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&mr(e.minAmount,e.maxAmount,"amountRange")}class kE extends Gr{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 is(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&os(t,"userAddress")&&ss(t,"offset")&&ss(t,"pageSize")&&ss(t,"page")&&ss(t,"limit")}(e))throw new qt("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:i,pageSize:o=Uv.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!Er(t))throw en("tokenName","Token name");const l={pageSize:String(Math.min(o,qn))};void 0!==i&&(l.cursor=i);const u={...l};u.tokenName=t;const d=await this.http.get(G.GET_TRADES,u);if(null==d)throw new qt("No response from trade service","response","NO_RESPONSE");const h=bn(d),g=mE(h,"trades"),f=h?.pageInfo;return{items:g,pageInfo:f??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=Tn(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?Kv(e.pageSize,1,wE.PAGINATION.MAX_LIMIT):wE.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){bE(e);const t=this.buildTradesQueryParams(e);return vn(()=>this.http.get(ct,t),{errorContext:"Failed to fetch trades"})}}function vE(e){return!!Er(e)&&Gn.PATTERN.test(e)}Nr({ALL:"all",DEFI:"DEFI",ASSET:"ASSET",COLLECTION:"COLLECTION",CREATED:"created"});class SE extends Gr{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!vE(t))throw tn("address","eth|[40-hex-chars] or client|[identifier]","Address");const n={userAddress:t},r=await this.http.get(G.GET_PROFILE,n);if(null==r)throw new qt("No response from user service","response","NO_RESPONSE");return r}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Er(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await vn(()=>this.http.put(G.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 qt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,r=oE(e.file,"image",n),i=await vn(()=>this.http.request({method:"POST",url:`${G.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:r,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof qt||e instanceof Gt)throw e;throw new qt(`Profile image upload failed: ${Dt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(G.GET_TOKEN_LIST,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(G.GET_TOKENS_HELD,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:r,tokenName:i,status:o}=e??{},s=e?.type??(void 0!==o?"created":"DEFI"),a=this.http.getAddress();if(null==a||""===a)throw new qt("Wallet address not available - wallet not configured","address","NO_WALLET");const c={type:s,address:a,pageSize:n??Uv.DEFAULT_LIMIT};return void 0!==t&&(c.cursor=t),void 0!==r&&(c.search=r),void 0!==i&&(c.tokenName=i),void 0!==o&&(c.status=o),this.fetchTokenList(c)}async getManagedTokens(e={}){const t=Wv({pageSize:e.pageSize??Uv.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},qn);return vn(()=>this.http.get(G.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const r=Wv({pageSize:t.pageSize??Uv.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},qn);zv(r,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(r.type="all"===(t.type??"DEFI")?"DEFI":t.type??"DEFI");let i=e;if(e.includes(":address")){const n=t.address??this.http.getAddress();if(0===n.length)throw en("address","User address");i=e.replace(":address",n),delete r.address}const o=bn(await An(()=>this.http.get(i,r),{errorContext:n.errorMessage})),s=mE(o,"token"),a={hasNextPage:o.hasNextPage??!1},c=o.count??o.total;void 0!==c&&(a.totalCount=c),void 0!==o.nextCursor&&(a.nextCursor=o.nextCursor),void 0!==o.prevCursor&&(a.prevCursor=o.prevCursor),void 0!==o.hasPrevPage&&(a.hasPrevPage=o.hasPrevPage);const l={tokens:s,pageInfo:a};return void 0!==c&&(l.total=c),l}async fetchUserBalances(e){if(!vE(e.address))throw tn("address","eth|[40-hex-chars] or client|[identifier]","Address");const t=Wv({pageSize:e.pageSize??Uv.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},qn),n=G.USER_BALANCES.replace(":address",e.address),r=bn(await An(()=>this.http.get(n,t),{errorContext:"Failed to fetch user balances"}));if(!r)throw new qt("Invalid response: missing data","response","NO_DATA");const i={hasNextPage:r.hasNextPage??!1};return void 0!==r.nextCursor&&(i.nextCursor=r.nextCursor),void 0!==r.prevCursor&&(i.prevCursor=r.prevCursor),void 0!==r.hasPrevPage&&(i.hasPrevPage=r.hasPrevPage),void 0!==r.total&&(i.totalCount=r.total),{balances:Array.isArray(r.balances)?r.balances:[],pageInfo:i,total:r.total}}async fetchUserReport(e){if(!vE(e.address))throw tn("address","eth|[40-hex-chars] or client|[identifier]","Address");if(!this.jwtAuth)throw new Gt("JWT authentication is required for fetchUserReport. Call sdk.login() first.","jwtAuth");const t=G.USER_REPORT.replace(":address",e.address),n=bn(await An(()=>this.http.get(t,{},this.getJwtHeaders()),{errorContext:"Failed to fetch user report"}));if(!n?.report)throw new qt("Invalid response: missing report data","response","NO_DATA");return{report:n.report}}validateGetTokenListOptions(e){const t=e.pageSize??Uv.DEFAULT_LIMIT;if(t<1||t>qn)throw new qt(`pageSize must be between 1 and ${qn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!vE(e.address))throw tn("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Ls(e.search);if(null!==n&&!(Er(r=n)&&r.length>=Zn&&r.length<=er))throw an("search",Zn,er,n.length,"Search query");var r;const i=Ls(e.tokenName);if(null!==i&&!(Er(o=i)&&o.length>=Fn.MIN_LENGTH&&o.length<=Fn.MAX_LENGTH))throw an("tokenName",Fn.MIN_LENGTH,Fn.MAX_LENGTH,i.length,"Token name");var o}validateUpdateProfileData(e){if(!vE(e.address))throw tn("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Er(t)&&t.length>=tr.FULL_NAME.MIN_LENGTH&&t.length<=tr.FULL_NAME.MAX_LENGTH&&tr.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw an("fullName",tr.FULL_NAME.MIN_LENGTH,tr.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!vE(e.address))throw tn("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class AE{constructor(e,t,n=!1){this.http=e,this.poolService=new yE(e,t,n),this.tradeService=new kE(e,n),this.userService=new SE(e,t,n),this.imageService=new sE(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 EE extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateContent(e,t){if(!Er(e))throw en("content","Message content");if(0===e.trim().length)throw en("content","Message content");fr(e,t===aE.CHAT_MESSAGE?Wn.CHAT_MESSAGES_V1.MAX_LENGTH:Wn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Er(e))throw en("id","Message ID");if(e.length<10||e.length>64)throw tn("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==aE.CHAT_MESSAGE&&e!==aE.COMMENT)throw new qt(`type must be one of: ${Object.values(aE).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,Un);const r={};void 0!==e.cursor&&(r.cursor=e.cursor),r.pageSize=e.pageSize??Uv.DEFAULT_LIMIT;const i=Wv(r,Kn.MAX_LIMIT),o={};void 0!==i.pageSize&&(o.pageSize=i.pageSize),void 0!==i.cursor&&(o.cursor=i.cursor),t&&(o.type=e.type.toUpperCase()),n&&(o.tokenName=Tn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(o.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(o.search=e.search);const s=await this.http.get(lt.GET_MESSAGES,o),a=this.extractData(s);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Un),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:Tn(e.tokenName),content:e.content.trim()},n=await this.http.post(lt.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(lt.UPDATE_MESSAGE,e),r={content:t.content.trim()},i=await this.http.put(n,r,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(lt.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Un);const t=await this.http.get(lt.GET_PINNED,{tokenName:Tn(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=lt.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=lt.UNPIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(lt.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const TE={MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"},IE=_r(TE),CE={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},NE=_r(CE),_E={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},xE=_r(_E);function DE(e){return IE.includes(e)}function PE(e){return xE.includes(e)}function BE(e){return Qn.PATTERN.test(e)}const RE=Mr([{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"}]),ME=Mr([{field:"tokenName",type:"string"},{field:"tokenSymbol",type:"string"},{field:"role",type:"string"},{field:"inviteScope",type:"string"},{field:"creatorAddress",type:"string"},{field:"claimedAt",type:"string"}]),OE=Mr([{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 LE(e){return NE.includes(e)}function UE(e){const t=[],n=e.inviteScope??CE.TOKEN;return void 0===e.inviteScope||LE(e.inviteScope)||Lt(t,()=>{throw gn("inviteScope",e.inviteScope,NE,"Invite scope")}),n===CE.TOKEN?Lt(t,()=>{Dr(e.tokenName??"","tokenName",Ln)}):n===CE.ALL_OWNER_TOKENS&&void 0!==e.tokenName&&""!==e.tokenName&&t.push("Token name should not be provided for ALL_OWNER_TOKENS scope invites"),DE(e.role)||Lt(t,()=>{throw gn("role",e.role,IE,"Role")}),void 0!==e.description&&""!==e.description&&Lt(t,()=>{fr(e.description,Wn.DESCRIPTION.MAX_LENGTH,"description")}),void 0===e.expiresAt||""===e.expiresAt||Mn(e.expiresAt)||Lt(t,()=>{throw function(e,t="a valid date",n){const r=Jt(e,n);return new qt(`${r} must be ${t}`,e,"INVALID_DATE")}("expiresAt","ISO 8601 format")}),t}function FE(e){const t=[];return Er(e)?BE(e)||t.push("Invalid invite code format"):t.push(en("inviteCode","Invite code").message),t}function $E(e){const t=[];return Lt(t,()=>{Dr(e.tokenName??"","tokenName",Ln)}),void 0===e.status||PE(e.status)||Lt(t,()=>{throw gn("status",e.status,xE,"Status")}),Lt(t,()=>{Cr(0,void 0,$n,e.pageSize)}),t}class qE extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateRole(e){if(!Er(e))throw en("role","Role");if(!DE(e))throw tn("role",`one of: ${IE.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Er(e))throw en("inviteCode","Invite code");if(!BE(e))throw tn("inviteCode","valid invite code format","Invite code")}validateInviteScope(e){if(void 0!==e&&!LE(e))throw new qt(`Invalid invite scope. Must be one of: ${NE.join(", ")}`,"inviteScope","INVALID_VALUE")}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??CE.TOKEN;if(t===CE.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new qt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Ln)}else if(t===CE.ALL_OWNER_TOKENS&&e.tokenName)throw new qt("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",Wn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Te,r={inviteScope:t,role:e.role};t===CE.TOKEN&&null!=e.tokenName&&""!==e.tokenName&&(r.tokenName=Tn(e.tokenName)),void 0!==e.description&&(r.description=e.description),void 0!==e.expiresAt&&(r.expiresAt=e.expiresAt);const i=await this.http.post(n,r,this.getMultiAuthHeaders());return{invite:this.extractData(i)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Ln),this.validateStatusFilter(e.status,_E);const t=Ne,n={...this.buildPaginationParams(e,Kn.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=Tn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.invites,pageInfo:i.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(_e,{id:String(e)});wn(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(xe,{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 qt("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",Wn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(De,{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=Ie,n={inviteCode:e.inviteCode},r=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return"tokenName"in i&&void 0!==i.tokenName?{token:i}:{blanketAccess:i}}async getModeratedTokens(e){const t=Ce,n=this.buildPaginationParams(e??{},Kn.MAX_LIMIT),r=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(r);return{items:i.tokens,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Pe,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}class KE{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=ir(Math.floor(.5*e.length),0),n=ir(Math.floor(.95*e.length),0),r=ir(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 ir(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=ir(On(this.startTime)/1e3,0);return 0===e?0:ir(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&"function"==typeof process.memoryUsage){const e=ir(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?ir(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?ir(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:ir(t.cacheHits/n*100,0)}getHealthMetrics(e,t,n,r,i){const o=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:o.p50,latencyP95:o.p95,latencyP99:o.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:ir(ps(s,1),0),maxMB:i,percentUsed:Math.min(100,ir(ps(s/i*100,1),0))},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:r}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?ir(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:ir(ps(e,0),0),memoryUsedMB:ir(ps(this.getMemoryUsedMB(),1),0),throughputPerSecond:ir(ps(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 GE{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!Er(e))return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),r=t[1]?.trim(),i=t[2]?.trim();if(""===n||""===r||""===i)return null;const o=or(i,-1);return o<0?null:{token0:n,token1:r,feeTier:o}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const r=this.parsePoolKey(e);if(!r)return!1;const i=r.token0===t||r.token1===t,o=r.token0===n||r.token1===n;return i&&o&&t!==n}static normalizeFee(e){if(Ir(e))return null;const t="number"==typeof e?e:lr(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`${ps(fs(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class HE{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 WE{constructor(e){this.logger=e??new _n({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],r=new WeakSet,i=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(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))i(t,o+1)}};return i(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,i=this.extractToken(r,"token0","fromToken","source"),o=this.extractToken(r,"token1","toToken","destination");if(null===i||null===o)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(i,o,c),d=this.determineDirection(r,i,o),h={transactionId:t,poolKey:u,token0:i,token1:o,amount0:s,amount1:a,feeTier:c,direction:d,timestamp:l,exactInput:this.determineExactInput(r,d)},g=this.extractUser(r);return void 0!==g&&(h.user=g),h}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Er(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(Er(t))return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(!Ir(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(Ir(e))return null;const t="number"==typeof e?e:lr(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(Er(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(Us(r,"zerotoone")||"0to1"===r)return"zeroForOne";if(Us(r,"onetozero")||"1to0"===r)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const i=this.extractAmount(e,"amount0","amountIn");return null!==i&&rr(i,0),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const n=void 0!==e.amountIn&&null!==e.amountIn,r=void 0!==e.amountOut&&null!==e.amountOut,i=void 0!==e.inputAmount&&null!==e.inputAmount,o=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||r)||!(r&&!n)&&(!(!i||o)||!(o&&!i))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}class zE{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,fs(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])}}}zE.CACHE=new Map,zE.ZERO=ar(0),zE.ONE=ar(1),zE.FEE_PIPS=ar(1e6),zE.MIN_SQRT_RATIO=ar("4295128739"),zE.MAX_SQRT_RATIO=new k("1461446703485210103287273052203988822378723970342");const jE={maxIterations:100,enableBigNumberCache:!0,roundingMode:k.ROUND_DOWN,debugLogging:!1};class VE{static calculateSwapDelta(e,t,n={}){const r=Date.now(),i={...jE,...n};try{const n=this.initializeSwapState(e,t,i);i.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const o=this.computeSwapLoop(n,e,t,i);i.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length,priceHitLimit:o.priceHitLimit});const s=this.createUpdatedPool(e.pool,o.state,t,i),a=this.calculateFinalAmounts(n,o.state,t);let c;if(void 0!==t.actualSqrtPrice&&""!==t.actualSqrtPrice){const e=fs(s.sqrtPrice),n=fs(t.actualSqrtPrice),r=e.minus(n).abs();c=ir(Ps(r,n).times(100).toNumber(),0)}const l=On(r);i.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length}),o.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:o.stepCount}),o.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:o.stepCount,ticksCrossed:o.ticksCrossed.length});return{updatedPool:s,updatedTicks:o.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:o.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:o.stepCount,priceHitLimit:o.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${Dt(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 i=n.enableBigNumberCache?zE.getCached.bind(zE):e=>ar(e),o="string"==typeof r.sqrtPrice?r.sqrtPrice:ps(r.sqrtPrice,0),s="string"==typeof r.liquidity?r.liquidity:ps(r.liquidity,0),a=i(o),c=i(s),l=r.tick??0,u=O(fs(o)),d=Math.abs(u-l);d>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:l,calculatedTick:u,drift:d,threshold:100});const h=i(t.amountSpecified);Ds(h,"amountSpecified");const g="string"==typeof r.feeGrowthGlobal1?r.feeGrowthGlobal1:ps(r.feeGrowthGlobal1,0),f="string"==typeof r.feeGrowthGlobal0?r.feeGrowthGlobal0:ps(r.feeGrowthGlobal0,0),p=t.zeroForOne?i(g):i(f);return{sqrtPrice:a,liquidity:c,tick:l,amountSpecifiedRemaining:h,amountCalculated:zE.ZERO,feeGrowthGlobalX:p,protocolFee:zE.ZERO}}static computeSwapLoop(e,t,n,r){const{pool:i,tickDataMap:o}=t,s=[],a={};let c=0;const l=n.zeroForOne?zE.MIN_SQRT_RATIO:zE.MAX_SQRT_RATIO,u=fs("0.000001");for(;e.amountSpecifiedRemaining.gt(u)&&!e.sqrtPrice.eq(l)&&c<r.maxIterations;){c++;const[t,u]=this.findNextInitializedTick(o,e.tick,i.tickSpacing,n.zeroForOne);let d;if(r.debugLogging&&this.logger.debug(`Swap step ${c}`,{currentTick:e.tick,tickNext:t,initialized:u,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),u&&t>=-887272&&t<=887272){const e=_(t);d=e instanceof k?e:fs(String(e))}else d=l;const h=n.zeroForOne?As(d,l):Ss(d,l),g=this.executeSwapStep(e.sqrtPrice,h,e.liquidity,e.amountSpecifiedRemaining,i.fee,n.exactInput);if(e.sqrtPrice=g.sqrtPriceNext,n.exactInput){const t=g.amountIn.plus(g.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=zE.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=zE.ZERO)),e.amountCalculated=e.amountCalculated.minus(g.amountOut)}else{g.amountOut.lte(0)?e.amountSpecifiedRemaining=zE.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(g.amountOut),e.amountCalculated=e.amountCalculated.plus(g.amountIn.plus(g.feeAmount))}if(e.liquidity.gt(0)){const t=Ps(g.feeAmount,e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(d)&&u){const i=o[t.toString()];if(null==i)throw new Error(`Missing tick data for initialized tick ${t}`);const c=n.zeroForOne?fs(i.liquidityNet).negated():fs(i.liquidityNet);if(e.liquidity=e.liquidity.plus(c),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);s.push(t),a[t.toString()]=i,r.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:c.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(d))e.tick=n.zeroForOne?t-1:t;else{const t=O(fs(e.sqrtPrice.toString()));e.tick=t}}if(c>=r.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${r.maxIterations}). Possible infinite loop or very complex swap.`);const d=e.sqrtPrice.eq(l);return{state:e,ticksCrossed:s,priceHitLimit:d,stepCount:c,updatedTicks:a}}static createUpdatedPool(e,t,n,r){const i=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(i.sqrtPrice=fs(t.sqrtPrice).toFixed(0),i.liquidity=fs(t.liquidity).toFixed(0),i.tick=t.tick,n.zeroForOne?i.feeGrowthGlobal1=fs(t.feeGrowthGlobalX).toFixed(0):i.feeGrowthGlobal0=fs(t.feeGrowthGlobalX).toFixed(0),n.zeroForOne){const n=fs(e.protocolFeesToken0);i.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=fs(e.protocolFeesToken1);i.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return i}static calculateFinalAmounts(e,t,n){let r,i,o,s;if(n.exactInput){const e=fs(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=e.negated(),i=a,o=zE.ZERO,s=zE.ZERO):(r=a,i=e.negated(),o=zE.ZERO,s=zE.ZERO)}else{const e=fs(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(r=a.negated(),i=e,o=zE.ZERO,s=zE.ZERO):(r=e,i=a.negated(),o=zE.ZERO,s=zE.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:o=a,{amount0:r,amount1:i,feeAmount0:o,feeAmount1:s}}static findNextInitializedTick(e,t,n,r){const i=Object.keys(e).map(e=>sr(e,0)).sort((e,t)=>e-t);if(0===i.length){return[r?-887272:887272,!1]}if(r){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,r,i,o){xs(n),Ds(r,"amountRemaining");const s=[500,3e3,1e4];if(!s.includes(i))throw new Error(`Invalid fee tier: ${i}. Must be one of: ${s.join(", ")}`);const a=L(e,t,n,r,i,t.lt(e)),c=a[0],l=a[1],u=a[2],d=a[3],h=k.isBigNumber(c)?c:fs(String(c)),g=k.isBigNumber(l)?l:fs(String(l)),f=k.isBigNumber(u)?u:fs(String(u)),p=k.isBigNumber(d)?d:fs(String(d));return{sqrtPriceStart:e,tickNext:O(h),sqrtPriceNext:h,initialised:!1,amountIn:g,amountOut:f,feeAmount:p}}}VE.logger=new _n({debug:!1,context:"SwapDeltaCalculator"});class XE extends Hr{constructor(e,t,n,r){super(!1,r),this.cache=new Map,this.tierSizes={hot:50,warm:200,cold:0},this.tierTTLs={hot:1/0,warm:18e5,cold:3e5},this.refetchThresholds={swapCount:50,driftPercent:.05},this.fetchPoolFn=e,this.config=t,this.metrics=n,this.tierSizes.cold=Math.max(0,this.config.maxPools-this.tierSizes.hot-this.tierSizes.warm),this.logger.debug(`Initialized with cache limits: hot=${this.tierSizes.hot}, warm=${this.tierSizes.warm}, cold=${this.tierSizes.cold}, max=${this.config.maxPools}`)}async getPool(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.lastAccessTime=Date.now(),this.checkRefetchNeeded(e,t),this.metrics.recordPoolCacheHit(e,0),t.poolData;this.cache.delete(e),this.logger.debug(`Cache expired for pool ${e}`)}this.metrics.recordPoolCacheMiss(e,0);try{const t=await this.fetchPoolFn(e),n=this.determineTier(),r={poolData:t,tier:n,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[n],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,r),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${n})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,n,r,i){const o=this.cache.get(e);if(!o)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(i){const s="zeroForOne"===t,a=s?n:r,c={transactionId:i.transactionId,timestamp:i.timestamp,amountSpecified:a,zeroForOne:s,exactInput:i.exactInput},l=VE.calculateSwapDelta(o.poolData,c);o.poolData={...o.poolData,pool:l.updatedPool},o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(o.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${o.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.ticksCrossed.length} ticks crossed`)}else o.swapsSinceRefetch++,o.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(o)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${o.swapsSinceRefetch}, drift=${(100*o.cumulativeDrift).toFixed(2)}%`),o.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),o.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(""===e)throw en("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await sa(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 en("poolKeys","Pool keys array");return sa(async()=>{const n={succeeded:0,failed:0,total:e.length};let r=0;const i=new Set;for(;r<e.length||i.size>0;){for(;r<e.length&&i.size<t;){const t=e[r];r++;const o=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});i.add(o),o.finally(()=>i.delete(o))}i.size>0&&await Promise.race(i)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n},"Failed to warm cache batch",this.logger)}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[n,r]of this.cache)e>r.expiresAt&&(this.cache.delete(n),t++);t>0&&this.logger.debug(`Cleared ${t} expired entries`)}determineTier(){const e=Array.from(this.cache.values()).filter(e=>"hot"===e.tier).length,t=Array.from(this.cache.values()).filter(e=>"warm"===e.tier).length;return e<this.tierSizes.hot?"hot":t<this.tierSizes.warm?"warm":"cold"}checkRefetchNeeded(e,t){this.shouldRefetch(t)&&(this.logger.debug(`Scheduling refetch for ${e}: swaps=${t.swapsSinceRefetch}, drift=${(100*t.cumulativeDrift).toFixed(2)}%`),t.expiresAt=Date.now())}shouldRefetch(e){return e.swapsSinceRefetch>=this.refetchThresholds.swapCount||e.cumulativeDrift>=this.refetchThresholds.driftPercent}evictLRU(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"cold"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(0===e.length){this.logger.warn("No cold cache entries to evict, trying warm cache");const e=Array.from(this.cache.entries()).filter(([e,t])=>"warm"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(e.length>0){const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted warm cache entry: ${t}`)}return}const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted cold cache entry: ${t}`)}async refreshWarmAndHotTiers(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"hot"===t.tier||"warm"===t.tier).sort((e,t)=>t[1].lastAccessTime-e[1].lastAccessTime).slice(0,10);if(0===e.length)return;const t=e.map(([e,t])=>this.fetchPoolFn(e).then(n=>{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 QE extends Hr{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(On(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=On(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class YE extends Hr{constructor(e,t,n,r={},i){super(!1,i),this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,e instanceof Promise?this.socketReady=e.then(e=>(this.socket=e,this.setupConnectionMonitoring(),e)).catch(e=>{throw this.logger.error("Failed to resolve socket promise:",e),e}):(this.socket=e,this.socketReady=Promise.resolve(e),this.setupConnectionMonitoring()),this.metrics=new KE,this.config=this.applyDefaults(r),this.eventExtractor=new WE(this.logger),this.cacheManager=new XE(t,this.config,this.metrics,this.logger),this.eventQueue=new QE(this.config,this.metrics,this.logger),this.seenTransactions=new JE(this.maxSeenTransactions),this.reconnectionManager=new HE({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),i={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectionManager.getAttempts()};this.socket?.connected&&(i.lastConnectionTime=new Date);const o=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(r,o,s,a,n.metrics.cacheHitRate);return{...n,status:r,websocket:i,recommendations:c,detailedMetrics:{eventQueueUtilization:o,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,r,i){const o=[];return"failed"===e&&(o.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||o.push("Reconnect WebSocket - connection lost"),t>90&&o.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(o.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&o.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),r>80&&o.push(`Memory usage ${r.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(i<50&&o.push(`Cache hit rate ${i.toFixed(1)}% is low - consider warming more pools`),r>50&&o.push("Memory usage is moderate - monitor for growth trends"),t>50&&o.push("Queue utilization is elevated - monitor for bottlenecks")),o}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){this.warmingIntervalHandle&&(clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.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(xt(e)?e:new Error(Dt(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(),i=r[0],o=t.eventExtractor.walkPayloadForSwaps(i,t.seenTransactions);if(0===o.length)return;t.logger.debug(`Extracted ${o.length} swaps from payload`);for(const n of o){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=On(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(xt(e)?e:new Error(Dt(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(!GE.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,r]=t.pairTokens;if(!GE.containsTokenPair(e.poolKey,n,r))return!1}if(void 0!==t.feeTierFilter&&""!==t.feeTierFilter){if(GE.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=On(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(xt(t)?t:new Error(Dt(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 JE{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 ZE={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 eT(e){return parseFloat(ZE[e])}function tT(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function nT(){return Date.now()+6e4}function rT(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function iT(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function oT(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class sT extends Gr{constructor(e){super(e)}getCollectionClaimFee(){return ZE.COLLECTION_CLAIM_FEE}getTokenClassCreateFee(){return ZE.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(!oT(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=ZE.COLLECTION_CLAIM_FEE;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const r=ZE.TOKEN_CLASS_CREATE_FEE,i=String(BigInt(r)*BigInt(e.createTokenClasses));n.tokenClassCreate=r,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(i))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!rT(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:nT(),uniqueKey:tT("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),!oT(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),!rT(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(!rT(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?iT(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?iT(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:nT(),uniqueKey:tT("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),!rT(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(!oT(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:nT(),uniqueKey:tT("mint")};this.logger.debug("Built mint DTO",r);const i=`mint-${Date.now()}`,o=Array.from({length:t},(e,t)=>t+1);return{transactionId:i,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:o,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!oT(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 aT extends Gr{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(G.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(G.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 qt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=G.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 qt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=G.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 qt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=G.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 qt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=G.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 cT(e){if(!Er(e))throw en("address","Address")}const lT={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},uT={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},dT=Nr(lT),hT=Nr(uT);function gT(e){if(e.status!==lT.PENDING)return!1;if(null!==e.expiresAt&&void 0!==e.expiresAt){if(Rn(e.expiresAt)<=new Date)return!1}return!0}function fT(e){try{Fr(e.description,"description",255)}catch(e){if(e instanceof qt){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(!Er(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{$r(e.expiresAt,"expiresAt")}catch(e){if(e instanceof qt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Mn(e.expiresAt)){if(Rn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function pT(e){if(void 0!==e.status&&!dT(e.status))throw gn("status",e.status,Object.values(lT),"status");Cr(0,void 0,50,e.pageSize,e.cursor)}function mT(e){if(void 0!==e.status&&!hT(e.status))throw gn("status",e.status,Object.values(uT),"status");Cr(0,void 0,50,e.pageSize,e.cursor)}function yT(e){if(!Er(e))throw new Error("Invite code must be a non-empty string");fr(e,100,"code")}function wT(e){if(!Er(e))throw new Error("Address must be a non-empty string");try{ri(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function bT(e){try{pr(e,"id")}catch(e){if(e instanceof qt)throw new Error("Invite ID must be a positive integer");throw e}}function kT(e){if(null==e||"object"!=typeof e)throw new qt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new qt("Search must be a string");if(0===e.search.length)throw new qt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new qt("Sort field must be a string");if(0===e.sortBy.length)throw new qt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new qt('Sort order must be "asc" or "desc"')}function vT(e){if(null==e||"object"!=typeof e)throw new qt("Options are required");if(!Er(e.userAddress))throw new qt("userAddress is required and must be a non-empty string");try{ri(e.userAddress,"userAddress")}catch{throw new qt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new qt("description must be a string");if(e.description.length>255)throw new qt("description must be at most 255 characters")}}class ST extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}validateInviteCodeFormat(e){if(!Er(e))throw en("inviteCode","Invite code");yT(e)}validateWalletAddressFormat(e){if(!Er(e))throw en("address","Address");wT(e)}async createInvite(e={}){fT(e),this.validateOptionalString(e.description,"description","Description",Wn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Re,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={}){pT(e),this.validateStatusFilter(e.status,lT);const t=Me,n={...this.buildPaginationParams(e,Kn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.invites,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Oe,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){bT(e);const t=this.buildEndpoint(Ue,{id:String(e)});wn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Le,n={inviteCode:e},r=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(r)}}async listOverseers(e={}){mT(e),this.validateStatusFilter(e.status,uT);const t=Fe,n={...this.buildPaginationParams(e,Kn.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.overseers,pageInfo:i.pageInfo}}async createOverseerDirect(e){vT(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",Wn.DESCRIPTION.MAX_LENGTH);const t=$e,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const r=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(r)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(qe,{address:e});wn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Ke,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=He,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=We,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=ze,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=je,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Ve,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&kT(t);const n=Xe,r=this.buildPaginationParams(t,Kn.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(r.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(r.sortBy=t.sortBy),void 0!==t.sortOrder&&(r.sortOrder=t.sortOrder);const i=await this.http.get(n,r,this.getDualAuthHeaders()),o=this.extractData(i);return{items:o.users,pageInfo:o.pageInfo}}async getOverseerUserSummary(e){if(!Er(e))throw en("address","User address");wT(e);const t=this.buildEndpoint(Qe,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){cT(e);const t=this.buildEndpoint(Ye,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Er(e))throw en("tokenName","Token name")}(e);const t=this.buildEndpoint(Je,{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 qt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Ze,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){cT(e);const t=this.buildEndpoint(et,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=tt,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}function AT(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 ET extends Gr{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),wn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(ie);return this.extractData(e)}async updatePlatformConfig(e){const t=AT(e);if(t.length>0)throw new qt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(oe,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(ce);return this.extractData(e)}}class TT extends Gr{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(vt),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class IT extends Gr{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw en("tokenName","Token name");if(!this.tokenResolverService)throw rn("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{Dr(e)}catch(e){throw rn(Dt(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 rn(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=fa(kS(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(xt(t)&&Dt(t).includes("ConfigurationError"))throw t;throw nn(`Failed to resolve token name '${e}': ${Dt(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw en("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await sa(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 rn("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return ES}),r=MS(fa(n(t))),{from:i,to:o,sortOrder:s="DESC"}=e,a=ir(e.offset,0),c=ir(e.limit,10),l={token:r,skip:String(a),take:String(c)};i&&(l.from=i.toISOString()),o&&(l.to=o.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 nn("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(!yn(e))throw nn("Invalid API response: missing data wrapper",500);const t=bn(e);if(!t||"object"!=typeof t)throw nn("Invalid API response: data is not an object",500);const n=t,r=n.data;if(!Array.isArray(r))throw nn("Invalid API response: missing or invalid data.data array",500);const i=n.meta;if(null==i||"object"!=typeof i)throw nn("Invalid API response: missing data.meta pagination info",500);const o=i,s=r.map(e=>{if("object"!=typeof e||null===e)throw nn("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:Rn(t.createdAt),tokenId:fa({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=or(o.currentPage,1),c=or(o.totalPages,1);return{snapshots:s,page:a,limit:or(o.pageSize,50),total:or(o.totalItems,0),totalPages:c,hasNext:a<c,hasPrevious:a>1}}async fetchAllPriceHistory(e){if(null==e)throw en("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),sa(async()=>{const t=await wS((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?Gv(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(xr(e,"tokenName","tokenId",{description:"token identifier"}),t&&!Mn(t))throw rn("from must be a valid Date","from");if(n&&!Mn(n))throw rn("to must be a valid Date","to");null!=r&&wr(r,"sortOrder"),Cr(0,void 0,50,e.pageSize)}}class CT extends Vv{constructor(e,t,n,r){super(e,t,n,!1,r)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(ut)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Er(e.content))throw new qt("Content is required");return{success:!0,data:(await this.http.put(dt,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}Ln.MIN_LENGTH,Ln.MAX_LENGTH,Ln.PATTERN;Nr({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});function NT(e){return"global"===e||"token"===e}function _T(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 xT(e){return _T(e)}function DT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}function PT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.messageId&&"string"==typeof t.deletedAt}function BT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.messageId&&"string"==typeof t.content&&"string"==typeof t.userAddress&&"string"==typeof t.pinnedBy&&"string"==typeof t.pinnedAt}function RT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&BT(t.pinnedMessage)}function MT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.unpinnedMessageId}function OT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.enabled&&(void 0===t.reason||NT(t.reason))}function LT(e){return!!Er(e)&&(e.length>=Wn.CHAT_MESSAGE.MIN_LENGTH&&e.length<=Wn.CHAT_MESSAGE.MAX_LENGTH)}function UT(e){return!!Er(e)&&Ln.PATTERN.test(e)}function FT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.emoji&&"number"==typeof t.timestamp&&"number"==typeof t.streamTime}function $T(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"string"==typeof t.message}const qT=Nr({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});function KT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.userAddress&&"string"==typeof t.fullName&&(void 0===t.profileImage||"string"==typeof t.profileImage)}function GT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&Array.isArray(t.typingUsers)&&t.typingUsers.every(KT)}class HT extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async getChatStatus(e){if(null==e||""===e)throw en("tokenName","Token name");return this.validateTokenName(e,Ln),sa(async()=>{const t=this.buildEndpoint(ht,{tokenName:e}),n=await this.http.get(t),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??Tn(e)};return void 0!==r.status&&null!==r.status&&(i.status=r.status),i},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw en("tokenName","Token name");return this.validateTokenName(e,Ln),sa(async()=>{const t=this.buildEndpoint(ft,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders()),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??Tn(e)};return void 0!==r.status&&null!==r.status&&(i.status=r.status),i},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw en("tokenName","Token name");return this.validateTokenName(e,Ln),sa(async()=>{const t=this.buildEndpoint(gt,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders()),r=this.extractData(n),i={enabled:r.enabled,tokenName:r.tokenName??Tn(e)};return void 0!==r.status&&null!==r.status&&(i.status=r.status),i},`Failed to enable chat for token: ${e}`,this.logger)}async setSlowMode(e,t){if(null==e||""===e)throw en("tokenName","Token name");if(this.validateTokenName(e,Ln),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return sa(async()=>{const n=this.buildEndpoint(wt,{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(pt);return this.extractData(e)}async disableGlobalChat(){const e=await this.http.post(yt,{enabled:!1},this.getAdminHeaders());return this.extractData(e)}async enableGlobalChat(){const e=await this.http.post(mt,{enabled:!0},this.getAdminHeaders());return this.extractData(e)}async setGlobalChatEnabled(e){return e?this.enableGlobalChat():this.disableGlobalChat()}async getEngagementStats(e){if(null==e)throw en("options","Engagement stats options");return function(e){if(!Er(e.tokenName))throw en("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw en("tokenName","Token name");if(!Ln.PATTERN.test(t))throw tn("tokenName",`match pattern ${String(Ln.PATTERN)}`,"Token name")}(e),sa(async()=>{const t=this.buildEndpoint(bt,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),r=this.extractData(n);return{tokenName:Tn(e.tokenName),chat:r.chat,comments:r.comments}},"Failed to get engagement stats",this.logger)}}class WT extends Hr{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 zT={IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"},jT={READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"},VT={ACTIVE:"ACTIVE",IDLE:"IDLE",ERRORED:"ERRORED",DISABLED:"DISABLED"},XT={YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"},QT=Nr(zT),YT=Nr(jT),JT=Nr(XT);function ZT(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&QT(t.status)&&(null===t.playbackId||"string"==typeof t.playbackId)&&"boolean"==typeof t.isLive}function eI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.tokenName&&"number"==typeof t.viewerCount}const tI={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"},nI={OWNER:"OWNER",MODERATOR:"MODERATOR"};Nr(tI),Nr(nI);const rI={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"},iI={...tI,OVERSEER:"OVERSEER"},oI={OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"};function sI(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 aI=Nr(iI),cI=Nr(oI);function lI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"boolean"==typeof t.hasAccess&&(null===t.role||aI(t.role))&&sI(t.permissions)&&(null===t.accessSource||cI(t.accessSource))&&"boolean"==typeof t.isOwner&&"boolean"==typeof t.isOverseer}function uI(e,t="tokenName"){Dr(e,t,Ln)}function dI(e){if(uI(e.tokenName),!Er(e.language))throw en("language");if(t=e.language,!Er(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new qt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",$t.INVALID_FORMAT);var t}const hI={STREAM_STARTED:"stream.started",STREAM_STOPPED:"stream.stopped",RECORDING_READY:"recording.ready",SIMULCAST_ERROR:"simulcast.error"};class gI extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async startStream(e){this.validateTokenName(e,Ln);const t=this.buildEndpoint(j,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Ln);const t=this.buildEndpoint(V,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,X,Ln)}async enableStream(e){return this.toggleFeature(e,Q,Ln)}async resetStreamKey(e){this.validateTokenName(e,Ln);const t=this.buildEndpoint(Y,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Ln);const t=this.buildEndpoint(ue,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){uI(e.tokenName),Cr(0,void 0,Jn,e.pageSize)}(e);const t=this.buildEndpoint(J,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Jn),r=e.offset;"number"==typeof r&&(n.offset=String(r));const i=await this.http.get(t,n),o=this.extractData(i),s=e,a=o.pageSize??o.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:o.recordings,tokenName:Tn(e.tokenName),page:o.page??l,limit:a,total:o.total,hasNext:o.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,Ln),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Z,{tokenName:e,assetId:t}),r=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(r)}async deleteRecording(e,t){this.validateTokenName(e,Ln),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(ee,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Ln);const t=this.buildEndpoint(te,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(uI(e.tokenName),!Er(e.platform))throw en("platform");if(!JT(e.platform))throw new qt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",$t.INVALID_VALUE);if(!Er(e.rtmpUrl))throw en("rtmpUrl");if(!Yn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new qt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",$t.INVALID_FORMAT);if(!Er(e.streamKey))throw en("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new qt("name must be a string","name",$t.INVALID_TYPE)}(e);const t=this.buildEndpoint(ne,{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,Ln),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(re,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(ie);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(oe,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(se,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(uI(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Er(e.nextLiveStreamAt)))throw new qt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",$t.INVALID_TYPE);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new qt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",$t.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,Ln);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){dI(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){uI(e.tokenName)}(e);const t=this.buildEndpoint(ae,{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(ce);return this.extractData(e)}async getTokenAccess(e){!function(e){uI(e.tokenName)}(e);const t=this.buildEndpoint(le,{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 fI={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 pI extends Hr{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 Gt("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 HE({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof F||(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:",Dt(e)),!1}}getRoomName(e){return`token:${Tn(e)}`}bufferEvent(e,t,n){const r=`${e}:${t}`;let i=this.eventBuffer.get(r);i||(i=[],this.eventBuffer.set(r,i)),i.length>=this.MAX_BUFFER_SIZE&&(i.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${r} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),i.push(n);const o=this.eventBufferTimeouts.get(r);o&&clearTimeout(o);const s=setTimeout(()=>{this.eventBuffer.delete(r),this.eventBufferTimeouts.delete(r),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${r}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(r,s)}processBufferedEvents(e,t){const n=Tn(e),r=[{key:`${fI.STREAM_STATUS}:${n}`,callback:t.onStreamStatus},{key:`${fI.VIEWER_COUNT}:${n}`,callback:t.onViewerCount},{key:`${fI.CHAT_MESSAGE}:${n}`,callback:t.onChatMessage},{key:`${fI.CHAT_STATUS}:${n}`,callback:t.onChatStatus},{key:`${fI.CHAT_PINNED}:${n}`,callback:t.onChatPinned},{key:`${fI.CHAT_UNPINNED}:${n}`,callback:t.onChatUnpinned},{key:`${fI.STREAM_COUNTDOWN_UPDATED}:${n}`,callback:t.onCountdownUpdated},{key:`${fI.STREAM_LANGUAGE_UPDATED}:${n}`,callback:t.onLanguageUpdated},{key:`${fI.TOKEN_BANNED}:${n}`,callback:t.onTokenBanned},{key:`${fI.TOKEN_UNBANNED}:${n}`,callback:t.onTokenUnbanned},{key:`${fI.MODERATOR_INVITE_CREATED}:${n}`,callback:t.onModeratorInviteCreated},{key:`${fI.MODERATOR_ADDED}:${n}`,callback:t.onModeratorAdded},{key:`${fI.MODERATOR_REMOVED}:${n}`,callback:t.onModeratorRemoved},{key:`${fI.MODERATOR_ROLE_UPDATED}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${fI.TRADE_EXECUTED}:${n}`,callback:t.onTradeExecuted},{key:`${fI.BALANCE_UPDATED}:${n}`,callback:t.onBalanceUpdated},{key:`${fI.POOL_METADATA_UPDATED}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${fI.POOL_SOCIAL_LINKS_UPDATED}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${fI.POOL_BADGE_ASSIGNED}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${fI.HOLDER_COUNT_UPDATED}:${n}`,callback:t.onHolderCountUpdated},{key:`${fI.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(fI.STREAM_STATUS,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(fI.STREAM_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Tn(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(fI.STREAM_SUBSCRIBED,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=Tn(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(fI.STREAM_UNSUBSCRIBED,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(Tn(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(fI.VIEWER_COUNT,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(fI.VIEWER_COUNT,e.tokenName,e);const t=this.roomCallbacks.get(Tn(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(fI.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(fI.CHAT_MESSAGE,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(fI.CHAT_MESSAGE,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(fI.CHAT_SENT,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(fI.CHAT_ERROR,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(fI.CHAT_STATUS,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(fI.CHAT_STATUS,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(fI.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(fI.CHAT_AUTHENTICATED,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(fI.CHAT_AUTH_ERROR,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(fI.REACTION,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(fI.REACTION_ERROR,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(fI.USER_TYPING,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(Tn(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(fI.CHAT_PINNED,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(fI.CHAT_PINNED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(fI.CHAT_UNPINNED,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(fI.CHAT_UNPINNED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(fI.STREAM_COUNTDOWN_UPDATED,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(fI.STREAM_COUNTDOWN_UPDATED,e.tokenName,e);const n=this.roomCallbacks.get(Tn(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(fI.STREAM_LANGUAGE_UPDATED,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(fI.STREAM_LANGUAGE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(fI.TOKEN_BANNED,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(fI.TOKEN_BANNED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(fI.TOKEN_UNBANNED,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(fI.TOKEN_UNBANNED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(fI.MODERATOR_INVITE_CREATED,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(fI.MODERATOR_INVITE_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(fI.MODERATOR_ADDED,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(fI.MODERATOR_ADDED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(fI.MODERATOR_REMOVED,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(fI.MODERATOR_REMOVED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(fI.MODERATOR_ROLE_UPDATED,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(fI.MODERATOR_ROLE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(fI.OVERSEER_ADDED,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(fI.OVERSEER_REMOVED,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(fI.TRADE_EXECUTED,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(fI.TRADE_EXECUTED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(fI.BALANCE_UPDATED,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(fI.BALANCE_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(fI.POOL_METADATA_UPDATED,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(fI.POOL_METADATA_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(fI.POOL_SOCIAL_LINKS_UPDATED,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(fI.POOL_SOCIAL_LINKS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(fI.POOL_BADGE_ASSIGNED,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(fI.POOL_BADGE_ASSIGNED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(fI.HOLDER_COUNT_UPDATED,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(fI.HOLDER_COUNT_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(fI.COMMENT_CREATED,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(fI.COMMENT_CREATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(fI.USER_PROFILE_UPDATED,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(fI.API_KEY_CREATED,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(fI.API_KEY_UPDATED,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(fI.API_KEY_REVOKED,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(fI.TOKEN_CONFIG_UPDATED,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(fI.TOKEN_CONFIG_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(fI.STATS_UPDATED,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(fI.STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(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(fI.ENGAGEMENT_STATS_UPDATED,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(fI.ENGAGEMENT_STATS_UPDATED,e.tokenName,e);const t=this.roomCallbacks.get(Tn(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(fI.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(fI.GLOBAL_FEED_UNSUBSCRIBED,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(fI.SITE_CONFIG_CHANGED,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(fI.STREAM_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(fI.CHAT_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(fI.COMMENTS_GLOBAL_STATUS,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(fI.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(fI.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(fI.SUBSCRIBE_GLOBAL_FEED)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{sa(async()=>{if(!this.isSocketIOAvailable)throw new Gt('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=F(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 qt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw en("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(fI.AUTHENTICATE,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw en("tokenName","Token name");if(!this.socket?.connected)throw new qt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=Tn(e);return this.subscribedRooms.has(n)?(this.logger.debug(`📡 Already subscribed to ${n}, updating callbacks`),this.roomCallbacks.set(n,t),this.processBufferedEvents(n,t),{tokenName:n,room:this.getRoomName(e)}):new Promise((r,i)=>{const o=setTimeout(()=>{this.pendingSubscriptions.delete(n),i(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:r,reject:i,timeoutId:o}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(fI.SUBSCRIBE,{tokenName:n})})}unsubscribeFromStream(e){const t=Tn(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(fI.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 en("tokenName","Token name");if(""===t)throw en("content","Message content");if(!this.socket?.connected)throw new qt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new qt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=Tn(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(fI.SEND_CHAT,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw en("tokenName","Token name");if(""===t)throw en("emoji");if(!this.socket?.connected)throw new qt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new qt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const r=Tn(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),this.socket.emit(fI.SEND_REACTION,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){if(""===e)throw en("tokenName","Token name");if(!this.socket?.connected)throw new qt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new qt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=Tn(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(fI.TYPING_START,{tokenName:t})}sendTypingStop(e){if(""===e)throw en("tokenName","Token name");if(!this.socket?.connected)throw new qt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new qt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=Tn(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(fI.TYPING_STOP,{tokenName:t})}subscribeTokenBanned(e,t){const n=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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=Tn(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 qt("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(fI.SUBSCRIBE_GLOBAL_FEED)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(fI.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 mI(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.id&&"string"==typeof t.tokenName&&"string"==typeof t.bannedBy&&"string"==typeof t.createdAt&&(null===t.reason||"string"==typeof t.reason)}function yI(e){return null==e||""===e||"string"==typeof e&&(!Ur(e)&&e.length<=Wn.BAN_REASON.MAX_LENGTH)}function wI(e){if(Dr(e.tokenName,"tokenName",Ln),!yI(e.reason))throw new qt(`reason must be at most ${Wn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG")}function bI(e){Dr(e.tokenName,"tokenName",Ln)}function kI(e){Cr(0,void 0,$n,e.pageSize)}function vI(e){Dr(e.tokenName,"tokenName",Ln)}class SI extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async banToken(e){wI(e);const t=nt,n={tokenName:Tn(e.tokenName)};if(void 0!==e.reason)try{yr(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:Tn(e.tokenName)}}async unbanToken(e){bI(e);const t=this.buildEndpoint(ot,{tokenName:e.tokenName});return wn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:Tn(e.tokenName)}}async listTokenBans(e={}){kI(e);const t=rt,n=this.buildPaginationParams(e,$n);this.addOptionalFilterParams(n,e,["search"]);const r=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.bans,pageInfo:i.pageInfo}}async getTokenBan(e){vI(e);const t=this.buildEndpoint(it,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),r=this.extractDataOrNull(n);return{banned:null!==r,...null!==r&&{ban:r},tokenName:Tn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class AI extends Hr{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(!Er(e))throw en("tokenName","Token name");const t=Tn(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(!Er(e))throw en("tokenName","Token name");const t=Tn(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 Zt(e);const i=this.parseVaultAddressToTokenClassKey(r);return this.setCacheEntry(t,{vaultAddress:r,tokenClassKey:i,cachedAt:Date.now()}),i}get(e){const t=this.getCacheEntry(Tn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=AI.MAX_CACHE_SIZE&&!this.cache.has(e)&&this.evictOldestEntry(),this.cache.set(e,t),this.updateAccessOrder(e)}updateAccessOrder(e){this.accessOrder.delete(e),this.accessOrder.add(e)}evictOldestEntry(){const e=this.accessOrder.values().next().value;void 0!==e&&""!==e&&(this.cache.delete(e),this.accessOrder.delete(e))}set(e,t){const n=Tn(e),r=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:r,cachedAt:Date.now()})}clear(){this.cache.clear(),this.accessOrder=new Set,this.cacheHits=0,this.cacheMisses=0}getStats(){const e=Array.from(this.cache.values()).map(e=>e.cachedAt),t=this.cacheHits+this.cacheMisses;return{size:this.cache.size,keys:Array.from(this.cache.keys()),maxSize:AI.MAX_CACHE_SIZE,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,oldestEntry:e.length>0?Math.min(...e):null,newestEntry:e.length>0?Math.max(...e):null}}getCachedTokenClassKey(e){const t=this.getCacheEntry(Tn(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=Tn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:r,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return kS(e)}catch(e){if(e instanceof qt)throw tn("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}AI.MAX_CACHE_SIZE=1e4;class EI extends Gr{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return vn(()=>this.http.get(St),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return vn(()=>this.http.get(At,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return vn(()=>this.http.get(Et,{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 vn(()=>this.http.get(Tt,{amount:e}),{errorContext:"Failed to get premint quote"})}}class TI extends Vv{constructor(e,t,n,r=!1,i){super(e,t,n,r,i)}async emitTradeExecuted(e,t){this.validateTokenName(e,Un);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,Un);const r={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(r)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Un);const r={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Un);const r={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Un);const r={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Un);const r={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Un);const r={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Un);const r={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitTokenBanned(e,t){this.validateTokenName(e,Un);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Un);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Un);const r={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(r)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Un);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 Gt("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,Un);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,Un);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Un);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Un);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}var II,CI;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(II||(II={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(CI||(CI={}));const NI={[II.PROCESSED]:CI.COMPLETED,[II.COMPLETED]:CI.COMPLETED,[II.SUCCESS]:CI.COMPLETED,[II.FAILED]:CI.FAILED,[II.ERROR]:CI.FAILED,[II.PROCESSING]:CI.PROCESSING,[II.PENDING]:CI.PENDING};class _I{constructor(e=0){this.defaultTtlMs=e,this.cache=new Map}get(e){const t=this.cache.get(e);if(t){if(!(void 0!==t.expiresAt&&Date.now()>t.expiresAt))return t.value;this.cache.delete(e)}}set(e,t,n){const r=n??this.defaultTtlMs,i={value:t};r>0&&(i.expiresAt=Date.now()+r),this.cache.set(e,i)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function xI(e,t,n,r={}){const{logger:i,cacheNullish:o=!1,keyGenerator:s}=r,a=s?s(e):String(e),c=n.get(a);if(void 0!==c)return i&&i.debug(`Cache hit for key: ${a}`),c;i&&i.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),i&&i.debug(`Cached result for key: ${a}`)):o&&(n.set(a,l),i&&i.debug(`Cached nullish result for key: ${a}`)),l}class DI extends Hr{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 HE({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new _I(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),DI.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof F||(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)=>{sa(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:",Dt(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=F(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,i=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(r/1e3),i={transactionId:e,status:CI.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},r);if(this.timeouts.set(e,i),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:CI.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const r=t,i=r?.data,o=r?.status??r?.Status??i?.status??i?.Status;let s=r?.message??r?.Message??i?.message??i?.Message??r?.error??i?.error;Er(s)||(s=o===II.FAILED||o===II.ERROR?"Transaction failed - check transaction details":o===II.COMPLETED||o===II.PROCESSED||o===II.SUCCESS?"Transaction completed successfully":null!=o?`Transaction status: ${String(o)}`:"Unknown transaction status");const a=r?.blockHash??i?.blockHash,c=r?.gasUsed??i?.gasUsed,l=r?.Data??i?.Data,u={transactionId:e,status:this.mapSocketStatus(o),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(o)} -> ${u.status}`),this.logger.debug(`📡 Final message: "${String(s)}"`),n(u),u.status===CI.COMPLETED||u.status===CI.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===CI.COMPLETED?t(e):e.status!==CI.FAILED&&e.status!==CI.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return NI[t]??CI.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")),DI.instances.delete(this)}static cleanupAll(e=!1){for(const e of DI.instances)e.disconnect();DI.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}DI.instances=new Set;class PI extends Gr{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 qt("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(It.GET_LEADERBOARD,n),i=this.extractData(r);return this.logger.debug("Fetched weekly challenge leaderboard",{count:i.count}),{leaderboard:i}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new qt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=It.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),r=await this.http.get(n),i=this.extractData(r);return this.logger.debug("Fetched token weekly history",{count:i.length}),{snapshots:i}}}class BI extends Wr{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return In(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 RI extends BI{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 MI extends TS{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new RI(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())})`),sa(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 sa(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:r,itemTypeName:i="items"}=e;if(t.has()){const e=t.getAll();return r&&r.debug(`Returning ${e.length} cached ${i}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}r&&r.debug(`Fetching all ${i} (no cache)`);const o=await n();try{t.setAll(o)}catch(e){r&&r.error("Cache operation failed (non-fatal):",e)}return{items:o,fetchedAt:Date.now(),itemCount:o.length}}({cache:this.cache,fetchFn:()=>this.autoPaginateFetch(),logger:this.logger,itemTypeName:"wrappable tokens"});return{tokens:e.items,fetchedAt:e.fetchedAt,tokenCount:e.itemCount}},"Failed to fetch wrappable tokens",this.logger)}async getWrappableToken(e){const t=AS(e),n=this.cache.getByTokenId(t);return n||(await xI("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=AS(e);await xI("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),r=void 0!==n,i={isWrappable:r,tokenId:t};return r&&(i.wrapCounterpart=n.wrapCounterpart),i}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class OI extends Hr{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 qt(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new qt(`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 qt(`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 qt(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new qt(`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 qt(`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 en("tokenId","Token identifier");if(0===t.length)throw en("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new qt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new qt(`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 en("tokenId","Token identifier");if(0===t.length)throw en("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new qt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new qt(`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 en("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:r,recipient:i,isWrap:o}=e;if(!this.wallet||void 0===this.walletAddress||0===this.walletAddress.length)throw new qt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,o),c=`galaswap-operation-${vk()}`,l=Dk,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:i??s,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${o?"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:o,senderAddress:s,typedDataTypes:l})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:r,message:i,routing:o,isWrap:s,typedDataTypes:a}=e;try{const e=await this.wallet.signTypedData(Ak,a,i),c=`Ethereum Signed Message:\n${bk({domain:Ak,message:i,primaryType:"GalaTransaction",types:a}).length}`,l={...i,signature:e,prefix:c,types:a,domain:Ak};this.logger.debug(`[WrapService] ${s?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:r,channel:o.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}`,i="string"==typeof u.Message&&u.Message.length>0?`: ${u.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`GalaChain request failed (${e}${i})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(u)){const e=u.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const i={bridgeFromChannel:o.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:i.bridgeFromChannel});const a=await this.galaConnectClient.bridgeTokenOut(i);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:o.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:o.sourceChannel,toChannel:s?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof u})`}}catch(e){const i=Dt(e);return this.logger.error(`[WrapService] ${s?"Wrap":"Unwrap"} operation failed:`,i),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:r,fromChannel:o.sourceChannel,toChannel:s?"asset":n.channel??"music",error:i}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:wa.ASSET,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:wa.MUSIC,authType:"automatic"}}requireWallet(){if(void 0===this.walletAddress||0===this.walletAddress.length)throw new qt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:fa(e)}}const LI=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function UI(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>UI(e,t+1));if(e instanceof Map){const n={};for(const[r,i]of e.entries()){const e=String(r);n[e]=LI.has(e.toLowerCase())?"[REDACTED]":UI(i,t+1)}return n}if("object"==typeof e){const n={};for(const[r,i]of Object.entries(e))n[r]=LI.has(r.toLowerCase())?"[REDACTED]":UI(i,t+1);return n}return e}class FI{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new _n({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??"https://lpad-backend-dev1.defi.gala.com",r=t.timeout??6e4;this.axios=QA(n,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return sa(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:hs(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout}};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]":UI(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:UI(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:UI(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 sa(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}async signWithGalaChain(e,t,n=f.SIGN_TYPED_DATA){const r=this.auth.getPrivateKey(),i={};Object.entries(t).forEach(([e,t])=>{void 0!==t&&(i[e]=t)});const o=new m(r);return await o.sign(e,i,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request 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??Dt(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 $I extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class qI extends $I{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class KI 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 GI(e,t){if(Ir(e))throw new $I(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new $I(`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 $I(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function HI(e,t,n,r){GI(e,t);const i=e,o=i.data??{};if(!function(e){if(Ir(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(o))throw new $I(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===r.type?"native":"exact",inputAmount:o.inputQuantity??r.amount,outputAmount:o.outputQuantity??r.expectedAmount??"0",totalFees:o.totalFees??"0",tokenName:r.tokenName,vaultAddress:o.vaultAddress??"",timestamp:Date.now()};return void 0!==i.blockHash&&(s.blockHash=i.blockHash),void 0!==i.gasUsed&&(s.gasUsed=i.gasUsed),void 0!==r.slippageToleranceFactor&&(s.slippageTolerance=r.slippageToleranceFactor),s}const WI=4001,zI=4100,jI=4900,VI=4901;class XI{constructor(e){if(this.providerType="external",this.connectedAddress=null,this.accountsChangedHandler=null,this.disconnectHandler=null,null==e)throw new la("EIP-1193 provider is required",ra.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(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===WI)throw new la(`User rejected ${t}`,ra.USER_REJECTED,e instanceof Error?e:void 0);if(n.code===zI)throw new la("Wallet is not authorized",ra.NOT_CONNECTED,e instanceof Error?e:void 0);if(n.code===jI||n.code===VI)throw this.connectedAddress=null,new la("Wallet disconnected",ra.NOT_CONNECTED,e instanceof Error?e:void 0);throw new la(n.message??`${t} failed`,t.includes("sign")?ra.SIGNING_FAILED:ra.UNKNOWN,e instanceof Error?e:void 0)}ensureConnected(){if(!this.connectedAddress)throw new la("Wallet is not connected. Call connect() first.",ra.NOT_CONNECTED)}async connect(){try{const t=await this.provider.request({method:"eth_requestAccounts"});if(null==t||0===t.length)throw new la("No accounts returned from wallet",ra.CONNECTION_FAILED);return this.connectedAddress=e(t[0]),this.connectedAddress}catch(e){if(e instanceof la)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 la)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 la)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 la("Private key is not accessible with external wallet providers. Use PrivateKeyProvider if you need private key access for @gala-chain operations.",ra.PRIVATE_KEY_NOT_ACCESSIBLE)}getProvider(){return this.provider}}function QI(e){if(null!=e.privateKey&&e.privateKey.length>0)return new ua(e.privateKey);if(null!=e.eip1193Provider)return new XI(e.eip1193Provider);throw new la("Invalid wallet provider config: must provide either privateKey or eip1193Provider",ra.INVALID_CONFIG)}function YI(e){return ua.fromWallet(e)}function JI(e){return new XI(e)}function ZI(e){return"privateKey"===e.providerType}function eC(e){return"external"===e.providerType}function tC(e){if(e)return ua.fromWallet(e)}function nC(e){if(e&&ZI(e))return e.getWallet()}async function rC(e){return e.isConnected()?e.getAddress():e.connect()}function iC(e){return"object"==typeof e&&null!==e&&"request"in e&&"function"==typeof e.request}function oC(){if("undefined"==typeof window)return null;const e=window.ethereum;return iC(e)?e:null}class sC{constructor(e){this.logger=e??new _n({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],r=new WeakSet,i=(e,o=0)=>{if(o>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(null!=e&&!Er(e)&&"object"==typeof e){if(r.has(e))return;r.add(e);const s=this.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,o+1)}};return i(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(null===t||""===t)return null;const n=e.Data,r=null==n||"object"!=typeof n||Array.isArray(n)?e:n,i=this.extractPositionId(r),o=this.extractPoolHash(r),s=this.extractAmounts(r),a=this.extractUserAddress(r),c=this.extractPoolFee(r);if(null===i||""===i||null===o||""===o||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,f={transactionId:t,positionId:i,poolHash:o,poolFee:c,amounts:s,userAddress:a};return void 0!==h&&(f.token0=h),void 0!==g&&(f.token1=g),void 0!==d&&(f.timestamp=d),void 0!==l&&(f.poolAlias=l),void 0!==u&&(f.userBalanceDelta=u),f}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Er(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(Er(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","pool"];for(const n of t){const t=e[n];if(Er(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(Er(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(Er(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(Er(t)){const e=rr(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(Er(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),i=this.extractBalanceObject(n.token1Balance);if(!r&&!i)return;const o={};return void 0!==r&&(o.token0Balance=r),void 0!==i&&(o.token1Balance=i),o}extractBalanceObject(e){if(null==e||"object"!=typeof e)return;const t=e,n=t.collection,r=t.category,i=t.type,o=t.additionalKey,s=t.quantity,a=t.owner;return Er(n)&&Er(r)&&Er(i)&&Er(o)&&Er(s)&&Er(a)?{collection:n,category:r,type:i,additionalKey:o,quantity:s,owner:a}:void 0}}class aC{constructor(e){let t,n;e.walletProvider?(t=e.walletProvider,n=nC(e.walletProvider)):e.wallet&&(n=e.wallet,t=ua.fromWallet(e.wallet)),this.wallet=n;let r=null,i="STAGE";if(void 0!==e.env?(i=e.env,r=ga(e.env)):e.baseUrl?.includes("prod")?(i="PROD",r=ga("PROD")):(i="STAGE",r=ga("STAGE")),this.environment=i,this.config={baseUrl:r.launchpadBaseUrl,galaChainBaseUrl:r.galaChainBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new _n({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?aC.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?aC.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??aC.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency??5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new da({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new oa,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new FI(this.auth,this.config),this.sessionAuth=new ca(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new FI(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new FI(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new FI(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new FI(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=QA(this.config.galaChainBaseUrl,this.config.timeout??3e4),this.cache=new zr(e.debug??!1),this.launchpadService=new AE(this.http,this.jwtAuth),this.tokenResolverService=new AI(this.launchpadService.poolService),this.launchpadAPI=new Zs(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new XA(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new lA(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new US(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new DI({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new IT(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService),this.dexQuoteService=new cA(this.galaChainHttp,this.config.galaChainBaseUrl,e.debug??!1,e.dexQuoteNetworkTimeout??3e4),this.gswapService=new iE({privateKey:n?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,gatewayBaseUrl:this.config.galaChainBaseUrl,bundlerBaseUrl:this.config.bundleBaseUrl,galaChainBaseUrl:this.config.galaChainBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new oA(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug??!1),this.nftCollectionService=new sT(this.galaChainHttp),this.tradingQuotesService=new EI(this.http,e.debug??!1)}createOverrideSdk(e){if(!Er(e))throw rn("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw rn('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const n=new t(e),r={...this.config,wallet:n};return new aC(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 en("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new qt("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?nC(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:i,headers:o,...s}=this.config;return{...s,...void 0!==n&&{streamAdminApiKey:"[REDACTED]"},...void 0!==r&&{userApiKey:"[REDACTED]"},...void 0!==i&&{accessToken:"[REDACTED]"},...void 0!==o&&{headers:Object.fromEntries(Object.keys(o).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:En.GAS_FEE}}getVersion(){return Lv}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw rn("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,i=t?.maxBalance??1/0,o=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<=i}).map(e=>({...e,rank:s.get(e.address)??0})).slice(0,o)}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}=xr(e,"tokenName","tokenId",{description:"token identifier"});if(r&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const i=n;try{return await this.dexService.fetchTokenPrice({tokenId:i})}catch(e){const t=function(e){if(Rt(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=Tn((await this.fetchTokenDetails(i)).name);if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;return this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`),this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}catch(t){throw this.logger.error(`Launchpad fallback failed: ${Dt(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(Ft(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 si}),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 Rv({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 _S(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new MI(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 gv({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 OI({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new gI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new HT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new yS(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new SI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Xv(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new PI(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new aT(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new TT(this.http,this.config.debug??!1)),this._platformStatsService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new aS(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new qE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new tA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new ST(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new TI(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new iA(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}getMessagesService(){return this._messagesService??(this._messagesService=new EE(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new CT(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new ET(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new hA(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 pI({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new WT(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===Ls(e.tokenName))throw en("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 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 si}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return ES}),r=t(e.tokenId),{collection:i,category:o,type:s,additionalKey:a}=r;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:o,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Cn(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const r=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:"Unit",additionalKey:"none",type:"none",instance:"0"},e.withExpired??!1)}}if(void 0!==e.tokenName&&""!==e.tokenName){const t=(await this.fetchTokensHeld({tokenName:e.tokenName,pageSize:1,...void 0!==n?{address:n}:{}})).tokens[0];if(void 0===t)return null;const r=t.collection??"Token",i={collection:r,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:r,category:"Unit",tokenId:fa(i)}}throw en("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:r,privateKey:i,calculateAmountMode:o,currentSupply:s}=e;let a=t;void 0===o&&void 0===s||(a={tokenName:t,...void 0!==o&&{calculateAmountMode:o},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==r&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=r),void 0!==i&&(l.privateKey=i),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.buy(r)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw on("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>HI(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 on("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>HI(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=>{GI(n,t);const r=n.data??{};if(!function(e){if(Ir(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress||void 0!==t.tokenStringKey&&"string"!=typeof t.tokenStringKey||void 0!==t.creatorAddress&&"string"!=typeof t.creatorAddress)}(r))throw new $I(`Invalid launch data received for transaction ${t}`);const i={transactionId:t,vaultAddress:r.vaultAddress??"",tokenStringKey:r.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:r.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),""!==i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...r}=e;return t.uploadTokenImage(r)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async 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 si}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(H,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 si}),r=n(e.address);if(void 0===r)throw new qt(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=e?.page??1,r=e?.limit??10,i={pageNumber:n,limit:r,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},o=await this.dexApiHttp.get(W,i,{"x-wallet-address":t});if(!Array.isArray(o))throw new Kt("Unexpected API response: expected array, got "+typeof o);return{referrals:o,page:n,limit:r,hasMore:o.length===r}}async fetchAllReferrals(e){const t=await wS((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 si}),r=n(e.address);if(void 0===r)throw new qt(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=r}else t=this.getAddress();const n=await this.dexApiHttp.get(z,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Kt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return si}),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 si}),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 si}),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 si}),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 si}),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 si}),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 si});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{gr(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 rn("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw rn("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw rn(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw rn(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.galaChainBaseUrl&&""!==this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw rn(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw rn(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw rn(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=rr("string"==typeof e||"number"==typeof e?e:String(e),aC.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${aC.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),aC.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=rr("string"==typeof e||"number"==typeof e?e:String(e),aC.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: ${aC.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),aC.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 KI(e,n.status,n.message);let r;try{r=t(n)}catch(t){if(t instanceof $I)throw t;throw new $I(`Failed to transform WebSocket response for transaction ${e}`,xt(t)?t:new Error(Dt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,r),r}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof KI||t instanceof $I)throw t;throw new $I(`WebSocket confirmation failed for transaction ${e}`,xt(t)?t:new Error(Dt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return B_});e.forEach(e=>{if(!n(e))return;const r=t(e,this.logger);r&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,r)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,r,i,o=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:r,feeTier:i,slippageTolerance:o})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,r){let i,o;"string"==typeof n?(i=n,o=r):"object"==typeof n?o=n:r&&(o=r);return await this.gswapService.getUserLiquidityPositions(e,t,i,o)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(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,i,o,s){return this.gswapService.getLiquidityPositionById(e,t,n,r,i,o,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const n=1e3,r=Math.max(t?.intervalMs??3e4,n);void 0!==t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.minTVL,o=t?.tokens,s=new Map;let a=!0,c=null;let l=0;const u=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.items.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),void 0!==i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(o&&o.length>0){if(!(o.includes(t.token0)||o.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=Dt(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 i=t?.creatorAddress,o=new Map;let s=!0,a=null;let c=0;const l=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{o.has(t.tokenName)||((e=>{if(o.set(e,!0),o.size>1e3){const e=o.keys().next().value;void 0!==e&&o.delete(e)}})(t.tokenName),void 0!==i&&""!==i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=Dt(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=lr(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 GE.isValidPoolKey(t)?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,n=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol"),r=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol"),i=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return""===n||""===r||null===i?null:`${n}/${r}/${i}`}parsePoolPairString(e){const t=GE.parsePoolKey(e);if(!t)return null;const n=Yk(t.token0)?Qk(t.token0).collection:t.token0,r=Yk(t.token1)?Qk(t.token1).collection:t.token1,i=t.feeTier.toString();return""===n||""===r||""===i?null:{token0:n,token1:r,fee:i,poolPair:e}}serializeBalanceToken(e){if(null==e||"object"!=typeof e)return"";const t=e,n=t.collection??t.token??"",r=t.category??"",i=t.type??"",o=t.additionalKey??"none";return[""!==n?n:"",""!==r?r:"none",""!==i?i:"none",""!==o?o:"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,i=r.token0Balance??r.token0??r.baseBalance??r.primaryBalance,o=r.token1Balance??r.token1??r.quoteBalance??r.secondaryBalance,s=this.serializeBalanceToken(i),a=this.serializeBalanceToken(o),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return""===s||""===a||null===c?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 i=this.buildPoolPairFromObject(t);if(null!==i)return this.parsePoolPairString(i);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,i=e.token0===n||e.token1===n,o=e.token0===r||e.token1===r;if(!i||!o||n===r)return!1}if(void 0!==t?.feeTierFilter){if(this.normalizeFee(t.feeTierFilter)!==this.normalizeFee(e.fee))return!1}return!0}matchesCreatorFilter(e,t){return 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 rn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=(n,...r)=>{try{if(r.length>0&&"object"==typeof r[0]&&null!==r[0]){const n=r[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const r=n.Data;if("CreateSale"===r.functionName){const n={tokenName:""!==r.tokenName?r.tokenName:"",symbol:""!==r.symbol?r.symbol:"",creatorAddress:""!==r.creatorAddress?r.creatorAddress:"",description:""!==r.description?r.description:"",image:""!==r.image?r.image:"",vaultAddress:""!==r.vaultAddress?r.vaultAddress:"",tokenStringKey:""!==r.tokenStringKey?r.tokenStringKey:"",preBuyQuantity:""!==r.initialBuyQuantity?r.initialBuyQuantity:"0",websiteUrl:""!==r.websiteUrl?r.websiteUrl:"",telegramUrl:""!==r.telegramUrl?r.telegramUrl:"",twitterUrl:""!==r.twitterUrl?r.twitterUrl:"",instagramUrl:""!==r.instagramUrl?r.instagramUrl:"",facebookUrl:""!==r.facebookUrl?r.facebookUrl:"",redditUrl:""!==r.redditUrl?r.redditUrl:"",tiktokUrl:""!==r.tiktokUrl?r.tiktokUrl:"",isFinalized:!1!==r.isFinalized&&null!==r.isFinalized&&void 0!==r.isFinalized&&r.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Dt(e)}`)}};let o=this.websocketService.getSocket();if(o)o.onAny(i),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${Dt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(o=this.websocketService.getSocket(),!o&&e<aC.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>s(),aC.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!o&&e>=aC.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${aC.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*aC.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}o&&(o.onAny(i),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(i),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}walkPayloadForPools(e,t,n=new WeakSet){const r=[];if("string"==typeof e){const n=this.looksLikePoolPair(e);if(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 i=this.extractPoolDataFromPayload(e);i&&!t.has(i.poolPair)&&(t.add(i.poolPair),r.push(i));for(const i of Object.values(e)){const e=this.walkPayloadForPools(i,t,n);r.push(...e)}return r}subscribeToDexPoolAdded(e,t){if(this.logger.debug("Subscribing to DEX pool creation broadcasts"+(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 rn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=new Set,o=(n,...r)=>{try{for(const n of r){const r=this.walkPayloadForPools(n,i);for(const n of r)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${Dt(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(o),n=!0,this.logger.debug("DEX pool broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${Dt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(s=this.websocketService.getSocket(),!s&&e<aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),aC.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS*aC.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(o),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};i()}return()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(o),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(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 rn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=null,r=null,i=null,o=!1;const s=async e=>{const t=GE.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));o=!0,r=new YE(c,s,this.dexQuoteService,t??{},this.logger),i=r.subscribe(t??{},e),this.logger.debug("DEX swap monitoring subscription established")};return this.websocketService.getSocket()||(this.logger.debug("WebSocket not yet connected, initiating connection for swap monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed for swap monitoring: ${Dt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),i&&o&&i(),r&&r.shutdown().catch(e=>{this.logger.warn("Error shutting down swap monitor:",e)})}catch(e){this.logger.warn("Error cleaning up swap monitor:",e)}}}subscribeToDexLiquidityAdded(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityRemoved(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityChanged(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityEvents(e,t){if(this.logger.debug("Subscribing to DEX liquidity broadcasts"+(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 rn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,r=null;const i=new Set,o=new sC(this.logger),s=(n,...r)=>{try{for(const n of r){const r=o.walkPayloadForLiquidityEvents(n,i);for(const n of r)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${Dt(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${Dt(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${Dt(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: ${Dt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(a=this.websocketService.getSocket(),!a&&e<aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(r=setTimeout(()=>i(),aC.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS*aC.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};i()}return async()=>{try{if(null!==r&&(clearTimeout(r),r=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to DEX liquidity broadcasts"))}catch(e){this.logger.warn("Error removing DEX liquidity listener:",e)}}}matchesLiquidityFilter(e,t){if(!t)return!0;if(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&&$s(e.token0,t.tokenFilter),r=void 0!==e.token1&&""!==e.token1&&$s(e.token1,t.tokenFilter);if(!n&&!r)return!1}if(void 0!==t.pairTokens){const[n,r]=t.pairTokens,i=e.token0??"",o=e.token1??"",s=$s(i,n)&&$s(o,r),a=$s(i,r)&&$s(o,n);if(!s&&!a)return!1}if(void 0!==t.minAmount&&""!==t.minAmount){const n=rr(t.minAmount),r=rr(e.amounts[0]),i=rr(e.amounts[1]);if(Math.abs(r)<n&&Math.abs(i)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);return function(e,t=3e3){if(Pn(e))return t;if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const n=String(e).trim();if(n.endsWith("%")){const e=rr(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 _n({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),DI.cleanupAll(e),t.debug("Global cleanup completed")}}aC.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,aC.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,aC.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=En.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,aC.DEFAULT_CALCULATE_AMOUNT_MODE=_t.LOCAL,aC.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,aC.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,aC.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,aC.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class cC{static generateWallet(){try{const e=t.createRandom();if(null==e.mnemonic?.phrase||""===e.mnemonic.phrase)throw en("mnemonic","Mnemonic phrase");const n=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:n,mnemonic:e.mnemonic.phrase,wallet:new t(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,n="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),r=new t(n),i=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:r}}throw e}}static fromPrivateKey(e){const n=new t(e),r=this.toGalaAddress(n.address);return{privateKey:n.privateKey,address:n.address,galaAddress:r,mnemonic:"",wallet:n}}static fromMnemonic(e,n=0){try{const r=l.fromPhrase(e),i=u.fromMnemonic(r,`m/44'/60'/0'/0/${n}`),o=new t(i.privateKey),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}catch(r){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const r=`test-mnemonic-index-${n}-${e}`,i="0x"+Buffer.from(r).toString("hex").padStart(64,"1").slice(0,64),o=new t(i),s=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:s,mnemonic:e,wallet:o}}throw r}}static toGalaAddress(t){const n=Jr(t);if(!/^[a-fA-F0-9]{40}$/.test(n))throw tn("address","a valid Ethereum address (40 hex characters)");return`eth|${e(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return ei(e)}catch(t){const n=Dt(t);if(n.includes("required")||!e?.startsWith("eth|"))throw en("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw tn("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=Jr(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===oi(e)}static generateMultipleWallets(e=1){gr(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 lC(e){if(void 0===e)return cC.generateWallet();const t=e.trim();if(!Er(t))throw tn("input","a non-empty string");if(function(e){const t=Jr(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return cC.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 cC.fromMnemonic(t);throw tn("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function uC(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw tn("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new h(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function dC(t){if(!t.match(/^0x[a-fA-F0-9]{64}$/))throw tn("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return e(d(t))}function hC(){const e=Ub.generate();return{privateKey:_v.encode(e.secretKey),publicKey:e.publicKey.toBase58(),address:e.publicKey.toBase58()}}function gC(e){Ir(e)&&(e={});const{wallet:n,env:r,config:i={},...o}=e,s={...o,...i},{wallet:a,env:c,config:l,...u}=s;let d;if(Ir(n)){d=lC().wallet}else if("string"==typeof n){d=lC(n).wallet}else{if(!(n instanceof t))throw rn("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 aC(h)}cC.testCounter=0;let fC=null;async function pC(){if(!1===fC)return null;try{const e=await import("@gala-chain/connect");return fC=!0,e}catch{return fC=!1,null}}class mC{constructor(e){if(this.providerType="external",this.connectedAddress=null,!e)throw new la("@gala-chain/connect client is required",ra.INVALID_CONFIG);if("function"!=typeof e.signMessage)throw new la("Invalid @gala-chain/connect client: signMessage method is required",ra.INVALID_CONFIG);this.client=e}static async createBrowserClient(e){const t=await pC();if(null==t)throw new la("Failed to create BrowserConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",ra.PROVIDER_NOT_AVAILABLE);const{BrowserConnectClient:n}=t,r=n,i=e?new r(e):new r;return new mC(i)}static async createTrustWalletClient(){const e=await pC();if(null==e)throw new la("Failed to create TrustWalletConnectClient: @gala-chain/connect is not installed. Install it with: npm install @gala-chain/connect",ra.PROVIDER_NOT_AVAILABLE);const{TrustWalletConnectClient:t}=e,n=new t;return new mC(n)}static async isAvailable(){return null!==await pC()}ensureConnected(){if(null===this.connectedAddress||void 0===this.connectedAddress)throw new la("Wallet is not connected. Call connect() first.",ra.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(t),this.connectedAddress}if("function"==typeof this.client.getAccount){const t=await this.client.getAccount();if(null!=t&&t.length>0)return this.connectedAddress=e(t),this.connectedAddress}throw new la("Failed to connect: no account returned",ra.CONNECTION_FAILED)}catch(e){if(e instanceof la)throw e;const t=e instanceof Error?e.message:String(e);if(t.length>0&&(t.includes("rejected")||t.includes("denied")))throw new la("User rejected connection",ra.USER_REJECTED,e instanceof Error?e:void 0);throw new la("Failed to connect to wallet",ra.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 la("User rejected signing",ra.USER_REJECTED,e instanceof Error?e:void 0);throw new la("Failed to sign message",ra.SIGNING_FAILED,e instanceof Error?e:void 0)}}async signTypedData(e,t,n){throw new la("signTypedData is not supported by GalaChainConnectProvider. Use ExternalWalletProvider with the underlying EIP-1193 provider instead.",ra.SIGNING_FAILED)}async getAddress(){return this.ensureConnected(),this.connectedAddress}async getGalaAddress(){return`eth|${(await this.getAddress()).slice(2)}`}async getPrivateKey(){throw new la("Private key is not accessible with @gala-chain/connect. Use PrivateKeyProvider if you need private key access.",ra.PRIVATE_KEY_NOT_ACCESSIBLE)}getClient(){return this.client}}const yC={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"},wC={[yC.METAMASK]:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIxLjU0IDQuMjJsLTguMzQgNi4yMSAxLjU0LTMuNjUtLTUuNTMtMi41MXoiIGZpbGw9IiNFMjc2MUIiLz48L3N2Zz4="};function bC(){return"undefined"!=typeof window&&"function"==typeof window.dispatchEvent}function kC(){if(!bC())return null;return window.ethereum??null}async function vC(e=500){const t=[],n=new Map;return bC()?new Promise(r=>{const i=new Set,o=e=>{const r=e,{info:o,provider:s}=r.detail;if(i.has(o.uuid))return;i.add(o.uuid);const a={id:o.rdns||o.uuid,name:o.name,rdns:o.rdns||o.uuid,icon:o.icon??wC[o.rdns||""]??"",provider:s,isInjected:!1};t.push(a),n.set(a.id,a)};window.addEventListener("eip6963:announceProvider",o),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{if(window.removeEventListener("eip6963:announceProvider",o),0===t.length){const e=kC();if(e){const r=window;let i="Browser Wallet",o="injected";r.ethereum?.isMetaMask?(i="MetaMask",o=yC.METAMASK):r.ethereum?.isCoinbaseWallet?(i="Coinbase Wallet",o=yC.COINBASE):r.ethereum?.isTrust&&(i="Trust Wallet",o=yC.TRUST_WALLET);const s={id:o,name:i,rdns:o,icon:wC[o]??"",provider:e,isInjected:!0};t.push(s),n.set(s.id,s)}}r({wallets:t,byId:n,hasWallets:t.length>0,primary:t[0]})},e)}):{wallets:t,byId:n,hasWallets:!1}}function SC(e){if(!bC())return()=>{};let t=!0,n={wallets:[],byId:new Map,hasWallets:!1};const r=r=>{if(!t)return;const i=r,{info:o,provider:s}=i.detail,a=o.rdns||o.uuid;if(n.byId.has(a))return;const c={id:a,name:o.name,rdns:a,icon:o.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),vC().then(r=>{t&&(n=r,e(r))}),()=>{t=!1,window.removeEventListener("eip6963:announceProvider",r)}}async function AC(e,t){return(await vC(t)).byId.get(e)??null}async function EC(e,t){return null!==await AC(e,t)}function TC(){return null!==kC()}class IC{static async quickSetup(e={}){const t=e.environment??this.detectEnvironment(),n=this.setupWallet(e.privateKey),r=e.galaChainAddress??process.env.WALLET_ADDRESS,i={wallet:n.wallet,baseUrl:e.baseUrl??this.getDefaultBaseUrl(t),timeout:e.timeout??this.getDefaultTimeout(t),debug:e.debug??"production"!==t,...this.getEnvironmentDefaults(t),...e.config??{},...void 0!==r&&""!==r?{galaChainAddress:r}:{}},o=new aC(i),s={sdk:o,wallet:n,config:i};if(!1!==e.autoValidate){const e=await this.validateSetup(o,n);return{...s,validation:e}}return s}static 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}:{}},i=new aC(r);return Promise.resolve({sdk:i,config:r})}static async validateSetup(e,t){const n=[],r=[],i={canTrade:!1,canCreateTokens:!1,hasBalance:!1,connectionHealthy:!1};try{const t=await e.fetchGalaBalance(e.getAddress());if(i.connectionHealthy=!0,void 0!==t?.quantity&&""!==t.quantity){const e=rr(t.quantity,0);i.hasBalance=e>0,i.canTrade=e>=.1,i.canCreateTokens=e>=100,0===e?r.push("Wallet has zero GALA balance - cannot perform transactions"):e<.1?r.push("GALA balance too low for trading (minimum 0.1 GALA)"):e<100&&r.push("GALA balance too low for token creation (minimum 100 GALA)")}else n.push("Failed to fetch GALA balance: No balance returned")}catch(e){n.push(`Balance check error: ${Dt(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: ${Dt(e)}`)}return{ready:0===n.length&&i.connectionHealthy,sdk:e,wallet:t??cC.generateWallet(),issues:n,warnings:r,capabilities:i}}static getRecommendedConfig(e,t="general"){const n={environment:e,autoValidate:!0};switch(e){case"production":Object.assign(n,{debug:!1,timeout:3e4});break;case"development":Object.assign(n,{debug:!0,timeout:45e3});break;case"testing":Object.assign(n,{debug:!0,timeout:6e4})}switch(t){case"trading":n.timeout=1.5*(n.timeout??3e4);break;case"creation":n.timeout=2*(n.timeout??3e4);break;case"monitoring":n.timeout=.5*(n.timeout??3e4);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,i]of Object.entries(e)){const{sdk:e}=await this.quickSetup({environment:t,privateKey:i,agentId:`multi-wallet-${r}`,autoValidate:!1});n[r]=e}return n}static detectEnvironment(){const e=process.env.NODE_ENV?.toLowerCase();return"development"===e?"development":"test"===e||"testing"===e?"testing":"production"}static setupWallet(e){if(void 0===e||""===e){const e=process.env.PRIVATE_KEY;return void 0!==e&&""!==e?cC.fromPrivateKey(e):cC.generateWallet()}return"generate"===e?cC.generateWallet():cC.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}}function CC(e,t,n){const r="number"==typeof e?new k(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 k(t).plus(new k(i).multipliedBy(r))}function NC(e,t,n){if(e>=t)throw new Error(`tickLower must be < tickUpper, got: ${e} >= ${t}`);if(n<=0)throw new Error(`tickSpacing must be > 0, got: ${n}`);return{tickLower:Math.floor(e/n)*n,tickUpper:Math.ceil(t/n)*n}}function _C(e,t,n=60){const r=fs(e),i=fs(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 o=Math.floor(bs(r)),s=Math.ceil(bs(i)),a=Math.floor(o/n)*n,c=Math.ceil(s/n)*n;return{minTick:a,maxTick:c,actualMinPrice:new k(1.0001).pow(a),actualMaxPrice:new k(1.0001).pow(c)}}function xC(e,t){if(0===e.length)return-1;if(t<0||t>100)throw new Error(`Percentile must be between 0 and 100, got: ${t}`);const n=(e.length-1)*(t/100),r=Math.floor(n);return Math.min(r,e.length-1)}function DC(e,t){if(t<0)throw new Error(`decimals must be >= 0, got: ${t}`);const n=fs(e),r=new k(10).pow(t);return n.multipliedBy(r).integerValue(k.ROUND_UP).dividedBy(r)}function PC(e,t,n,r="0"){const i=fs(t);if(Es(i))return fs(r);const o=fs(e).dividedBy(i);if(null!=n){const e=fs(n);if(e.isLessThan(0))throw new Error(`minimum must be >= 0, got: ${e.toString()}`);if(o.isLessThan(e))return e}return o}function BC(e,t){if(t<=0)throw new Error(`tickSpacing must be > 0, got: ${t}`);return Math.floor(e/t)*t}function RC(e,t){if(t<0)throw new Error(`feeFactor must be >= 0, got: ${t}`);return fs(e).multipliedBy(t).integerValue(k.ROUND_DOWN)}function MC(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 OC(e){if(null==e||"object"!=typeof e)throw new Error("Token must be an object");const t=e,n=(Er(t.name)?t.name:void 0)??(Er(t.tokenName)?t.tokenName:void 0)??"";if(!Er(n))throw new Error("Token name is required and must be a non-empty string");const r=(Er(t.symbol)?t.symbol:void 0)??(Er(t.tokenSymbol)?t.tokenSymbol:void 0)??(Er(t.collection)?t.collection:void 0)??"";if(!Er(r))throw new Error("Token symbol is required and must be a non-empty string");let i=8;"number"==typeof t.decimals&&t.decimals>=0&&(i=Math.floor(t.decimals));const o={name:n,symbol:r,decimals:i};return Er(t.address)&&(o.address=t.address),"boolean"==typeof t.verified&&(o.verified=t.verified),o}function LC(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(Er(n))return n;if(null!=n&&""!==n)return n}return n}function UC(e,t){return e.map(e=>{const n={};for(const[r,i]of Object.entries(t)){const t=i(e);void 0!==t&&(n[r]=t)}return n})}function FC(e,t,n=!0){const r=new Map;if(e.forEach((e,n)=>{const i=t(e);r.set(i,n)}),n){const n=new Set;return e.filter(e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)})}return e.filter((e,n)=>{const i=t(e);return r.get(i)===n})}function $C(e,t){const n={...e};for(const[e,r]of Object.entries(t))void 0!==r&&(n[e]=r);return n}class qC{constructor(){this.rooms=new Set}addRoom(e){this.rooms.add(e)}removeRoom(e){this.rooms.delete(e)}getRooms(){return Array.from(this.rooms)}isSubscribedTo(e){return this.rooms.has(e)}clear(){this.rooms.clear()}get size(){return this.rooms.size}}class KC{constructor(e,t,n=50){this.seen=new Set,this.extractor=e,this.dedupeKeyFn=t,this.maxDepth=n}walk(e){const t=[],n=new WeakSet,r=(e,i=0)=>{if(i>this.maxDepth)return;if(null==e||"object"!=typeof e)return;if(n.has(e))return;n.add(e);const o=this.extractor(e);if(null!==o){const e=this.dedupeKeyFn(o);this.seen.has(e)||(this.seen.add(e),t.push(o))}for(const t of Object.values(e))r(t,i+1)};return r(e,0),t}reset(){this.seen.clear()}getSeenCount(){return this.seen.size}}class GC{constructor(){this.pending=new Map}addPending(e,t){this.removePending(e);const n=setTimeout(()=>{this.pending.delete(e)},t);this.pending.set(e,{timeoutId:n,addedAt:Date.now()})}removePending(e){const t=this.pending.get(e);t&&(clearTimeout(t.timeoutId),this.pending.delete(e))}isPending(e){return this.pending.has(e)}getPendingCount(){return this.pending.size}clearExpired(){for(const[e,t]of this.pending.entries())null==t&&this.pending.delete(e)}clear(){for(const e of this.pending.values())clearTimeout(e.timeoutId);this.pending.clear()}}class HC{constructor(e){this.globalCallbacks=[],this.roomCallbacks=new Map,this.logger=e}registerGlobalCallback(e){this.globalCallbacks.push(e)}registerRoomCallback(e,t){const n=this.roomCallbacks.get(e)??[];n.push(t),this.roomCallbacks.set(e,n)}dispatch(e,t){for(const e of this.globalCallbacks)try{e(t)}catch(e){this.logger?.error(`Error in global callback: ${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)}}class WC{constructor(){this.filters=[]}addFilter(e){return this.filters.push(e),this}forward(e){for(const t of this.filters)if(!t(e))return!1;return!0}clearFilters(){this.filters=[]}get filterCount(){return this.filters.length}}class zC{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}}class jC{constructor(e={},t){this.events=[],this.timeouts=new Map,this.maxSize=e.maxSize??100,this.defaultTtlMs=e.defaultTtlMs??3e4,this.logger=t}push(e){if(this.events.length>=this.maxSize){const e=0;this.events.shift();const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.logger?.warn(`Buffer full (${this.maxSize}), dropped oldest event`)}this.events.push(e);const t=this.events.length-1,n=setTimeout(()=>{this.events[t]===e&&this.events.splice(t,1),this.timeouts.delete(t)},this.defaultTtlMs);this.timeouts.set(t,n)}getAll(){return[...this.events]}clear(){for(const e of this.timeouts.values())clearTimeout(e);this.events=[],this.timeouts.clear()}get size(){return this.events.length}}class VC{constructor(e={},t){this.pendingIndicators=new Map,this.activeIndicators=new Set,this.delayMs=e.delayMs??3e3,this.onTyping=e.onTyping,this.onStopTyping=e.onStopTyping}indicate(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&clearTimeout(r),this.activeIndicators.has(n)||(this.activeIndicators.add(n),this.onTyping?.(e,t));const i=setTimeout(()=>{this.activeIndicators.delete(n),this.pendingIndicators.delete(n),this.onStopTyping?.(e,t)},this.delayMs);this.pendingIndicators.set(n,i)}stopTyping(e,t){const n=`${e}:${t}`,r=this.pendingIndicators.get(n);r&&(clearTimeout(r),this.pendingIndicators.delete(n)),this.activeIndicators.has(n)&&(this.activeIndicators.delete(n),this.onStopTyping?.(e,t))}clear(){for(const e of this.pendingIndicators.values())clearTimeout(e);this.pendingIndicators.clear(),this.activeIndicators.clear()}get activeCount(){return this.activeIndicators.size}}function XC(e){return e.filter(e=>Ts(e.liquidity))}function QC(e,t){const n=fs(t);return e.filter(e=>fs(e.liquidity).isGreaterThanOrEqualTo(n))}function YC(e,t="desc"){return[...e].sort((e,n)=>{const r=fs(e.liquidity),i=fs(n.liquidity);return"desc"===t?i.minus(r).toNumber():r.minus(i).toNumber()})}function JC(e,t,n){const r=t.toUpperCase(),i=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return t===r&&n===i||t===i&&n===r})}function ZC(e,t){return e.filter(e=>Us(e.token0,t)||Us(e.token1,t))}function eN(e,t){return e.filter(e=>e.feeTier===t)}function tN(e){return MC(e,e=>`${e.token0.toUpperCase()}/${e.token1.toUpperCase()}`)}function nN(e){return MC(e,e=>e.feeTier)}function rN(e,t,n,r){const i=t.toUpperCase(),o=n.toUpperCase();return e.filter(e=>{const t=e.token0.toUpperCase(),n=e.token1.toUpperCase();return(t===i&&n===o||t===o&&n===i)&&e.feeTier===r})}function iN(e){return MC(e,e=>`${e.token0.toUpperCase()}|${e.token1.toUpperCase()}|${e.feeTier}`)}const oN=5,sN=8,aN=18,cN={collection:"GALA",category:"Unit",type:"none",additionalKey:"none"},lN={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"};function uN(e){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize),t}function dN(e,t){return uN({...e,...t})}function hN(e,t){return void 0===t?e:{...e,cursor:t}}async function gN(e,t,n,r){const i=r?.logger,o=new Array(e.length);let s=0,a=0;i?.debug(`Starting concurrent batch requests: ${e.length} URLs, batch size: ${t}`);for(let r=0;r<e.length;r+=t){const c=e.slice(r,r+t),l=r;try{const t=c.map((t,r)=>{const c=l+r;return(async()=>{try{const r=await n(t);return o[c]=r,s++,i?.debug(`Fetched [${c+1}/${e.length}]: ${t}`),r}catch(n){throw a++,i?.warn(`Failed [${c+1}/${e.length}]: ${t} - ${Dt(n)}`),n}})()}),r=await Promise.allSettled(t);for(let e=0;e<r.length;e++){"rejected"===r[e].status&&i?.debug(`Promise rejected in batch at index ${l+e}`)}}catch(e){i?.error(`Batch processing error at index ${r}: ${Dt(e)}`)}}return i?.debug(`Batch complete: ${s} succeeded, ${a} failed`),o}function fN(e){const t={page:1,pageSize:20,totalCount:-1,hasMore:!1};if(null==e||"object"!=typeof e)return t;const n=e,r=sr(String(n.page??n.Page??n.current??1),t.page),i=sr(String(n.pageSize??n.limit??n.size??t.pageSize),t.pageSize),o=n.data,s=o?.meta;let a;a="number"==typeof n.totalCount?n.totalCount:"number"==typeof n.total?n.total:"number"==typeof s?.totalItems?s.totalItems:"number"==typeof o?.count?o.count:sr(String(n.totalCount??n.total??-1),t.totalCount);let c=t.hasMore;return"boolean"==typeof n.hasMore?c=n.hasMore:"boolean"==typeof n.has_more?c=n.has_more:"boolean"==typeof s?.hasMore&&(c=s.hasMore),{page:r,pageSize:i,totalCount:a,hasMore:c}}function pN(e){if(null==e||"object"!=typeof e)return"";const t=[];for(const[n,r]of Object.entries(e)){if(Tr(r))continue;let e;e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):Array.isArray(r)?r.map(e=>String(e)).join(","):"object"==typeof r?JSON.stringify(r):String(r);const i=encodeURIComponent(n),o=encodeURIComponent(e);t.push(`${i}=${o}`)}return t.length>0?`?${t.join("&")}`:""}async function mN(e,t){const n=t?.maxRetries??3,r=t?.backoffMs??100,i=t?.retryableStatus??[429,503,504];let o,s=0;for(;s<=n;)try{return await e()}catch(e){o=e,s++;const t=bN(e),a=i.includes(t);if(s>n||!a)throw e;const c=r*Math.pow(2,s-1);await new Promise(e=>setTimeout(e,c))}throw o}function yN(e){const t={statusCode:0,errorMessage:"Unknown error",raw:e};if(null==e)return t;const n=e;let r=t.statusCode;"number"==typeof n.status?r=n.status:"number"==typeof n.statusCode?r=n.statusCode:"number"==typeof n.code&&(r=n.code);let i,o=t.errorMessage;"string"==typeof n.message?o=n.message:"string"==typeof n.error?o=n.error:e instanceof Error?o=e.message:"string"==typeof e&&(o=e);const s=n.response;if(s){const e=s.data;if("object"==typeof e&&null!==e){i=e;const t=e;"string"==typeof t.message?o=t.message:"string"==typeof t.error&&(o=t.error)}}const a={statusCode:r,errorMessage:o,raw:e};return null!=i&&(a.errorData=i),a}async function wN(e,t,n){const r=n?.logger,i=n?.fetcher??(async e=>{const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()});r?.debug(`Aggregating from ${e.length} endpoints`);const o=e.map(async(t,n)=>{try{const o=await i(t);return r?.debug(`Endpoint [${n+1}/${e.length}] succeeded: ${t}`),o}catch(i){return void r?.warn(`Endpoint [${n+1}/${e.length}] failed: ${t} - ${Dt(i)}`)}}),s=(await Promise.allSettled(o)).map(e=>{if("fulfilled"===e.status)return e.value});return r?.debug(`Aggregating ${s.filter(e=>void 0!==e).length} successful results`),t(s)}function bN(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 kN(e){const t=e.trim().toLowerCase();if(0===t.length)throw new Error("Token name cannot be empty");return t}function vN(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 SN(e,t){return`${e.replace(/\/$/,"")}${t}`}function AN(e,t){const n=kN(e);return SN(t,`/v1/tokens/${encodeURIComponent(n)}/assets/image`)}function EN(e,t,n="jpg"){const r=kN(e);vN(n);return SN(t,`/v1/tokens/${encodeURIComponent(r)}/assets/thumbnail.${n.toLowerCase()}`)}function TN(e,t,n="gif"){const r=kN(e);vN(n);return SN(t,`/v1/tokens/${encodeURIComponent(r)}/assets/animated.${n.toLowerCase()}`)}function IN(e,t){const n=kN(e);return SN(t,`/v1/tokens/${encodeURIComponent(n)}/assets/poster.jpg`)}function CN(e,t,n="vtt"){const r=kN(e);vN(n);return SN(t,`/v1/tokens/${encodeURIComponent(r)}/assets/storyboard.${n.toLowerCase()}`)}function NN(e,t){const n=kN(e);return SN(t,`/v1/tokens/${encodeURIComponent(n)}/assets/live.m3u8`)}function _N(e,t,n,r){const i=kN(e),o=t.trim().toLowerCase();if(0===o.length)throw new Error("Asset type cannot be empty");vN(r);const s=void 0!==r&&r.length>0?`.${r.toLowerCase()}`:"";return SN(n,`/v1/tokens/${encodeURIComponent(i)}/assets/${encodeURIComponent(o)}${s}`)}function xN(e,t,n,r="jpg"){const i=kN(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");vN(r);return SN(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/thumbnail.${r.toLowerCase()}`)}function DN(e,t,n,r="gif"){const i=kN(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");vN(r);return SN(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/animated.${r.toLowerCase()}`)}function PN(e,t,n){const r=kN(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return SN(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(i)}/assets/poster.jpg`)}function BN(e,t,n,r="vtt"){const i=kN(e),o=t.trim();if(0===o.length)throw new Error("Recording ID cannot be empty");vN(r);return SN(n,`/v1/tokens/${encodeURIComponent(i)}/recordings/${encodeURIComponent(o)}/assets/storyboard.${r.toLowerCase()}`)}function RN(e,t,n){const r=kN(e),i=t.trim();if(0===i.length)throw new Error("Recording ID cannot be empty");return SN(n,`/v1/tokens/${encodeURIComponent(r)}/recordings/${encodeURIComponent(i)}/assets/stream.m3u8`)}function MN(e,t,n,r,i){const o=kN(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");vN(i);const c=void 0!==i&&i.length>0?`.${i.toLowerCase()}`:"";return SN(r,`/v1/tokens/${encodeURIComponent(o)}/recordings/${encodeURIComponent(s)}/assets/${encodeURIComponent(a)}${c}`)}class ON extends Gr{constructor(e,t=!1){super(e,t)}async getChart(e){if(null==e)throw en("options","Chart options");const{tokenName:t,from:n,to:r,resolution:i}=e;if(null==t||""===t)throw en("tokenName","Token name");if(null==n)throw en("from","Start timestamp");if(null==r)throw en("to","End timestamp");if(null==i)throw en("resolution","Data resolution interval");Vs(t);const o=173e6;if("number"!=typeof n||n<o)throw new qt("from must be a valid timestamp (min: 173000000)","from","INVALID_TIMESTAMP");if("number"!=typeof r||r<o)throw new qt("to must be a valid timestamp (min: 173000000)","to","INVALID_TIMESTAMP");if("number"!=typeof i||i<1)throw new qt("resolution must be a number >= 1","resolution","INVALID_RESOLUTION");const{adaptQueryParams:s}=await Promise.resolve().then(function(){return gs}),a=s({tokenName:t,from:n,to:r,resolution:i}),c=await An(()=>this.http.get(G.CHART,a),{errorContext:"Failed to fetch chart data"}),l=bn(c);if(null==l||"object"!=typeof l)throw nn("Invalid API response: missing or invalid data",c.status??500);const u=l,d=u.data;if(!Array.isArray(d))throw nn("Invalid API response: expected data array",c.status??500);const h={dataPoints:d.map(e=>{if("object"!=typeof e||null===e)throw nn("Invalid API response: invalid data point structure",c.status??500);const t=e,n=t.startTime??t.timestamp,r=t.openPrice??t.value,i=t.closePrice??t.value,o=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(i),lowPrice:String(o),highPrice:String(s),volume:String(a)}})};return"boolean"==typeof u.isPreviousData&&(h.isPreviousData=u.isPreviousData),h}}const LN={NEW_HOLDER:"NEW_HOLDER",EXITED_HOLDER:"EXITED_HOLDER",BALANCE_CHANGED:"BALANCE_CHANGED"},UN=ls({type:"string",userAddress:"string",balance:"string",rank:"number",previousRank:"optional-number"}),FN=ls({tokenName:"string",userAddress:"string",quantity:"optional-string",percentage:"optional-number",holderTier:"optional-object",isCreator:"boolean",rank:"optional-number"});function $N(e){return"string"==typeof e&&(e===LN.NEW_HOLDER||e===LN.EXITED_HOLDER||e===LN.BALANCE_CHANGED)}class qN{static fastValidation(e,t,n,r=qN.DEFAULT_CONFIG){const i=Date.now();let o=!0;try{const s=fs(e.sqrtPrice),a=fs(t.sqrtPrice);n.zeroForOne?a.gte(s)&&(this.logger.error("Fast validation failed: price did not decrease for zeroForOne swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1):a.lte(s)&&(this.logger.error("Fast validation failed: price did not increase for oneForZero swap",{originalSqrtPrice:s.toString(),updatedSqrtPrice:a.toString(),zeroForOne:n.zeroForOne}),o=!1);const c=fs(e.liquidity),l=fs(t.liquidity);if(!Es(c)){const e=Ps(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:ps(e.times(100),2)})}const u=fs(e.feeGrowthGlobal0),d=fs(t.feeGrowthGlobal0),h=fs(e.feeGrowthGlobal1),g=fs(t.feeGrowthGlobal1);n.zeroForOne?g.lt(h)&&(this.logger.error("Fast validation failed: feeGrowthGlobal1 decreased for zeroForOne",{originalFeeGrowth1:h.toString(),updatedFeeGrowth1:g.toString()}),o=!1):d.lt(u)&&(this.logger.error("Fast validation failed: feeGrowthGlobal0 decreased for oneForZero",{originalFeeGrowth0:u.toString(),updatedFeeGrowth0:d.toString()}),o=!1);const f=fs(e.protocolFeesToken0),p=fs(t.protocolFeesToken0),m=fs(e.protocolFeesToken1),y=fs(t.protocolFeesToken1);p.lt(f)&&(this.logger.error("Fast validation failed: protocolFeesToken0 decreased",{originalProtocolFees0:f.toString(),updatedProtocolFees0:p.toString()}),o=!1),y.lt(m)&&(this.logger.error("Fast validation failed: protocolFeesToken1 decreased",{originalProtocolFees1:m.toString(),updatedProtocolFees1:y.toString()}),o=!1);const w=On(i);return this.logger.debug("Fast validation completed",{passed:o,elapsedMs:w}),o}catch(e){return this.logger.error("Fast validation exception",e),!1}}static moderateValidation(e,t,n=qN.DEFAULT_CONFIG){const r=Date.now(),i=[];let o=0;try{if(void 0!==t.actualSqrtPrice){const r=fs(e.sqrtPrice),s=fs(t.actualSqrtPrice),a=this.calculateDriftPercentage(r,s);o=a,a>100*n.maxDriftThreshold&&i.push(`Price drift detected: ${ps(a,4)}% (threshold: ${ps(100*n.maxDriftThreshold,4)}%)`),this.logger.debug("Price drift comparison",{calculatedSqrtPrice:r.toString(),actualSqrtPrice:s.toString(),driftPct:a.toFixed(4)})}const s=fs(e.sqrtPrice),a=Ps(s,vs()),c=O(a),l=e.tick??0,u=Math.abs(c-l);u>n.maxTickDrift&&i.push(`Tick/price mismatch: tick=${l}, calculated=${c}, drift=${u}`);const d=fs(e.feeGrowthGlobal0),h=fs(e.feeGrowthGlobal1),g=fs(e.liquidity);try{xs(d,h,g)}catch(e){i.push(e.message)}const f=0===i.length,p=!f||o>100*n.maxDriftThreshold,m=On(r);return this.logger.debug("Moderate validation completed",{isValid:f,shouldRefetch:p,driftPercentage:o,errorCount:i.length,elapsedMs:m}),this.buildValidationResult(f,o,p,i)}catch(e){return this.logger.error("Moderate validation exception",e),this.buildValidationResult(!1,0,!0,[`Exception during validation: ${Dt(e)}`])}}static async fullValidation(e,t,n){const r=Date.now(),i=[];let o=0;try{this.logger.debug("Starting full validation with fresh pool data fetch",{poolKey:e});const s=await n(),a=fs(t.pool.sqrtPrice),c=fs(s.pool.sqrtPrice),l=this.calculateDriftPercentage(a,c);o=Math.max(o,l),l>100*this.DEFAULT_CONFIG.maxPriceDriftPct&&i.push(`Price drift: ${l.toFixed(4)}% (cached: ${a.toString()}, fresh: ${c.toString()})`);const u=fs(t.pool.liquidity),d=fs(s.pool.liquidity),h=this.calculateDriftPercentage(u,d);o=Math.max(o,h),h>100*this.DEFAULT_CONFIG.maxLiquidityDriftPct&&i.push(`Liquidity drift: ${h.toFixed(4)}% (cached: ${u.toString()}, fresh: ${d.toString()})`);const g=Object.keys(t.tickDataMap).length,f=Object.keys(s.tickDataMap).length;if(f>0){const e=Math.abs(f-g)/f;e>this.DEFAULT_CONFIG.maxTickCountDriftPct&&i.push(`Tick data incomplete: cached has ${g} ticks, fresh has ${f} ticks (${(100*e).toFixed(2)}% difference)`)}const p=0===i.length,m=!p,y=On(r);return this.logger.debug("Full validation completed",{poolKey:e,isValid:p,shouldRefetch:m,maxDriftPercentage:o,priceDrift:l,liquidityDrift:h,cachedTickCount:g,freshTickCount:f,errorCount:i.length,elapsedMs:y}),this.buildValidationResult(p,o,m,i)}catch(t){return this.logger.error("Full validation exception",{poolKey:e,error:t}),this.buildValidationResult(!1,0,!0,[`Exception during full validation: ${Dt(t)}`])}}static calculateDriftPercentage(e,t){if(Es(t))return this.logger.warn("Cannot calculate drift: actual value is zero"),1/0;return Ps(t.minus(e).abs(),t).times(100).toNumber()}static buildValidationResult(e,t,n,r=[]){let i;if(n&&r.length>0){const e=r.join(" ").toLowerCase();i=e.includes("drift")?"drift":e.includes("tick")&&e.includes("mismatch")?"tick-mismatch":e.includes("tick")?"missing-tick-data":"manual"}const o={isValid:e,driftPercentage:t,shouldRefetch:n,validationErrors:r};return void 0!==i&&(o.refetchReason=i),o}}qN.logger=new _n({debug:!1,context:"PoolStateValidator"}),qN.DEFAULT_CONFIG={maxDriftThreshold:.001,maxLiquidityChangePct:.5,maxTickDrift:1,maxTickCountDriftPct:.1,maxPriceDriftPct:.001,maxLiquidityDriftPct:.01};class KN extends Hr{static calculatePoolStateHash(e){return Sk(`${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??k.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=qN.DEFAULT_CONFIG,this.pool=e.pool,this.tickDataMap=e.tickDataMap,this.metadata={lastFullRefetch:Date.now(),swapsSinceRefetch:0,cumulativeDrift:0,processedTransactions:[],stateHash:KN.calculatePoolStateHash(this.pool)};if(!qN.fastValidation(this.pool,this.pool,{transactionId:"init",timestamp:Date.now(),amountSpecified:"0",zeroForOne:!1,exactInput:!0},this.validationConfig)&&this.config.strictValidation)throw new qt("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 en("swapEvent","Swap event");if(!e.transactionId)throw en("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 Ht(`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=VE.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(!qN.fastValidation(t.pool,r.updatedPool,e,this.validationConfig)&&this.config.strictValidation)throw new qt("Swap validation failed","swapResult","VALIDATION_FAILED");if(null!=e.actualAmount0&&null!=e.actualAmount1&&null!=e.actualSqrtPrice){const t=fs(e.actualAmount0),n=fs(e.actualAmount1),i=r.amount0.minus(t).abs(),o=r.amount1.minus(n).abs(),s=Ps(i,t.abs(),fs(0)).times(100).toNumber(),a=Ps(o,n.abs(),fs(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=KN.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=KN.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=Dt(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:fs(0),amount1:fs(0),feeAmount0:fs(0),feeAmount1:fs(0),ticksCrossed:[],metadata:{calculationTimeMs:On(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:KN.calculatePoolStateHash(this.pool)},this.logger.info("PoolStateManager reset",{sqrtPrice:this.pool.sqrtPrice.toString()})}}function GN(e,t){return new KN(e,t)}class HN extends Hr{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 Tn(e);const t=e;return Tn(`${t.type??t.symbol??"unknown"}|${t.additionalKey??"none"}`)}extractMetadata(e){let t,n,r="Token",i="Unit",o="none";if("string"==typeof e)if(Yk(e)){const s=Qk(e);"Token"===s.collection&&""!==s.type?(r=s.collection,i=""!==s.category?s.category:"Unit",t=s.type,o=""!==s.additionalKey?s.additionalKey:"none",n=t):(t=s.collection,n=t,i=""!==s.category?s.category:"Unit",o=""!==s.additionalKey?s.additionalKey:"none")}else t=e,n=e;else{const s=e;t=s.type??"unknown",r=s.collection??"Token",i=s.category??"Unit",o=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:i,type:t.toUpperCase(),additionalKey:o,verified:!1}}getDecimalsForToken(e){return{GALA:8,GUSDC:6,USDC:6,USDT:6,WETH:18,DAI:18}[e.toUpperCase()]??18}isCacheExpired(e){return On(e)>this.cacheExpiry}setCacheExpiry(e){this.cacheExpiry=e,this.logger.debug(`Set token metadata cache expiry to ${e}ms`)}}class WN extends Hr{constructor(e){super(e.debugMode??!1),e.dexBackendHttp?this.dexBackendHttp=e.dexBackendHttp:this.dexBackendHttp=QA(e.dexBackendBaseUrl,3e4)}parseTokenFlexible(e){try{return Xk(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=bn(await this.dexBackendHttp.get("/api/tokens/balances",{params:{wallet:e,limit:t,page:n}})),i=r?.data??{},o=Array.isArray(i?.tokens)?i.tokens:[],s="number"==typeof i?.count?i.count:o.length;return{assets:o.map(e=>this.transformRawTokenToUserAsset(e)),count:s,page:n,limit:t,hasMore:n*t<s}}catch(t){throw this.logger.error("Failed to fetch user assets",t),new Vt(`Failed to fetch user assets: ${Dt(t)}`,t,e)}}async getAllUserAssets(e){try{this.logger.debug("Fetching all user assets",{walletAddress:e});return(await wS(async(t,n)=>{const r=await this.getUserAssets(e,n,t);return{items:r.assets,page:t,limit:n,total:r.count,totalPages:Gv(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 Vt(`Failed to fetch all user assets: ${Dt(t)}`,t,e)}}async fetchAvailableDexTokens(e={}){try{const{search:t,limit:n=20,page:r=1}=e;this.logger.debug("Fetching available DEX tokens",{search:t,limit:n,page:r});const i={limit:n,page:r};null!=t&&t.length>0&&(i.search=t);const o=bn(await this.dexBackendHttp.get("/api/tokens",{params:i})),s=o?.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 Vt(`Failed to fetch available DEX tokens: ${Dt(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 Vt(`Failed to fetch all available DEX tokens: ${Dt(e)}`,e)}}}class zN extends Hr{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 RS,""!==e.bundlerBaseUrl&&(this.bundlerClient=YA.createClient(e.bundlerBaseUrl,3e4))}getBundlerClient(){if(""===this.bundlerBaseUrl)throw new Gt("Bundler URL not configured","bundlerBaseUrl");return this.bundlerClient??(this.bundlerClient=YA.createClient(this.bundlerBaseUrl,3e4)),this.bundlerClient}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildLiquidityStringsInstructions(e,t,n,r){const i=ma(e),o=ma(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}async monitorBundlerTransaction(e,t,n){return{...{transactionId:e,liquidity:"0",amount0:"0",amount1:"0",status:"pending"},wait:async(r=12e4)=>sa(async()=>{const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Transaction ${e} timed out after ${r}ms`)),r)});await Promise.race([t,i]),this.logger.debug(`${n} confirmed`,{transactionId:e})},`${n} failed or timed out`,this.logger,(t,r,i)=>{throw i?.error(`GSwapLiquidityMutationService: ${r}`,{error:Dt(t),operationType:n,transactionId:e}),t})}}async sendAddLiquidityToBundler(e){if(void 0===this.privateKey)throw new Gt("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===this.bundlerBaseUrl)throw new Gt("Bundler URL not configured","bundlerBaseUrl");return sa(async()=>{const t=`galaswap - operation - ${w()}-${Date.now()}-${e.owner}`,n={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:t},r=new c.Wallet(this.privateKey),i={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"}]},o={name:"ethereum",chainId:1},s=this.calculatePersonalSignPrefix(n),a={...n,prefix:s},l=await r.signTypedData(o,i,a),u={...a,signature:l,types:i,domain:o},d=this.buildLiquidityStringsInstructions(e.token0,e.token1,e.fee,e.owner),h=bn(await this.getBundlerClient().post("/bundle",{method:"AddLiquidity",signedDto:u,stringsInstructions:d})),g="string"==typeof h?.data?h.data:h?.data?.transactionId??h?.data?.id??h?.transactionId??h?.id;if(void 0===g)throw new Ht("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return g},"Failed to send AddLiquidity to bundler",this.logger)}async sendRemoveLiquidityToBundler(e,t,n,r,i,o,s,a,l){if(void 0===this.privateKey)throw new Gt("RemoveLiquidity requires wallet (full-access mode)","privateKey");return sa(async()=>{const u=new c.Wallet(this.privateKey),d=await u.getAddress(),h=`galaswap - operation - ${w()}-${Date.now()}-${d}`,g={tickLower:e,tickUpper:t,amount:n,token0:r,token1:i,fee:o,amount0Min:s,amount1Min:a,positionId:l,uniqueKey:h},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"}]},p={name:"ethereum",chainId:1},m=this.calculatePersonalSignPrefix(g),y={...g,prefix:m},b=await u.signTypedData(p,f,y),k={...y,signature:b,types:f,domain:p},v=this.buildLiquidityStringsInstructions(r,i,o,d),S=bn(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 Ht("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return A},"Failed to send RemoveLiquidity to bundler",this.logger)}async sendCollectPositionFeesToBundler(e,t,n,r,i,o,s,a){if(void 0===this.privateKey)throw new Gt("CollectPositionFees requires wallet (full-access mode)","privateKey");return sa(async()=>{const l=new c.Wallet(this.privateKey),u=await l.getAddress(),d=`galaswap - operation - ${w()}-${Date.now()}-${u}`,h={token0:e,token1:t,fee:n,amount0Requested:r,amount1Requested:i,tickLower:o,tickUpper:s,positionId:a,uniqueKey:d},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},f={name:"ethereum",chainId:1},p=this.calculatePersonalSignPrefix(h),m={...h,prefix:p},y=await l.signTypedData(f,g,m),b={...m,signature:y,types:g,domain:f},k=this.buildLiquidityStringsInstructions(e,t,n,u),v=bn(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 Ht("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 Gt("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===e.token0)throw en("token0","Token 0");if(""===e.token1)throw en("token1","Token 1");if(""===e.minPrice)throw en("minPrice","Minimum price");if(""===e.maxPrice)throw en("maxPrice","Maximum price");if(""===e.amount0Desired)throw en("amount0Desired","Desired amount 0");if(""===e.amount1Desired)throw en("amount1Desired","Desired amount 1");return sa(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=Xk(t),i=Xk(n),o=(await this.gatewayClient.getPoolData({token0:r,token1:i,fee:e.fee})).tickSpacing,s=fs(e.minPrice),a=fs(e.maxPrice),c=Math.floor(bs(s)),l=Math.ceil(bs(a)),u=Bs(c,o),d=Bs(l,o),h=this.getWalletAddress();if(void 0===h)throw new Gt("Wallet address not available","walletAddress");const g=await this.sendAddLiquidityToBundler({token0:r,token1:i,fee:e.fee,tickLower:u,tickUpper:d,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min??"0",amount1Min:e.amount1Min??"0",owner:h}),f=this.webSocketService.waitForTransaction(g);return this.monitorBundlerTransaction(g,f,"addLiquidityByPrice")},"Failed to add liquidity by price",this.logger,(e,t,n)=>{throw n?.error(t,{error:Dt(e)}),new Xt(`${t}: ${Dt(e)}`,e,"ADD_FAILED")})}async addSwapLiquidityByTicks(e){if(void 0===this.privateKey)throw new Gt("AddLiquidity requires wallet (full-access mode)","privateKey");if(""===e.token0)throw en("token0","Token 0");if(""===e.token1)throw en("token1","Token 1");if(""===e.amount0Desired)throw en("amount0Desired","Desired amount 0");if(""===e.amount1Desired)throw en("amount1Desired","Desired amount 1");return sa(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=Xk(t),i=Xk(n),o=this.getWalletAddress();if(void 0===o)throw new Gt("Wallet address not available","walletAddress");const s=await this.sendAddLiquidityToBundler({token0:r,token1:i,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min??"0",amount1Min:e.amount1Min??"0",owner:o}),a=this.webSocketService.waitForTransaction(s);return this.monitorBundlerTransaction(s,a,"addSwapLiquidityByTicks")},"Failed to add liquidity by ticks",this.logger,(e,t,n)=>{throw n?.error(t,{error:Dt(e)}),new Xt(`${t}: ${Dt(e)}`,e,"ADD_FAILED")})}async removeLiquidity(e){if(void 0===this.privateKey)throw new Gt("RemoveLiquidity requires wallet (full-access mode)","privateKey");if("string"==typeof e.token0&&""===e.token0||"string"!=typeof e.token0&&void 0===e.token0)throw en("token0","Token 0");if("string"==typeof e.token1&&""===e.token1||"string"!=typeof e.token1&&void 0===e.token1)throw en("token1","Token 1");if(""===e.liquidity)throw en("liquidity","Liquidity amount");return sa(async()=>{this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});const t=fs(e.liquidity);try{xs(t)}catch(t){const n=`Invalid liquidity value: "${e.liquidity}". Must be a valid number.`;throw this.logger.error(n,{error:Dt(t)}),new qt(n,"liquidity","INVALID_VALUE")}if(Es(t))throw new qt("Cannot remove zero liquidity from position.","liquidity","ZERO_VALUE");const n="string"==typeof e.token0?Xk(e.token0):e.token0,r="string"==typeof e.token1?Xk(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,n,r,e.fee,e.amount0Min??"0",e.amount1Min??"0",e.positionId??""),o=this.webSocketService.waitForTransaction(i);return this.monitorBundlerTransaction(i,o,"removeLiquidity")},"Failed to remove liquidity",this.logger,(e,t,n)=>{throw n?.error(t,{error:Dt(e)}),new Xt(`${t}: ${Dt(e)}`,e,"REMOVE_FAILED")})}async collectPositionFees(e){if(void 0===this.privateKey)throw new Gt("CollectPositionFees requires wallet (full-access mode)","privateKey");if(void 0===e.positionId)throw en("positionId","Position ID");return sa(async()=>{if(void 0!==e.ownerAddress&&void 0!==e.positionId&&("string"==typeof e.token0?""===e.token0:void 0===e.token0))throw new qt("collectPositionFees requires direct parameters: token0, token1, fee, tickLower, tickUpper. Use GSwapService.collectPositionFees() for automatic position lookup.","parameters",$t.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 qt("Missing required parameters: token0, token1, fee, tickLower, tickUpper are required","parameters",$t.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?Xk(e.token0):e.token0,i="string"==typeof e.token1?Xk(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendCollectPositionFeesToBundler(r,i,e.fee,e.amount0Requested??"0",e.amount1Requested??"0",e.tickLower,e.tickUpper,e.positionId??""),s=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,s,"collectPositionFees")},"Failed to collect position fees",this.logger,(e,t,n)=>{throw n?.error(t,{error:Dt(e)}),new Xt(`${t}: ${Dt(e)}`,e,"COLLECT_FAILED")})}}class jN extends Hr{constructor(e){super(e.debugMode??!1),this.gatewayClient=e.gatewayClient,this.calculationService=e.calculationService,this.tokenConverter=new RS}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}parseTokenFlexible(e){try{return Xk(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 i=r.positionId??r.id??n.positionId??n.id??"",o=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",f=r.feeAmount1?.toString()??r.feesB?.toString()??r.tokensOwed1?.toString()??"0";return{positionId:i,ownerAddress:t,token0:o,token1:s,feeTier:sr(a,3e3),tickLower:sr(c,0),tickUpper:sr(l,0),liquidity:u,amount0:d,amount1:h,feeAmount0:g,feeAmount1:f}}async getLiquidityPosition(e,t){try{this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.calculationService.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(t.token0,t.token1),i=sA(n),o=sA(r),s=(await this.gatewayClient.getPositions({owner:e,token0:i,token1:o,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new Xt("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:Dt(e)}),new Xt(`Failed to fetch liquidity position: ${Dt(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 Xt("Position not found: API returned no position data",null,"NOT_FOUND");const i=r.positions[0];return this.normalizePositionResponse(i,e.owner)}catch(e){throw this.logger.error("Failed to fetch swap position via compound key",{error:Dt(e)}),new Xt(`Failed to fetch swap position: ${Dt(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=sA(t),i=sA(n);return await this.gatewayClient.getRemoveLiquidityEstimation({token0:r,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner})}catch(e){throw this.logger.error("Failed to estimate liquidity removal",{error:Dt(e)}),new Xt(`Failed to estimate liquidity removal: ${Dt(e)}`,e,"ESTIMATE_FAILED")}}}class VN{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 qt(`Invalid fee tier: ${e}. Valid values are 500, 3000, or 10000.`,"feeTier",$t.INVALID_FEE_TIER)}}validateTickSpacing(e,t,n){const r=this.getTickSpacing(n);if(e%r!==0)throw new qt(`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 qt(`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 aa(()=>{const t=vs();return Ps(e,t).pow(2)},"calculatePriceFromSqrtPriceX96 failed",this.logger)}calculatePriceFromSqrtPriceDecimal(e){return aa(()=>e.pow(2),"calculatePriceFromSqrtPriceDecimal failed",this.logger)}calculateLiquidityFromAmount0(e,t,n){return aa(()=>{const r=_(t),i=_(n);return P(e,r,i)},"calculateLiquidityFromAmount0 failed",this.logger)}calculateLiquidityFromAmount1(e,t,n){return aa(()=>{const r=_(t),i=_(n);return B(e,r,i)},"calculateLiquidityFromAmount1 failed",this.logger)}calculateAmount0FromLiquidity(e,t,n){return aa(()=>{const r=_(t),i=_(n);return R(r,i,e)},"calculateAmount0FromLiquidity failed",this.logger)}calculateAmount1FromLiquidity(e,t,n){return aa(()=>{const r=_(t),i=_(n);return M(r,i,e)},"calculateAmount1FromLiquidity failed",this.logger)}calculateOptimalPositionSize(e,t,n,r,i){if(""===t)throw en("desiredAmount0","Desired amount 0");if(""===n)throw en("desiredAmount1","Desired amount 1");const o=_(r),s=_(e),a=_(i),c=x(fs(t),fs(n),o,s,a),l=D(c,s,o,a),u=l[0],d=l[1],h=fs(t),g=fs(n);Es(fs(d))&&this.logger?.warn("GSwapPoolCalculationService: Calculated amount1 is zero - position may be heavily skewed to amount0",{desiredAmount0:t,desiredAmount1:n,currentTick:r,tickUpper:i});const f=Ps(u,d,fs(0));return{amount0:ps(u),amount1:ps(d),liquidity:ps(c),ratio:ps(f),utilizationPercent:{amount0:ps(Ns(Ps(u,h),100),2),amount1:ps(Ns(Ps(d,g),100),2)}}}validatePositionParameters(e,t,n,r,i,o,s){if(""===r)throw en("amount0","Amount 0");if(""===i)throw en("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=aa(()=>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=fs(r),h=fs(i);if(d.isNaN()||h.isNaN())a.push("Amounts must be valid numbers");else try{aa(()=>xs(d,h),"validatePositionParameters amounts validation",this.logger)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}if(void 0!==o&&(o<t||o>n)&&c.push("Position is out of current price range - will not earn fees until price moves into range"),void 0!==s){fs(s).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance")}const g=0===a.length?35e4:0,f={valid:0===a.length,errors:a,warnings:c,gasEstimate:g};return void 0!==u&&(f.tickSpacing=u),void 0!==o&&(f.currentTick=o),void 0!==s&&(f.poolLiquidity=s),f}calculateTicksForPrice(e,t,n){if(""===e)throw en("minPrice","Minimum price");if(""===t)throw en("maxPrice","Maximum price");const r=this.getTickSpacing(n),i=fs(e),o=fs(t);mr(e,t,"priceRange");const s=ir(Math.floor(bs(i)),0),a=ir(Math.ceil(bs(o)),0),c=ir(Bs(s,r),0),l=ir(Bs(a,r),0),u=ir(Math.pow(1.0001,c),0===c?1:NaN),d=ir(Math.pow(1.0001,l),0===l?1:NaN),h=fs(u),g=fs(d);return{tickLower:c,tickUpper:l,tickSpacing:r,requestedMinPrice:e,requestedMaxPrice:t,actualMinPrice:h.toFixed(8),actualMaxPrice:g.toFixed(8),priceDeviation:{minPriceDeviation:Ns(Ps(h.minus(i),i),100).toFixed(4),maxPriceDeviation:Ns(Ps(g.minus(o),o),100).toFixed(4)}}}calculatePriceForTicks(e,t){const n=ir(Math.pow(1.0001,e),1),r=ir(Math.pow(1.0001,t),1),i=fs(n),o=fs(r);return{tickLower:e,tickUpper:t,minPrice:i.toFixed(8),maxPrice:o.toFixed(8),priceRange:`${i.toFixed(4)} - ${o.toFixed(4)}`,tickSpread:ir(t-e,0)}}calculateExecutionPrice(e,t){if(null==e||"string"==typeof e&&""===e)throw en("inputAmount","Input amount");if(null==t||"string"==typeof t&&""===t)throw en("outputAmount","Output amount");return aa(()=>{const n=fs(e);return ps(Ps(fs(t),n,fs("0")))},"calculateExecutionPrice failed",this.logger)}}class XN extends Hr{constructor(e){super(e.debugMode??!1),this.gatewayClient=e.gatewayClient,this.calculationService=e.calculationService,this.tokenConverter=new RS}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:r,gswapToken1:i}=this.convertTokenPair(e,t),o=Xk(r),s=Xk(i),a=await this.gatewayClient.getPoolData({token0:o,token1:s,fee:n}),c=this.calculationService.calculatePriceFromSqrtPriceX96(fs(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 jt(`Failed to get pool data: ${Dt(n)}`,n,e,t)}}async getPoolInfo(e,t){try{this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:r}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let o=fs(0),s=0;for(const a of i)try{const e=Xk(n),t=Xk(r),i=await this.gatewayClient.getPoolData({token0:e,token1:t,fee:a});null!=i&&(o=o.plus(fs(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:o.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new jt(`Failed to fetch pool info: ${Dt(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?Xk(e):e,i="string"==typeof t?Xk(t):t,o=await this.gatewayClient.getSlot0({token0:r,token1:i,fee:n}),s={sqrtPrice:""!==o.sqrtPrice?o.sqrtPrice:"0",tick:0!==o.tick?o.tick:0,liquidity:""!==o.liquidity?o.liquidity:"0",grossPoolLiquidity:o.grossPoolLiquidity??"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(e){throw this.logger.error("Failed to fetch pool slot0 data",e),new jt(`Failed to fetch pool slot0 data: ${Dt(e)}`,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const r=await this.getPoolData(e,t,n),i=fs(r.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:ks(i,!0),tick:r.tick,liquidity:r.liquidity}}catch(n){throw this.logger.error("Failed to calculate spot price",n),new jt(`Failed to calculate spot price: ${Dt(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=fs(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 jt(`Failed to fetch position current price: ${Dt(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}}class QN extends Hr{constructor(e){super(e.debugMode??!1),this.privateKey=e.privateKey,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.gatewayBaseUrl=e.gatewayBaseUrl,this.webSocketService=e.webSocketService,this.dexQuoteService=e.dexQuoteService,this.tokenConverter=new RS}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=fs(e),r=fs(t);return ps(Ps(r,n,fs("0")))}catch(n){return this.logger.warn("Failed to calculate execution price",{inputAmount:e,outputAmount:t,error:Dt(n)}),"0"}}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}buildSwapStringsInstructions(e,t,n,r){const i=ma(e),o=ma(t),s=`$pool${i}${o}$${n}`;return[s,`$userPosition${r}`,`$tokenBalance${i}${r}`,`$tokenBalance${o}${r}`,`$tokenBalance${i}${s}`,`$tokenBalance${o}${s}`]}async sendSwapToBundler(e){return sa(async()=>{if("string"!=typeof this.privateKey||0===this.privateKey.length)throw new Gt("Swap requires wallet (full-access mode)","privateKey");if("string"!=typeof this.bundlerBaseUrl||0===this.bundlerBaseUrl.length)throw new Gt("Bundler URL not configured","bundlerBaseUrl");const t=[500,3e3,1e4];if(!t.includes(e.feeTier))throw new qt(`Invalid fee tier ${e.feeTier}. Must be one of: ${t.join(", ")}`,"feeTier","INVALID_FEE_TIER");this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken?.type??"unknown",toToken:"string"==typeof e.toToken?e.toToken:e.toToken?.type??"unknown",inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let n=e.fromToken,r=e.toToken;"string"==typeof n&&(n=Xk(n)),"string"==typeof r&&(r=Xk(r));const i=fa(n),o=fa(r),s=i<o?[n,r,i,o]:[r,n,o,i],[a,l,u,d]=s,h=fa("string"==typeof e.fromToken?Xk(e.fromToken):e.fromToken),g=h===u,f=`galaswap - operation - ${w()}-${Date.now()}-${e.walletAddress}`;let p;if("string"!=typeof e.currentSqrtPrice||0===e.currentSqrtPrice.length)throw en("currentSqrtPrice","Current sqrt price");const m=fs(e.currentSqrtPrice),y=e.slippageTolerance??.01;if(g){const e=ys(y);p=ps(m.multipliedBy(e))}else{const e=ws(y);p=ps(m.multipliedBy(e))}const b={token0:a,token1:l,fee:e.feeTier,amount:ps(fs(e.inputAmount)),zeroForOne:g,sqrtPriceLimit:p,recipient:e.walletAddress,amountOutMinimum:ps(fs(e.minOutput).multipliedBy(-1)),uniqueKey:f};this.logger.info("SWAP DTO DETAILS",{orderedToken0String:u,orderedToken1String:d,fromTokenStr:h,zeroForOne:g?`TRUE (${u} -> ${d})`:`FALSE (${d} -> ${u})`,inputAmount:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(e.slippageTolerance??.01)+"%"});const k=new c.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(a,l,e.feeTier,e.walletAddress),N=YA.createClient(this.bundlerBaseUrl,3e4),_=bn(await N.post("/bundle",{method:"Swap",signedDto:I,stringsInstructions:C})),x=_?.data??_?.transactionId??_?.id;if("string"!=typeof x||0===x.length)throw new Ht("Bundler response does not contain transaction ID",void 0,"INVALID_RESPONSE");return x},"Failed to send Swap to bundler",this.logger)}async getSwapQuoteExactInput(e){return sa(async()=>{if(fs(e.amount).isLessThanOrEqualTo(0))throw new Wt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new Wt("DexQuoteService not configured. Quote operations require DexQuoteService.",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting exact input quote",e);const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await sa(async()=>{const o=await a.fetchCompositePoolData({token0:r,token1:i,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),l=fs(s.currentSqrtPrice),u=fs(s.newSqrtPrice),d=l.gt(u)?Ps(l.minus(u),l,"0"):fs(0),h=fs(s.amount0),g=fs(s.amount1);if(!Is(h)&&!Is(g))throw new Wt("Unexpected quote result: neither amount is negative (no output from pool)",{amount0:s.amount0,amount1:s.amount1,fromToken:e.fromToken,toToken:e.toToken});const f=(Is(h)?h:g).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:f,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,f),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:Dt(e)})}throw s??new Wt("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact input quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new Wt(`${n}: ${Dt(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async getSwapQuoteExactOutput(e){return sa(async()=>{if(fs(e.amount).isLessThanOrEqualTo(0))throw new Wt("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new Wt("DexQuoteService not configured. Quote operations require DexQuoteService.",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting exact output quote",e);const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[r,i]=t<n?[t,n]:[n,t],o=[3e3,500,1e4];let s;const a=this.dexQuoteService;for(const c of o)try{return await sa(async()=>{const o=await a.fetchCompositePoolData({token0:r,token1:i,fee:c,gatewayBaseUrl:this.gatewayBaseUrl}),s=await a.calculateDexPoolQuoteExactAmount({compositePoolData:o,fromToken:t,toToken:n,amount:e.amount}),l=fs(s.currentSqrtPrice),u=fs(s.newSqrtPrice),d=l.gt(u)?Ps(l.minus(u),l,"0"):fs(0),h=fs(s.amount0),g=fs(s.amount1),f=(Ts(h)?h:Ts(g)?g:h).absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:f,estimatedOutput:e.amount,feeTier:c,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(f,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:Dt(e)})}throw s??new Wt("No available fee tiers for quote",{feeTiers:o,fromToken:e.fromToken,toToken:e.toToken})},"Failed to get exact output quote",this.logger,(t,n,r)=>{throw r?.error(n,t),new Wt(`${n}: ${Dt(t)}`,{fromToken:e.fromToken,toToken:e.toToken})})}async executeSwap(e){return sa(async()=>{if("string"!=typeof this.privateKey||0===this.privateKey.length)throw new Gt("ExecuteSwap requires wallet (full-access mode)","privateKey");this.logger.debug("Executing swap",e);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),r=e.slippageTolerance??.01,i=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount}),o=ms(e.estimatedOutput,r).toFixed();await this.ensureWebSocketConnected();const s=this.getWalletAddress();if("string"!=typeof s||0===s.length)throw new Gt("Wallet address not available","walletAddress");const a=await this.sendSwapToBundler({fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o,feeTier:e.feeTier,walletAddress:s,currentSqrtPrice:i.currentSqrtPrice,slippageTolerance:r}),c=this.webSocketService.waitForTransaction(a);return{transactionId:a,status:"pending",fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:r,timestamp:new Date,wait:async(e=12e4)=>{await sa(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:Dt(e)}),e})}}},"Failed to execute swap",this.logger,(e,t,n)=>{throw n?.error(t,e),new zt(`${t}: ${Dt(e)}`,e)})}}function YN(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)}const JN={ONE_SECOND_MS:1e3,ONE_MINUTE_MS:6e4,ONE_HOUR_MS:36e5,ONE_DAY_MS:864e5,ONE_WEEK_MS:6048e5,ONE_MONTH_MS:2592e6};var ZN,e_,t_,n_,r_,i_;!function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"}(ZN||(ZN={})),function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO"}(e_||(e_={})),function(e){e.NO_ACTION="NO_ACTION",e.REVIEW_REQUIRED="REVIEW_REQUIRED",e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(t_||(t_={})),function(e){e.VIOLENCE="VIOLENCE",e.HATE_SPEECH="HATE_SPEECH",e.SEXUAL_CONTENT="SEXUAL_CONTENT",e.HARASSMENT="HARASSMENT",e.SPAM="SPAM",e.SCAM="SCAM",e.SELF_HARM="SELF_HARM",e.ILLEGAL_ACTIVITY="ILLEGAL_ACTIVITY",e.MISINFORMATION="MISINFORMATION",e.COPYRIGHT="COPYRIGHT",e.SAFE="SAFE"}(n_||(n_={})),function(e){e.QUICK="QUICK",e.DETAILED="DETAILED"}(r_||(r_={})),function(e){e.DISABLED="DISABLED",e.ADVISORY="ADVISORY"}(i_||(i_={}));const o_={[ZN.PENDING]:"Pending",[ZN.PROCESSING]:"Processing",[ZN.COMPLETED]:"Completed",[ZN.FAILED]:"Failed"},s_={[t_.NO_ACTION]:"No Action Needed",[t_.REVIEW_REQUIRED]:"Human Review Required",[t_.DELETE_CONTENT]:"Delete Content",[t_.BAN_USER]:"Ban User",[t_.DELETE_AND_BAN]:"Delete & Ban"},a_={[n_.VIOLENCE]:"Violence",[n_.HATE_SPEECH]:"Hate Speech",[n_.SEXUAL_CONTENT]:"Sexual Content",[n_.HARASSMENT]:"Harassment",[n_.SPAM]:"Spam",[n_.SCAM]:"Scam",[n_.SELF_HARM]:"Self Harm",[n_.ILLEGAL_ACTIVITY]:"Illegal Activity",[n_.MISINFORMATION]:"Misinformation",[n_.COPYRIGHT]:"Copyright",[n_.SAFE]:"Safe"},c_={[r_.QUICK]:"Quick Scan",[r_.DETAILED]:"Detailed Scan"},l_={[e_.TEXT]:"Text",[e_.IMAGE]:"Image",[e_.VIDEO]:"Video"},u_={[i_.DISABLED]:"Disabled",[i_.ADVISORY]:"Advisory"},d_=Nr(ZN),h_=Nr(e_),g_=Nr(t_),f_=Nr(n_),p_=Nr(r_),m_=Nr(i_),y_=Mr([{field:"id",type:"number"},{field:"flagId",type:"number"},{field:"status",type:"string",validator:d_},{field:"analysisType",type:"string",validator:h_},{field:"provider",type:"string"}]),w_=Mr([{field:"enabled",type:"boolean"},{field:"mode",type:"string",validator:m_},{field:"provider",type:"string"}]);function b_(e){return null!==e.analysisTier}function k_(e){return!0===e.escalatedFromQuick}function v_(e,t){if(!b_(e)||null===e.tokensUsed)return 0;const n=1500*t.maxFrames;if(0===n)return 0;const r=(n-e.tokensUsed)/n*100;return Math.max(0,Math.round(r))}function S_(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw fn(["tokenName","userAddress"]);if(void 0!==e.tokenName&&""!==e.tokenName){const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=Un;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw tn("tokenName",`${t}-${n} alphanumeric characters`,"Token name")}Cr(0,void 0,Kn.MAX_LIMIT,e.pageSize,e.cursor)}function A_(e){if(!Er(e.tokenName))throw en("tokenName","Token name");const{MIN_LENGTH:t,MAX_LENGTH:n,PATTERN:r}=Un;if(e.tokenName.length<t||e.tokenName.length>n||!r.test(e.tokenName))throw tn("tokenName",`${t}-${n} alphanumeric characters`,"Token name");if(!Er(e.content))throw en("content");if(0===e.content.trim().length)throw mn("content","Content");if(e.content.length>Wn.COMMENTS_V1.MAX_LENGTH)throw pn("content",Wn.COMMENTS_V1.MAX_LENGTH,e.content.length)}function E_(e){if(!Er(e.content))throw en("content");if(0===e.content.trim().length)throw mn("content","Content");if(e.content.length>Wn.COMMENTS_V1.MAX_LENGTH)throw pn("content",Wn.COMMENTS_V1.MAX_LENGTH,e.content.length)}function T_(e){if(!(void 0!==e.tokenName&&""!==e.tokenName||void 0!==e.userAddress&&""!==e.userAddress))throw new qt("At least one of tokenName or userAddress is required","options",$t.REQUIRED);if(void 0!==e.tokenName){if(!Er(e.tokenName))throw un("tokenName","string");if(e.tokenName.length>Fn.MAX_LENGTH)throw new qt(`tokenName must be at most ${Fn.MAX_LENGTH} characters`,"tokenName",$t.TOO_LONG)}if(void 0!==e.userAddress){if(!Er(e.userAddress))throw un("userAddress","string");if(e.userAddress.length>Hn.MAX_LENGTH)throw new qt(`userAddress must be at most ${Hn.MAX_LENGTH} characters`,"userAddress",$t.TOO_LONG)}void 0!==e.pageSize&&Cr(0,void 0,Kn.MAX_LIMIT,e.pageSize)}function I_(e){if(!Er(e.tokenName))throw en("tokenName");if(e.tokenName.length>Fn.MAX_LENGTH)throw new qt(`tokenName must be at most ${Fn.MAX_LENGTH} characters`,"tokenName",$t.TOO_LONG);if(!Er(e.content))throw en("content");if(0===e.content.trim().length)throw new qt("content cannot be empty","content",$t.REQUIRED);if(e.content.length>Wn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new qt(`content must be at most ${Wn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",$t.TOO_LONG)}function C_(e){if(!Er(e.content))throw en("content");if(0===e.content.trim().length)throw new qt("content cannot be empty","content",$t.REQUIRED);if(e.content.length>Wn.CHAT_MESSAGES_V1.MAX_LENGTH)throw new qt(`content must be at most ${Wn.CHAT_MESSAGES_V1.MAX_LENGTH} characters`,"content",$t.TOO_LONG)}function N_(e){if(!Er(e))throw en("id","Message ID");if(!zn.CHAT_MESSAGE.PATTERN.test(e))throw new qt("Invalid message ID format. Expected: chat-{timestamp}-{uuid}","id",$t.INVALID_FORMAT)}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}function x_(){const e=K.join(process.cwd(),"..","..",".env");q.existsSync(e)&&$.config({path:e});const t=K.join(process.cwd(),".env");q.existsSync(t)&&$.config({path:t})}function D_(e,t){const n=process.env[e];if(Pn(n)||!xn(n)){throw en(e,`${e} (${void 0!==t?`${t} (checked root .env and local .env)`:"checked root .env and local .env"})`)}return n}function P_(e,t){return process.env[e]??t}var B_=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=rr(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=rr(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(r)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=r}return void 0!==n.reverseBondingCurveMaxFeeFactor&&void 0!==n.reverseBondingCurveMinFeeFactor&&(n.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveMaxFeeFactor-n.reverseBondingCurveMinFeeFactor),Object.keys(n).length>0?n:null},isValidPoolForCaching:function(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"tokenName"in t&&"string"==typeof t.tokenName&&t.tokenName.length>0}});export{oI as ACCESS_SOURCE,lS as ACTIVE_USER_TYPE,i_ as AIModerationMode,t_ as AIRecommendation,u_ as AI_MODE_LABELS,s_ as AI_RECOMMENDATION_LABELS,eS as ALL_PERMISSIONS,a_ as ANALYSIS_CATEGORY_LABELS,o_ as ANALYSIS_STATUS_LABELS,c_ as ANALYSIS_TIER_LABELS,l_ as ANALYSIS_TYPE_LABELS,Jv as API_KEY_PERMISSION,Qv as API_KEY_ROLE,Yv as API_KEY_ROLES,oS as API_KEY_ROLE_HIERARCHY,Qr as AddressFormatter,IC as AgentConfig,n_ as AnalysisCategory,ZN as AnalysisStatus,r_ as AnalysisTier,e_ as AnalysisType,ia as AuthError,na as AuthErrorType,cS as BAN_DURATIONS,Ua as BRIDGE_CONTRACT_ABI,Oa as BRIDGE_TOKEN_METADATA,pv as BaseBridgeStrategy,Uk as BridgeRateLimiter,fv as BridgeStatusCode,$A as BurnError,FA as BurnErrorType,_t as CALCULATION_MODES,ya as CHAIN_IDS,aA as COMPOSITE_POOL_FETCH_CONCURRENCY,nA as CONTENT_REACTION_TYPES,zS as CONTENT_TYPE_LABELS,_k as CROSS_RATE_TYPED_DATA_TYPES,ON as ChartService,Gt as ConfigurationError,FS as ContentType,Ia as DEFAULT_ETHEREUM_BRIDGE_CONTRACT,Ea as DEFAULT_ETHEREUM_RPC_URL,Ra as DEFAULT_ETHEREUM_TOKENS,uA as DEFAULT_EVENTS_CONFIG,va as DEFAULT_POLL_INTERVAL_MS,Sa as DEFAULT_POLL_TIMEOUT_MS,Mv as DEFAULT_PRICING_CONCURRENCY,ka as DEFAULT_RATE_LIMIT_RPS,Na as DEFAULT_SOLANA_BRIDGE_PROGRAM,Ta as DEFAULT_SOLANA_RPC_URL,Ma as DEFAULT_SOLANA_TOKENS,Ov as DEFAULT_WEBSOCKET_RECONNECT_ATTEMPTS,Yt as DexPoolNotFoundError,Qt as DexQuoteError,La as ERC20_ABI,$t as ERROR_CODES,Ca as ETHEREUM_BRIDGE_CONTRACT_SEPOLIA,xa as ETHEREUM_TOKENS_PROD,Da as ETHEREUM_TOKENS_STAGE,dA as EVENT_TYPES,iI as EXTENDED_STREAM_ROLE,mv as EthereumBridgeStrategy,jC as EventBufferWithAutoCleanup,hA as EventsBatcherService,XI as ExternalWalletProvider,WS as FLAG_ACTION_LABELS,jS as FLAG_DETAILS_MAX_LENGTH,GS as FLAG_REASON_LABELS,HS as FLAG_STATUS_LABELS,Ms as FileValidationError,KS as FlagAction,$S as FlagReason,qS as FlagStatus,wa as GALACHAIN_CHANNELS,_a as GALACONNECT_PRODUCTION_URL,Ak as GALA_BRIDGE_TYPED_DATA_DOMAIN,sN as GALA_DECIMALS,cN as GALA_TOKEN_CLASS_KEY,Vt as GSwapAssetError,WN as GSwapAssetService,zN as GSwapLiquidityMutationService,jN as GSwapLiquidityQueryService,VN as GSwapPoolCalculationService,jt as GSwapPoolError,XN as GSwapPoolQueryService,Wt as GSwapQuoteError,zt as GSwapSwapError,QN as GSwapSwapService,mC as GalaChainConnectProvider,gv as GalaConnectClient,sv as GalaConnectHttpError,HC as GlobalAndRoomCallbackDispatcher,LN as HOLDER_DELTA_TYPES,Ri as IMAGE_EXTENSIONS,_E as INVITE_STATUS,xE as INVITE_STATUSES,ea as JWT_CONSTANTS,yC as KNOWN_WALLET_RDNS,aN as LAUNCHPAD_TOKEN_DECIMALS,Nk as LEGACY_TYPED_DATA_TYPES,aC as LaunchpadSDK,zC as ListenerCleanupManager,CA as LockError,TA as LockErrorType,UA as MAX_BURN_BATCH_SIZE,oN as MAX_CONCURRENT_POOL_FETCHES,AA as MAX_LOCK_BATCH_SIZE,EA as MAX_UNLOCK_BATCH_SIZE,cE as MESSAGES_CONSTRAINTS,aE as MESSAGE_TYPES,TE as MODERATOR_ROLE,IE as MODERATOR_ROLES,ZE as NFT_FEES,Kt as NetworkError,sT as NftCollectionService,aT as OEmbedService,lT as OVERSEER_INVITE_STATUS,uT as OVERSEER_STATUS,Uv as PAGINATION_DEFAULTS,Zv as PERMISSION,Fv as POOL_FETCH_CONFIG,Nt as POOL_TYPES,KC as PayloadWalkerWithDeduplication,GC as PendingSubscriptionTracker,TT as PlatformStatsService,KN as PoolStateManager,ua as PrivateKeyProvider,lN as QUERY_FIELD_NAMES,rA as REACTION_EMOJI_MAP,jT as RECORDING_STATUS,nI as ROLE_SOURCE,qC as RoomSubscriptionManager,CI as SDKTransactionStatus,Lv as SDK_VERSION,hI as SIMULATE_EVENT_TYPE,XT as SIMULCAST_PLATFORM,VT as SIMULCAST_STATUS,Aa as SOLANA_COMPUTE,Fa as SOLANA_DISCRIMINATORS,fI as STREAM_EVENTS,rI as STREAM_PERMISSION,tI as STREAM_ROLE,zT as STREAM_STATUS,WC as SelectiveEventForwarding,Dv as SolanaBridgeStrategy,pI as StreamWebSocketService,WT as StreamingEventService,JN as TIME_CONSTANTS,wE as TRADES_QUERY_CONSTRAINTS,Ct as TRADING_TYPES,HN as TokenMetadataService,EI as TradingQuotesService,Ht as TransactionError,KI as TransactionFailedError,VC as TypingIndicatorDebouncer,qt as ValidationError,$I as WebSocketError,qI as WebSocketTimeoutError,PI as WeeklyChallengeService,hN as addCursorToPagination,gi as addressFormatSchema,wN as aggregateMultipleApiSources,Qi as amountMethodSchema,Xi as amountTypeSchema,ri as assertValidWalletAddress,qs as bidirectionalTokenMatch,Oi as browserFileSchema,Li as bufferFileSchema,gN as buildConcurrentBatchRequests,pN as buildQueryParametersWithValidation,uN as buildSafePaginationOptions,uo as buyTokensDataSchema,CC as calculateLinearFeeInterpolation,wo as calculatePreMintDataSchema,RC as calculateScaledFeeAmount,Gv as calculateTotalPages,Jt as capitalize,Us as caseInsensitiveTokenComparison,Vi as checkPoolOptionsSchema,Or as commonValidators,iv as compareAmounts,$C as conditionalSpreadBuilder,Ls as conditionalTrimAndValidateString,gC as createLaunchpadSDK,Si as createLimitSchema,Lr as createOptionsValidator,so as createPaginatedResultSchema,$v as createPaginationQuery,GN as createPoolStateManager,JI as createProviderFromEip1193,YI as createProviderFromWallet,hC as createSolanaWallet,lo as createTradeDataSchema,lC as createWallet,QI as createWalletProvider,DC as decimalRoundingUp,FC as deduplicateByKey,vC as detectWallets,rC as ensureConnected,Fs as errorMessageCaseNormalization,fi as ethereumAddressSchema,LC as extractFieldWithFallbackPath,fN as extractPaginationMetadata,Ao as fetchGalaBalanceOptionsSchema,bo as fetchPoolDetailsDataSchema,Co as fetchTokenBalanceOptionsSchema,Ii as fileSizeSchema,Mi as fileUploadSchema,Ci as filenameSchema,eN as filterByFeeTier,XC as filterByLiquidity,QC as filterByMinLiquidity,rN as filterByPoolKey,ZC as filterByToken,JC as filterByTokenPair,pi as flexibleAddressSchema,Ui as flexibleFileSchema,dr as formatGalaForDTO,hr as formatLaunchpadTokenForDTO,rv as formatTokenAmount,Ga as formatTokenDescriptor,ei as fromBackendAddressFormat,nv as fromBaseUnits,hi as fullNameSchema,mA as generateUniqueKey,yo as getAmountOptionsSchema,P_ as getEnv,D_ as getEnvOrThrow,dC as getEthereumAddressFromPrivateKey,Ba as getEthereumBridgeContractByEnvironment,qa as getEthereumTokenConfig,Pa as getEthereumTokensByEnvironment,xk as getGalaBridgeTypedDataTypes,oC as getInjectedEip1193Provider,ns as getLaunchTokenDataValidationErrors,eT as getNftFeeAsNumber,uC as getPublicKeyFromPrivateKey,DN as getRecordingAnimatedUrl,MN as getRecordingAssetUrl,PN as getRecordingPosterUrl,BN as getRecordingStoryboardUrl,RN as getRecordingStreamUrl,xN as getRecordingThumbnailUrl,Ka as getSolanaTokenConfig,$a as getStaticTokenMetadata,v_ as getTieredModerationSavings,TN as getTokenAnimatedUrl,_N as getTokenAssetUrl,AN as getTokenImageUrl,NN as getTokenLiveStreamUrl,IN as getTokenPosterUrl,CN as getTokenStoryboardUrl,EN as getTokenThumbnailUrl,go as getTradeOptionsSchema,AC as getWalletByRdns,Ji as graduateTokenOptionsSchema,Yi as graphDataOptionsSchema,nN as groupByFeeTier,MC as groupByKey,iN as groupByPoolKey,tN as groupByTokenPair,TC as hasAnyWallet,Hv as hasMorePages,Ks as hexStringExtractionAndNormalization,Fi as imageExtensionSchema,$i as imageFilenameSchema,Ni as imageMimeTypeSchema,zi as imageUploadOptionsSchema,y_ as isAIModerationData,m_ as isAIModerationMode,w_ as isAIModerationSettings,g_ as isAIRecommendation,cI as isAccessSource,uS as isActiveUserType,f_ as isAnalysisCategory,d_ as isAnalysisStatus,p_ as isAnalysisTier,h_ as isAnalysisType,dS as isBanData,fS as isBanEnforcementEvent,OA as isBurnTokenEntry,LA as isBurnTokensData,NT as isChatDisabledReason,__ as isChatMessageItem,OT as isChatStatusResponse,gT as isClaimableInvite,VS as isContentType,iC as isEip1193Provider,Tr as isEmptyValue,aI as isExtendedStreamRole,eC as isExternalProvider,YS as isFlagAction,JS as isFlagData,XS as isFlagReason,QS as isFlagStatus,UN as isHolderDelta,$N as isHolderDeltaType,bA as isLockTokenEntry,vA as isLockTokensData,fE as isMessage,pE as isMessageType,ME as isModeratedToken,b_ as isModerationTiered,RE as isModeratorInvite,Er as isNonEmptyString,dT as isOverseerInviteStatus,hT as isOverseerStatus,BT as isPinnedMessage,ZI as isPrivateKeyProvider,OE as isPublicInviteInfo,qT as isReactionErrorCode,YT as isRecordingStatus,JT as isSimulcastPlatform,PT as isStreamChatDeletedEvent,DT as isStreamChatErrorEvent,_T as isStreamChatMessage,xT as isStreamChatMessageEvent,RT as isStreamChatPinnedEvent,MT as isStreamChatUnpinnedEvent,$T as isStreamReactionErrorEvent,FT as isStreamReactionEvent,QT as isStreamStatus,ZT as isStreamStatusEvent,YN as isStreamingEvent,sI as isTokenAccessPermissions,lI as isTokenAccessResult,mI as isTokenBanData,GT as isTypingIndicatorEvent,KT as isTypingUser,kA as isUnlockTokenEntry,SA as isUnlockTokensData,hS as isUserBannedEvent,FN as isUserHoldingData,gS as isUserUnbannedEvent,ni as isValidAddress,tS as isValidApiKeyRole,mS as isValidBanDuration,pS as isValidBanReason,LT as isValidChatContent,UT as isValidChatTokenName,ba as isValidGalaChainChannel,BE as isValidInviteCode,PE as isValidInviteStatus,ts as isValidLaunchTokenData,DE as isValidModeratorRole,yI as isValidTokenBanReason,Br as isValidTokenName,eI as isViewerCountEvent,EC as isWalletAvailable,_i as isoDateStringSchema,Wi as launchTokenDataSchema,x_ as loadEnvWithFallback,dN as mergeSafePaginationOptions,wi as nonNegativeDecimalStringSchema,ti as normalizeAddressInput,UC as normalizeDataWithMapping,$s as normalizeErrorMessage,Kv as normalizeLimit,In as normalizeTokenKey,Tn as normalizeTokenName,Cn as normalizeTokenSymbol,ki as optionalUrlSchema,vi as pageNumberSchema,oo as paginationResultMetaSchema,yN as parseHttpErrorResponse,xC as percentileIndexCalculation,ji as poolFetchTypeSchema,no as poolPaginationSchema,yi as positiveDecimalStringSchema,_C as priceTickRangeMapping,Di as privateKeySchema,nC as providerToWallet,xs as requireNonNegative,_s as requirePositive,Ds as requirePositiveWithContext,mN as retryableHttpRequest,Hi as reverseBondingCurveConfigSchema,ko as reverseBondingCurveConfigurationSchema,sS as roleHasSufficientPermission,NC as roundTickBoundaries,BC as roundTickToSpacing,PC as safeDivideWithMinimum,di as searchQuerySchema,ho as sellTokensDataSchema,YC as sortByLiquidity,Ai as standardLimitSchema,Zi as standardPaginationSchema,Vr as stripHexPrefix,SC as subscribeToWalletChanges,xi as timestampSchema,Zr as toBackendAddressFormat,ii as toBackendAddressFromEthers,tv as toBaseUnits,Ki as tokenCategorySchema,Gi as tokenCollectionSchema,li as tokenDescriptionSchema,Io as tokenHoldSchema,So as tokenListOptionsSchema,ai as tokenNameSchema,ci as tokenSymbolSchema,qi as tokenUrlsSchema,mo as tradeCalculationMethodSchema,po as tradeCalculationTypeSchema,Ti as tradeLimitSchema,fo as tradeListParamsSchema,to as tradePaginationSchema,io as tradePaginationWithFiltersSchema,co as tradeTypeBackendSchema,ao as tradeTypeSchema,Pi as transactionIdSchema,OC as transformRawApiTokenToDomainModel,Gs as trimmedLengthValidation,Bi as uniqueKeySchema,Eo as updateProfileDataSchema,To as uploadProfileImageOptionsSchema,bi as urlSchema,Ei as userLimitSchema,eo as userPaginationSchema,ui as userTokenNameSchema,vo as userTokenTypeSchema,ro as userTokensPaginationSchema,Po as validateAddress,Ro as validateAmountString,wI as validateBanTokenOptions,Vo as validateBuyTokensData,Zo as validateCalculatePreMintData,N_ as validateChatMessageId,qo as validateCheckPoolOptions,Sr as validateConstrainedEnumVariant,nS as validateCreateApiKeyOptions,I_ as validateCreateChatMessageOptions,A_ as validateCreateCommentOptions,uE as validateCreateMessageOptions,UE as validateCreateModeratorInviteOptions,vT as validateCreateOverseerDirectOptions,fT as validateCreateOverseerInviteOptions,jo as validateCreateTradeData,br as validateDecimalRangeStrict,kr as validateFeePortionConstraints,Go as validateFetchGalaBalanceOptions,lE as validateFetchMessagesOptions,es as validateFetchPoolDetailsData,zo as validateFetchTokenBalanceOptions,Mo as validateFullName,Jo as validateGetAmountOptions,T_ as validateGetChatMessagesOptions,S_ as validateGetCommentsOptions,vI as validateGetTokenBanOptions,Qo as validateGetTradeOptions,bE as validateGetTradesOptions,$o as validateImageUploadOptions,FE as validateInviteCode,rs as validateLaunchTokenData,iS as validateListApiKeysOptions,$E as validateListModeratorInvitesOptions,pT as validateListOverseerInvitesOptions,mT as validateListOverseersOptions,kI as validateListTokenBansOptions,kT as validateListUsersOptions,hE as validateMessageId,vr as validateMinMaxRelationship,Pr as validateOptionalTokenName,yT as validateOverseerInviteCode,bT as validateOverseerInviteId,wT as validateOverseerWalletAddress,qv as validatePaginationParams,Oo as validateSearchQuery,Xo as validateSellTokensData,wr as validateSortOrderDirection,Do as validateTokenDescription,Ko as validateTokenListOptions,Rr as validateTokenName,xo as validateTokenSymbol,Fo as validateTokenUrls,Yo as validateTradeListParams,bI as validateUnbanTokenOptions,rS as validateUpdateApiKeyOptions,C_ as validateUpdateChatMessageOptions,E_ as validateUpdateCommentOptions,dE as validateUpdateMessageOptions,AT as validateUpdatePlatformConfigOptions,Ho as validateUpdateProfileData,gE as validateUpdateTokenConfigOptions,Wo as validateUploadProfileImageOptions,Lo as validateUserTokenName,Bo as validateVaultAddress,mi as vaultAddressSchema,tC as walletToProvider,k_ as wasModerationEscalated};