@gala-chain/launchpad-sdk 8.1.0 → 9.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +837 -0
- package/EXAMPLES.md +95 -681
- package/MIGRATING-TO-9.0.md +343 -0
- package/README.md +46 -17
- package/dist/LaunchpadSDK.d.ts +536 -616
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/LaunchpadAPI.d.ts +6 -176
- package/dist/api/LaunchpadAPI.d.ts.map +1 -1
- package/dist/auth/SessionAuthService.d.ts +32 -2
- package/dist/auth/SessionAuthService.d.ts.map +1 -1
- package/dist/auth/SignatureAuth.d.ts +2 -2
- package/dist/auth/SignatureAuth.d.ts.map +1 -1
- package/dist/auth/session.d.ts +59 -0
- package/dist/auth/session.d.ts.map +1 -0
- package/dist/auth/types.d.ts +7 -2
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/config/environments.d.ts +7 -2
- package/dist/config/environments.d.ts.map +1 -1
- package/dist/constants/decimals.d.ts +0 -23
- package/dist/constants/decimals.d.ts.map +1 -1
- package/dist/constants/endpoints.d.ts +19 -8
- package/dist/constants/endpoints.d.ts.map +1 -1
- package/dist/constants/enums.d.ts +19 -0
- package/dist/constants/enums.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +1 -1
- package/dist/constants/version.generated.d.ts.map +1 -1
- package/dist/errors/LaunchpadSDKError.d.ts +18 -0
- package/dist/errors/LaunchpadSDKError.d.ts.map +1 -1
- package/dist/helpers/sdk.d.ts.map +1 -1
- package/dist/index.browser.d.ts +40 -45
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.browser.esm.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.node.d.ts +4 -5
- package/dist/index.node.d.ts.map +1 -1
- package/dist/launchpad/bundle-submission.d.ts +57 -10
- package/dist/launchpad/bundle-submission.d.ts.map +1 -1
- package/dist/launchpad/create-sale-validation.d.ts +19 -0
- package/dist/launchpad/create-sale-validation.d.ts.map +1 -0
- package/dist/launchpad/transport.d.ts +33 -2
- package/dist/launchpad/transport.d.ts.map +1 -1
- package/dist/launchpad/writes.d.ts +37 -11
- package/dist/launchpad/writes.d.ts.map +1 -1
- package/dist/native.cjs +1 -1
- package/dist/native.d.ts +4 -5
- package/dist/native.d.ts.map +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/schemas/launchpad.d.ts +3 -2
- package/dist/schemas/launchpad.d.ts.map +1 -1
- package/dist/schemas/primitives.d.ts +12 -2
- package/dist/schemas/primitives.d.ts.map +1 -1
- package/dist/schemas/user.d.ts +3 -18
- package/dist/schemas/user.d.ts.map +1 -1
- package/dist/schemas/validators.d.ts +3 -3
- package/dist/services/AbstractCacheService.d.ts +2 -2
- package/dist/services/ApiKeyService.d.ts +1 -1
- package/dist/services/BanService.d.ts +1 -1
- package/dist/services/ChartService.d.ts.map +1 -1
- package/dist/services/ContentReactionService.d.ts +6 -18
- package/dist/services/ContentReactionService.d.ts.map +1 -1
- package/dist/services/EventsQueryService.d.ts +47 -0
- package/dist/services/EventsQueryService.d.ts.map +1 -0
- package/dist/services/GalaChainBalanceService.d.ts +17 -89
- package/dist/services/GalaChainBalanceService.d.ts.map +1 -1
- package/dist/services/GalaChainLockService.d.ts +19 -20
- package/dist/services/GalaChainLockService.d.ts.map +1 -1
- package/dist/services/GalaChainService.d.ts +28 -15
- package/dist/services/GalaChainService.d.ts.map +1 -1
- package/dist/services/GalaChainTokenService.d.ts +25 -53
- package/dist/services/GalaChainTokenService.d.ts.map +1 -1
- package/dist/services/GalaChainTransferService.d.ts +42 -41
- package/dist/services/GalaChainTransferService.d.ts.map +1 -1
- package/dist/services/HealthService.d.ts +33 -0
- package/dist/services/HealthService.d.ts.map +1 -0
- package/dist/services/ImageService.d.ts +3 -3
- package/dist/services/ImageService.d.ts.map +1 -1
- package/dist/services/LaunchpadPriceService.d.ts +66 -0
- package/dist/services/LaunchpadPriceService.d.ts.map +1 -0
- package/dist/services/LaunchpadService.d.ts +34 -42
- package/dist/services/LaunchpadService.d.ts.map +1 -1
- package/dist/services/MessagesService.d.ts +12 -44
- package/dist/services/MessagesService.d.ts.map +1 -1
- package/dist/services/ModeratorService.d.ts +2 -2
- package/dist/services/ModeratorService.d.ts.map +1 -1
- package/dist/services/NftCollectionService.d.ts +22 -6
- package/dist/services/NftCollectionService.d.ts.map +1 -1
- package/dist/services/OverseerService.d.ts +3 -3
- package/dist/services/OverseerService.d.ts.map +1 -1
- package/dist/services/PlatformStatsService.d.ts +1 -2
- package/dist/services/PlatformStatsService.d.ts.map +1 -1
- package/dist/services/PoolService.d.ts +28 -65
- package/dist/services/PoolService.d.ts.map +1 -1
- package/dist/services/RestrictedNamesService.d.ts +1 -1
- package/dist/services/RestrictedNamesService.d.ts.map +1 -1
- package/dist/services/StreamChatService.d.ts +8 -19
- package/dist/services/StreamChatService.d.ts.map +1 -1
- package/dist/services/StreamTokenServiceBase.d.ts +2 -1
- package/dist/services/StreamTokenServiceBase.d.ts.map +1 -1
- package/dist/services/StreamWebSocketService.d.ts +423 -451
- package/dist/services/StreamWebSocketService.d.ts.map +1 -1
- package/dist/services/StreamingService.d.ts +14 -15
- package/dist/services/StreamingService.d.ts.map +1 -1
- package/dist/services/TokenBanService.d.ts +1 -1
- package/dist/services/TokenResolverService.d.ts +5 -5
- package/dist/services/TokenResolverService.d.ts.map +1 -1
- package/dist/services/TradeService.d.ts +13 -9
- package/dist/services/TradeService.d.ts.map +1 -1
- package/dist/services/TradingQuotesService.d.ts.map +1 -1
- package/dist/services/UserService.d.ts +64 -20
- package/dist/services/UserService.d.ts.map +1 -1
- package/dist/services/gateway-transport.d.ts +32 -0
- package/dist/services/gateway-transport.d.ts.map +1 -0
- package/dist/services/gateway-writes.d.ts +83 -0
- package/dist/services/gateway-writes.d.ts.map +1 -0
- package/dist/services/realtime/event-catalog.d.ts +456 -0
- package/dist/services/realtime/event-catalog.d.ts.map +1 -0
- package/dist/services/shared/pagination-helpers.d.ts +22 -5
- package/dist/services/shared/pagination-helpers.d.ts.map +1 -1
- package/dist/services/shared/service-validators.d.ts.map +1 -1
- package/dist/signing/index.d.ts +2 -3
- package/dist/signing/index.d.ts.map +1 -1
- package/dist/signing/signers.d.ts +64 -9
- package/dist/signing/signers.d.ts.map +1 -1
- package/dist/signing/types.d.ts +7 -10
- package/dist/signing/types.d.ts.map +1 -1
- package/dist/types/api-key.dto.d.ts +1 -1
- package/dist/types/ban.dto.d.ts +21 -16
- package/dist/types/ban.dto.d.ts.map +1 -1
- package/dist/types/burn.dto.d.ts +4 -2
- package/dist/types/burn.dto.d.ts.map +1 -1
- package/dist/types/chat-messages.dto.d.ts +10 -72
- package/dist/types/chat-messages.dto.d.ts.map +1 -1
- package/dist/types/comments.dto.d.ts +8 -78
- package/dist/types/comments.dto.d.ts.map +1 -1
- package/dist/types/common.d.ts +42 -85
- package/dist/types/common.d.ts.map +1 -1
- package/dist/types/constraints.d.ts +47 -23
- package/dist/types/constraints.d.ts.map +1 -1
- package/dist/types/content-flag.dto.d.ts +5 -1
- package/dist/types/content-flag.dto.d.ts.map +1 -1
- package/dist/types/content-reactions.dto.d.ts +0 -4
- package/dist/types/content-reactions.dto.d.ts.map +1 -1
- package/dist/types/dto.d.ts +0 -5
- package/dist/types/dto.d.ts.map +1 -1
- package/dist/types/engagement-stats.dto.d.ts +16 -27
- package/dist/types/engagement-stats.dto.d.ts.map +1 -1
- package/dist/types/events.dto.d.ts +89 -0
- package/dist/types/events.dto.d.ts.map +1 -1
- package/dist/types/global-feed.dto.d.ts +23 -164
- package/dist/types/global-feed.dto.d.ts.map +1 -1
- package/dist/types/health.dto.d.ts +32 -0
- package/dist/types/health.dto.d.ts.map +1 -0
- package/dist/types/launchpad.dto.d.ts +77 -323
- package/dist/types/launchpad.dto.d.ts.map +1 -1
- package/dist/types/lock.dto.d.ts +12 -7
- package/dist/types/lock.dto.d.ts.map +1 -1
- package/dist/types/messages.dto.d.ts +168 -118
- package/dist/types/messages.dto.d.ts.map +1 -1
- package/dist/types/moderator.dto.d.ts +1 -1
- package/dist/types/options.dto.d.ts +8 -36
- package/dist/types/options.dto.d.ts.map +1 -1
- package/dist/types/overseer.dto.d.ts +2 -1
- package/dist/types/overseer.dto.d.ts.map +1 -1
- package/dist/types/platform-stats.dto.d.ts +3 -3
- package/dist/types/realtime-events.dto.d.ts +340 -0
- package/dist/types/realtime-events.dto.d.ts.map +1 -0
- package/dist/types/restricted-names.dto.d.ts +2 -2
- package/dist/types/restricted-names.dto.d.ts.map +1 -1
- package/dist/types/stream-chat.dto.d.ts +15 -14
- package/dist/types/stream-chat.dto.d.ts.map +1 -1
- package/dist/types/streaming.dto.d.ts +73 -104
- package/dist/types/streaming.dto.d.ts.map +1 -1
- package/dist/types/token-ban.dto.d.ts.map +1 -1
- package/dist/types/token-config.dto.d.ts +34 -19
- package/dist/types/token-config.dto.d.ts.map +1 -1
- package/dist/types/trades-query.dto.d.ts +8 -24
- package/dist/types/trades-query.dto.d.ts.map +1 -1
- package/dist/types/user.dto.d.ts +133 -112
- package/dist/types/user.dto.d.ts.map +1 -1
- package/dist/types/websocket-events.dto.d.ts +5 -5
- package/dist/types/websocket-events.dto.d.ts.map +1 -1
- package/dist/utils/address-formatter.d.ts +25 -2
- package/dist/utils/address-formatter.d.ts.map +1 -1
- package/dist/utils/agent-config.d.ts +9 -4
- package/dist/utils/agent-config.d.ts.map +1 -1
- package/dist/utils/auto-pagination.d.ts +7 -240
- package/dist/utils/auto-pagination.d.ts.map +1 -1
- package/dist/utils/bignumber-helpers.d.ts +3 -2
- package/dist/utils/bignumber-helpers.d.ts.map +1 -1
- package/dist/utils/delimiter-parser.d.ts +0 -13
- package/dist/utils/delimiter-parser.d.ts.map +1 -1
- package/dist/utils/error-factories.d.ts +4 -3
- package/dist/utils/error-factories.d.ts.map +1 -1
- package/dist/utils/error-patterns.d.ts +0 -47
- package/dist/utils/error-patterns.d.ts.map +1 -1
- package/dist/utils/error-wrapper.d.ts +5 -5
- package/dist/utils/errors.d.ts +53 -318
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/http.d.ts +36 -3
- package/dist/utils/http.d.ts.map +1 -1
- package/dist/utils/message-validators.d.ts.map +1 -1
- package/dist/utils/pagination-helpers.d.ts +17 -0
- package/dist/utils/pagination-helpers.d.ts.map +1 -1
- package/dist/utils/pagination-validation.d.ts +2 -2
- package/dist/utils/response-handlers.d.ts.map +1 -1
- package/dist/utils/service-validators.d.ts +6 -6
- package/dist/utils/service-validators.d.ts.map +1 -1
- package/dist/utils/token-format-converter.d.ts +1 -1
- package/dist/utils/token-parser.d.ts +6 -127
- package/dist/utils/token-parser.d.ts.map +1 -1
- package/dist/utils/token-stringification.d.ts +7 -7
- package/dist/utils/token-stringification.d.ts.map +1 -1
- package/dist/utils/tokenNameNormalizer.d.ts +2 -2
- package/dist/utils/tokenNormalizer.d.ts +5 -29
- package/dist/utils/tokenNormalizer.d.ts.map +1 -1
- package/dist/utils/unique-key-generator.d.ts +7 -134
- package/dist/utils/unique-key-generator.d.ts.map +1 -1
- package/dist/utils/validation-helpers.d.ts +21 -64
- package/dist/utils/validation-helpers.d.ts.map +1 -1
- package/dist/utils/validation.d.ts +4 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/package.json +47 -87
- package/dist/api/dto/BurnTokensDto.d.ts +0 -77
- package/dist/api/dto/BurnTokensDto.d.ts.map +0 -1
- package/dist/api/dto/LockTokenDto.d.ts +0 -85
- package/dist/api/dto/LockTokenDto.d.ts.map +0 -1
- package/dist/api/dto/TransferTokenDto.d.ts +0 -64
- package/dist/api/dto/TransferTokenDto.d.ts.map +0 -1
- package/dist/api/dto/UnlockTokenDto.d.ts +0 -74
- package/dist/api/dto/UnlockTokenDto.d.ts.map +0 -1
- package/dist/bridge/BridgeService.d.ts +0 -484
- package/dist/bridge/BridgeService.d.ts.map +0 -1
- package/dist/bridge/GalaConnectClient.d.ts +0 -170
- package/dist/bridge/GalaConnectClient.d.ts.map +0 -1
- package/dist/bridge/constants/index.d.ts +0 -7
- package/dist/bridge/constants/index.d.ts.map +0 -1
- package/dist/bridge/constants/tokens.d.ts +0 -212
- package/dist/bridge/constants/tokens.d.ts.map +0 -1
- package/dist/bridge/index.d.ts +0 -24
- package/dist/bridge/index.d.ts.map +0 -1
- package/dist/bridge/public-types.d.ts +0 -2
- package/dist/bridge/public-types.d.ts.map +0 -1
- package/dist/bridge/strategies/BridgeStrategy.d.ts +0 -204
- package/dist/bridge/strategies/BridgeStrategy.d.ts.map +0 -1
- package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts +0 -178
- package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts.map +0 -1
- package/dist/bridge/strategies/SolanaBridgeStrategy.d.ts +0 -236
- package/dist/bridge/strategies/SolanaBridgeStrategy.d.ts.map +0 -1
- package/dist/bridge/types/bridge.dto.d.ts +0 -772
- package/dist/bridge/types/bridge.dto.d.ts.map +0 -1
- package/dist/bridge/types/bridgeable-token.dto.d.ts +0 -209
- package/dist/bridge/types/bridgeable-token.dto.d.ts.map +0 -1
- package/dist/bridge/types/eip712.d.ts +0 -66
- package/dist/bridge/types/eip712.d.ts.map +0 -1
- package/dist/bridge/types/index.d.ts +0 -8
- package/dist/bridge/types/index.d.ts.map +0 -1
- package/dist/bridge/utils/RateLimiter.d.ts +0 -34
- package/dist/bridge/utils/RateLimiter.d.ts.map +0 -1
- package/dist/bridge/utils/address-formatter.d.ts +0 -25
- package/dist/bridge/utils/address-formatter.d.ts.map +0 -1
- package/dist/bridge/utils/addressValidation.d.ts +0 -200
- package/dist/bridge/utils/addressValidation.d.ts.map +0 -1
- package/dist/bridge/utils/balanceHelpers.d.ts +0 -215
- package/dist/bridge/utils/balanceHelpers.d.ts.map +0 -1
- package/dist/bridge/utils/bridgeErrors.d.ts +0 -98
- package/dist/bridge/utils/bridgeErrors.d.ts.map +0 -1
- package/dist/bridge/utils/bridgeOutHelpers.d.ts +0 -68
- package/dist/bridge/utils/bridgeOutHelpers.d.ts.map +0 -1
- package/dist/bridge/utils/bridgePayload.d.ts +0 -98
- package/dist/bridge/utils/bridgePayload.d.ts.map +0 -1
- package/dist/bridge/utils/bridgeStatusParser.d.ts +0 -76
- package/dist/bridge/utils/bridgeStatusParser.d.ts.map +0 -1
- package/dist/bridge/utils/eip712Helpers.d.ts +0 -66
- package/dist/bridge/utils/eip712Helpers.d.ts.map +0 -1
- package/dist/bridge/utils/index.d.ts +0 -19
- package/dist/bridge/utils/index.d.ts.map +0 -1
- package/dist/bridge/utils/retry.d.ts +0 -112
- package/dist/bridge/utils/retry.d.ts.map +0 -1
- package/dist/bridge/utils/strategyDelegation.d.ts +0 -126
- package/dist/bridge/utils/strategyDelegation.d.ts.map +0 -1
- package/dist/bridge/utils/tokenIdUtils.d.ts +0 -86
- package/dist/bridge/utils/tokenIdUtils.d.ts.map +0 -1
- package/dist/bridge/utils/tokenMath.d.ts +0 -39
- package/dist/bridge/utils/tokenMath.d.ts.map +0 -1
- package/dist/bridge/utils/tokenMetadataResolver.d.ts +0 -97
- package/dist/bridge/utils/tokenMetadataResolver.d.ts.map +0 -1
- package/dist/helpers/wallet.d.ts +0 -151
- package/dist/helpers/wallet.d.ts.map +0 -1
- package/dist/react/WalletContext.d.ts +0 -60
- package/dist/react/WalletContext.d.ts.map +0 -1
- package/dist/react/index.d.ts +0 -65
- package/dist/react/index.d.ts.map +0 -1
- package/dist/react/types.d.ts +0 -76
- package/dist/react/types.d.ts.map +0 -1
- package/dist/react/useWallet.d.ts +0 -123
- package/dist/react/useWallet.d.ts.map +0 -1
- package/dist/react/useWalletConnection.d.ts +0 -89
- package/dist/react/useWalletConnection.d.ts.map +0 -1
- package/dist/react/useWalletDetection.d.ts +0 -81
- package/dist/react/useWalletDetection.d.ts.map +0 -1
- package/dist/react.cjs +0 -1
- package/dist/react.esm.js +0 -1
- package/dist/services/AbstractTokenFetchService.d.ts +0 -150
- package/dist/services/AbstractTokenFetchService.d.ts.map +0 -1
- package/dist/services/BatchedCacheService.d.ts +0 -133
- package/dist/services/BatchedCacheService.d.ts.map +0 -1
- package/dist/services/BridgeableTokenCache.d.ts +0 -120
- package/dist/services/BridgeableTokenCache.d.ts.map +0 -1
- package/dist/services/BridgeableTokenService.d.ts +0 -218
- package/dist/services/BridgeableTokenService.d.ts.map +0 -1
- package/dist/services/DexService.d.ts +0 -440
- package/dist/services/DexService.d.ts.map +0 -1
- package/dist/services/NetworkKeyedCacheService.d.ts +0 -185
- package/dist/services/NetworkKeyedCacheService.d.ts.map +0 -1
- package/dist/services/PriceHistoryService.d.ts +0 -209
- package/dist/services/PriceHistoryService.d.ts.map +0 -1
- package/dist/services/StreamingEventService.d.ts +0 -441
- package/dist/services/StreamingEventService.d.ts.map +0 -1
- package/dist/services/WrapService.d.ts +0 -171
- package/dist/services/WrapService.d.ts.map +0 -1
- package/dist/services/WrappableTokenCache.d.ts +0 -100
- package/dist/services/WrappableTokenCache.d.ts.map +0 -1
- package/dist/services/WrappableTokenService.d.ts +0 -130
- package/dist/services/WrappableTokenService.d.ts.map +0 -1
- package/dist/setup.d.ts +0 -8
- package/dist/setup.d.ts.map +0 -1
- package/dist/tokens/transfers.d.ts +0 -95
- package/dist/tokens/transfers.d.ts.map +0 -1
- package/dist/types/comment.dto.d.ts +0 -176
- package/dist/types/comment.dto.d.ts.map +0 -1
- package/dist/types/galachain-api.types.d.ts +0 -297
- package/dist/types/galachain-api.types.d.ts.map +0 -1
- package/dist/types/priceHistory.dto.d.ts +0 -134
- package/dist/types/priceHistory.dto.d.ts.map +0 -1
- package/dist/types/streaming-events.dto.d.ts +0 -605
- package/dist/types/streaming-events.dto.d.ts.map +0 -1
- package/dist/types/token.types.d.ts +0 -359
- package/dist/types/token.types.d.ts.map +0 -1
- package/dist/types/wrappable-token.dto.d.ts +0 -305
- package/dist/types/wrappable-token.dto.d.ts.map +0 -1
- package/dist/utils/crypto-compat.d.ts +0 -40
- package/dist/utils/crypto-compat.d.ts.map +0 -1
- package/dist/utils/load-env.d.ts +0 -31
- package/dist/utils/load-env.d.ts.map +0 -1
- package/dist/utils/token-instance-key.d.ts +0 -57
- package/dist/utils/token-instance-key.d.ts.map +0 -1
- package/dist/utils/wallet.d.ts +0 -166
- package/dist/utils/wallet.d.ts.map +0 -1
- package/dist/wallet/ExternalWalletProvider.d.ts +0 -90
- package/dist/wallet/ExternalWalletProvider.d.ts.map +0 -1
- package/dist/wallet/GalaWalletProvider.d.ts +0 -122
- package/dist/wallet/GalaWalletProvider.d.ts.map +0 -1
- package/dist/wallet/PrivateKeyProvider.d.ts +0 -90
- package/dist/wallet/PrivateKeyProvider.d.ts.map +0 -1
- package/dist/wallet/detection.d.ts +0 -107
- package/dist/wallet/detection.d.ts.map +0 -1
- package/dist/wallet/event-handlers.d.ts +0 -50
- package/dist/wallet/event-handlers.d.ts.map +0 -1
- package/dist/wallet/index.d.ts +0 -51
- package/dist/wallet/index.d.ts.map +0 -1
- package/dist/wallet/signing-operation.d.ts +0 -19
- package/dist/wallet/signing-operation.d.ts.map +0 -1
- package/dist/wallet/typed-data-helpers.d.ts +0 -68
- package/dist/wallet/typed-data-helpers.d.ts.map +0 -1
- package/dist/wallet/types.d.ts +0 -267
- package/dist/wallet/types.d.ts.map +0 -1
- package/dist/wallet/utils.d.ts +0 -117
- package/dist/wallet/utils.d.ts.map +0 -1
- package/dist/wallet.cjs +0 -1
- package/dist/wallet.esm.js +0 -1
package/dist/native.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z as e}from"zod";import{getAddress as t,Wallet as n,isAddress as a,JsonRpcProvider as s,Contract as r,Signature as i,keccak256 as o,toUtf8Bytes as c,Mnemonic as l,HDNodeWallet as d,computeAddress as u,SigningKey as h}from"ethers";import{BrowserWalletSigner as g,generateEIP712Types as m,GalaWalletSigner as p,PrivateKeySigner as f,GSwap as y}from"@gala-chain/gswap-sdk";export{generateEIP712Types}from"@gala-chain/gswap-sdk";import{PublicKey as v,Connection as k,Keypair as b,Transaction as w,ComputeBudgetProgram as A,TransactionInstruction as S,SystemProgram as E,LAMPORTS_PER_SOL as T}from"@solana/web3.js";import C from"json-stringify-deterministic";import*as N from"node:crypto";import{TOKEN_PROGRAM_ID as I,AccountLayout as D,ASSOCIATED_TOKEN_PROGRAM_ID as _}from"@solana/spl-token";import R from"bs58";import{ChainCallDTO as x,TokenClassKey as F}from"@gala-chain/api";import{v4 as B}from"uuid";import O from"bignumber.js";import{io as U}from"socket.io-client";import P from"axios";const M={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},L="/v1/users/referrals/url",$="/v1/users/referrals",K="/v1/users/referrals/summary",G="/market/price-series",W="/v1/tokens/:tokenName/start-stream",H="/v1/tokens/:tokenName/stop-stream",q="/v1/tokens/:tokenName/stream/disable",j="/v1/tokens/:tokenName/stream/enable",V="/v1/tokens/:tokenName/reset-key",z="/v1/tokens/:tokenName/recordings",X="/v1/tokens/:tokenName/recordings/:assetId/download",Q="/v1/tokens/:tokenName/recordings/:assetId",J="/v1/tokens/:tokenName/simulcasts",Y="/v1/tokens/:tokenName/simulcasts",Z="/v1/tokens/:tokenName/simulcasts/:targetId",ee="/v1/config",te="/v1/config",ne="/v1/config",ae="/v1/tokens/:tokenName/role",se="/v1/roles",re="/v1/permissions",ie="/v1/tokens/:tokenName/credentials",oe="/auth/login",ce="/auth/logout",le="/auth/refresh",de="/auth/session",ue="/v1/tokens/:tokenName/bans",he="/v1/tokens/:tokenName/bans",ge="/v1/tokens/:tokenName/bans/:userAddress",me="/v1/tokens/:tokenName/bans/:userAddress",pe="/v1/tokens/:tokenName/active-users",fe="/v1/user-bans",ye="/v1/user-bans",ve="/v1/user-bans/:userAddress",ke="/v1/user-bans/:userAddress",be={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},we="/v1/moderator-invites",Ae="/v1/moderator-invites/claim",Se="/v1/moderated-tokens",Ee="/v1/moderator-invites",Te="/v1/moderator-invites/:id",Ce="/v1/moderator-invites/:id/role",Ne="/v1/moderator-invites/:id",Ie="/v1/moderator-invites/code/:code",De={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},_e="/v1/overseer-invites",Re="/v1/overseer-invites",xe="/v1/overseer-invites/code/:code",Fe="/v1/overseer-invites/claim",Be="/v1/overseer-invites/:id",Oe="/v1/overseers",Ue="/v1/overseers",Pe="/v1/overseers/:address",Me="/v1/overseers/me",Le="/v1/overseer-summary",$e="/v1/overseer-summary/bans",Ke="/v1/overseer-summary/token-bans",Ge="/v1/overseer-summary/invites",We="/v1/overseer-summary/flags",He="/v1/overseer-summary/users",qe="/v1/users",je="/v1/users/:address/summary",Ve="/v1/cache/flush/address/:address",ze="/v1/cache/flush/token/:tokenName",Xe="/v1/cache/flush/all",Qe="/v1/cache/flush/wallet-aliases/:address",Je="/v1/cache/flush/wallet-aliases",Ye="/v1/token-bans",Ze="/v1/token-bans",et="/v1/token-bans/:tokenName",tt="/v1/token-bans/:tokenName",nt="/v1/reactions",at="/v1/reactions",st="/v1/trades",rt={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},it="/v1/restricted-token-names",ot="/v1/restricted-token-names",ct="/live/:tokenName/chat",lt="/live/:tokenName/chat",dt="/live/:tokenName/chat",ut="/live/:tokenName/chat/slow-mode",ht={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"},gt="/v1/stats",mt="/v1/trading/fee",pt="/v1/trading/sale-details",ft="/v1/trading/quote",yt="/v1/trading/premint-quote",vt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},kt="/v1/notifications/register",bt="/v1/notifications/unregister",wt="/v1/notifications/preferences",At="/v1/notifications/preferences",St="/v1/config/client-flags",Et="native",Tt="exact",Ct="REQUIRED",Nt="INVALID_TYPE",It="INVALID_VALUE",Dt="INVALID_FORMAT",_t="TOO_LARGE",Rt="INVALID_RANGE";class xt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class Ft extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class Bt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class Ot extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Ut(e){return e instanceof Error}function Pt(e){return Ut(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 Mt(e){return Ut(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Lt(e){if(function(e){return"object"==typeof e&&null!==e&&"code"in e&&("string"==typeof e.code||"number"==typeof e.code)}(e))return e.code}function $t(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Kt(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 a=n.Status;if("number"!=typeof a)throw new Error(`${t}: Response Status must be a number, got ${typeof a}`);if(1!==a)throw new Error(`${t}: Response status indicates failure (Status: ${a})`);return n}function Gt(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function Wt(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)}}}function Ht(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function qt(e,t){return new xt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function jt(e,t){const n=Ht(e,t);return new xt(`${n} is required`,e,"REQUIRED")}function Vt(e,t,n){const a=Ht(e,n);return new xt(`${a} must be ${t}`,e,"INVALID_FORMAT")}function zt(e,t,n){return new Ft(e,t,n)}function Xt(e,t){return new Bt(e,t)}function Qt(e,t,n){return new Ot(e,t,n)}function Jt(e,t,n,a){n&&n.error(`${t}:`,e);const s=$t(e)?e.response?.status:void 0;return zt(`${t}: ${Pt(e)}`,s,Ut(e)?e:void 0)}function Yt(e,t,n,a,s){const r=Ht(e,s);return new xt(`${r} must be between ${t} and ${n}${void 0!==a?`, received: ${a}`:""}`,e,"OUT_OF_RANGE")}function Zt(e,t,n,a){const s=Ht(e,a);return new xt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function en(e,t,n,a){const s=Ht(e,a);return new xt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function tn(e,t,n,a){const s=Ht(e,a),r=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new xt(`${s} must be ${t}${r}`,e,"INVALID_TYPE")}function nn(e,t,n){const a=Ht(e,n);return new xt(`${a} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function an(e,t,n,a){const s=Ht(e,a);return new xt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function sn(e){return null!=e&&"object"==typeof e&&"data"in e}function rn(e,t,n=!1){const a=!0===e.error,s=n&&(null===e.data||void 0===e.data);if(a||s){const n=e?.statusCode??e.status??void 0;throw zt(e?.message??t,n)}}function on(e){if(sn(e))return e.data}function cn(e,t="No data found in response"){if(!sn(e))throw zt(t);const n=e.data;if(null==n)throw zt(t);return n}async function ln(e,t={}){return hn(e,t,e=>{if(void 0===e.data)throw new xt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function dn(e,t={}){const{errorContext:n="Operation failed",logger:a,debugLogEnabled:s=!1}=t;s&&a&&a.debug(`${n}: starting operation`);try{const t=await e();return s&&a&&a.debug(`${n}: completed successfully`),t}catch(e){throw a&&a.error(n,{error:e}),e}}async function un(e,t={}){return hn(e,t,e=>e)}async function hn(e,t,n){const{errorContext:a="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${a}: starting operation`);try{const t=await e();if(null==t)throw new xt(`${a}: No response from server`,"response","NO_RESPONSE");return rn(t,a,!0),r&&s&&s.debug(`${a}: completed successfully`),n(t)}catch(e){throw s&&s.error(a,{error:e}),e}}const gn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function mn(e){return e.trim().toLowerCase()}function pn(e){return e.trim().toUpperCase()}function fn(e){return e.trim().toUpperCase()}var yn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(yn||(yn={}));class vn{constructor(e){this.levelPriority={[yn.DEBUG]:0,[yn.INFO]:1,[yn.WARN]:2,[yn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?yn.DEBUG:yn.INFO)}debug(e,t){this.log(yn.DEBUG,e,t)}info(e,t){this.log(yn.INFO,e,t)}warn(e,t){this.log(yn.WARN,e,t)}error(e,t){this.log(yn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===yn.DEBUG&&!this.debugEnabled)return;const a=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?Ut(n)?s(`${a} ${t}`,n.message,Mt(n)??""):s(`${a} ${t}`,n):s(`${a} ${t}`)}getConsoleMethod(e){switch(e){case yn.DEBUG:return console.debug;case yn.INFO:return console.info;case yn.WARN:return console.warn;case yn.ERROR:return console.error;default:return console.log}}child(e){return new vn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[yn.DEBUG]>=this.levelPriority[this.minLevel]}}function kn(e){return null==e||""===e}function bn(e){return null==e}const wn=new vn({debug:!1,context:"DateUtils"});function An(e,t){if(null==e)return t??new Date;if(e instanceof Date)return isNaN(e.getTime())?t??new Date:e;try{const n=new Date(e);return isNaN(n.getTime())?(wn.warn(`Invalid date string received: "${e}". Using fallback.`),t??new Date):n}catch(n){return wn.warn(`Date parsing error for "${e}":`,n),t??new Date}}function Sn(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 En(e){return Date.now()-e}const Tn={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},Cn={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},Nn={MIN_LENGTH:1,MAX_LENGTH:50},In=100,Dn=20,_n={MAX_LIMIT:50},Rn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},xn={COMMENTS_V1:{MAX_LENGTH:2e3},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}},Fn={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})$/}},Bn=60,On=31536e3,Un={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Pn={PATTERN:/^[a-fA-F0-9]{64}$/},Mn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Ln=50,$n=1,Kn=100,Gn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function Wn(e,t){if(kn(e))return t;try{return JSON.parse(e)}catch{return t}}function Hn(e,t=0){if(kn(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 qn(e,t,n){if(bn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const a=Number(e);return isNaN(a)?t:a}function jn(e,t,n){if(bn(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 a=parseInt(String(e),10);return isNaN(a)?t:a}function Vn(e,t){if(bn(e)||""===e)throw jt(t);if(O.isBigNumber(e)){if(e.isNaN())throw nn(t,"NaN");return e}try{const n=new O(e);if(n.isNaN())throw nn(t,e);if(!n.isFinite())throw nn(t,e);return n}catch(n){if(n instanceof xt)throw n;throw nn(t,e)}}function zn(e,t=0){if(bn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Hn(String(e).replace("%","").trim(),t)}function Xn(e,t=18){const n=Hn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Qn(e){return Xn(e,8)}function Jn(e){return Xn(e,18)}function Yn(e,t,n,a){if("number"!=typeof e)throw tn(a,"a number",e,a);if(e<t||e>n)throw Yt(a,t,n,e)}function Zn(e,t,n){if("string"!=typeof e)throw tn(n,"a string",e,n);if(e.length>t)throw en(n,t,e.length)}function ea(e,t){if("number"!=typeof e)throw tn(t,"a number",e,t);if(!Number.isInteger(e))throw tn(t,"an integer",e,t);if(e<=0)throw Zt(t,1,e,t)}function ta(e,t,n=!1){if("string"!=typeof e)throw tn(t,"a string",e,t);if(!n&&0===e.trim().length)throw jt(t,`${t} (non-empty string)`)}const na={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},aa=function(e){return"string"==typeof e&&e.trim().length>0},sa=bn;function ra(e,t,n=100,a,s){if(void 0!==s&&"string"!=typeof s)throw new xt("cursor must be a string","cursor",Nt);const r=a??t,i=void 0!==a?"pageSize":"limit";if(void 0!==r&&(ea(r,i),r>n))throw new xt(`${i} must be at most ${n}`,i,_t)}function ia(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function oa(e){return Object.values(e)}function ca(e,t,n,a={}){const{description:s="parameter",treatEmptyAsNull:r=!0}=a,i=e[t],o=e[n],c=null!=i&&(!r||""!==i),l=null!=o&&(!r||""!==o);if(!c&&!l)throw Xt(`Either ${t} or ${n} must be provided (${s})`,n);if(c&&l)throw Xt(`Cannot provide both ${t} and ${n}. Provide exactly one (${s}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function la(e,t="tokenName",n=Tn){if(!aa(e))throw jt(t);const a=e.trim();if(0===a.length)throw jt(t);if(a.length<n.MIN_LENGTH)throw Yt(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(a.length>n.MAX_LENGTH)throw Yt(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(!n.PATTERN.test(a))throw new xt(`${t} must contain only alphanumeric characters`,t,Dt)}function da(e,t="tokenName",n=Tn){if(null==e)throw jt(t,t);if("string"!=typeof e)throw tn(t,"a string",e);const a=e.trim();if(0===a.length)throw jt(t,t);if(!n.PATTERN.test(a))throw new xt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Dt)}function ua(e){return""===e||0===e.trim().length}function ha(e,t,n){if(!sa(e)){if("string"!=typeof e)throw tn(t,"a string",e,t);if(e.length>n)throw new xt(`${t} must be at most ${n} characters`,t,_t)}}function ga(e,t){sa(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw tn(t,"a date",e,t);if(isNaN(n.getTime()))throw new xt(`${t} must be a valid date`,t,Dt)}(e,t)}function ma(e,t,n){try{ea(e,t)}catch{throw function(e,t,n,a="OPERATION_FAILED"){return new xt(`${e} failed: ${t}`,n,a)}(n,"must be a positive integer",t)}}function pa(e,t,n="status"){void 0!==e&&function(e,t,n){const a=Object.values(t);if(!a.includes(e))throw new xt(`${n} must be one of: ${a.join(", ")}`,n,Dt)}(e,t,n)}class fa{constructor(e,t=!1,n){this.http=e,this.logger=new vn({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new Bt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Mt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){ma(e,t,n)}}class ya{constructor(e=!1,t){this.logger=t||new vn({debug:e,context:this.constructor.name})}}class va extends ya{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 ka extends va{constructor(e=!1){super(e)}normalizeKey(e){return mn(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>=ka.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??gn.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,a)=>{n.lastUpdated<e&&(e=n.lastUpdated);let s=0;s+=2*a.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(s+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(s+=8),s+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(s+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(s+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(s+=2*n.symbol.length),s+=32,t+=s}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${mn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${mn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${mn(e)}`;return this.cache.has(t)}}function ba(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}ka.MAX_CACHE_SIZE=1e4;const wa={ETHEREUM:na.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:na.BACKEND_ADDRESS,CLIENT:na.CLIENT_ADDRESS};class Aa{toBackendFormat(e){if(!aa(e))throw new xt("Address is required and must be a string","address","REQUIRED");let n=e;if(e.startsWith("eth|")){if(n=e.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new xt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=ba(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new xt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!aa(e))throw new xt("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 xt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],a=void 0!==n&&""!==n?6:4;return`0x${e.substring(a)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!wa.CLIENT.test(e))throw new xt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!wa.BACKEND.test(e))throw new xt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!aa(e)&&(!!wa.ETHEREUM.test(e)||(!!wa.ETHEREUM_NO_PREFIX.test(e)||(!!wa.BACKEND.test(e)||!!wa.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new xt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return aa(e)?wa.ETHEREUM.test(e)||wa.ETHEREUM_NO_PREFIX.test(e)?"ethereum":wa.BACKEND.test(e)?"backend":wa.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 ba(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new xt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Sa=new Aa,Ea=ba;function Ta(e){return Sa.toBackendFormat(e)}function Ca(e){return Sa.toEthereumFormat(e)}function Na(e){return Sa.isValid(e)}function Ia(e,t="address"){Sa.assertValid(e,t)}function Da(e){return Sa.detectFormat(e)}var _a=Object.freeze({__proto__:null,AddressFormatter:Aa,assertValidWalletAddress:Ia,detectFormat:Da,fromBackendAddressFormat:Ca,isValidAddress:Na,normalizeAddressInput:function(e){return Sa.normalizeInput(e)},stripHexPrefix:Ea,toBackendAddressFormat:Ta});const Ra=e.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"),xa=e.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"),Fa=e.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Ba=e.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Oa=e.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Ua=e.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");e.string().regex(na.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.string().regex(na.ETH_ADDRESS,"Invalid Ethereum address format");const Pa=e.string().refine(e=>na.BACKEND_ADDRESS.test(e)||na.ETH_ADDRESS.test(e)||na.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Aa).normalizeInput(e)??e),Ma=e.string().refine(e=>na.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),La=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Hn(e,0)>0,"Amount must be greater than zero"),$a=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Hn(e,0)>=0,"Amount must be zero or greater");e.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const Ka=e.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function Ga(t=100){return e.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(t,`Limit must be at most ${t}`).default(10)}e.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),Ga(100),Ga(20),Ga(20);const Wa=e.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"),Ha=e.string().max(255,"Filename must be at most 255 characters"),qa=e.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.string().datetime("Must be a valid ISO 8601 date string"),e.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const ja=e.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.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"),e.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const Va=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),name:Ha,size:Wa,type:qa});const za=e.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"),Xa=e.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.union([za,Xa]),e.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ha.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Va.includes(t)},`Filename must end with one of: ${Va.join(", ")}`),e.object({websiteUrl:Ka,telegramUrl:Ka,twitterUrl:Ka,instagramUrl:Ka,facebookUrl:Ka,redditUrl:Ka,tiktokUrl:Ka}).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");const Qa=e.string().min(1,"Token category must not be empty").default("Unit"),Ja=e.string().min(1,"Token collection must not be empty").default("Token"),Ya=e.object({minFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Hn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Hn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Hn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Hn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Hn(e.maxFeePortion,0)>=Hn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Za=e.object({tokenName:Ra,tokenSymbol:xa,tokenDescription:Fa,tokenImage:e.union([e.instanceof(File),e.instanceof(Buffer),e.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:$a.default("0"),websiteUrl:Ka,telegramUrl:Ka,twitterUrl:Ka,instagramUrl:Ka,facebookUrl:Ka,redditUrl:Ka,tiktokUrl:Ka,tokenCategory:Qa,tokenCollection:Ja,reverseBondingCurveConfiguration:Ya.optional(),saleStartTime:e.number().int().positive().optional(),privateKey:ja.optional()});e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),tokenName:Ra}),e.enum(["RECENT","POPULAR"]);const es=e.object({tokenName:Ra.optional(),symbol:xa.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.enum(["NATIVE","MEME"]),e.enum(["IN","OUT"]);const ts=e.object({from:e.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:Ra});e.object({tokenName:Ra,slippageToleranceFactor:e.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.number().min(0).max(1).optional(),privateKey:ja.optional()});const ns=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(100).default(10)}),as=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)}),ss=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)});ns.extend({type:e.enum(["RECENT","POPULAR"]).optional(),tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),as.extend({tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),ss.extend({tradeType:e.enum(["BUY","SELL"]).optional(),tokenName:e.string().min(1).max(50).optional(),userAddress:e.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:e.string().datetime().optional(),endDate:e.string().datetime().optional(),sortOrder:e.enum(["ASC","DESC"]).default("DESC")});const rs={page:e.number().int().min(1),limit:e.number().int().min(1),total:e.number().int().min(0),totalPages:e.number().int().min(0),hasNext:e.boolean(),hasPrevious:e.boolean()};e.object(rs);const is=e.enum(["buy","sell"]);e.enum(["BUY","SELL"]),e.object({tradeType:is,tokenAmount:La,vaultAddress:Ma,userAddress:Pa,slippageTolerance:La.optional(),deadline:e.number().int().positive().optional()}),e.object({tokenSymbol:xa,nativeTokenQuantity:La,expectedToken:La,maxAcceptableReverseBondingCurveFee:$a.default("0").optional()}),e.object({tokenSymbol:xa,tokenQuantity:La,expectedNativeToken:La,maxAcceptableReverseBondingCurveFee:$a.default("0").optional()}),ss.extend({tokenName:Ba.optional()}),e.object({page:e.number().int().min(1).max(1e3).default(1).optional(),limit:e.number().int().min(1).max(20).default(10).optional()});const os=e.enum(["NATIVE","MEME"]),cs=e.enum(["IN","OUT"]);e.object({type:os,method:cs,vaultAddress:Ma,amount:La}),e.object({nativeTokenQuantity:La}),e.object({vaultAddress:Ma}),e.object({minFeePortion:La,maxFeePortion:La});const ls=e.enum(["both","held","created"]);function ds(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)}}}as.extend({type:ls.optional(),address:Pa.optional(),search:Oa.optional(),tokenName:Ba.optional()}),e.object({address:Pa.optional(),refresh:e.boolean().optional()}),e.object({profileImage:e.string(),fullName:Ua,address:Pa,privateKey:ja.optional()}),e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),address:Pa.optional(),privateKey:ja.optional()}),e.object({created:e.number(),createdBy:e.string(),expires:e.number(),instanceId:e.string(),lockAuthority:e.string(),name:e.string(),quantity:e.string(),vestingPeriodStart:e.number()}),e.object({address:Pa,tokenId:e.union([e.string(),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string()}),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string(),instance:e.string()})]).optional(),tokenName:Ba.optional(),withExpired:e.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const us=ds(Ra),hs=ds(Za),gs=ds(es);function ms(e){const t=function(e){const t=hs(e);return t.success?[]:t.errors??["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function ps(e,t){return"string"==typeof e[t]}function fs(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 vs(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}}ia({BUY:"buy",SELL:"sell"});const ks=(bs={nativeTokenQuantity:"string"},e=>{if(null==e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const[e,n]of Object.entries(bs))if(!vs(t[e],n))return!1;return!0});var bs;function ws(e){if(sa(e)||"object"!=typeof e)return{};const t={};for(const[n,a]of Object.entries(e))sa(a)||(aa(a)?t[n]=a:"number"==typeof a||"boolean"==typeof a?t[n]=a.toString():Array.isArray(a)?t[n]=a.join(","):t[n]="object"==typeof a?JSON.stringify(a):String(a));return t}function As(e,t="0"){return function(e,t="0"){if(kn(e))return new O(t);if(O.isBigNumber(e))return e.isNaN()?new O(t):e;try{const n=new O(e);return n.isNaN()||!n.isFinite()?new O(t):n}catch{return new O(t)}}(e,t)}function Ss(e,t){return void 0!==t?As(e).toFixed(t):As(e).toFixed()}function Es(e){return As(e).isZero()}function Ts(e,t){return As(e).isLessThan(As(t))}function Cs(...e){e.forEach(e=>{if(e.isNaN())throw nn("value","NaN");if(!e.isFinite())throw en("value","finite");if(e.isLessThanOrEqualTo(0))throw Zt("value","0",e.toString())})}function Ns(e,t,n="0"){const a=As(t);return Es(a)?As(n):As(e).dividedBy(a)}const Is={calculateBuyWithExact(e,t){const n=Hn(e),a=Hn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=gn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(s*(Math.exp((a+n)*r)-Math.exp(a*r))/r,8),l=Ss(As(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=Hn(e),a=Hn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=gn,c=Math.log(n*r/s+Math.exp(a*r))/r-a,l=Ss(As(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,a,s){const r=Hn(e),i=Hn(t),o=Hn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=gn,h=c*(Math.exp(i*l)-Math.exp((i-r)*l))/l,g=As(h),m=a+i/o*(s-a),p=Ss(g.multipliedBy(m),8),f=Ss(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,a,s){const r=Hn(e),i=Hn(t),o=Hn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=gn;if(r>=c*(Math.exp(i*l)-1)/l){const e=As(r),t=a+i/o*(s-a),n=Ss(e.multipliedBy(t),8),c=Ss(e.multipliedBy(d));return{amount:i.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=i-Math.log(Math.exp(i*l)-r*l/c)/l,g=As(r),m=a+i/o*(s-a),p=Ss(g.multipliedBy(m),8),f=Ss(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}};class Ds extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function _s(e,t,n){if(null==e)throw new Ds("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=za.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Ds(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Ds("Filename is required when uploading Buffer objects",t,n);const a=Xa.safeParse(e);if(!a.success){const e=a.error.issues.map(e=>e.message).join("; ");throw new Ds(e,t,n)}try{Zn(t,255,"filename")}catch(e){throw new Ds(e.message,t,n)}const s=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!s.includes(n))throw new Ds(`Invalid file type "${n}" is not allowed. Allowed types: ${s.join(", ")}`,t,n);const r=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),i=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!i.includes(r))throw new Ds(`File extension "${r}" is not allowed. Allowed extensions: ${i.join(", ")}`,t,n);const o=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"}}(r);if(o!==n&&"application/octet-stream"!==o)throw new Ds(`File extension "${r}" does not match MIME type "${n}"`,t,n);return}throw new Ds("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Rs(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xs(e,t){if(!function(e){if(!Rs(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return Rs(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw zt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:gn.GAS_FEE}}class Fs{validate(e,t={}){const{allowZero:n=!0,minimum:a,maximum:s,maxDecimals:r=Fs.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!aa(e))throw new xt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new xt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const o=Hn(e,NaN);if(isNaN(o))throw new xt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new xt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(o<0)throw new xt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new xt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=As(e),l=c.decimalPlaces()??0;if(l>r)throw new xt(`${i} cannot exceed ${r} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==a&&Ts(c,a))throw new xt(`${i} must be at least ${a}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,As(c).isGreaterThan(As(d))))throw new xt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return As(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 Ss(e,t)}clampAmount(e,t,n){const a=As(e),s=As(t),r=As(n);return function(e,t,n){const a=As(e),s=As(t),r=As(n);return a.isGreaterThanOrEqualTo(s)&&a.isLessThanOrEqualTo(r)}(a,s,r)?Ss(a):Ts(a,s)?Ss(s):Ss(r)}}function Bs(e,t){throw new xt(e.join("; "),t,"VALIDATION_ERROR")}function Os(e){const t=us(e);!t.success&&t.errors&&Bs(t.errors,"tokenName")}function Us(e){const t=ts.safeParse(e);var n;t.success||Bs((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 Ps(e,t,n=!0){Ms.validate(e,{fieldName:t,allowZero:n})}Fs.MAX_DECIMAL_PLACES=18,Fs.MIN_POSITIVE="0.00000000000000001";const Ms=new Fs;function Ls(e,t,n=Ss){if(!Array.isArray(e))throw zt("Invalid API response: expected array of holders",t);for(const n of e){if(!$s(n))throw zt("Invalid holder data: missing or invalid owner field",t);if(!Ks(n))throw zt("Invalid holder data: missing or invalid quantity field",t);const e=Hn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw zt(`Invalid holder quantity: "${n.quantity}"`,t)}const a=e,s=a.reduce((e,t)=>e.plus(t.quantity),As(0));return{holders:a.map(e=>({address:e.owner,balance:e.quantity,percentage:Ns(As(e.quantity),s,As(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:a.length,lastUpdated:new Date}}function $s(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Ks(e){return"string"==typeof e.quantity&&""!==e.quantity}class Gs{constructor(e,t,n,a,s="local",r){this.http=e,this.logger=t,this.bundleHttp=n,this.dexApiHttp=a,this.defaultCalculateAmountMode=s,this.launchpadWrites=r,this.metadataCache=new ka}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Os(t);const a=`${t}.png`;_s(n.file,a,"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 Vt("file","a File object (browser) or Buffer (Node.js)");{const a=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,s=new Blob([n.file],{type:"image/png"});e.append("image",s,a)}}const a=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===a.error||200!==a.status)throw zt(void 0!==a.message&&""!==a.message?a.message:"Image upload failed - no URL returned",a.status);const s=on(a);if(!s?.imageUrl)throw zt("Image upload failed - no URL returned",a.status);return s.imageUrl}catch(e){if(Ut(e)&&e.message.includes("FormData"))throw Xt("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&&ra(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&Os(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=ws(t),a=await this.http.get(M.FETCH_POOLS,n);if(!0===a.error||200!==a.status)throw zt(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch pools",a.status);const s=on(a);if(null==s)throw zt("Failed to fetch pools - no data returned",a.status);let r=[];if(s.tokens)if(Array.isArray(s.tokens))r=s.tokens.map(e=>this.normalizePoolData(e));else{const e=s.tokens;r=[this.normalizePoolData(e)]}else s.pools&&Array.isArray(s.pools)&&(r=s.pools.map(e=>this.normalizePoolData(e)));const{extractMetadataFromPoolData:i,isValidPoolForCaching:o}=await Promise.resolve().then(function(){return rh});r.forEach(e=>{if(!o(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=i(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=s.count??s.total??0,l={hasNextPage:s.hasNextPage??!1};return void 0!==s.hasPrevPage&&(l.hasPrevPage=s.hasPrevPage),void 0!==s.nextCursor&&(l.nextCursor=s.nextCursor),void 0!==s.prevCursor&&(l.prevCursor=s.prevCursor),c>0&&(l.totalCount=c),{items:r,pageInfo:l}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={pageSize:e.pageSize??10};return void 0!==e.cursor&&(n.cursor=e.cursor),void 0!==e.search&&""!==e.search&&(n.search=e.search),void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),null!=t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),void 0!==e.language&&""!==e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw Vt("options","an options object");const{tokenName:t,amount:n,type:a,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[Et,Tt],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:a}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:a},"currentSupply",s))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:a}=e;return this.validateExternalAmountInputs(t,n),"exact"===a?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return xs(await ln(()=>this.http.get(ft,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[Tt,Et],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:a});{const e={tokenName:t,amount:n,type:a,...void 0!==s&&{currentSupply:s},...void 0!==r&&{maxSupply:r},...void 0!==i&&{reverseBondingCurveMaxFeeFactor:i},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:a}=e;return this.validateExternalAmountInputs(t,n),"exact"===a?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s}=e;if(!aa(n))throw jt("amount","Amount");if(a!==Et&&a!==Tt)throw tn("type",'"native" or "exact"',a);void 0!==s&&Ps(s,"currentSupply");const r=null==s||""===s;if(r&&(null==t||""===t))throw jt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Os(t);let i=s;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return a===Tt?Is.calculateBuyWithExact(n,i):Is.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if(!aa(n))throw jt("amount","Amount");if(a!==Tt&&a!==Et)throw tn("type",'"exact" or "native"',a);void 0!==s&&Ps(s,"currentSupply");const c=null==s||""===s||null==r||""===r||void 0===i||void 0===o;if(c&&(null==t||""===t))throw jt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Os(t);let l=s,d=r,u=i,h=o;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return a===Tt?Is.calculateSellWithExact(n,l,d,h,u):Is.calculateSellWithNative(n,l,d,h,u)}async calculateBuyAmountForGraduation(e){const t="string"==typeof e?{tokenName:e}:e;if("object"==typeof e&&!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ps(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&fs(t,"currentSupply")}(e))throw tn("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:a,currentSupply:s}=t;Os(n);const r=await this.fetchSaleDetails(n),i=s??Ss(As(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity;if("0"===o)throw jt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:i,...void 0!==a&&{mode:a}};return{...await this.calculateBuyAmount(c),remainingTokens:o}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw Xt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ms(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Hn(t);if(0===n&&"0"!==t)throw nn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw nn("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const a="string"==typeof e?parseFloat(e):e,s="string"==typeof t?parseFloat(t):t;if(!isFinite(a))throw new xt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new xt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(a<.1)throw new xt(`${n} minFee must be >= 0.1, received ${a}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new xt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(a>s)throw new xt(`${n} minFee (${a}) must be <= maxFee (${s})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async fetchTokenDistribution(e){if(null==e||""===e)throw jt("tokenName","Token name");Os(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw zt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=on(t);if(null==n)throw zt("Failed to fetch token distribution - no data returned",t.status);return Ls(n,t.status)}async calculateInitialBuyAmount(e){if(!ks(e))throw Vt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return xs(await ln(()=>this.http.get(yt,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ss(As(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.sellingTokenQuantity,s=t.maxSupply;let r=.5,i=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(r=zn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(i=zn(o.minFeePortion,.1)),void 0===o&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=r-i;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:a,maxSupply:s,reverseBondingCurveMaxFeeFactor:r,reverseBondingCurveMinFeeFactor:i,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Os(e);const t=await this.fetchSaleDetails(e),n=Ss(As(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.maxSupply;return this.metadataCache.set(e,{maxSupply:a}),n}async fetchPoolDetails(e){Os(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...a}=t,s=n?.minFeePortion??"0",r=n?.maxFeePortion??"0";return{...a,reverseBondingCurveMinFeePortion:s,reverseBondingCurveMaxFeePortion:r,hasReverseBondingCurveFee:!Es(s)||!Es(r),isGraduated:"Finished"===t.saleStatus}}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!Es(t)||!Es(n),createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}async fetchSaleDetails(e){return ln(()=>this.http.get(pt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,a,s,r){const i=a??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw tn("mode",'"local" or "external"',i);if(!aa(e))throw jt("tokenName","Token name");if(!aa(t))throw jt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw tn("type",r,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new xt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new xt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Ta(e)}validateTokenName(e){return Os(e)}validatePagination(e){void 0!==e.pageSize&&ra(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw Xt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw jt("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 zt(`Failed to fetch token prices: ${Pt(e)}`,void 0,Ut(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const Ws=3e5,Hs="Sign in to Launchpad t:",qs="Authorization",js="Bearer ";class Vs{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 zs,Xs;!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"}(zs||(zs={}));class Qs extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Js{constructor(e,t=Ws){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 Vs,this.refreshThresholdMs=t}setToken(e,t){if(!aa(e))throw new Qs(zs.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Qs(zs.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Qs(zs.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Qs(zs.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,a){if(this.setToken(e,t),n){const e=Date.now()+1e3*(a??7776e3);if(!this.tokenState)throw new Qs(zs.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:`${js}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Qs(zs.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[qs]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const a=Date.now();this.tokenState={token:e,issuedAt:a,expiresAt:n};const s=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),r=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(s&&r){const e=Number(r);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=s,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 Ys(e,t,n,a){try{return await e()}catch(e){throw a?(a(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Jt(e,t,n))}}class Zs{constructor(e,t,n,a=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new vn({debug:a,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 Qs(zs.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 Ys(async()=>{const e=Date.now(),t=`${Hs}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),a=this.signatureAuth.getAddress();Ia(a,"address");const s={address:a,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:a,message:t});const r=await this.http.post(oe,s),i=this.extractLoginData(r);return await this.jwtAuth.setTokens(i.accessToken,i.expiresIn,i.refreshToken,i.refreshExpiresIn),this.logger.debug("Login successful",{address:i.address,expiresIn:i.expiresIn,hasRefreshToken:!!i.refreshToken}),i},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,`Login failed: ${Pt(e)}`,Ut(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 Qs(zs.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 Ys(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(le,{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(le,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,`Token refresh failed: ${Pt(e)}`,Ut(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(ce,{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): ${Pt(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 Qs(zs.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Ys(async()=>{const e=await this.http.get(de,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,`Failed to get session: ${Pt(e)}`,Ut(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 Qs(zs.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: ${Pt(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 Qs(zs.SIGNATURE_FAILED,""!==Pt(e)?Pt(e):"Authentication failed");const t=cn(e,"No data in authentication response"),{accessToken:n,expiresIn:a,address:s,refreshToken:r,refreshExpiresIn:i}=t;if(!aa(n))throw new Qs(zs.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof a||a<=0)throw new Qs(zs.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:a,address:s,...void 0!==r&&{refreshToken:r},...void 0!==i&&{refreshExpiresIn:i}}}extractSessionData(e){if(e.error)throw new Qs(zs.SIGNATURE_FAILED,""!==Pt(e)?Pt(e):"Failed to get session");return cn(e,"No data in session response")}}class er 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"}(Xs||(Xs={}));class tr{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new n(e)}catch(e){throw new er("Invalid private key provided",Xs.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new tr(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new er("Failed to sign message",Xs.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 er("Failed to sign typed data",Xs.SIGNING_FAILED,e instanceof Error?e:void 0)}}getAddress(){return Promise.resolve(t(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 nr{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{ta(e.messagePrefix,"messagePrefix",!1)}catch{throw new Qs(zs.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=tr.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Ta(this.wallet.address)}catch(e){if(e instanceof Qs)throw e;if(e instanceof xt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Qs(zs.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Qs(zs.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Qs(zs.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Qs(zs.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=tr.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Ta(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 Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,"Failed to generate signature for authentication",Ut(e)?e:new Error(Pt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Qs(zs.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 Qs(zs.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new Qs(zs.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 Qs(zs.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 Qs(zs.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Qs(zs.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Ut(e)?e:void 0)}}formatAddress(e){try{return Ta(e)}catch{throw new Qs(zs.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 Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,Pt(e),Ut(e)?e:new Error(Pt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),a=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,s=await this.walletProvider.signMessage(a);return{"x-signature":s,"x-address":await this.walletProvider.getGalaAddress(),"x-message":a,"x-timestamp":n.toString()}}catch(e){if(e instanceof Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,"Failed to generate authentication headers",Ut(e)?e:new Error(Pt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const a={};for(const[e,n]of Object.entries(t))a[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,a,n)}catch(e){if(e instanceof Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,"Failed to sign typed data",Ut(e)?e:new Error(Pt(e)))}}async generateCustomSignature(e){if(!aa(e))throw new Qs(zs.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 Qs)throw e;throw new Qs(zs.SIGNATURE_FAILED,"Failed to generate custom message signature",Ut(e)?e:new Error(Pt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Qs(zs.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Qs(zs.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Qs(zs.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ar={prod:{bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",gatewayBaseUrl:"https://gateway-mainnet.galachain.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{bundleBaseUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadBaseUrl:"https://lpad-backend.stage.defi.ovh.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",gatewayBaseUrl:"https://gateway-testnet.galachain.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function sr(e){return ar[e]}function rr(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function ir(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const or=1,cr=2,lr=1002,dr=1,ur=3,hr=[{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}],gr=[{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 mr(e){return"prod"===e?hr:gr}function pr(e){return"prod"===e?"0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9":"0x6a1734E09f3099a3675645D214ce547080ea67e0"}const fr=hr,yr=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],vr={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"}},kr=["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)"],br=["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"],wr={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 Ar(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Sr(e){const t=new Map;for(const n of e)t.set(pn(n.symbol),n);return t}function Er(e,t,n){const a=function(e,t){return e.get(pn(t))}(e,t);if(!a){throw Xt(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return a}function Tr(e){if(null==e||!Ar(e))throw Vt("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function Cr(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function Nr(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function Ir(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function Dr(e,t,n){const a=e.find(e=>e.symbol===t);if(!a){const a=e.map(e=>e.symbol).join(", ");throw jt("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${a}`)}return a}const _r={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function Rr(e,t,n){if(void 0===e)throw Xt(n??_r[t],`${t.toLowerCase()}Strategy`);return e}function xr(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 Fr="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",Br="Bridge request ID missing from RequestTokenBridgeOut response",Or="BridgeTokenOut response missing transaction hash";function Ur(e){if(void 0===e||""===e)throw Xt(Fr,"tokenSymbol");return e}function Pr(e,t){if(!a(e)){throw Vt(t??"address","a valid 0x-prefixed Ethereum address",e)}}function Mr(e,t){try{return new v(e)}catch{throw Vt(t??"address","a valid Solana address (base58)",e)}}function Lr(e){try{return new v(e)}catch{throw Vt("address","a valid Solana address (base58)",e)}}function $r(e){const t={};for(const[n,a]of Object.entries(e))void 0!==a&&(a&&"object"==typeof a&&!Array.isArray(a)?t[n]=$r(a):t[n]=a);return t}function Kr(e,t){const n=Hn(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}let Gr=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{Gr=N}catch{}function Wr(){if(void 0!==Gr?.randomUUID)try{return Gr.randomUUID()}catch{}if(void 0!==globalThis.crypto&&"function"==typeof globalThis.crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const Hr={name:"GalaConnect",chainId:1},qr=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],jr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Vr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],zr=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Xr={GalaTransaction:qr,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:jr,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:Vr,externalQuoteToken:zr,tokenInstance:Vr},Qr={GalaTransaction:qr,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:jr,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:zr,externalQuoteToken:zr,externalCrossRateToken:zr,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:Vr,tokenInstance:Vr};async function Jr(e,t){const{wallet:n}=t,a=e.uniqueKey??`galaconnect-operation-${Wr()}`,s="string"==typeof e.destinationChainId?jn(e.destinationChainId,1):e.destinationChainId,r=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?jn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?jn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?jn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?jn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?jn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?jn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),i=Boolean(r.galaExchangeCrossRate),o={destinationChainId:s,destinationChainTxFee:$r(i?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:a},c=function(e){return e?Qr:Xr}(i),l=await n.signTypedData(Hr,c,o),d=`Ethereum Signed Message:\n${C({domain:Hr,message:o,primaryType:"GalaTransaction",types:c}).length}`;return{...o,signature:l,prefix:d,types:c,domain:Hr}}async function Yr(e,t){const{amount:n,recipientAddress:a,tokenSymbol:s}=e,{galaConnectClient:r,tokenMetadataResolver:i,ethereumWallet:o,destinationChainId:c,destinationChain:l,validateRecipientAddress:d}=t,u=Ur(s);Kr(n,u),d(a,"recipient");const h=await i.getTokenMetadata(u),g=await r.fetchBridgeFee({chainId:l,bridgeToken:h.descriptor}),m=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:a,tokenDescriptor:h.descriptor}),p=await Jr(m,{wallet:o}),f=function(e){if(void 0===e||""===e)throw Xt(Br,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;const t=e.data;if(null!=t){if("string"==typeof t)return t;if("object"==typeof t){const e=t;if("string"==typeof e.Data)return e.Data}}}(await r.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 Xt(Or,"transactionHash");return t}(await r.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:f})),tokenSymbol:u,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:r.getBaseUrl()})}var Zr;!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"}(Zr||(Zr={}));const ei={COMPLETED:Zr.COMPLETED,FAILED:Zr.FAILED,DELIVERY_FAILED:Zr.DELIVERY_FAILED};class ti{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw Zt("requestsPerSecond","1",e,"Requests per second");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const a=new Promise((e,a)=>{t=e,n=a});if(this.pendingPromise=this.pendingPromise.then(async()=>{const a=Date.now()-this.lastTimestamp,s=Math.max(0,this.minIntervalMs-a);s>0&&await new Promise(e=>setTimeout(e,s)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(Ut(e)?e:new Error(Pt(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return a}}const ni={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},ai=new Set([408,429,500,502,503,504]),si=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function ri(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return ai.has(t.status);if("number"==typeof t.statusCode)return ai.has(t.statusCode);const n=Lt(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=Pt(e);return si.some(e=>e.test(t))}function ii(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),a=Math.min(n,t.maxDelayMs),s=a*t.jitterFactor*Math.random();return Math.floor(a+s)}function oi(e){return new Promise(t=>setTimeout(t,e))}function ci(e,t){return Rr(e.get("Ethereum"),"Ethereum",t)}function li(e,t){return Rr(e.get("Solana"),"Solana",t)}function di(e,t){return e??t.getWalletAddress()}async function ui(e,t,n,a,s){const r=await t.getTokenMetadata(a);return function(e){const t="string"==typeof e.timestamp?jn(e.timestamp,0):e.timestamp;return{estimatedFeeInGala:e.estimatedTotalTxFeeInGala,estimatedFeeInExternalToken:e.estimatedTotalTxFeeInExternalToken,feeToken:e.bridgeToken,pricePerUnit:e.estimatedPricePerTxFeeUnit,estimatedGasUnits:e.estimatedTxFeeUnitsTotal,exchangeRate:e.galaExchangeRate?.exchangeRate??"0",timestamp:t,raw:e}}(await e.fetchBridgeFee({chainId:n,bridgeToken:r.descriptor}))}async function hi(e,t){return function(e){const t=jn(e.status,0);return{status:t,statusDescription:e.statusDescription,fromChain:e.fromChain,toChain:e.toChain,quantity:e.quantity,transactionHash:e.emitterTransactionHash,tokenInstance:e.tokenInstance,isComplete:t===Number(ei.COMPLETED),isFailed:t===Number(ei.FAILED)||t===Number(ei.DELIVERY_FAILED)}}(await e.getBridgeStatus(t))}function gi(e,t){if(!aa(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function mi(e,t,n,a){const s=e?.split?.(t)??[],r=void 0!==n?` (${n})`:"";return new xt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${s.length} parts)${r}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${s.map(e=>`"${e}"`).join(", ")}]. Error: ${Pt(a)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function pi(e,t,n){try{const n=gi(e,t),a=n[n.length-1],s=n[n.length-2],r=n[n.length-3],i=n.slice(0,n.length-3).join(t);if(void 0===i||void 0===r||void 0===s||void 0===a||""===a||""===i||""===r||""===s)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:i,category:r,type:s,additionalKey:a}}catch(a){throw mi(e,t,n,a)}}function fi(e){if("object"==typeof e&&null!==e)return function(e){if(null===e||"object"!=typeof e)throw new xt("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:a,additionalKey:s}=e;if(!aa(t))throw new xt("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!aa(n))throw new xt("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!aa(a))throw new xt("Token.type must be a non-empty string, got "+typeof a,"token.type","MISSING_OR_INVALID_TYPE");if(!aa(s))throw new xt("Token.additionalKey must be a non-empty string, got "+typeof s,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:a,additionalKey:s}}(e);if(null==e)throw new xt(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new xt("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(ki(e))return yi(e);if(bi(e))return vi(e);throw new xt(`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 yi(e){return function(e,t,n){try{const n=gi(e,t),[a,s,r,...i]=n;if(""===a||""===s||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.join(t);if(void 0===a||void 0===s||void 0===r||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:a,category:s,type:r,additionalKey:o}}catch(a){throw mi(e,t,n,a)}}(e,"|","pipe-delimited token")}function vi(e){return pi(e,"$","dollar-delimited token")}function ki(e){return aa(e)&&e.includes("|")}function bi(e){return"string"==typeof e&&e.includes("$")}function wi(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,a=t.category,s=t.type,r=t.additionalKey;return"string"==typeof n&&"string"==typeof a&&"string"==typeof s&&"string"==typeof r&&n.length>0&&a.length>0&&s.length>0&&r.length>0}function Ai(e){let t;if("string"==typeof e)t=yi(e);else{if(!wi(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:rr(t)}}function Si(e,t){let n;try{n=Vn(e,"amount")}catch(t){throw nn("amount",`${e} (${Pt(t)})`)}if(!n.isFinite())throw nn("amount",e);const a=n.multipliedBy(As(10).pow(t));if(!a.isInteger())throw nn("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(a.toFixed(0))}function Ei(e,t){return As(e.toString()).dividedBy(As(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class Ti{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=fn(e),n=this.cache.get(t);if(n)return n;const a=vr[t];if(void 0!==a)return this.cache.set(t,a),a;const s=await this.fetchFromApi(e);return this.cache.set(t,s),s}hasMetadata(e){const t=fn(e);return this.cache.has(t)||t in vr}clearCache(){this.cache.clear()}async fetchFromApi(e){const t=(await this.galaConnectClient.getBridgeConfigurations(e)).find(t=>fn(t.symbol)===fn(e)&&t.verified);if(!t)throw new Error(`Unable to locate token metadata for ${e}`);return n={collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey},a=t.decimals,s=t.channel,{descriptor:{collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey},decimals:a,...void 0!==s?{channel:s}:{}};var n,a,s}}class Ci 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 Ni="https://dex-api-platform-dex-prod-gala.gala.com",Ii="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Di=12,_i=!0,Ri=3,xi=1e3;class Fi{constructor(e){this.baseUrl=e.baseUrl??Ni,this.galachainBaseUrl=e.galachainBaseUrl??Ii,this.walletAddress=e.walletAddress,this.rateLimiter=new ti(e.requestsPerSecond??Di),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??_i;this.retryOptions=t?{maxRetries:e.maxRetries??Ri,initialDelayMs:e.retryInitialDelayMs??xi,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>ri(e instanceof Ci?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Ys(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?Wn(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new Ci(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof Ci)throw e;throw Jt(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 Ys(async()=>{const a=n.baseUrl??this.baseUrl,s=new URL(e,a),r=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,i=await this.request(s.toString(),{method:"POST",headers:r,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!i.ok){const t=await i.text(),n=500,a=Wn(t,{rawBody:t.slice(0,n)});throw new Ci(i.status,e,a)}const o=await i.text();if(""!==o){const t=function(e){if(kn(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: ${Pt(e)}`}}}(o);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${String(t.error)}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t)=>{if(e instanceof Ci)throw e;throw Jt(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 a=await fetch(e,{...t,headers:n});if(this.retryOptions&&!a.ok){const t=a.status;if(429===t||t>=500){const n=a.clone(),s=await this.safeParseJson(n);throw new Ci(t,e,s)}}return a});return this.retryOptions?async function(e,t={}){const n={...ni,...t},a=t.shouldRetry??(e=>ri(e));let s;for(let r=1;r<=n.maxRetries+1;r++)try{return await e()}catch(e){if(s=e,r>n.maxRetries)break;if(!a(e,r))break;const i=ii(r,n);t.onRetry&&t.onRetry(e,r,i),await new Promise(e=>setTimeout(e,i))}throw s}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}class Bi{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:a=27e5,onStatusUpdate:s}=t,r=Date.now();for(;;){const t=await this.getStatus(e);if(s&&s(t),t.status===Zr.COMPLETED||t.status===Zr.FAILED||t.status===Zr.DELIVERY_FAILED)return t;if(En(r)>a)throw Qt(`Bridge transaction timed out after ${a}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class Oi extends Bi{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return hi(this.galaConnectClient,e)}getSupportedTokens(){return e=this.tokenConfigs,Array.from(e.keys());var e}isTokenSupported(e){return function(e,t){return e.has(pn(t))}(this.tokenConfigs,e)}}async function Ui(e,t,...n){const a=e[t];return"function"==typeof a?await a(...n):await e.getFunction(t)(...n)}class Pi extends Oi{constructor(e){const t=e.tokenConfigs??fr;super(e.galaConnectClient,Sr(t)),this.network="Ethereum",this.galaChainWalletAddress=e.galaChainWalletAddress,Tr(e.ethereumPrivateKey);const a=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new s(a),this.ethereumWallet=new n(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2",this.tokenMetadataResolver=new Ti({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return ui(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return Yr(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:cr,destinationChain:"Ethereum",validateRecipientAddress:Pr})}async bridgeIn(e){const{amount:a,sourcePrivateKey:s,recipientAddress:i,tokenSymbol:o}=e,c=Ur(o);if(Kr(a,c),void 0!==s&&""!==s&&!Ar(s))throw Vt("sourcePrivateKey","0x-prefixed 64-character hex string",s.slice(0,10)+"...");const l=void 0!==s&&""!==s?new n(s,this.ethereumProvider):this.ethereumWallet,d=Er(this.tokenConfigs,c,"Ethereum bridge"),u=await this.tokenMetadataResolver.getTokenMetadata(c),h=new r(d.contractAddress,kr,l),g=await Ui(h,"decimals"),m=jn("string"==typeof g||"number"==typeof g||"bigint"==typeof g?g:void 0,18),p=Si(a,m),f=await Ui(h,"balanceOf",l.address);if("bigint"!=typeof f)throw new Error("Ethereum balance response was not a bigint");const y=f;if(y<p){throw Xt(`Insufficient ${c} balance on Ethereum. Needed ${Ei(p,m)}, have ${Ei(y,m)}`,"amount")}const v=function(e){const n=new Aa;if("client"===n.detectFormat(e))return e;const a=n.normalizeInput(e);if(null==a)throw Vt("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const s=n.extractHex(a);return`eth|${t("0x"+s).slice(2)}`}(i??this.galaChainWalletAddress);return xr({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:l,tokenContract:h,tokenConfig:d,amountBaseUnits:p,decimals:m,recipient:v,metadata:u})).txHash,tokenSymbol:c,amount:a,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){return na.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=Er(this.tokenConfigs,e,"Ethereum"),a=t??this.ethereumWalletAddress;Pr(a);const s=new r(n.contractAddress,kr,this.ethereumProvider),i=await Ui(s,"balanceOf",a);if("bigint"!=typeof i)throw new Error("Ethereum balance response was not a bigint");return Ei(i,n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;Pr(t);return Ei(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 Vt("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>=Pi.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: ${Pt(e)}`}}}async executeBridgeDeposit(e){const t=new r(this.ethereumBridgeContract,br,e.wallet),n=(new TextEncoder).encode(e.recipient);let a;a=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 a.wait())throw Xt("Bridge transaction receipt not available","ethereumRpcUrl");await oi(3e4);const s={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:Ei(e.amountBaseUnits,e.decimals),tokenInstance:s,fromChain:"Ethereum",toChain:"GC",hash:a.hash}),{txHash:a.hash}}async bridgeWithPermit(e,t,n,a,s,r){const o=await this.ethereumProvider.getNetwork(),c=await Ui(t,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,d=await Ui(t,"nonces",e.address);if("bigint"!=typeof d)throw new Error("Ethereum token nonce response was not a bigint");const u=d,h=BigInt(Math.floor(Date.now()/1e3)+3600),g=await e.signTypedData({name:l,version:"1",chainId:jn(o.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:s,nonce:u,deadline:h}),m=i.from(g);return await Ui(a,"bridgeOutWithPermit",n.contractAddress,s,or,r,h,m.v,m.r,m.s)}async bridgeWithApproval(e,t,n,a,s,r){const i=await Ui(t,"allowance",e.address,this.ethereumBridgeContract);if("bigint"!=typeof i)throw new Error("Ethereum allowance response was not a bigint");if(BigInt(i)<s){const e=await Ui(t,"approve",this.ethereumBridgeContract,s);await e.wait()}return await Ui(n,"bridgeOut",a.contractAddress,s,0,or,r)}}Pi.ETHEREUM_FINALITY_THRESHOLD=12;function Mi(e,t,n,a,s){const[r]=v.findProgramAddressSync([t.toBuffer(),a.toBuffer(),e.toBuffer()],s);return r}class Li extends Oi{constructor(e){const t=e.tokenConfigs??yr;super(e.galaConnectClient,Sr(t)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=e.galaChainWalletAddress,Tr(e.ethereumPrivateKey);const a=new s("https://ethereum.publicnode.com");this.ethereumWallet=new n(e.ethereumPrivateKey,a);const r=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let i;this.solanaConnection=new k(r,"confirmed");try{i=R.decode(e.solanaPrivateKeyBase58)}catch{throw Vt("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw Vt("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=b.fromSecretKey(i);const o=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new v(o),[this.solanaBridgeTokenAuthority]=v.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=v.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=v.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new Ti({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return ui(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return Yr(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:lr,destinationChain:"Solana",validateRecipientAddress:Mr})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:a,tokenSymbol:s}=e,r=Ur(s);Kr(t,r);let i=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=R.decode(n)}catch{throw Vt("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Vt("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);i=b.fromSecretKey(e)}const o=Er(this.tokenConfigs,r,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(r),l=Si(t,c.decimals),d=a??this.galaChainWalletAddress;return xr({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:i,tokenConfig:o,metadata:c,amountBaseUnits:l,recipient:d,amount:t}),tokenSymbol:r,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}isValidAddress(e){try{return new v(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=Er(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const a=t??this.solanaKeypair.publicKey.toBase58(),s=Lr(a),r=Mi(new v(n.mintAddress),s,0,I,_);try{const e=await async function(e,t,n,a){const s=await e.getAccountInfo(t);if(!s)throw new Error(`could not find account ${t.toBase58()}`);if(!s.owner.equals(a))throw new Error(`account owner mismatch: expected ${a.toBase58()}, got ${s.owner.toBase58()}`);return{amount:D.decode(s.data).amount,decimals:0}}(this.solanaConnection,r,0,I),t=n.decimals??8;return Ei(e.amount,t)}catch(t){if(Ut(t)&&t.message.includes("could not find")){return Ei(0n,n.decimals??8)}throw Xt(`Failed to fetch ${e} balance for ${a}: ${Pt(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=Lr(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Ei(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){Yn(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?Lr(t):this.solanaKeypair.publicKey,a=this.solanaConnection.rpcEndpoint;if(!a.includes("devnet"))throw Xt(`Solana devnet faucet only available on devnet. Current RPC: ${a}. Ensure SDK is configured with environment='stage' for devnet access.`,"solanaRpcUrl");const s=Math.floor(e*T);return await this.solanaConnection.requestAirdrop(n,s)}async getSolanaTransactionStatus(e){if(!aa(e))throw Vt("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Vt("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 v(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),a=n?void 0:await this.getSolanaBridgeAccounts(t),s=n?void 0:Mi(t,e.keypair.publicKey,0,I,_),r=Buffer.from(e.recipient,"utf8"),i=Buffer.alloc(8);i.writeBigUInt64LE(e.amountBaseUnits);const o=Buffer.alloc(4);o.writeUInt32LE(r.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,i,o,r):this.buildTokenBridgeInstruction(e.keypair.publicKey,s,t,a,i,o,r),l=new w;l.add(A.setComputeUnitPrice({microLamports:375e3}),A.setComputeUnitLimit({units:2e5}),c),l.feePayer=e.keypair.publicKey;const d=await this.sendAndConfirmWithFallback(l,e.keypair),u={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:u,fromChain:"Solana",toChain:"GC",hash:d}),d}async sendAndConfirmWithFallback(e,t,n=3){let a=null;for(let s=1;s<=n;s++){try{const r=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=r.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const i=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:i,blockhash:r.blockhash,lastValidBlockHeight:r.lastValidBlockHeight},"confirmed"),i}catch(e){const t=Ut(e)?e.message.toLowerCase():"";if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("expired")))throw e;const r=await this.solanaConnection.getSignatureStatuses([i]);if("confirmed"===r.value[0]?.confirmationStatus||"finalized"===r.value[0]?.confirmationStatus)return i;a=new Error(`Transaction ${i} not confirmed - block height exceeded (attempt ${s}/${n})`)}}catch(e){a=Ut(e)?e:new Error(Pt(e));const t=a.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||s===n)throw a}const r=Math.min(1e3*Math.pow(2,s-1),5e3);await oi(r)}throw a??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,a){const s=Buffer.concat([wr.BRIDGE_OUT_NATIVE,t,n,a]);return new S({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:E.programId,isSigner:!1,isWritable:!1}],data:s})}buildTokenBridgeInstruction(e,t,n,a,s,r,i){const o=Buffer.concat([wr.BRIDGE_OUT,s,r,i]);return new S({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:a.mintLookup,isSigner:!1,isWritable:!1},{pubkey:a.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:a.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:E.programId,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!1}],data:o})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[a]=v.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),s=await this.solanaConnection.getAccountInfo(a,"confirmed");if(!s)throw Xt(`Mint lookup account not found for ${a.toBase58()}`,"solanaBridgeProgram");if(!s.owner.equals(this.solanaBridgeProgramId))throw Xt("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(s.data.length<40)throw Xt("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const r={mintLookup:a,tokenBridge:new v(s.data.slice(8,40)),bridgeTokenAccount:Mi(e,this.solanaBridgeTokenAuthority,0,I,_)};return this.solanaBridgeAccountCache.set(t,r),r}}const $i={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"}},Ki={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};function Gi(e){const t=vr[e];if(void 0===t)throw new xt(`Bridge token ${e} has no explicit GalaChain class key in STATIC_TOKEN_METADATA; a class key cannot be derived from a symbol.`,"symbol","CLASS_KEY_NOT_DERIVABLE_FROM_SYMBOL");return{...t.descriptor}}class Wi{static normalizeGalaChainAddress(e){const t=new Aa;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 a=t.normalizeInput(n);if(!a)throw Xt(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const s=t.extractHex(a);return`eth|${Wi.checksumAddress(s)}`}static checksumAddress(e){const t=e.toLowerCase(),n=ba(o(c(t)));let a="";for(let e=0;e<t.length;e++){const s=t[e],r=n[e];void 0!==s&&void 0!==r&&parseInt(r,16)>=8?a+=s.toUpperCase():a+=s??""}return a}constructor(e){const t=Wi.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"prod",a=ar["stage"===n?"stage":"prod"],s=$i[n],r={galaConnectBaseUrl:e.galaConnectBaseUrl??a.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??a.gatewayBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??s.ethereum,solanaRpcUrl:e.solanaRpcUrl??s.solana,ethereumBridgeContract:e.ethereumBridgeContract??pr(n),solanaBridgeProgram:e.solanaBridgeProgram??Ki.solanaBridgeProgram,rateLimit:e.rateLimit??Ki.rateLimit,pollInterval:e.pollInterval??Ki.pollInterval,pollTimeout:e.pollTimeout??Ki.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...r,solanaPrivateKey:e.solanaPrivateKey}:r,this.galaConnectClient=new Fi({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=mr(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 Pi(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:yr};this.strategies.set("Solana",new Li(e))}}async resolveTokenSymbol(e,t){return Ys(async()=>{if(!this.bridgeableTokenService)throw Xt("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=Ai(e).stringified,a="Ethereum"===t?"ETHEREUM":"SOLANA",s=await this.bridgeableTokenService.getTokenByTokenId(n,a);if(!s){throw Xt([`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('${a}')`," - 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 s.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return Ys(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 Ys(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw Xt(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw Xt(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return Ys(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw Xt(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return Ys(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let a;if(n)try{return await n.getStatus(e)}catch(e){a=Ut(e)?e:new Error(Pt(e))}const s=this.strategies.get("Solana");if(s)try{return await s.getStatus(e)}catch(e){a=Ut(e)?e:new Error(Pt(e))}const r=a?` (last error: ${a.message})`:"";throw Qt(`Unable to get status for transaction ${e}${r}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Ys(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},a=this.strategies.get("Ethereum");if(a)try{return await a.getStatus(e),a.waitForCompletion(e,n)}catch{}const s=this.strategies.get("Solana");if(s)return s.waitForCompletion(e,n);throw Qt(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=mr(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:Gi(e.symbol),externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of yr){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:Gi(e.symbol),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 Ys(async()=>ci(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Ys(async()=>ci(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Ys(async()=>li(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Ys(async()=>li(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Ys(async()=>{const n=ci(this.strategies),a=Dr(mr(this.config.environment),e,"Ethereum"),s=di(t,n);return Nr(a,await n.getEthereumTokenBalance(e,s))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Ys(async()=>{const t=ci(this.strategies),n=di(e,t);return Cr("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Ys(async()=>{const n=li(this.strategies),a=Dr(yr,e,"Solana"),s=di(t,n);return Ir(a,await n.getSolanaTokenBalance(e,s))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Ys(async()=>{const t=li(this.strategies),n=di(e,t);return Cr("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Ys(async()=>li(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Ys(async()=>li(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 Ys(async()=>ci(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 Ys(async()=>{const t=ci(this.strategies),n=di(e,t),a=mr(this.config.environment),[s,...r]=await Promise.all([t.getEthereumNativeBalance(n),...a.map(async e=>Nr(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:Cr("ETH",s,18),tokens:r,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Ys(async()=>{const t=li(this.strategies),n=di(e,t),[a,...s]=await Promise.all([t.getSolanaNativeBalance(n),...yr.map(async e=>Ir(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:Cr("SOL",a,9),tokens:s,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw Xt(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}var Hi,qi;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Hi||(Hi={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(qi||(qi={}));const ji={[Hi.PROCESSED]:qi.COMPLETED,[Hi.COMPLETED]:qi.COMPLETED,[Hi.SUCCESS]:qi.COMPLETED,[Hi.FAILED]:qi.FAILED,[Hi.ERROR]:qi.FAILED,[Hi.PROCESSING]:qi.PROCESSING,[Hi.PENDING]:qi.PENDING},Vi="8.1.0",zi={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Xi(e,t){if("number"!=typeof e||!Number.isInteger(e))throw tn("total","a non-negative integer",e);if(e<0)throw Yt("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw tn("limit","a non-negative integer",t);if(t<0)throw Yt("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function Qi(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function Ji(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const a=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(a),n}function Yi(e,t,n){for(const a of n){const n=t[a];null!=n&&""!==n&&(e[a]=Qi(n))}return e}const Zi="x-api-key";class eo extends fa{constructor(e,t,n,a=!1,s){super(e,a),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=s??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!aa(e))throw jt("tokenName","Token name");const n=mn(e);if(!t.PATTERN.test(n))throw Vt("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!aa(e))throw jt(t,n)}(e,t,n)}validateOptionalString(e,t,n,a){!function(e,t,n,a){if(null!=e){if("string"!=typeof e)throw tn(t,"string",typeof e,n);if(e.length>a)throw en(t,a,e.length,n)}}(e,t,n,a)}validateOptionalNumber(e,t,n,a,s,r,i){!function(e,t,n,a,s){if(null!=e){if("number"!=typeof e)throw tn(t,"number",typeof e,n);if(e<a||e>s)throw Yt(t,a,s,e,n)}}(e,t,n,a,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Sn(e))throw Vt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){ma(e,t,n)}validateStatusFilter(e,t,n="status"){pa(e,t,n)}buildPaginationParams(e,t){return Ji(e,t)}addOptionalFilterParams(e,t,n){return Yi(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,a]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(a.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 Bt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Zi]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Bt("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?{[Zi]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return rn(e,"Backend request failed",!0),cn(e,"No data in backend response")}extractDataOrNull(e){return rn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const a=this.buildEndpoint(t,{tokenName:e}),s=await this.http.post(a,{},this.getAdminHeaders()),r=this.extractData(s);return{enabled:r.enabled,tokenName:r.tokenName??mn(e)}}}class to extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getSettings(){return{settings:(await this.http.get(ht.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(ht.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=ht.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=ht.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(ht.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const no=oa({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function ao(e){return no.includes(e)}function so(e,t,n=!1){const a=t.length;if(Wt(t,()=>{ha(e.description,"description",255)}),t.length>a&&(t[a]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Wt(t,()=>{if(!Array.isArray(e.tokenNames))throw tn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw tn("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;Wt(t,()=>{ga(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class ro extends fa{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),rn(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):ao(e.role)||t.push(`Invalid role. Must be one of: ${no.join(", ")}`),so(e,t),t}(e);if(t.length>0)throw new xt(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 a=await this.http.post(be.CREATE,n,this.getJwtHeaders()),s=this.extractData(a);return this.logger.debug("API key created",{id:s.id,keyPrefix:s.keyPrefix}),s}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>In))throw tn("pageSize",`number between 1 and ${In}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw tn("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=Ji(e,In),n=await this.http.get(be.LIST,t,this.getJwtHeaders()),a=this.extractData(n);return this.logger.debug("Listed API keys",{count:a.apiKeys.length,total:a.pageInfo.totalCount}),a}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=be.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),a=this.extractData(n);return this.logger.debug("Got API key",{id:a.id,keyPrefix:a.keyPrefix}),a}async update(e,t){this.validateApiKeyId(e);const n=function(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||ao(e.role)||t.push(`Invalid role. Must be one of: ${no.join(", ")}`),so(e,t,!0),t}(t);if(n.length>0)throw new xt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const a={};void 0!==t.role&&(a.role=t.role),void 0!==t.description&&(a.description=t.description),void 0!==t.delegateAllTokens&&(a.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(a.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(a.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(a.tokenPermissions=t.tokenPermissions);const s=be.UPDATE.replace(":id",String(e)),r=await this.http.patch(s,a,this.getJwtHeaders()),i=this.extractData(r);return this.logger.debug("Updated API key",{id:i.id,keyPrefix:i.keyPrefix}),i}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=be.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...no]}}const io={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},oo=ia(io);function co(e){if(!aa(e.userAddress))throw jt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!ua(t)&&t.length<=xn.BAN_REASON.MAX_LENGTH))throw new xt(`reason must be at most ${xn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(sa(n)||"number"==typeof n&&n>=Bn&&n<=On))throw new xt(`durationSeconds must be between ${Bn} and ${On} seconds`,"durationSeconds","OUT_OF_RANGE")}class lo extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createBan(e){!function(e){la(e.tokenName,"tokenName",Tn),co(e)}(e);const t=this.buildEndpoint(ue,{tokenName:e.tokenName}),n=uo(e),a=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(a),tokenName:mn(e.tokenName)}}async removeBan(e){!function(e){if(la(e.tokenName,"tokenName",Tn),!aa(e.userAddress))throw jt("userAddress")}(e);const t=this.buildEndpoint(me,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,tokenName:mn(e.tokenName),userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){la(e.tokenName,"tokenName",Tn),ra(0,void 0,In,e.pageSize)}(e);const t=this.buildEndpoint(he,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,In);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getBanStatus(e){!function(e){if(la(e.tokenName,"tokenName",Tn),!aa(e.userAddress))throw jt("userAddress")}(e);const t=this.buildEndpoint(ge,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:mn(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(la(e.tokenName,"tokenName",Tn),void 0!==e.type&&!oo(e.type))throw new xt(`type must be one of: ${Object.values(io).join(", ")}`,"type",It)}(e);const t=this.buildEndpoint(pe,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const a=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(a)}async createGlobalBan(e){!function(e){co(e)}(e);const t=uo(e),n=await this.http.post(fe,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!aa(e.userAddress))throw jt("userAddress")}(e);const t=this.buildEndpoint(ke,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){ra(0,void 0,In,e.pageSize)}(t);const n=this.buildPaginationParams(t,In);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const a=await this.http.get(ye,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!aa(e.userAddress))throw jt("userAddress")}(e);const t=this.buildEndpoint(ve,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},userAddress:e.userAddress.toLowerCase()}}}function uo(e){const t={userAddress:e.userAddress};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}async function ho(e,t={}){const{maxPages:n=1e4,logger:a,pageSize:s=20,concurrency:r=1,startPage:i=1}=t,o=[];let c=i;const l=i+n-1;let d=!0,u=0;if(r<=1)for(;d&&c<=l;){a&&a.debug(`Auto-pagination: fetching page ${c} with limit ${s}`);const t=await e(c,s);if(null==t||!Array.isArray(t.items)){a&&a.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,a&&a.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){a&&a.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(a&&a.debug(`Auto-pagination: using concurrent mode with concurrency=${r}`);d&&c<=l;){const t=[];for(let e=0;e<r&&c+e<=l;e++)t.push(c+e);a&&a.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,s).catch(e=>{const n=e,r=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===r||404===r)return a&&a.debug(`Auto-pagination: page ${t} returned ${r} (end of pagination)`,{statusCode:r}),{items:[],total:0,totalPages:0,page:t,limit:s,hasNext:!1,hasPrevious:!1};throw e})),i=await Promise.all(n);for(const e of i){if(null==e||!Array.isArray(e.items)){a&&a.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){a&&a.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(o.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,a&&a.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&a&&a.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),a&&a.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,total:u}}function go(e){if("string"==typeof e){if(!ki(e))throw new xt(`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=yi(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...yi(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(!wi(e))throw new xt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!wi(e))throw new xt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new xt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function mo(e){return function(e){try{if(!aa(e))throw new Error("Vault address must be a non-empty string");const t=e.split("|")[1];if(""===t||void 0===t)throw new Error("Missing token part after service prefix");const n=t.split("$");return pi((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new xt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Pt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function po(e){return{...mo(e),instance:"0"}}function fo(e){const t=mo(e);if("Token"!==t.collection)throw new xt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}function yo(e){return rr(go(e))}var vo=Object.freeze({__proto__:null,extractTokenSymbolFromVault:fo,isTokenClassKeyStrict:wi,normalizeToTokenInstanceKey:go,normalizeTokenIdToString:yo,parseVaultAddressToTokenClassKey:mo,parseVaultAddressToTokenInstance:po});class ko{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new vn({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const a=Math.min(t,this.getMaxLimit()),s=this.buildApiParams(n),r=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...s,pageSize:a,offset:e}});if(sa(r)||!Array.isArray(r.tokens))throw new xt("Invalid API response: expected { tokens: array }","response","INVALID_RESPONSE");return{items:this.transformApiResponse(r.tokens),rawCount:r.tokens.length}}async autoPaginateFetch(e){return async function(e,t){const{maxLimit:n,logger:a,maxPages:s=1e4}=t,r=[];let i=0,o=!0,c=0;for(;o&&c<s;){a&&a.debug(`Auto-pagination (offset): fetching at offset ${i} with limit ${n}`);const t=await e(i,n);if(null==t||!Array.isArray(t.items)){a&&a.warn("Auto-pagination (offset): received invalid result structure, stopping");break}r.push(...t.items),o=t.rawCount===n,i+=n,c++,a&&a.debug(`Auto-pagination (offset): fetched ${r.length} items so far (hasMore=${String(o)})`)}return c>=s&&a&&a.warn(`Auto-pagination (offset): exceeded maxPages limit of ${s}, stopping`),a&&a.debug(`Auto-pagination (offset): completed with total items: ${r.length}`),r}(async(t,n)=>this.executePaginatedRequest(t,n,e),{maxLimit:this.getMaxLimit(),logger:this.logger})}handleError(e,t){throw Jt(e,t,this.logger)}}class bo extends ya{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return pn(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,a=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));a.set(s,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,a),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 a=this.secondaryIndex.get(e);a||(a=new Map,this.secondaryIndex.set(e,a));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const s=this.normalizeKey(this.extractSecondaryKey(e));a.set(s,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 a={},s={};for(const t of e)a[t]=0;for(const[e,r]of this.primaryIndex){t.push(e),n+=r.size,a[e]=r.size;const i=this.fetchTimestamps.get(e);void 0!==i&&(s[e]=i)}return{networks:t,totalItems:n,itemsByNetwork:a,fetchTimestamps:s}}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 wo=["ETHEREUM","SOLANA"];class Ao extends bo{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(wo);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class So extends ko{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new Ao(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),a=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),s={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:a};return void 0!==t?.contractAddress&&(s.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(s.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(s.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(s.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(s.solanaSymbol=n.symbol),void 0!==e.image&&(s.image=e.image),void 0!==e.description&&(s.description=e.description),s})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:a=this.getDefaultLimit()}=e,s=Math.min(a,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${s})`),Ys(async()=>{const e=(await this.executePaginatedRequest(n,s,{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 Ys(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:a,logger:s,itemTypeName:r="items"}=e;if(n.has(t)){const e=n.getAll(t);return s&&s.debug(`Returning ${e.length} cached ${r} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}s&&s.debug(`Fetching all ${r} for ${t} (no cache)`);const i=await a();return n.set(t,i),{items:i,fetchedAt:Date.now(),itemCount:i.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,a=yo(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const s=this.cache.getByTokenId(n,a),r=void 0!==s,i=r?"ETHEREUM"===n?s.ethereumContractAddress:s.solanaContractAddress:void 0,o={isBridgeable:r,network:n};return void 0!==s?.symbol&&(o.tokenSymbol=s.symbol),void 0!==i&&(o.contractAddress=i),o}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 Eo(e){return{maxAcceptableReverseBondingCurveFee:Qn(e.maxAcceptableReverseBondingCurveFee)}}const To={BuyNativeDto:class extends x{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Qn(t),this.expectedToken=Jn(n),this.extraFees=Eo(a)}},BuyExactDto:class extends x{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Jn(t),this.expectedNativeToken=Qn(n),this.extraFees=Eo(a)}},SellExactDto:class extends x{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Jn(t),this.expectedNativeToken=Qn(n),this.extraFees=Eo(a)}},SellNativeDto:class extends x{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Qn(t),this.expectedToken=Jn(n),this.extraFees=Eo(a)}}};function Co(e,t,n){let a;Yn(t,0,1,"slippageToleranceFactor");try{a=Vn(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const s=a.multipliedBy(t);let r;switch(n){case"buy-native":case"sell-exact":r=a.minus(s);break;case"buy-exact":case"sell-native":r=a.plus(s);break;default:throw new Error(`Unknown operation type: ${n}`)}return As(r).isLessThan(0)&&(r=As(0)),Ss(r)}function No(e){return`${e}-${Date.now()}_${B().replace(/-/gu,"").substring(0,26)}`}function Io(){return No("galaconnect-operation")}const Do={name:"GalaChain"},_o={name:"ethereum",chainId:1};function Ro(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function xo(e){const t={};for(const[n,a]of Object.entries(e))void 0!==a&&(t[n]=Fo(a));return t}function Fo(e){return Array.isArray(e)?e.map(Fo):"object"==typeof e&&null!==e?xo(e):e}function Bo(e,t,n,a){return{...e,signature:t,types:n,domain:a}}class Oo extends f{constructor(e){super(e),this.typedDataWallet=new n(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=xo(t),a=m(e,n);return Bo(n,await this.typedDataWallet.signTypedData(Do,a,n),a,Do)}}class Uo extends p{async signTypedData(e,t){const n=xo(t),a=m(e,n),s={domain:_o,types:a,message:n,Primary_type:e},r=function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();return Bo(n,Ro(await r.request({method:"eth_signTypedData",params:[JSON.stringify(s),await this.typedDataAccount(r)]})),a,_o)}async typedDataAccount(e){if(a(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,s="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!a(s))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return s}}class Po extends g{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(e,n){const s=xo(n),r=this.typedDataProvider,i=await r.getNetwork(),o={name:i.name,chainId:Number(i.chainId)},c=m(e,s),l=await r.getSigner(),d=t(await l.getAddress());if(a(this.walletAddress)&&d!==t(this.walletAddress))throw new Error(`Wallet account ${d} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`);return Bo(s,Ro(await l.signTypedData(o,c,s)),c,o)}}function Mo(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const a=n.split("$"),s=a[a.length-1],r=a.slice(0,-1),i=r.slice(0,-3).join("$"),[o,c,l]=r.slice(-3);if("launchpad"!==s||r.length<4||""===i||void 0===o||void 0===c||void 0===l||""===o||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:i,category:o,type:c,additionalKey:l}}function Lo(e){const{collection:t,category:n,type:a}=Mo(e),s=`${t}$${n}$${a}$none`,r="GALA$Unit$none$none";return[`$service$${s}$launchpad`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${s}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`]}function $o(e){const t=`${e.tokenName}$Unit$none$none`,n=`$service$${t}$launchpad`;return Number(e.preBuyQuantity??"0")>0?[n,`$token$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`]:[n,`token$${t}$${n}`,`tokenBalance$${t}$${n}`]}class Ko extends ya{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Lo(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Pt(e);throw new xt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new F;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(!aa(e))throw jt("vaultAddress","Vault address");try{const t=fo(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof xt)throw Vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!aa(e))throw jt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Vt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Vt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!aa(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],a=t[2];return void 0===n||void 0===a?null:{tokenSymbol:n,creatorAddress:a.toLowerCase()}}(e);if(!t)throw Vt("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 Vt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,a){return`${e}$${t}$${n}$${a}`}parseTokenClassKeyString(e){try{return vi(e)}catch(e){if(e instanceof xt)throw Vt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Go(e){return"object"==typeof e&&null!==e?e:void 0}class Wo extends fa{constructor(e,t,n=!1,a,s,r=.05,i=.01,o){if(super(e,n),this.tokenResolver=t,this._walletProvider=a,this.userAddress=s,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.sellFeeCeiling=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=Go(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Oo(t):function(e){const t=Go(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new Po(this._walletProvider,this.userAddress)),this.tokenKeyService=new Ko(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 dn(()=>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:sn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof xt)return{success:!1,error:Pt(e)};throw e}}validateBundleData(e){if(null==e)throw jt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw jt("signedDto","Signed DTO");if(!aa(e.method))throw jt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Vt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new xt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Vt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!aa(e))throw new xt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!bi(e))throw new xt(`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=on(e);if(null!=t&&!1===e.error)return this.logger.debug("✅ Bundle transaction successful:",t),{success:!0,data:t};const n=("string"==typeof e.error?e.error:e.message)??"Bundle transaction failed";return this.logger.debug("❌ Bundle transaction failed:",n),{success:!1,error:n}}formatErrorMessage(e){if("string"==typeof e)return e;if($t(e)&&null!==e.response&&void 0!==e.response){const t=on(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 Pt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!aa(e))throw jt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await dn(()=>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 xt)return{success:!1,error:Pt(e)};throw e}}async cancelTransaction(e){try{if(!aa(e))throw jt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await dn(()=>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 xt)return{success:!1,error:Pt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await dn(()=>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:a,expectedAmount:s}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===a){if(null==s||""===s)throw new xt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(s,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:s,slippageFactor:r,adjustedMinTokens:e});const t=new To.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==s||""===s)throw new xt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(s,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:s,slippageFactor:r,adjustedMaxGalaCost:e});const t=new To.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:a,expectedAmount:s}=e,{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,o):i;if("exact"===a){if(null==s||""===s)throw new xt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(s,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:s,slippageFactor:r,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},a=new To.SellExactDto(o,n,e,t);return await this.executeBundleTransaction(a,"SellExactToken",o)}{if(null==s||""===s)throw new xt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Co(s,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:s,slippageFactor:r,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},a=new To.SellNativeDto(o,n,e,t);return await this.executeBundleTransaction(a,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,a){const{effectiveSlippageFactor:s,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,n,a),i=await this.resolveTokenNameToVault(e);if(null==i)throw qt(e);return{effectiveSlippageFactor:s,effectiveMaxFee:r,vaultAddress:i}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw Xt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const a=n??this.defaultSlippageToleranceFactor,s=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e??"0";return null!=e&&(r=Co(e,s,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:s,adjustedMaxFee:r})),{effectiveSlippageFactor:a,effectiveFeeSlippageFactor:s,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Xt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw jt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=No("galaswap-operation");const a=await this.signer.signObject(t,e),s=this.tokenKeyService.generateStringsInstructions(n),r={stringsInstructions:s,method:t,signedDto:a};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:s,dtoKeys:Object.keys(a)});const i=await this.submitTransaction(r);if(i.success){const e=on(i);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 o=i.error;throw new Ot("string"==typeof o?o:"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 Ho extends fa{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(St),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var qo,jo,Vo,zo;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(qo||(qo={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(jo||(jo={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Vo||(Vo={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(zo||(zo={})),jo.INAPPROPRIATE_CONTENT,jo.SPAM,jo.HARASSMENT,jo.SCAM,jo.OTHER,Vo.PENDING,Vo.DISMISSED,Vo.ACTIONED,zo.DELETE_CONTENT,zo.BAN_USER,zo.DELETE_AND_BAN,qo.CHAT_MESSAGE,qo.COMMENT,qo.STREAM,qo.RECORDING;const Xo=ia(qo),Qo=ia(jo),Jo=ia(Vo),Yo=ia(zo),Zo={TOKEN_NAME:Cn,CONTENT_ID:xn.CONTENT_ID,DETAILS:xn.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:In}};function ec(e,t="tokenName"){la(e,t,Zo.TOKEN_NAME)}function tc(e){if(void 0!==e.contentType&&!Xo(e.contentType))throw Vt("contentType",`one of: ${Object.values(qo).join(", ")}`,"Content type");if(void 0!==e.status&&!Jo(e.status))throw Vt("status",`one of: ${Object.values(Vo).join(", ")}`);if(void 0!==e.reason&&!Qo(e.reason))throw Vt("reason",`one of: ${Object.values(jo).join(", ")}`);if(void 0!==e.reporterAddress&&!aa(e.reporterAddress))throw tn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&Ia(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!aa(e.reportedUserAddress))throw tn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&Ia(e.reportedUserAddress,"reportedUserAddress"),ra(0,void 0,Zo.PAGINATION.MAX_LIMIT,e.pageSize)}class nc extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createFlag(e){!function(e){if(ec(e.tokenName),void 0===e.contentType)throw jt("contentType","Content type");if(!Xo(e.contentType))throw Vt("contentType",`one of: ${Object.values(qo).join(", ")}`,"Content type");if(!aa(e.contentId))throw jt("contentId","Content ID");if(e.contentId.length>Zo.CONTENT_ID.MAX_LENGTH)throw en("contentId",Zo.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!aa(e.reportedUserAddress))throw jt("reportedUserAddress","Reported user address");if(Ia(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==qo.STREAM&&e.contentType!==qo.RECORDING||void 0!==e.reason&&null!==e.reason))throw jt("reason","Reason");if(void 0!==e.reason&&!Qo(e.reason))throw Vt("reason",`one of: ${Object.values(jo).join(", ")}`,"Reason");if(void 0!==e.details&&!aa(e.details))throw tn("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Zo.DETAILS.MAX_LENGTH)throw en("details",Zo.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(De.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){ec(e.tokenName),tc(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&ec(e.tokenName),tc(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw jt("flagId","Flag ID");try{ea(e.flagId,"flagId")}catch{throw Vt("flagId","a positive integer","Flag ID")}}(e);const t=De.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 jt("flagId","Flag ID");try{ea(e.flagId,"flagId")}catch{throw Vt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw jt("action","Action");if(!Yo(e.action))throw Vt("action",`one of: ${Object.values(zo).join(", ")}`,"Action")}(e);const t=De.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=Ji(e,In);Yi(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(De.LIST,t,this.getMultiAuthHeaders()),a=this.extractData(n);return{items:a.flags,pageInfo:a.pageInfo}}}const ac=["heart","fire","laugh","wow","thumbs_up"];class sc extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateReactionTokenName(e){this.validateTokenName(e,Cn)}validateMessageId(e){if(!aa(e))throw jt("messageId","Message ID");if(Zn(e,Fn.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Fn.CONTENT_REACTION.PATTERN.test(e))throw Vt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!aa(e))throw jt("reactionType","Reaction type");if(!ac.includes(e))throw Vt("reactionType",`one of: ${ac.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=nt,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=mn(e.tokenName));const a=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(a),{created:r,...i}=s;return{data:i,created:r}}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)}}const rc="Token name is required and must be a string";function ic(e){if(!aa(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}class oc extends ya{constructor(e,t,n,a=!1){super(a),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=ca(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 xt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async resolveAuthoritativeSymbol(e,t){if("GALA|Unit|none|none"===t)return"GALA";const n=this.cache?.getByTokenId(t);if(null!=n?.symbol&&""!==n.symbol)return n.symbol;let a;this.logger.debug(`Symbol cache miss for ${t}, fetching from API`);try{a=(await this.fetchTokenDetails(e)).symbol}catch(e){throw zt(`Could not resolve the symbol for ${t} from the token class, and a symbol cannot be derived from the class key: ${Pt(e)}`)}if(""===a)throw zt(`Token class for ${t} has no symbol`);return this.cache?.setByTokenId(t,{symbol:a}),this.logger.debug(`Cached symbol for ${t}: ${a}`),a}async _fetchDexTokenSpotPrice(e){if(null==e)throw jt("tokenId","Token ID");try{const t=rr(go(e)),n=ic(t);if(this.logger.debug(`Fetching DEX spot price for token: ${n}`),!this.dexBackendHttp)throw zt("DEX Backend API client not configured");const a=t,s=await this.resolveAuthoritativeSymbol(e,a),r=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:n}}),i=null!==r&&"object"==typeof r?r:{},o=Object.keys(i).find(e=>e.toUpperCase()===s.toUpperCase()),c=void 0!==o?i[o]:1===Object.keys(i).length?Object.values(i)[0]:void 0,l=c?.price;if("number"!=typeof l||!Number.isFinite(l))throw new xt(`Invalid price response: no market price for ${n}`,"data","INVALID_RESPONSE");return this.logger.debug(`DEX spot price for ${s}: $${l}`),{symbol:s,price:l}}catch(e){if(e instanceof xt)throw e;throw zt(`Failed to fetch DEX spot price: ${Pt(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!aa(e))throw new xt(rc,"tokenName",Ct);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=rr(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Pt(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const a=await t({tokenName:e,amount:"1",type:"native"}),s=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==s)throw zt("GALA price not available");const r=Hn(a.amount,0)/1e18;if(r<=0)throw new xt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const i=s.price/r;return{symbol:fn(e),price:i}}catch(t){if(Ut(t))throw zt(`Failed to calculate launchpad token spot price for ${e}: ${Pt(t)}`);throw zt(`Failed to calculate launchpad token spot price for ${e}: ${Pt(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw zt("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 xt||Ut(t))&&("NetworkError"===t.name||Pt(t).includes("Token not found")))throw t;throw zt(`Failed to fetch token details from GalaChain for ${String(e)}: ${Pt(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw zt("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=on(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:An(t?.start??null),end:An(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(Ut(e)&&Pt(e).includes("not configured"))throw e;if($t(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw zt(`Failed to fetch DEX seasons: ${Pt(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{ea(e,"seasonId")}catch{throw jt("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw zt("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 a=on(t);if(null!=a&&"object"==typeof a&&Array.isArray(a.leaderboard))n=a.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(a))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=a}}}const a=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 ${a.length} entries`),{entries:a,seasonId:e,totalEntries:a.length}}catch(t){if(Ut(t)&&Pt(t).includes("must be a positive number"))throw t;throw zt(`Failed to fetch DEX leaderboard for season ${e}: ${Pt(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 zt("DEX Backend API client not configured");const e=on(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw zt("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 zt(`Failed to fetch DEX volume summary: ${Pt(e)}`)}}}const cc=20,lc=3e3,dc=1e3,uc=!0,hc=!0,gc=!1,mc={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 pc{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 vn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??cc,flushIntervalMs:t.flushIntervalMs??lc,maxQueueSize:t.maxQueueSize??dc,flushOnPageHide:t.flushOnPageHide??uc,flushOnPageUnload:t.flushOnPageUnload??hc,debug:t.debug??gc},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const a={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(a),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 fc(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>O(e).plus(t.quantity).toString(),"0")}function yc(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 vc extends fa{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(bi(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`,a=await this.http.post(n,e);if(null==a)return null;try{Kt(a,"Fetch balances")}catch{return null}if(0===(a.Data?.length??0))return null;const s=a.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!s||"0"===s.quantity)return null;const r=rr(s),i={quantity:s.quantity,collection:s.collection,category:s.category,tokenId:r};if((s.inUseHolds?.length??0)>0){const e=yc(s.inUseHolds??[],t);e.length>0&&(i.inUseHolds=e,i.inUseQuantity=fc(e))}if((s.lockedHolds?.length??0)>0){const e=yc(s.lockedHolds??[],t);e.length>0&&(i.lockedHolds=e,i.lockedQuantity=fc(e))}return void 0===i.lockedQuantity&&void 0===i.inUseQuantity||(i.availableQuantity=function(e,t="0",n="0"){return O(e).minus(t).minus(n).toString()}(i.quantity,i.lockedQuantity,i.inUseQuantity)),i}catch(e){throw zt(`Failed to fetch token balance from GalaChain: ${Pt(e)}`,void 0,Ut(e)?e:void 0)}}}function kc(e){return"string"==typeof e?{...vi(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function bc(e){return ir(e)}function wc(e){const t=e[0];return void 0===t?void 0:bc(t.tokenInstanceKey)}class Ac extends x{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),void 0!==e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a,s){const r=kc(a);return new Ac({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:r}],...void 0!==s?.expires&&{expires:s.expires},...void 0!==s?.name&&{name:s.name},uniqueKey:s?.uniqueKey??Io()})}static forGALA(e,t,n,a){return new Ac({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==a?.expires&&{expires:a.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:a?.uniqueKey??Io()})}getTokenClassKey(){return wc(this.tokenInstances)}toSigningPayload(){return{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Sc extends x{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a){const s=kc(n);return new Sc({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:s}],...void 0!==a?.name&&{name:a.name},uniqueKey:a?.uniqueKey??Io()})}static forGALA(e,t,n){return new Sc({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??Io()})}getTokenClassKey(){return wc(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function Ec(e){if(null==e||"object"!=typeof e)return!1;const t=e;return aa(t.amount)&&(void 0!==t.tokenId||aa(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 aa(t.amount)&&(void 0!==t.tokenId||aa(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Cc,Nc;!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"}(Cc||(Cc={}));class Ic 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"}(Nc||(Nc={}));class Dc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function _c(e){const t=e?.tokens?.[0];if(void 0===t)return;const n={};return void 0!==t.tokenName&&(n.tokenName=t.tokenName),void 0!==t.amount&&(n.amount=t.amount),Object.keys(n).length>0?n:void 0}async function Rc(e,t,n,a="[DEBUG] Token resolution (launchpad)"){const s=await t.resolveTokenToVault(e);if(null!==s){const t=po(s);return n.debug(a,{tokenName:e,vaultAddress:s,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new xt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}const xc=100,Fc=100;class Bc extends fa{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new Oo(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new Ic("Wallet required for token lock operations",Cc.WALLET_REQUIRED);return Ys(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),a=[];let s=t;const r=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==r?.lockAuthority&&(s=Ta(r.lockAuthority));const i=e.tokens.find(e=>void 0!==e.expires),o=e.tokens.find(e=>void 0!==e.name);for(const r of e.tokens){const e=await this.resolveTokenEntry(r);n.push({owner:t,quantity:r.amount,tokenInstanceKey:e}),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:r.amount,lockAuthority:void 0!==r.lockAuthority?Ta(r.lockAuthority):s})}const c=new Ac({lockAuthority:s,tokenInstances:n,...void 0!==i?.expires&&{expires:i.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:e.uniqueKey??Io()}),l=await this.nativeSigner.signObject("LockToken",c.toSigningPayload()),d=new Ac({...c.toSigningPayload(),signedPayload:l}),u=await this.http.post("/api/asset/token-contract/LockToken",d);try{Kt(u,"Token lock failed")}catch(e){const t=Gt(u);throw new Ic(`${Pt(e)}${t}`,Cc.NETWORK_ERROR)}return this.extractLockResult(u,a)},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.nativeSigner)throw new Ic("Wallet required for token unlock operations",Cc.WALLET_REQUIRED);return Ys(async()=>{const{ownerAddress:t,tokenInstances:n}=this.createTokenOperationContext(),a=[],s=e.tokens.find(e=>void 0!==e.name);for(const s of e.tokens){const e=await this.resolveTokenEntry(s);n.push({owner:t,quantity:s.amount,tokenInstanceKey:e}),a.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:s.amount})}const r=new Sc({tokenInstances:n,...void 0!==s?.name&&{name:s.name},uniqueKey:e.uniqueKey??Io()}),i=await this.nativeSigner.signObject("UnlockToken",r.toSigningPayload()),o=new Sc({...r.toSigningPayload(),signedPayload:i}),c=await this.http.post("/api/asset/token-contract/UnlockToken",o);try{Kt(c,"Token unlock failed")}catch(e){const t=Gt(c);throw new Ic(`${Pt(e)}${t}`,Cc.NETWORK_ERROR)}return this.extractUnlockResult(c,a)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Ic("Must provide either tokenId or tokenName for token identification",Cc.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{da(e.tokenName,"tokenName")}catch{throw new Ic("Invalid token name format",Cc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Cs(As(e.amount))}catch{throw new Ic(Vt(t,"a positive number",n).message,Cc.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!function(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)}(e))throw new Ic("Invalid lock data: missing required fields",Cc.VALIDATION_ERROR);if(e.tokens.length>xc)throw new Ic(`Batch size exceeds maximum limit of ${xc} tokens per lock operation`,Cc.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!Na(t.lockAuthority))throw new Ic("Invalid lock authority address format",Cc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{ea(t.expires,"expires")}catch{throw new Ic(Vt("expires","a positive integer (epoch milliseconds)","Expires").message,Cc.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!function(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)}(e))throw new Ic("Invalid unlock data: missing required fields",Cc.VALIDATION_ERROR);if(e.tokens.length>Fc)throw new Ic(`Batch size exceeds maximum limit of ${Fc} tokens per unlock operation`,Cc.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}extractLockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{locked:t};n=a.transactionId??a.txnId??a.TxnId??a.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 a=e.Data[0];if(void 0===a)return{unlocked:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof Ic)return e;let a=t,s=Cc.NETWORK_ERROR;if($t(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(a=`${t}: ${e}`);const r="string"==typeof e?e.toLowerCase():"";r.includes("insufficient")||r.includes("balance")?s=Cc.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?s=Cc.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?s=Cc.TOKEN_NOT_FOUND:r.includes("authority")?s=Cc.NOT_LOCK_AUTHORITY:r.includes("expired")&&(s=Cc.LOCK_EXPIRED)}}else Ut(e)&&(a=`${t}: ${Pt(e)}`);return new Ic(a,s,_c(n))}async resolveTokenInstance(e){return Ys(async()=>Rc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Dc)throw new Ic(Pt(t),Cc.TOKEN_NOT_FOUND);throw new Ic(`Failed to resolve token '${e}': ${Pt(t)}`,Cc.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=go(e.tokenId);return this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),t}if(void 0!==e.tokenName)return this.resolveTokenInstance(e.tokenName);throw new Ic("Must provide either tokenId or tokenName for token identification",Cc.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:Ta(this.wallet.address),tokenInstances:[]}}}class Oc extends fa{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?go(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw jt("publicAxios","Public Axios instance");const a=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(Kt(a,"Failed to fetch token class from GalaChain"),null===a.Data||void 0===a.Data||0===a.Data.length)throw zt(`Token not found on GalaChain: ${rr(t)}`,404);const s=a.Data[0];if(void 0===s)throw zt(`Token not found on GalaChain: ${rr(t)}`,404);return s}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw jt("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw jt("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(Kt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw zt("No token supply data found for requested token classes",404);return n.Data}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}handleTokenServiceError(e,t,n){if(e instanceof xt)throw e;if($t(e)&&404===e.response?.status)throw zt(t,404,Ut(e)?e:void 0);if(Ut(e)&&"Error"===e.name&&Pt(e).includes("status indicates failure"))throw zt(Pt(e),400,Ut(e)?e:void 0);const a=Pt(e);if(a.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(a)}throw zt(`${n}: ${a}`,void 0,Ut(e)?e:void 0)}}class Uc extends x{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokens(e,t){const n=e.map(e=>{const t=kc(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new Uc({tokenInstances:n,uniqueKey:t?.uniqueKey??Io()})}static fromTokenClassKey(e,t,n){return Uc.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new Uc({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??Io()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;const e=this.tokenInstances[0];return void 0!==e?bc(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class Pc extends x{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature)}static fromTokenClassKey(e,t,n,a,s){let r;if("string"==typeof a){r={...vi(a),instance:"0"}}else r={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey,instance:"0"};return new Pc({from:e,to:t,quantity:n,tokenInstance:r,uniqueKey:s??Io()})}static forGALA(e,t,n,a){return new Pc({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:a??Io()})}getTokenClassKey(){return ir(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function Mc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return aa(t.amount)&&(void 0!==t.tokenId||aa(t.tokenName))}var Lc;!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"}(Lc||(Lc={}));class $c extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Kc={validateAmount(e){const t=As(e);try{!function(e,t){if(e.isNaN())throw nn(t,"NaN");if(!e.isFinite())throw en(t,"finite");if(e.isLessThanOrEqualTo(0))throw Zt(t,"0",e.toString())}(t,"amount")}catch(t){throw new Dc(t.message,Nc.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!sa(e)&&aa(e)){if(e.length>Un.MAX_LENGTH)throw new xt(`Unique key too long. Maximum length: ${Un.MAX_LENGTH}`);if(!Un.PATTERN.test(e))throw new Dc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Nc.INVALID_AMOUNT,{uniqueKey:e})}}},Gc="gala-transfer-successful",Wc="token-transfer-successful",Hc="token-locked-successfully",qc="token-unlocked-successfully",jc="transfer-successful-no-id",Vc=50;class zc extends fa{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new Oo(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new Dc("Wallet required for GALA transfer operations",Nc.WALLET_REQUIRED);try{const t=Ta(e.recipientAddress),n=Ta(this.wallet.address),a=Pc.forGALA(n,t,e.amount,e.uniqueKey),s=await this.nativeSigner.signObject("TransferToken",a.toSigningPayload()),r=new Pc({...a.toSigningPayload(),signedPayload:s}),{data:i,headers:o}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",r);if(null==i)throw new Dc("No response from GalaChain transfer service",Nc.NETWORK_ERROR);return this.extractTransferResult(i,o,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.nativeSigner)throw new Dc("Wallet required for token transfer operations",Nc.WALLET_REQUIRED);try{const t=Ta(e.to),n=Ta(this.wallet.address);let a;if(null!==e.tokenId&&void 0!==e.tokenId)a=go(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:a.collection,category:a.category,type:a.type,instance:a.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new Dc("Must provide either tokenId or tokenName for token identification",Nc.TOKEN_NOT_FOUND);a=await this.resolveTokenInstance(e.tokenName)}const s=new Pc({from:n,to:t,quantity:e.amount,tokenInstance:a,uniqueKey:e.uniqueKey??Io()}),r=await this.nativeSigner.signObject("TransferToken",s.toSigningPayload()),i=new Pc({...s.toSigningPayload(),signedPayload:r}),{data:o,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",i);if(null==o)throw new Dc("No response from GalaChain transfer service",Nc.NETWORK_ERROR);return this.extractTransferResult(o,c,"token")}catch(t){throw this.handleTransferError(t,"Token transfer failed",e)}}async resolveTokenClassKey(e){try{const t=await this.tokenResolver.resolveTokenClassKey(e);return this.logger.debug(`[DEBUG] Token class key resolution for '${e}':`,{collection:t.collection,category:t.category,type:t.type}),t}catch(t){if(t instanceof Dc)throw t;throw new Dc(`Failed to resolve token class key for '${e}': ${Pt(t)}`,Nc.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new $c("Wallet required for token burn operations",Lc.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=go(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new $c("Must provide either tokenId or tokenName for token identification",Lc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new Uc({tokenInstances:t,uniqueKey:e.uniqueKey??Io()}),a=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),s=new Uc({...n.toSigningPayload(),signedPayload:a}),r=await this.http.post("/api/asset/token-contract/BurnTokens",s);if(null==r)throw new $c("No response from GalaChain burn service",Lc.NETWORK_ERROR);try{Kt(r,"Token burn operation")}catch(e){throw new Ft(Pt(e),500)}return this.extractBurnResult(r)}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 aa(t.recipientAddress)&&aa(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new xt("Invalid GALA transfer data: missing required fields");if(!Na(e.recipientAddress))throw new Dc("Invalid recipient address format",Nc.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Kc.validateAmount(e.amount),Kc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return aa(t.to)&&aa(t.amount)&&(void 0!==t.tokenId||aa(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new xt("Invalid token transfer data: missing required fields");if(!Na(e.to))throw new Dc("Invalid recipient address format",Nc.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Dc("Must provide either tokenId or tokenName for token identification",Nc.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{da(e.tokenName,"tokenName")}catch{throw new Dc("Invalid token name format",Nc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Kc.validateAmount(e.amount),Kc.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!function(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)}(e))throw new $c("Invalid burn data: missing required fields",Lc.VALIDATION_ERROR);if(e.tokens.length>Vc)throw new $c(`Batch size exceeds maximum limit of ${Vc} tokens per burn operation`,Lc.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 $c("Must provide either tokenId or tokenName for token identification",Lc.TOKEN_NOT_FOUND);const e=As(t.amount);try{Cs(e)}catch{throw new $c("Burn amount must be a positive number",Lc.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await Rc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Dc)throw t;throw new Dc(`Failed to resolve token '${e}': ${Pt(t)}`,Nc.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const a=this.readHeaderValue(t,"x-transaction-id"),s=this.readBlockNumberHeader(t),r=null!=e&&"object"==typeof e&&"Status"in e;r&&Kt(e,"Extract transaction ID");const i=r&&"Data"in e;if(void 0!==a&&a.length>0)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(null!=e&&"object"==typeof e){if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return{transactionId:e.transactionId,...void 0!==s?{blockNumber:s}:{}};if(i){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==s?{blockNumber:s}:{}}}}let e=jc;if(t.Data.length>0)switch(n){case"gala":e=Gc;break;case"token":e=Wc;break;case"lock":e=Hc;break;case"unlock":e=qc}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}}throw new Dc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Nc.NETWORK_ERROR)}readHeaderValue(e,t){const n=e[t.toLowerCase()];if("string"==typeof n&&n.trim().length>0)return n.trim()}readBlockNumberHeader(e){const t=this.readHeaderValue(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}extractBurnResult(e){const t=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const n of e.Data)t.push({collection:n.collection??"",category:n.category??"",type:n.type??"",additionalKey:n.additionalKey??"",instance:n.instance??"0",quantity:n.quantity??"0",burnedBy:n.burnedBy??""});let n;if(null!==e.Data&&void 0!==e.Data&&e.Data.length>0){const a=e.Data[0];if(void 0===a)return{burned:t};n=a.transactionId??a.txnId??a.TxnId??a.id??void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof Dc)return e;if(e instanceof xt)return new Dc(Pt(e),Nc.INVALID_AMOUNT);if($t(e)&&e.response){const t=e.response.status,a=e.response.data;if(400===t){const e=a?.message;return new Dc(("string"==typeof e?e:void 0)??"Invalid transfer request",Nc.INVALID_AMOUNT)}if(403===t)return new Dc("Insufficient balance for transfer",Nc.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Dc("Token not found",Nc.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Lt(e)||"ETIMEDOUT"===Lt(e)))return new Dc("Transfer request timed out",Nc.NETWORK_ERROR);const a=""!==Pt(e)?Pt(e):t;return new Dc(a,Nc.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof $c)return e;let a=t,s=Lc.NETWORK_ERROR;if($t(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){a=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?s=Lc.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(s=Lc.TOKEN_NOT_FOUND)}}}else Ut(e)&&(a=`${t}: ${Pt(e)}`);return new $c(a,s,_c(n))}}class Xc extends fa{constructor(e,t,n,a=!1,s){super(e,a),this.balanceService=new vc(e,a),this.tokenService=new Oc(e,a,s),this.lockService=new Bc(e,t,n,a),this.transferService=new zc(e,t,n,a)}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 Qc(e,t="image",n){const a=new FormData;if("undefined"!=typeof File&&e instanceof File)a.append(t,e);else{if(!Buffer.isBuffer(e))throw Vt("file","a File object (browser) or Buffer (Node.js)");{const s=new Blob([e],{type:"image/png"});a.append(t,s,n)}}return a}class Jc extends fa{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Os(t);const a=`${t}.png`;_s(n.file,a,"image/png");try{const e=`${n.tokenName??t}.png`,a=Qc(n.file,"image",e),s=await ln(()=>this.http.request({method:"POST",url:`${M.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Bt)throw e;if(Ut(e)&&Pt(e).includes("FormData"))throw Xt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const Yc={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};function Zc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class el extends fa{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!sa(e.search)&&{search:e.search},...!sa(e.tokenName)&&{tokenName:e.tokenName},...!sa(e.type)&&{type:e.type},...!sa(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!sa(e.language)&&{language:e.language},...!sa(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!sa(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!sa(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,a={pageSize:String(t)};void 0!==n&&(a.cursor=n),sa(e.type)||(a.type=e.type),sa(e.tokenName)||(a.tokenName=e.tokenName),sa(e.search)||(a.search=e.search),sa(e.hasUpcomingShows)||(a.hasUpcomingShows=e.hasUpcomingShows.toString()),sa(e.language)||(a.language=e.language),sa(e.recentlyStreamed)||(a.recentlyStreamed=e.recentlyStreamed.toString()),sa(e.hasRecordings)||(a.hasRecordings=e.hasRecordings.toString()),sa(e.streamStatus)||(a.streamStatus=e.streamStatus);const s=ws(a),r=on(await un(()=>this.http.get(M.FETCH_POOLS,s),{errorContext:"Failed to fetch pools"})),i=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else 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}(r),o={hasNextPage:r.hasNextPage??r.pageInfo?.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(o.totalCount=c);const l=r.nextCursor??r.pageInfo?.endCursor;null!=l&&(o.nextCursor=l);const d=r.prevCursor??r.pageInfo?.startCursor;null!=d&&(o.prevCursor=d);const u=r.hasPrevPage??r.pageInfo?.hasPreviousPage;return void 0!==u&&(o.hasPrevPage=u),{items:i,pageInfo:o}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??zi.DEFAULT_LIMIT;aa(e?.tokenName)&&Os(e.tokenName);const a=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,s=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,r={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:a,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:s}),pageSize:n,...void 0!==t&&{cursor:t}},i=await this.fetchSinglePage(r);return{items:i.items,pageInfo:i.pageInfo}}async fetchAllPools(e){const t=[];let n;const a=zi.BACKEND_MAX_PAGE_SIZE;for(;;){const s={...e,pageSize:a,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;if(!r.pageInfo.hasNextPage)break;n=r.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=gs(e);!t.success&&t.errors&&Bs(t.errors,"options")}(e),aa(e.tokenName)&&Os(e.tokenName);try{const t=await this.http.post(M.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===aa(e.symbol)){return!n.symbolAvailable}if(!0===aa(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,a="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||a.includes("404")||a.includes("Pool not found"))return!1;const s="number"==typeof n.statusCode?n.statusCode:null;if(404===s)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||a.includes("400")||a.includes("Missing required pool identifier"))return!1;if(400===s&&a.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ps(t,"tokenName")&&ys(t,"from")&&ys(t,"to")&&ys(t,"resolution")}(e))throw new xt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:a,resolution:s}=e;if(Os(t),null==n||null==a||null==s)throw new xt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:n,to:a,resolution:s};Us(r);const i=ws(r);return{dataPoints:await ln(()=>this.http.get(M.CHART,i),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw jt("tokenName","Token name");let t;Os(e);try{t=await un(()=>this.http.get(`${M.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if($t(t)&&500===t.response?.status)throw zt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return Ls(on(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw jt("tokenName","Token name");if(""===t||null==t)throw jt("userAddress","User address");return Os(e),ln(()=>this.http.get(`${M.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");Os(e);try{const t=M.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=on(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&&Os(e.tokenName);try{const t=await this.http.post(M.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(!aa(e))throw jt("tokenName","Token name");Os(e);const t=M.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=on(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 jt("tokenName","Token name");Os(e),function(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 xt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",Ct);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw tn("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw tn("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw tn("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw tn("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 tn(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw tn("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new xt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Dt)}}(t);const n=M.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),a={};void 0!==t.messagesEnabled&&(a.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(a.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(a.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(a.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(a.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(a.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(a.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(a.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(a.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(a.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(a.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(a.tiktokUrl=t.tiktokUrl),await this.http.patch(n,a,this.getJwtHeaders())}async getTokenConfig(e){if(!aa(e))throw jt("tokenName","Token name");Os(e);const t=M.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=on(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const tl=_n,nl=Nn,al={MAX_LENGTH:100};function sl(e){if(void 0!==e.tokenName){if(!aa(e.tokenName))throw tn("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>nl.MAX_LENGTH)throw en("tokenName",nl.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!aa(e.userAddress))throw tn("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>al.MAX_LENGTH)throw en("userAddress",al.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw tn("search","a string",typeof e.search);if(e.search.length>256)throw en("search",256,e.search.length)}if(ra(0,void 0,tl.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Vt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!aa(e.startDate))throw tn("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Vt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!aa(e.endDate))throw tn("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Vt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Yn(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Vt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Yn(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Vt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const a="number"==typeof e?e:Number(e),s="number"==typeof t?t:Number(t);if(isNaN(a)||isNaN(s))throw tn(n,"numeric values",void 0,n);if(a>s)throw new xt(`Minimum value (${a}) must be less than or equal to maximum value (${s}) for ${n}`,n,Rt)}(e.minAmount,e.maxAmount,"amountRange")}class rl extends fa{constructor(e,t=!1){super(e,t)}async fetchTrades(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ps(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&fs(t,"userAddress")&&ys(t,"offset")&&ys(t,"pageSize")&&ys(t,"page")&&ys(t,"limit")}(e))throw new xt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:a=zi.DEFAULT_LIMIT}=e;if(!aa(t))throw jt("tokenName","Token name");const s={pageSize:String(Math.min(a,Dn))};void 0!==n&&(s.cursor=n);const r={...s};r.tokenName=t;const i=await this.http.get(M.GET_TRADES,r);if(null==i)throw new xt("No response from trade service","response","NO_RESPONSE");const o=on(i),c=Zc(o,"trades"),l=o?.pageInfo;return{items:c,pageInfo:l??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=mn(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?function(e,t=1,n=zi.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,tl.MAX_LIMIT):tl.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){sl(e);const t=this.buildTradesQueryParams(e);return ln(()=>this.http.get(st,t),{errorContext:"Failed to fetch trades"})}}function il(e){return!!aa(e)&&Rn.PATTERN.test(e)}function ol(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const a=e.trim();return a.length<n?null:a}ia({BOTH:"both",HELD:"held",CREATED:"created"});class cl extends fa{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!il(t))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,a=n?M.GET_CURRENT_USER:M.GET_PROFILE.replace(":address",t),s=await this.http.get(a,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new xt("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!aa(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await ln(()=>this.http.put(M.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 xt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,a=Qc(e.file,"image",n),s=await ln(()=>this.http.request({method:"POST",url:`${M.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof xt||e instanceof Bt)throw e;throw new xt(`Profile image upload failed: ${Pt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new xt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},a="created"===e.type;a&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const s=await this.buildFetchRequest(M.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:a?"launches":"token",errorMessage:"Failed to fetch token list"});return a&&void 0!==t?{...s,tokens:s.tokens.filter(e=>e.tokenName===t||e.name===t)}:s}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new xt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new xt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(M.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:a,tokenName:s,status:r}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new xt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const i=e?.address??this.http.getAddress();if(null==i||""===i)throw new xt("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:i,pageSize:n??zi.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==a&&(o.search=a),void 0!==s&&void 0===a&&(o.search=s),void 0!==s&&(o.tokenName=s),void 0!==r&&(o.status=r),this.fetchTokenList(o)}async getManagedTokens(e={}){const t=Ji({pageSize:e.pageSize??zi.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},Dn);return ln(()=>this.http.get(M.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const a=Ji({pageSize:t.pageSize??zi.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Dn);Yi(a,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(a.type=n.requestType);let s=e;const r=t.address??this.http.getAddress();if(e.includes(":address")){if(0===r.length)throw jt("address","User address");s=e.replace(":address",r),delete a.address}const i=on(await un(()=>this.http.get(s,a),{errorContext:n.errorMessage})),o=Zc(i,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",a="string"==typeof e.name?e.name:t,s="string"==typeof e.createdAt?e.createdAt:"",i=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:a,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:r,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==i&&"object"==typeof i?{metadata:i}:{},createdAt:s,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:s}}),c={hasNextPage:i.hasNextPage??!1},l=i.pageInfo,d=i.count??i.total??l?.totalCount;void 0!==l&&(c.hasNextPage=l.hasNextPage??!1,void 0!==l.hasPreviousPage&&(c.hasPrevPage=l.hasPreviousPage),null!==l.endCursor&&void 0!==l.endCursor&&(c.nextCursor=l.endCursor),null!==l.startCursor&&void 0!==l.startCursor&&(c.prevCursor=l.startCursor)),void 0!==d&&(c.totalCount=d),void 0!==i.nextCursor&&(c.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(c.prevCursor=i.prevCursor),void 0!==i.hasPrevPage&&(c.hasPrevPage=i.hasPrevPage);const u={tokens:o,pageInfo:c};return void 0!==d&&(u.total=d),u}validateGetTokenListOptions(e){const t=e.pageSize??zi.DEFAULT_LIMIT;if(t<1||t>Dn)throw new xt(`pageSize must be between 1 and ${Dn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!il(e.address))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=ol(e.search);if(null!==n&&!(aa(a=n)&&a.length>=$n&&a.length<=Kn))throw Yt("search",$n,Kn,n.length,"Search query");var a;const s=ol(e.tokenName);if(null!==s&&!(aa(r=s)&&r.length>=Nn.MIN_LENGTH&&r.length<=Nn.MAX_LENGTH))throw Yt("tokenName",Nn.MIN_LENGTH,Nn.MAX_LENGTH,s.length,"Token name");var r}validateUpdateProfileData(e){if(!il(e.address))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(aa(t)&&t.length>=Gn.FULL_NAME.MIN_LENGTH&&t.length<=Gn.FULL_NAME.MAX_LENGTH&&Gn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw Yt("fullName",Gn.FULL_NAME.MIN_LENGTH,Gn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!il(e.address))throw Vt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class ll{constructor(e,t,n=!1){this.http=e,this.poolService=new el(e,t,n),this.tradeService=new rl(e,n),this.userService=new cl(e,t,n),this.imageService=new Jc(e,t,n)}setJwtAuth(e){this.poolService.setJwtAuth(e),this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async getTrades(e){return this.tradeService.getTrades(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}async getManagedTokens(e={}){return this.userService.getManagedTokens(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Os(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 getTokenConfig(e){return this.poolService.getTokenConfig(e)}}class dl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateContent(e,t){if(!aa(e))throw jt("content","Message content");if(0===e.trim().length)throw jt("content","Message content");Zn(e,t===Yc.CHAT_MESSAGE?xn.CHAT_MESSAGES_V1.MAX_LENGTH:xn.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!aa(e))throw jt("id","Message ID");if(e.length<10||e.length>64)throw Vt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Yc.CHAT_MESSAGE&&e!==Yc.COMMENT)throw new xt(`type must be one of: ${Object.values(Yc).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,Cn);const a={};void 0!==e.cursor&&(a.cursor=e.cursor),a.pageSize=e.pageSize??zi.DEFAULT_LIMIT;const s=Ji(a,_n.MAX_LIMIT),r={};void 0!==s.pageSize&&(r.pageSize=s.pageSize),void 0!==s.cursor&&(r.cursor=s.cursor),t&&(r.type=e.type.toUpperCase()),n&&(r.tokenName=mn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(r.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(r.search=e.search);const i=await this.http.get(rt.GET_MESSAGES,r),o=this.extractData(i);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,Cn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:mn(e.tokenName),content:e.content.trim()},n=await this.http.post(rt.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(rt.UPDATE_MESSAGE,e),a={content:t.content.trim()},s=await this.http.put(n,a,this.getJwtHeaders());return{message:this.extractData(s)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(rt.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Cn);const t=await this.http.get(rt.GET_PINNED,{tokenName:mn(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=rt.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=rt.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(rt.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const ul=oa({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),hl={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},gl=oa(hl),ml={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};oa(ml);class pl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateRole(e){if(!aa(e))throw jt("role","Role");if(!function(e){return ul.includes(e)}(e))throw Vt("role",`one of: ${ul.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!aa(e))throw jt("inviteCode","Invite code");if(t=e,!Pn.PATTERN.test(t))throw Vt("inviteCode","valid invite code format","Invite code");var t}validateInviteScope(e){if(void 0!==e&&(t=e,!gl.includes(t)))throw new xt(`Invalid invite scope. Must be one of: ${gl.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??hl.TOKEN;if(t===hl.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new xt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,Tn)}else if(t===hl.ALL_OWNER_TOKENS&&e.tokenName)throw new xt("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",xn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=we,a={inviteScope:t,role:e.role};t===hl.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(a.tokenName=mn(e.tokenName)),void 0!==e.description&&(a.description=e.description),void 0!==e.expiresAt&&(a.expiresAt=e.expiresAt);const s=await this.http.post(n,a,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,Tn),this.validateStatusFilter(e.status,ml);const t=Ee,n={...this.buildPaginationParams(e,_n.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=mn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.invites,pageInfo:s.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Te,{id:String(e)});rn(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(Ce,{id:String(e.inviteId)}),n={role:e.role},a=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new xt("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",xn.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Ne,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const a=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(a)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=Ae,n={inviteCode:e.inviteCode},a=await this.http.post(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return"tokenName"in s&&void 0!==s.tokenName?{token:s}:{blanketAccess:s}}async getModeratedTokens(e){const t=Se,n=this.buildPaginationParams(e??{},_n.MAX_LIMIT),a=await this.http.get(t,n,this.getMultiAuthHeaders()),s=this.extractData(a);return{items:s.tokens,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ie,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const fl="10000",yl="1000";function vl(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function kl(){return Date.now()+6e4}function bl(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function wl(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function Al(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Sl extends fa{constructor(e){super(e)}getCollectionClaimFee(){return fl}getTokenClassCreateFee(){return yl}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(!Al(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=fl;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const a=yl,s=String(BigInt(a)*BigInt(e.createTokenClasses));n.tokenClassCreate=a,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(s))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!bl(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:kl(),uniqueKey:vl("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),!Al(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),!bl(e))throw new Error(`Invalid collection name format: ${e}`);const t=!0;return this.logger.debug(`Collection ${e} available:`,t),t}catch(e){throw this.logger.error("Failed to check collection availability",e),e}}async createTokenClass(e){try{if(this.logger.debug("Creating NFT token class",e),null===e.collection||void 0===e.collection||0===e.collection.length||null===e.type||void 0===e.type||0===e.type.length||null===e.category||void 0===e.category||0===e.category.length)throw new Error("Missing required parameters: collection, type, category");if(!bl(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?wl(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?wl(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:kl(),uniqueKey:vl("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),!bl(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(!Al(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 a={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:kl(),uniqueKey:vl("mint")};this.logger.debug("Built mint DTO",a);const s=`mint-${Date.now()}`,r=Array.from({length:t},(e,t)=>t+1);return{transactionId:s,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:r,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}),!Al(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 El extends fa{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(kt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),a=this.extractData(n);return this.logger.debug("Push token registered",{registered:a.registered}),a}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:bt,data:{token:e},headers:t}),a=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:a.unregistered}),a}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(wt,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(At,e,t),a=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:a.tradesEnabled,streamsEnabled:a.streamsEnabled}),{preferences:a}}}class Tl extends fa{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(M.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(M.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 xt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=M.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),a=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:a.title}),{oembed:a}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new xt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=M.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),a=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:a}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new xt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=M.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),a=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:a.title}),{oembed:a}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new xt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=M.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),a=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:a}}}function Cl(e){if(!aa(e))throw jt("address","Address")}const Nl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Il={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Dl=ia(Nl),_l=ia(Il);function Rl(e){if(!aa(e))throw new Error("Address must be a non-empty string");try{Ia(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function xl(e){try{ea(e,"id")}catch(e){if(e instanceof xt)throw new Error("Invite ID must be a positive integer");throw e}}class Fl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateInviteCodeFormat(e){if(!aa(e))throw jt("inviteCode","Invite code");!function(e){if(!aa(e))throw new Error("Invite code must be a non-empty string");Zn(e,100,"code")}(e)}validateWalletAddressFormat(e){if(!aa(e))throw jt("address","Address");Rl(e)}async createInvite(e={}){!function(e){try{ha(e.description,"description",255)}catch(e){if(e instanceof xt)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(!aa(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{ga(e.expiresAt,"expiresAt")}catch(e){if(e instanceof xt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Sn(e.expiresAt)&&An(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}(e),this.validateOptionalString(e.description,"description","Description",xn.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=_e,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const a=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(a)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!Dl(e.status))throw an("status",e.status,Object.values(Nl),"status");ra(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Nl);const t=Re,n={...this.buildPaginationParams(e,_n.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.invites,pageInfo:s.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(xe,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){xl(e);const t=this.buildEndpoint(Be,{id:String(e)});rn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Fe,n={inviteCode:e},a=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(a)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!_l(e.status))throw an("status",e.status,Object.values(Il),"status");ra(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Il);const t=Oe,n={...this.buildPaginationParams(e,_n.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.overseers,pageInfo:s.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new xt("Options are required");if(!aa(e.userAddress))throw new xt("userAddress is required and must be a non-empty string");try{Ia(e.userAddress,"userAddress")}catch{throw new xt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new xt("description must be a string");if(e.description.length>255)throw new xt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",xn.DESCRIPTION.MAX_LENGTH);const t=Ue,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const a=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(a)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Pe,{address:e});rn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Me,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=$e,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=We,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=He,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&function(e){if(null==e||"object"!=typeof e)throw new xt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new xt("Search must be a string");if(0===e.search.length)throw new xt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new xt("Sort field must be a string");if(0===e.sortBy.length)throw new xt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new xt('Sort order must be "asc" or "desc"')}(t);const n=qe,a=this.buildPaginationParams(t,_n.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(a.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(a.sortBy=t.sortBy),void 0!==t.sortOrder&&(a.sortOrder=t.sortOrder);const s=await this.http.get(n,a,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.users,pageInfo:r.pageInfo}}async getOverseerUserSummary(e){if(!aa(e))throw jt("address","User address");Rl(e);const t=this.buildEndpoint(je,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Cl(e);const t=this.buildEndpoint(Ve,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!aa(e))throw jt("tokenName","Token name")}(e);const t=this.buildEndpoint(ze,{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 xt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Xe,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Cl(e);const t=this.buildEndpoint(Qe,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Je,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class Bl extends fa{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),rn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(ee);return this.extractData(e)}async updatePlatformConfig(e){const t=function(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}(e);if(t.length>0)throw new xt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(te,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(se);return this.extractData(e)}}class Ol extends fa{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(gt),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Ul extends fa{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw jt("tokenName","Token name");if(!this.tokenResolverService)throw Xt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{la(e)}catch(e){throw Xt(Pt(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 Xt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=rr(mo(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(Ut(t)&&Pt(t).includes("ConfigurationError"))throw t;throw zt(`Failed to resolve token name '${e}': ${Pt(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw jt("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Ys(async()=>{let t=e.tokenId;if(null!==e.tokenName&&void 0!==e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(null==t)throw Xt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return vo}),a=ic(rr(n(t))),{from:s,to:r,sortOrder:i="DESC"}=e,o=e.timeframe??this.inferTimeframe(s,r),c={token:a,timeframe:o};this.logger.debug(`Querying price series for token ${a}, timeframe ${o}`);const l=await this.http.get(G,c);if(null==l)throw zt("No response from price history service",500);const d=this.transformApiResponseToPriceHistory(l,e,i);return this.logger.debug(`Found ${d.snapshots.length} price snapshots, total ${d.total}`),d},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e,t,n){if(!Array.isArray(e.prices))throw zt("Invalid API response: missing price series",500);const a="string"==typeof t.tokenId?t.tokenId:t.tokenName??rr(t.tokenId),s=t.from?.getTime(),r=t.to?.getTime(),i=e.prices.filter(e=>"number"==typeof e.time&&"number"==typeof e.price).filter(e=>(void 0===s||1e3*e.time>=s)&&(void 0===r||1e3*e.time<=r)).sort((e,t)=>"ASC"===n?e.time-t.time:t.time-e.time),o=qn(t.offset,0),c=qn(t.pageSize??t.limit,10),l=i.slice(o,o+c).map(e=>({price:String(e.price),timestamp:new Date(1e3*e.time),tokenId:a})),d=Math.max(1,Math.ceil(i.length/c)),u=Math.floor(o/c)+1;return{snapshots:l,page:u,limit:c,total:i.length,totalPages:d,hasNext:u<d,hasPrevious:u>1}}async fetchAllPriceHistory(e){if(null==e)throw jt("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Ys(async()=>{const t=await ho((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 a=e.length;return{offset:0,limit:a,total:t,totalPages:0!==a?Xi(t,a):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:a}=e;if(ca(e,"tokenName","tokenId",{description:"token identifier"}),t&&!Sn(t))throw Xt("from must be a valid Date","from");if(void 0!==n&&!Sn(n))throw Xt("to must be a valid Date","to");null!=a&&function(e,t){if("ASC"!==e&&"DESC"!==e)throw new xt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}(a,"sortOrder"),ra(0,void 0,50,e.pageSize)}inferTimeframe(e,t){if(void 0===e||void 0===t)return"1M";const n=Math.max(0,t.getTime()-e.getTime())/864e5;return n<=1?"1D":n<=7?"1W":n<=31?"1M":n<=365?"1Y":"ALL"}}class Pl extends eo{constructor(e,t,n,a){super(e,t,n,!1,a)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(it)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!aa(e.content))throw new xt("Content is required");return{success:!0,data:(await this.http.put(ot,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Ml extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getChatStatus(e){if(null==e||""===e)throw jt("tokenName","Token name");return this.validateTokenName(e,Tn),Ys(async()=>{const t=this.buildEndpoint(ct,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResult(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw jt("tokenName","Token name");return this.validateTokenName(e,Tn),Ys(async()=>{const t=this.buildEndpoint(dt,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw jt("tokenName","Token name");return this.validateTokenName(e,Tn),Ys(async()=>{const t=this.buildEndpoint(lt,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResult(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResult(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??mn(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw jt("tokenName","Token name");if(this.validateTokenName(e,Tn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Ys(async()=>{const n=this.buildEndpoint(ut,{tokenName:e}),a=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(a)},`Failed to set slow mode for token: ${e}`,this.logger)}}class Ll extends ya{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 a of n)try{const e=a(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)}}ia({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),ia({READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"});const $l=ia({YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"});const Kl={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};ia(Kl),ia({OWNER:"OWNER",MODERATOR:"MODERATOR"});function Gl(e,t="tokenName"){la(e,t,Tn)}function Wl(e){if(Gl(e.tokenName),!aa(e.language))throw jt("language");if(t=e.language,!aa(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new xt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Dt);var t}ia({...Kl,OVERSEER:"OVERSEER"});class Hl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async startStream(e){this.validateTokenName(e,Tn);const t=this.buildEndpoint(W,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Tn);const t=this.buildEndpoint(H,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,q,Tn)}async enableStream(e){return this.toggleFeature(e,j,Tn)}async resetStreamKey(e){this.validateTokenName(e,Tn);const t=this.buildEndpoint(V,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Tn);const t=this.buildEndpoint(ie,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Gl(e.tokenName),ra(0,void 0,Ln,e.pageSize)}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Ln),a=e.offset;"number"==typeof a&&(n.offset=String(a));const s=await this.http.get(t,n),r=this.extractData(s),i=e,o=r.pageSize??r.limit??e.pageSize??("number"==typeof i.limit?i.limit:20),c="number"==typeof i.offset?i.offset:0,l=Math.floor(c/o)+1;return{recordings:r.recordings,tokenName:mn(e.tokenName),page:r.page??l,limit:o,total:r.total,hasNext:r.recordings.length===o}}async getRecordingDownload(e,t){this.validateTokenName(e,Tn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(X,{tokenName:e,assetId:t}),a=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(a)}async deleteRecording(e,t){this.validateTokenName(e,Tn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Q,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Tn);const t=this.buildEndpoint(J,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Gl(e.tokenName),!aa(e.platform))throw jt("platform");if(!$l(e.platform))throw new xt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",It);if(!aa(e.rtmpUrl))throw jt("rtmpUrl");if(!Mn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new xt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",Dt);if(!aa(e.streamKey))throw jt("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new xt("name must be a string","name",Nt)}(e);const t=this.buildEndpoint(Y,{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,Tn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(Z,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(ee);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(te,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(ne,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Gl(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||aa(e.nextLiveStreamAt)))throw new xt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",Nt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new xt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Dt)}}}(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,Tn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Wl(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Gl(e.tokenName)}(e);const t=this.buildEndpoint(ae,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},a=await this.http.get(t,{},n);return this.extractData(a)}async getAvailableRoles(){const e=await this.http.get(se);return this.extractData(e)}async getTokenAccess(e){!function(e){Gl(e.tokenName)}(e);const t=await this.http.get(re,{tokenName:mn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}class ql{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`}}const jl="subscribe_token",Vl="unsubscribe_token",zl="authenticate",Xl="send_stream_chat",Ql="SEND_STREAM_REACTION",Jl="typing_start",Yl="typing_stop",Zl="STREAM_STATUS",ed="STREAM_COUNTDOWN_UPDATED",td="STREAM_LANGUAGE_UPDATED",nd="VIEWER_COUNT",ad="token_subscribed",sd="token_unsubscribed",rd="STREAM_GLOBAL_STATUS",id="ENGAGEMENT_STATS_UPDATED",od="STREAM_CHAT_MESSAGE",cd="STREAM_CHAT_SENT",ld="stream_chat_error",dd="CHAT_STATUS_CHANGED",ud="STREAM_CHAT_GLOBAL_STATUS",hd="authenticated",gd="stream_chat_auth_error",md="STREAM_REACTION",pd="stream_reaction_error",fd="USER_TYPING",yd="STREAM_CHAT_PINNED",vd="STREAM_CHAT_UNPINNED",kd="COMMENT_CREATED",bd="USER_BANNED",wd="USER_UNBANNED",Ad="BAN_ENFORCEMENT",Sd="TOKEN_BANNED",Ed="TOKEN_UNBANNED",Td="MODERATOR_INVITE_CREATED",Cd="MODERATOR_ADDED",Nd="MODERATOR_REMOVED",Id="MODERATOR_ROLE_UPDATED",Dd="OVERSEER_ADDED",_d="OVERSEER_REMOVED",Rd="TRADE_EXECUTED",xd="BALANCE_UPDATED",Fd="STATS_UPDATED",Bd="POOL_METADATA_UPDATED",Od="POOL_SOCIAL_LINKS_UPDATED",Ud="POOL_BADGE_ASSIGNED",Pd="HOLDER_COUNT_UPDATED",Md="USER_PROFILE_UPDATED",Ld="API_KEY_CREATED",$d="API_KEY_UPDATED",Kd="API_KEY_REVOKED",Gd="TOKEN_CONFIG_UPDATED",Wd="SITE_CONFIG_CHANGED",Hd="COMMENTS_GLOBAL_STATUS",qd="WEBHOOKS_GLOBAL_STATUS",jd="subscribe_global_feed",Vd="unsubscribe_global_feed",zd="global_feed_subscribed",Xd="global_feed_unsubscribed";class Qd extends ya{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 Bt("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 ql({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof U||(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:",Pt(e)),!1}}getRoomName(e){return`token:${mn(e)}`}bufferEvent(e,t,n){const a=`${e}:${t}`;let s=this.eventBuffer.get(a);s||(s=[],this.eventBuffer.set(a,s)),s.length>=this.MAX_BUFFER_SIZE&&(s.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${a} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),s.push(n);const r=this.eventBufferTimeouts.get(a);r&&clearTimeout(r);const i=setTimeout(()=>{this.eventBuffer.delete(a),this.eventBufferTimeouts.delete(a),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${a}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(a,i)}processBufferedEvents(e,t){const n=mn(e),a=[{key:`${Zl}:${n}`,callback:t.onStreamStatus},{key:`${nd}:${n}`,callback:t.onViewerCount},{key:`${od}:${n}`,callback:t.onChatMessage},{key:`${dd}:${n}`,callback:t.onChatStatus},{key:`${yd}:${n}`,callback:t.onChatPinned},{key:`${vd}:${n}`,callback:t.onChatUnpinned},{key:`${ed}:${n}`,callback:t.onCountdownUpdated},{key:`${td}:${n}`,callback:t.onLanguageUpdated},{key:`${Sd}:${n}`,callback:t.onTokenBanned},{key:`${Ed}:${n}`,callback:t.onTokenUnbanned},{key:`${Td}:${n}`,callback:t.onModeratorInviteCreated},{key:`${Cd}:${n}`,callback:t.onModeratorAdded},{key:`${Nd}:${n}`,callback:t.onModeratorRemoved},{key:`${Id}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${Rd}:${n}`,callback:t.onTradeExecuted},{key:`${xd}:${n}`,callback:t.onBalanceUpdated},{key:`${Bd}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${Od}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${Ud}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${Pd}:${n}`,callback:t.onHolderCountUpdated},{key:`${kd}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of a){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const a of n)try{t(a)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const a=this.eventBufferTimeouts.get(e);a&&(clearTimeout(a),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(Zl,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Zl,e.tokenName,e);const t=this.roomCallbacks.get(mn(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(ad,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=mn(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const a=this.roomCallbacks.get(t);a?.onStreamSubscribed&&a.onStreamSubscribed(e)}),this.socket.on(sd,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(mn(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(nd,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(nd,e.tokenName,e);const t=this.roomCallbacks.get(mn(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(rd,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(od,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(od,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(cd,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(ld,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(dd,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(dd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(ud,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(hd,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(gd,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(md,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(pd,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(fd,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(mn(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(yd,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(yd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(vd,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(vd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(ed,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(ed,e.tokenName,e);const n=this.roomCallbacks.get(mn(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(td,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(td,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(Sd,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(Sd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(Ed,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(Ed,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(bd,e=>{this.logger.debug(`📡 [User Banned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserBanned(e)}),this.socket.on(wd,e=>{this.logger.debug(`📡 [User Unbanned] ${e.tokenName}: ${e.userAddress}`),this.streamingEventService?.emitUserUnbanned(e)}),this.socket.on(Ad,e=>{this.logger.debug(`📡 [Ban Enforcement] ${e.tokenName}: ${e.action}`),this.streamingEventService?.emitBanEnforcement(e)}),this.socket.on(Td,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(Td,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(Cd,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Cd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(Nd,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Nd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(Id,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Id,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(Dd,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(_d,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(Rd,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Rd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(xd,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(xd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(Bd,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(Bd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(Od,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(Od,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(Ud,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(Ud,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(Pd,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(Pd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(kd,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(kd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(Md,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(Ld,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on($d,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(Kd,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(Gd,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(Gd,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(Fd,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(Fd,e.tokenName,e);const t=this.roomCallbacks.get(mn(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(id,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(id,e.tokenName,e);const t=this.roomCallbacks.get(mn(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(zd,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(Xd,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(Wd,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(rd,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(ud,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(Hd,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(qd,e=>{this.logger.debug(`📡 [Webhooks Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onWebhooksGlobalStatus&&this.globalFeedCallbacks.onWebhooksGlobalStatus(e)}))}resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(jl,{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(jd)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}setStreamingEventService(e){this.streamingEventService=e}async connect(){return new Promise((e,t)=>{Ys(async()=>{if(!this.isSocketIOAvailable)throw new Bt('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=U(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")}),Promise.resolve(void 0)},"Stream WebSocket connection setup",this.logger,e=>{const n=e instanceof Error?e:new Error(String(e));throw t(n),n})})}authenticate(e){if(!this.socket?.connected)throw new xt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw jt("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(zl,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw jt("tokenName","Token name");if(!this.socket?.connected)throw new xt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=mn(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((a,s)=>{const r=setTimeout(()=>{this.pendingSubscriptions.delete(n),s(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:a,reject:s,timeoutId:r}),this.roomCallbacks.set(n,t),this.subscribedRooms.set(n,{tokenName:n,subscribedAt:Date.now()}),this.logger.debug(`📡 Subscribing to stream: ${n}`),this.socket.emit(jl,{tokenName:n})})}unsubscribeFromStream(e){const t=mn(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(Vl,{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 jt("tokenName","Token name");if(""===t)throw jt("content","Message content");if(!this.socket?.connected)throw new xt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new xt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=mn(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Xl,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw jt("tokenName","Token name");if(""===t)throw jt("emoji");if(!this.socket?.connected)throw new xt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new xt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=mn(e);this.logger.debug(`📡 Sending reaction to ${a}: ${t}`),this.socket.emit(Ql,{tokenName:a,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Jl,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,Yl,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw jt("tokenName","Token name");if(!this.socket?.connected)throw new xt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new xt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=mn(e);this.logger.debug(`📡 Sending ${n} to ${a}`),this.socket.emit(t,{tokenName:a})}subscribeTokenBanned(e,t){const n=mn(e),a={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenBanned,this.roomCallbacks.set(n,t)}}}subscribeTokenUnbanned(e,t){const n=mn(e),a={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTokenUnbanned,this.roomCallbacks.set(n,t)}}}subscribeModeratorInviteCreated(e,t){const n=mn(e),a={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorInviteCreated,this.roomCallbacks.set(n,t)}}}subscribeModeratorAdded(e,t){const n=mn(e),a={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorAdded,this.roomCallbacks.set(n,t)}}}subscribeModeratorRemoved(e,t){const n=mn(e),a={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRemoved,this.roomCallbacks.set(n,t)}}}subscribeModeratorRoleUpdated(e,t){const n=mn(e),a={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onModeratorRoleUpdated,this.roomCallbacks.set(n,t)}}}subscribeOverseerAdded(e){return this.globalCallbacks.onOverseerAdded=e,()=>{delete this.globalCallbacks.onOverseerAdded}}subscribeOverseerRemoved(e){return this.globalCallbacks.onOverseerRemoved=e,()=>{delete this.globalCallbacks.onOverseerRemoved}}subscribeTradeExecuted(e,t){const n=mn(e),a={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onTradeExecuted,this.roomCallbacks.set(n,t)}}}subscribePoolMetadataUpdated(e,t){const n=mn(e),a={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolMetadataUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolSocialLinksUpdated(e,t){const n=mn(e),a={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolSocialLinksUpdated,this.roomCallbacks.set(n,t)}}}subscribePoolBadgeAssigned(e,t){const n=mn(e),a={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onPoolBadgeAssigned,this.roomCallbacks.set(n,t)}}}subscribeHolderCountUpdated(e,t){const n=mn(e),a={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onHolderCountUpdated,this.roomCallbacks.set(n,t)}}}subscribeCommentCreated(e,t){const n=mn(e),a={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...a}),()=>{const e=this.roomCallbacks.get(n);if(e){const t={...e};delete t.onCommentCreated,this.roomCallbacks.set(n,t)}}}subscribeUserProfileUpdated(e){return this.globalCallbacks.onUserProfileUpdated=e,()=>{delete this.globalCallbacks.onUserProfileUpdated}}subscribeApiKeyCreated(e){return this.globalCallbacks.onApiKeyCreated=e,()=>{delete this.globalCallbacks.onApiKeyCreated}}subscribeApiKeyUpdated(e){return this.globalCallbacks.onApiKeyUpdated=e,()=>{delete this.globalCallbacks.onApiKeyUpdated}}subscribeApiKeyRevoked(e){return this.globalCallbacks.onApiKeyRevoked=e,()=>{delete this.globalCallbacks.onApiKeyRevoked}}subscribeStatsUpdated(e){return this.globalCallbacks.onStatsUpdated=e,()=>{delete this.globalCallbacks.onStatsUpdated}}subscribeEngagementStatsUpdated(e){return this.globalCallbacks.onEngagementStatsUpdated=e,()=>{delete this.globalCallbacks.onEngagementStatsUpdated}}setGlobalCallbacks(e){this.globalCallbacks=e}getSubscribedTokens(){return Array.from(this.subscribedRooms.keys())}isConnected(){return this.socket?.connected??!1}isAuthenticatedForChat(){return this.isAuthenticated}async subscribeToGlobalFeed(e){if(!this.socket?.connected)throw new xt("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 a=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:a},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(jd)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(Vd),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 Jd(e){if(la(e.tokenName,"tokenName",Tn),!(null==(t=e.reason)||""===t||"string"==typeof t&&!ua(t)&&t.length<=xn.BAN_REASON.MAX_LENGTH))throw new xt(`reason must be at most ${xn.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Yd extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async banToken(e){Jd(e);const t=Ye,n={tokenName:mn(e.tokenName)};if(void 0!==e.reason)try{ta(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const a=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(a),tokenName:mn(e.tokenName)}}async unbanToken(e){!function(e){la(e.tokenName,"tokenName",Tn)}(e);const t=this.buildEndpoint(tt,{tokenName:e.tokenName});return rn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:mn(e.tokenName)}}async listTokenBans(e={}){!function(e){ra(0,void 0,In,e.pageSize)}(e);const t=Ze,n=this.buildPaginationParams(e,In);this.addOptionalFilterParams(n,e,["search"]);const a=await this.http.get(t,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getTokenBan(e){!function(e){la(e.tokenName,"tokenName",Tn)}(e);const t=this.buildEndpoint(et,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:mn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class Zd extends ya{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(!aa(e))throw jt("tokenName","Token name");const t=mn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const a=await this.poolService.resolveTokenNameToVault(e);if(null!==a&&""!==a){const e=this.parseVaultAddressToTokenClassKey(a);this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:e,cachedAt:Date.now()})}return a}async resolveTokenClassKey(e){if(!aa(e))throw jt("tokenName","Token name");const t=mn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const a=await this.poolService.resolveTokenNameToVault(e);if(null===a||""===a)throw qt(e);const s=this.parseVaultAddressToTokenClassKey(a);return this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(mn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=Zd.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=mn(e),a=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:a,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:Zd.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(mn(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:a}of e){const e=mn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:a,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return mo(e)}catch(e){if(e instanceof xt)throw Vt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}Zd.MAX_CACHE_SIZE=1e4;class eu extends fa{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return ln(()=>this.http.get(mt),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return ln(()=>this.http.get(pt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return xs(await ln(()=>this.http.get(ft,{tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return xs(await ln(()=>this.http.get(yt,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class tu extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,Cn);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,Cn);const a={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(a)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Cn);const a={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Cn);const a={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Cn);const a={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Cn);const a={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Cn);const a={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Cn);const a={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTokenBanned(e,t){this.validateTokenName(e,Cn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Cn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Cn);const a={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Cn);const a={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}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 a=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(a)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new Bt("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,Cn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const a=await this.getConnectedClients(n);return{clients:a.clients,count:a.summary.totalConnected,authenticatedCount:a.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,Cn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Cn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Cn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class nu{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 a=n??this.defaultTtlMs,s={value:t};a>0&&(s.expiresAt=Date.now()+a),this.cache.set(e,s)}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 au(e,t,n,a={}){const{logger:s,cacheNullish:r=!1,keyGenerator:i}=a,o=i?i(e):String(e),c=n.get(o);if(void 0!==c)return s&&s.debug(`Cache hit for key: ${o}`),c;s&&s.debug(`Cache miss for key: ${o}, fetching...`);const l=await t();return null!=l?(n.set(o,l),s&&s.debug(`Cached result for key: ${o}`)):r&&(n.set(o,l),s&&s.debug(`Cached nullish result for key: ${o}`)),l}class su extends ya{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 ql({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new nu(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),su.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof U||(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)=>{Ys(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:",Pt(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=U(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],a=n.status??n.Status;"string"==typeof a&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${a}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Ut(e)?e:new Error(Pt(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const a=this.config.timeout??3e5,s=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(a/1e3),s={transactionId:e,status:qi.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(s),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},a);if(this.timeouts.set(e,s),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:qi.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const a=t,s=a?.data,r=a?.status??a?.Status??s?.status??s?.Status;let i=a?.message??a?.Message??s?.message??s?.Message??a?.error??s?.error;aa(i)||(i=r===Hi.FAILED||r===Hi.ERROR?"Transaction failed - check transaction details":r===Hi.COMPLETED||r===Hi.PROCESSED||r===Hi.SUCCESS?"Transaction completed successfully":null!=r?`Transaction status: ${String(r)}`:"Unknown transaction status");const o=a?.blockHash??s?.blockHash,c=a?.gasUsed??s?.gasUsed,l=a?.Data??s?.Data,d={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof i?i:"Transaction update received",timestamp:Date.now(),...null!=o?{blockHash:o}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(r)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(i)}"`),n(d),d.status===qi.COMPLETED||d.status===qi.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} (${d.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===qi.COMPLETED?t(e):e.status!==qi.FAILED&&e.status!==qi.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return ji[t]??qi.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")),su.instances.delete(this)}static cleanupAll(e=!1){for(const e of su.instances)e.disconnect();su.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}su.instances=new Set;class ru extends fa{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 xt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},a=await this.http.get(vt.GET_LEADERBOARD,n),s=this.extractData(a);return this.logger.debug("Fetched weekly challenge leaderboard",{count:s.count}),{leaderboard:s}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new xt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=vt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),a=await this.http.get(n),s=this.extractData(a);return this.logger.debug("Fetched token weekly history",{count:s.length}),{snapshots:s}}}class iu extends va{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return pn(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 ou extends iu{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 cu extends ko{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new ou(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())})`),Ys(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 Ys(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:a,itemTypeName:s="items"}=e;if(t.has()){const e=t.getAll();return a&&a.debug(`Returning ${e.length} cached ${s}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}a&&a.debug(`Fetching all ${s} (no cache)`);const r=await n();try{t.setAll(r)}catch(e){a&&a.error("Cache operation failed (non-fatal):",e)}return{items:r,fetchedAt:Date.now(),itemCount:r.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=yo(e),n=this.cache.getByTokenId(t);return n||(await au("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=yo(e);await au("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),a=void 0!==n,s={isWrappable:a,tokenId:t};return a&&(s.wrapCounterpart=n.wrapCounterpart),s}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class lu extends ya{constructor(e){super(!1,e.logger),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService;const t=e.wallet?.privateKey;this.nativeSigner=e.signer??("string"==typeof t?new Oo(t):void 0),this.walletAddress=e.walletAddress}async wrapToken(e){return this.executeWrapOrUnwrap(e,!0)}async unwrapToken(e){return this.executeWrapOrUnwrap(e,!1)}async estimateWrapFee(e,t){return this.estimateChannelFee(e,t,!0)}async estimateUnwrapFee(e,t){return this.estimateChannelFee(e,t,!1)}getWrapStatus(e){if(0===e.length)throw jt("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeWrapOrUnwrap(e,t){const n=await this.getWrappableTokenOrThrow(e.tokenId);if(t?"asset"===n.channel:"asset"!==n.channel){const e=t?"already on asset channel":"not on asset channel",a=t?"unwrapToken()":"wrapToken()",s=t?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new xt(`Cannot ${t?"wrap":"unwrap"} ${n.symbol} - it's ${e}. Use ${a} instead.`,"tokenId",s)}const a=await this.getCounterpartOrThrow(e.tokenId,n.symbol);return this.executeChannelBridge({sourceToken:n,destinationToken:a,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:t})}async estimateChannelFee(e,t,n){if("string"==typeof e&&0===e.length)throw jt("tokenId","Token identifier");if(0===t.length)throw jt("amount");const a=await this.getWrappableTokenOrThrow(e);if(n?"asset"===a.channel:"asset"!==a.channel){const e=n?"already on asset channel":"not on asset channel",t=n?"ALREADY_ON_ASSET_CHANNEL":"NOT_ON_ASSET_CHANNEL";throw new xt(`Cannot ${n?"wrap":"unwrap"} ${a.symbol} - it's ${e}`,"tokenId",t)}const s=this.determineChannelRouting(a,n);return{fee:"0",feeToken:"GALA",authorizationType:s.authType,feeChannel:s.sourceChannel}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:a,recipient:s,isWrap:r}=e;if(void 0===this.nativeSigner||void 0===this.walletAddress||0===this.walletAddress.length)throw new xt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const i=this.walletAddress,o=this.determineChannelRouting(t,r),c=`galaswap-operation-${Wr()}`,l={quantity:a,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:o.destinationChannelId,recipient:s??i,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${r?"Wrap":"Unwrap"} message (pre-signing)`,{amount:a,uniqueKey:c,sourceChannel:o.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:a,message:l,routing:o,isWrap:r,senderAddress:i})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:a,message:s,routing:r,isWrap:i}=e;try{const e=await this.nativeSigner.signObject("RequestTokenBridgeOut",s);this.logger.debug(`[WrapService] ${i?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:a,channel:r.sourceChannel});const o=await this.galaConnectClient.requestBridgeOut(e);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:o.Status,hasData:"Data"in o}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(o)){const e=`Status=${o.Status}`,s="string"==typeof o.Message&&o.Message.length>0?`: ${o.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`GalaChain request failed (${e}${s})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(o)){const e=o.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const s={bridgeFromChannel:r.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:s.bridgeFromChannel});const c=await this.galaConnectClient.bridgeTokenOut(s);return this.logger.debug("[WrapService] BridgeTokenOut response",{status:c.Status,hash:c.Hash}),1!==c.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(c.Status)}`}:{success:!0,transactionId:c.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof o})`}}catch(e){const s=Pt(e);return this.logger.error(`[WrapService] ${i?"Wrap":"Unwrap"} operation failed:`,s),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:a,fromChannel:r.sourceChannel,toChannel:i?"asset":n.channel??"music",error:s}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:dr,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:ur,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new xt(`Counterpart token not found for ${t}`,"tokenId","COUNTERPART_NOT_FOUND");return n}async getWrappableTokenOrThrow(e){const t=await this.wrappableTokenService.getWrappableToken(e);if(null==t)throw new xt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:rr(e)}}class du extends Error{constructor(e,t,n={}){super(e),this.name="LaunchpadSDKError",this.code=t,this.status=n.status,this.chainMessage=n.chainMessage,this.details=n.details}}class uu{constructor(e){this.bundleId=e.bundleId,this.uniqueKey=e.uniqueKey,this.method=e.method,this.waitForResult=e.wait}wait(e){return this.waitForResult(e)}}class hu{constructor(e){this.bundleBaseUrl=bu(e.bundleBaseUrl),this.launchpadBaseUrl=bu(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>U(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof du)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new du(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),a=`${this.bundleBaseUrl}/bundle`,s=await this.requestor(a,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),r=await vu(s);if(!s.ok)throw mu(s.status,r,a);const i=function(e){if("string"==typeof e&&""!==e)return e;if(!ku(e))throw new du("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(ku(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new du("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(r),o=yu(e.dto,"uniqueKey");return new uu({bundleId:i,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,i,t)})}async waitForResult(e,t,n={}){const a=n.timeoutMs??6e4,s=n.pollIntervalMs??2500,r=Date.now();let i,o,c=!1,l=new Promise(()=>{});try{i=this.socketFactory(this.bundleBaseUrl),l=new Promise((e,n)=>{o=t=>{const a=function(e){if(!ku(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(t);void 0===a||c||(c=!0,"FAILED"===a.status?n(gu(a.data)):e(a))},i?.on(t,o)})}catch{i=void 0}const d=this.pollConfirmation(e,t,r,a,s);try{return await Promise.race([l,d])}finally{c=!0,void 0!==i&&(void 0!==o&&i.off(t,o),i.disconnect())}}async pollConfirmation(e,t,n,a,s){const r="CreateSale"===e.method,i=r?function(e,t){const n=yu(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`;for(;Date.now()-n<=a;){const e=await this.requestor(i,{method:"GET"}),t=await vu(e);if(r){if(e.ok)return{status:"PROCESSED",data:fu(t)};if(404!==e.status&&202!==e.status)throw mu(e.status,t,i)}else{if(!e.ok)throw mu(e.status,t,i);const n=ku(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw gu(t)}const o=a-(Date.now()-n);if(o<=0)break;await wu(Math.min(Math.max(0,s),o))}throw new du(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function gu(e){const t=pu(e)??"Launchpad bundle failed on chain.";return new du(t,"BUNDLE_FAILED",{chainMessage:t})}function mu(e,t,n){const a=pu(t)??`Bundle request failed with HTTP ${e}`;return new du(a,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:a,details:{body:t,url:n}})}function pu(e){if("string"==typeof e&&""!==e)return e;if(ku(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(ku(n)){const e=pu(n);if(void 0!==e)return e}}}function fu(e){return ku(e)?e.data??e.Data??e:e}function yu(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new du(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function vu(e){try{return await e.json()}catch{return e.text()}}function ku(e){return"object"==typeof e&&null!==e}function bu(e){return e.replace(/\/$/u,"")}function wu(e){return new Promise(t=>setTimeout(t,e))}function Au(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Mo(t).type,a=await e.findTokenNameByVault(t,n);if(void 0===a)throw new xt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return a}(e,t.vaultAddress);return function(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new xt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new xt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new O(e).multipliedBy(new O(1).plus(new O(String(t)))).decimalPlaces(8,O.ROUND_UP).toFixed()}((await e.getTradeQuote("SellExactToken"===t.method?{tokenName:n,amount:t.quantity,type:"MEME",method:"IN"}:{tokenName:n,amount:t.quantity,type:"NATIVE",method:"OUT"})).reverseBondingCurveFee,t.feeSlippageFactor??e.defaultFeeSlippageFactor())}}const Su="0.1",Eu="0.5";class Tu{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){!function(e){const t=hs(e);!t.success&&t.errors&&Bs(t.errors,"data")}(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:e.preBuyQuantity??"0",websiteUrl:e.websiteUrl??"",telegramUrl:e.telegramUrl??"",twitterUrl:e.twitterUrl??"",instagramUrl:e.instagramUrl??"",facebookUrl:e.facebookUrl??"",redditUrl:e.redditUrl??"",tiktokUrl:e.tiktokUrl??"",tokenCategory:e.tokenCategory??"Unit",tokenCollection:e.tokenCollection??"Token",uniqueKey:e.uniqueKey??Cu(t)},a=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:a?.minFeePortion??Su,maxFeePortion:a?.maxFeePortion??Eu},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:$o(e)})}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const a={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??Cu(this.walletAddress)};return this.transport.submit({method:e,dto:a,stringsInstructions:Lo(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new xt("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Cu(e){return`galaswap-operation-${B()}-${Date.now()}-${e}`}class Nu{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=Bu(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=Iu(e),n={from:this.walletAddress,to:Bu(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??Fu(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:Iu(e)}],uniqueKey:e.uniqueKey??Fu(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:Iu(e)}],uniqueKey:e.uniqueKey??Fu(this.walletAddress)};return void 0!==e.expires&&(t.expires=e.expires),void 0!==e.name&&(t.name=e.name),this.direct("LockToken",t)}unlock(e){const t={tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:Iu(e)}],uniqueKey:e.uniqueKey??Fu(this.walletAddress)};return void 0!==e.name&&(t.name=e.name),this.direct("UnlockToken",t)}async direct(e,t){const n=await this.signNative(e,t),a=`${this.gatewayBaseUrl}/api/asset/token-contract/${e}`,s=await this.post(a,n),r=await async function(e){try{return await e.json()}catch{return e.text()}}(s),i=xu(r);if(!s.ok||void 0!==i?.Status&&1!==i.Status)throw function(e,t,n){const a=xu(t),s=Ru(a,"Message")??Ru(a,"message")??Ru(a,"ErrorKey")??`Gateway request failed with HTTP ${e}`,r=Ru(a,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new du(s,r,{status:e,chainMessage:s,details:{body:t,url:n}})}(s.status,r,a);const o=xu(Du(r))?.mode??i?.mode;if(void 0!==o&&"sync"!==o){throw new du(`Unsupported gateway transaction mode: ${"string"==typeof o?o:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:s.status,details:{body:r,url:a}})}const c=Du(r),l=Ou(s,"x-transaction-id")??_u(c)??_u(r),d=function(e){const t=Ou(e,"x-block-number");if(void 0===t)return;const n=Number.parseInt(t,10);return Number.isFinite(n)?n:void 0}(s);return{status:"PROCESSED",data:c,...void 0!==l&&{transactionId:l},...void 0!==d&&{blockNumber:d}}}post(e,t){return this.requestor(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)})}async signNative(e,t){try{return await this.signer.signObject(e,t)}catch(e){if(e instanceof du)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new du(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function Iu(e){const t=e.tokenClassKey;if(void 0===t)throw new du("tokenClassKey is required.","INVALID_TOKEN_IDENTIFIER");const n=function(e){if("string"!=typeof e){const{collection:t,category:n,type:a,additionalKey:s}=e;if([t,n,a,s].some(e=>"string"!=typeof e||""===e))throw new du("Invalid token class key: all four fields are required.","INVALID_TOKEN_IDENTIFIER");return{collection:t,category:n,type:a,additionalKey:s}}if(!e.includes("|")&&!e.includes("$"))throw new du(`Invalid token class key "${e}": a bare symbol is not a class key and none is derived from it. Pass "collection|category|type|additionalKey".`,"INVALID_TOKEN_IDENTIFIER");try{return fi(e)}catch{throw new du(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER")}}(t);return{...n,instance:e.instance??"0"}}function Du(e){const t=xu(e);return t?.Data??t?.data??e}function _u(e){if("string"==typeof e&&""!==e)return e;const t=xu(e);return Ru(t,"transactionId")??Ru(t,"txnId")??Ru(t,"id")}function Ru(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function xu(e){return"object"==typeof e&&null!==e?e:void 0}function Fu(e){return`galaswap-operation-${B()}-${Date.now()}-${e}`}function Bu(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function Ou(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return Uu(n.get(t));const a=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===a)return Uu(t)}function Uu(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function Pu(e,t=3e4){return P.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Mu=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Lu(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Lu(e,t+1));if(e instanceof Map){const n={};for(const[a,s]of e.entries()){const e=String(a);n[e]=Mu.has(e.toLowerCase())?"[REDACTED]":Lu(s,t+1)}return n}if("object"==typeof e){const n={};for(const[a,s]of Object.entries(e))n[a]=Mu.has(a.toLowerCase())?"[REDACTED]":Lu(s,t+1);return n}return e}class $u{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new vn({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??sr("stage").launchpadBaseUrl,a=t.timeout??6e4;this.axios=Pu(n,a),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return Ys(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:ws(e.params)},...void 0!==e.headers&&{headers:e.headers},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};e.data instanceof FormData&&(void 0!==t.headers&&"Content-Type"in t.headers&&delete t.headers["Content-Type"],this.logger.debug("FormData detected - removing Content-Type header for multipart upload")),e.headers&&this.logger.debug("Custom headers provided:",Object.keys(t.headers??{}));const n=e.data instanceof FormData?"[FormData object - multipart/form-data]":Lu(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Lu(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const a=await this.axios.request(t),s=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,a]of Object.entries(e))"string"==typeof a?t[n.toLowerCase()]=a:"number"!=typeof a&&"boolean"!=typeof a||(t[n.toLowerCase()]=String(a));return t}(a.headers);return this.logger.debug("Response:",{status:a.status,data:Lu(a.data),transactionId:s["x-transaction-id"],blockNumber:s["x-block-number"]}),{data:a.data,headers:s,status:a.status}},`HTTP ${e.method} ${e.url}`,this.logger)}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return Ys(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,a={message:n?.message??Pt(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=a,this.logger.error("Backend error:",a)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class Ku extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Gu extends Ku{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Wu 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 Hu(e,t){if(sa(e))throw new Ku(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Ku(`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 Ku(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function qu(e,t,n,a){Hu(e,t);const s=e,r=s.data??{};if(!function(e){if(sa(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)}(r))throw new Ku(`Invalid trade data received for transaction ${t}`);const i={transactionId:t,type:n,method:"native"===a.type?"native":"exact",inputAmount:r.inputQuantity??a.amount,outputAmount:r.outputQuantity??a.expectedAmount??"0",totalFees:r.totalFees??"0",tokenName:a.tokenName,vaultAddress:r.vaultAddress??"",timestamp:Date.now()};return void 0!==s.blockHash&&(i.blockHash=s.blockHash),void 0!==s.gasUsed&&(i.gasUsed=s.gasUsed),void 0!==a.slippageToleranceFactor&&(i.slippageTolerance=a.slippageToleranceFactor),i}function ju(e){if(e&&function(e){return"privateKey"===e.providerType}(e))return e.getWallet()}const Vu={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function zu(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const Xu=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function Qu(e,t,n){if(void 0===e||void 0===t)return;const a=Xu.exec(e)?.[1],s=Xu.exec(t)?.[1];if(void 0!==a&&void 0!==s&&a.toLowerCase()!==s.toLowerCase())throw Xt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Ju{constructor(e){let t,n;this._tokenRoomRefCounts=new Map,this._tokenRoomListeners=new Map,this._tokenRoomUnsubscribers=new Map,e.walletProvider?(t=e.walletProvider,n=ju(e.walletProvider)):e.wallet&&(n=e.wallet,t=tr.fromWallet(e.wallet)),this.wallet=n;const a=e.env??"prod",s=sr(a);this.environment=a,this.config={baseUrl:e.launchpadBaseUrl??s.launchpadBaseUrl,gatewayBaseUrl:s.gatewayBaseUrl,bundleBaseUrl:s.bundleBaseUrl,webSocketUrl:s.webSocketUrl,dexApiBaseUrl:s.dexApiBaseUrl,dexBackendBaseUrl:s.dexBackendBaseUrl,launchpadFrontendUrl:s.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const r=e.signer??(void 0!==n?new Oo(n.privateKey):void 0),i=void 0!==n?`eth|${n.address.slice(2)}`:zu(r);Qu(i,e.walletAddress,"walletAddress"),Qu(i,e.galaChainAddress,"galaChainAddress");const o=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.address.slice(2)}`:zu(r)),c=r??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},l=o??"",d=new hu({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),u=Au({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});if(this.launchpad=new Tu({transport:d,walletAddress:l,sellFeeCeiling:u}),this.tokens=new Nu({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:c,walletAddress:l,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),this.logger=new vn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Ju.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ju.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Ju.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===n?o:void 0),this.auth=new nr({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Js,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new $u(this.auth,this.config),this.sessionAuth=new Zs(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new $u(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new $u(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new $u(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new $u(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=Pu(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new ka(e.debug??!1),this.launchpadService=new ll(this.http,this.jwtAuth),this.tokenResolverService=new Zd(this.launchpadService.poolService),this.launchpadAPI=new Gs(this.http,this.logger,this.bundleHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new Xc(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new oc(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new Wo(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor,u),this.websocketService=new su({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Ul(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const h=e.signer??(void 0===n?void 0:new Oo(n.privateKey)),g=e.walletAddress??(void 0===n?void 0:this.getAddress());this.dexClient=new y({env:this.environment,...void 0===h?{}:{signer:h},...void 0===g?{}:{walletAddress:g},...void 0===this.config.dexBackendBaseUrl?{}:{dexBackendBaseUrl:this.config.dexBackendBaseUrl},...void 0===this.config.gatewayBaseUrl?{}:{gatewayBaseUrl:this.config.gatewayBaseUrl},...void 0===e.httpRequestor?{}:{httpRequestor:e.httpRequestor}}),this.nftCollectionService=new Sl(this.galaChainHttp),this.tradingQuotesService=new eu(this.http,e.debug??!1)}createOverrideSdk(e){if(!aa(e))throw Xt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Xt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n(e),a={...this.config,wallet:t};return new Ju(a)}get dex(){return this.dexClient}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw jt("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new xt("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?ju(e):void 0}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:a,streamAdminApiKey:s,userApiKey:r,accessToken:i,headers:o,...c}=this.config;return{...c,...void 0!==s&&{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:gn.GAS_FEE}}getVersion(){return Vi}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Xt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),a=Math.min(t,100);return n.holders.slice(0,a).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),a=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===a)return null;const s=n.holders[a];return void 0===s?null:{rank:a+1,balance:s.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),a=t?.minBalance??0,s=t?.maxBalance??1/0,r=Math.min(t?.limit??100,1e3),i=new Map;return n.holders.forEach((e,t)=>{i.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=a&&t<=s}).map(e=>({...e,rank:i.get(e.address)??0})).slice(0,r)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:a}=ca(e,"tokenName","tokenId",{description:"token identifier"});if(a&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const s=n;try{return await this.dexService.fetchTokenPrice({tokenId:s})}catch(e){const t=function(e){if($t(e)&&e.response)return e.response.status}(e);if(400===t||404===t){this.logger.debug(`DEX spot price not available (HTTP ${t}) for tokenId, attempting launchpad fallback`);try{const t=mn((await this.fetchTokenDetails(s)).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: ${Pt(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.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}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 _a}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=e?.solanaPrivateKey??globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new Wi({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 So(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new cu(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 Fi({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new lu({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Hl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Ml(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new lo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Yd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new to(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new ru(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Tl(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Ol(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new El(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new Ho(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new ro(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new pl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new nc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new Fl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new tu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new sc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}toLegacyPinnedMessage(e){return{messageId:e.id,content:e.content,userAddress:e.userAddress,pinnedBy:""!==e.pinnedBy?e.pinnedBy:e.userAddress,pinnedAt:""!==e.pinnedAt?e.pinnedAt:e.createdAt}}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}async resolveReferralAddress(e){if(void 0===e||""===e)return this.getAddress();if(e.startsWith("client|"))return e;const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n=t(e);if(void 0===n)throw new xt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new dl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Pl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Bl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new pc(this.http,this.config.events)),this._eventsBatcherService}getStreamWebSocketService(){if(null===this._streamWebSocketService||void 0===this._streamWebSocketService){if(void 0===this.config.streamWebSocketUrl||""===this.config.streamWebSocketUrl)throw new Error('Stream WebSocket URL is required for real-time streaming features.\n\nConfigure SDK:\n const sdk = createLaunchpadSDK({\n wallet: yourWallet,\n streamWebSocketUrl: getEnvironmentConfig("stage").launchpadBaseUrl\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new Qd({url:this.config.streamWebSocketUrl},this.config.debug??!1),this._streamWebSocketService.setStreamingEventService(this.getStreamingEventService())}return this._streamWebSocketService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new Ll(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===n.message?null:this.toLegacyPinnedMessage(n.message)}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);const a=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:null===a.message?null:this.toLegacyPinnedMessage(a.message)}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.id),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.id}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}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 emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}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 getPoolRealtimeState(e){const[t,n,a,s]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===a.status?a.value:null,..."rejected"===a.status&&{recentTradesError:String(a.reason)},price:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{priceError:String(s.reason)}}}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)}watchBanEnforcement(e,t={}){const n=(e,n,a,s)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===a)&&!!(void 0===t.reason||null!==s&&s.includes(t.reason)))),a=this.onUserBanned(t=>{n("BANNED",t.userAddress,t.tokenName,t.reason)&&e({actionType:"BANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason})}),s=this.onUserUnbanned(t=>{n("UNBANNED",t.userAddress,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:t.userAddress,tokenName:t.tokenName,reason:null,timestamp:t.timestamp})}),r=this.onBanEnforcement(t=>{n("ENFORCEMENT",t.userAddress,t.tokenName,t.reason)&&e({actionType:"ENFORCEMENT",userAddress:t.userAddress,tokenName:t.tokenName,reason:t.reason,timestamp:t.timestamp})});return()=>{a(),s(),r()}}watchTokenRoomEvent(e,t,n,a){const s=a.tokenName;if(void 0===s||""===s)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);const r=s.toLowerCase(),i=`${e}:${r}`,o=n;let c=this._tokenRoomListeners.get(i);const l=void 0===c;void 0===c&&(c=new Set,this._tokenRoomListeners.set(i,c)),c.add(o),this._tokenRoomRefCounts.set(r,(this._tokenRoomRefCounts.get(r)??0)+1);const d=this.getStreamWebSocketService(),u=(async()=>{d.isConnected()||await this.connectStreamWebSocket(),await d.subscribeToStream(r),l&&this._tokenRoomUnsubscribers.set(i,t.call(d,r,e=>{for(const t of c)t(e)}))})();let h=!1;return()=>{if(h)return;h=!0,c.delete(o);const e=(this._tokenRoomRefCounts.get(r)??1)-1,t=e<=0;t?this._tokenRoomRefCounts.delete(r):this._tokenRoomRefCounts.set(r,e),u.then(()=>{if(0===c.size){this._tokenRoomListeners.delete(i);const e=this._tokenRoomUnsubscribers.get(i);this._tokenRoomUnsubscribers.delete(i),e?.()}t&&!this._tokenRoomRefCounts.has(r)&&d.unsubscribeFromStream(r)})}}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{void 0!==t.authorAddress&&t.authorAddress!==n.userAddress||void 0!==t.minLength&&n.content.length<t.minLength||e(n)},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||void 0!==t.userAddress&&t.userAddress!==n.userAddress||void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n)},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&(void 0===t.moderatorAddress||t.moderatorAddress===n),a=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),s=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),r=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{a(),s(),r()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,a=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),s=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),r=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{a(),s(),r()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,a=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),s=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{a(),s()}}onDexPoolCreation(e,t={}){const n=t.intervalMs??3e4;let a,s=!1;const r=async()=>{let n;try{n=await this.dex.pools.getPools()}catch{return}if(!s)if(void 0!==a)for(const s of n)a.has(s.poolRef)||(a.add(s.poolRef),void 0!==t.minTVL&&(s.tvlUsd??0)<t.minTVL||(void 0===t.tokens||t.tokens.includes(s.token0)||t.tokens.includes(s.token1))&&e({poolRef:s.poolRef,token0:s.token0,token1:s.token1,fee:s.fee,tvlUsd:s.tvlUsd}));else a=new Set(n.map(e=>e.poolRef))};r();const i=setInterval(()=>{r()},n);return()=>{s=!0,clearInterval(i)}}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 _a}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return vo}),a=t(e.tokenId),{collection:s,category:r,type:i,additionalKey:o}=a;return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:r,additionalKey:o,type:i,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=fn(e.tokenName),a=Vu[t];if(void 0!==a)return this.galaChainService.fetchTokenBalance({owner:n,collection:a,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 a=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:a.collection,category:a.category,tokenId:rr(a)}}throw jt("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:a,privateKey:s,calculateAmountMode:r,currentSupply:i}=e;let o=t;void 0===r&&void 0===i||(o={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==i&&{currentSupply:i}});const c=await this.calculateBuyAmountForGraduation(o),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!==a&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=a),void 0!==s&&(l.privateKey=s),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,...a}=e;return t.buy(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Qt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>qu(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.sell(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Qt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>qu(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,...a}=e;return t.launchToken(a)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{Hu(n,t);const a=n.data??{};if(!function(e){if(sa(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)}(a))throw new Ku(`Invalid launch data received for transaction ${t}`);const s={transactionId:t,vaultAddress:a.vaultAddress??"",tokenStringKey:a.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:a.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&&(s.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(s.preBuyQuantity=e.preBuyQuantity),""!==s.vaultAddress&&this.tokenResolverService.set(e.tokenName,s.vaultAddress),s})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...a}=e;return t.uploadTokenImage(a)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(L,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,a=e?.limit??10,s={pageNumber:n,limit:a,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},r=await this.dexApiHttp.get($,s,{"x-wallet-address":t});if(!Array.isArray(r))throw new Ft("Unexpected API response: expected array, got "+typeof r);return{referrals:r,page:n,limit:a,hasMore:r.length===a}}async fetchAllReferrals(e){const t=await ho((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(K,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Ft(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.updateProfile(a)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.uploadProfileImage(a)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n=t(e?.address)??this.getAddress(),a={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(a.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(a.search=e.search),this.launchpadService.fetchTokensHeld(a)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n={type:"created",address:t(e?.address)??this.getAddress(),pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(n.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(n.search=e.search),void 0!==e?.status&&(n.status=e.status),this.launchpadService.fetchTokenList(n)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async fetchPriceHistory(e){return this.priceHistoryService.fetchPriceHistory(e)}async fetchAllPriceHistory(e){return this.priceHistoryService.fetchAllPriceHistory(e)}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.transferGala(a)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return _a}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...a}=n;return e.transferToken(a)}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 _a});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,...a}=n;return e.lockTokens(a)}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,...a}=e;return t.unlockTokens(a)}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,...a}=e;return t.burnTokens(a)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let a=0;a<10;a+=1){const a=await this.launchpadAPI.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),s=a.items.find(t=>t.vaultAddress===e);if(void 0!==s)return s.tokenName;if(!a.pageInfo.hasNextPage||void 0===a.pageInfo.nextCursor)return;n=a.pageInfo.nextCursor}}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{Yn(this.config.timeout,1,3e5,"timeout")}catch{this.logger.warn(`Invalid timeout value: ${this.config.timeout??"undefined"}. Using default 30000ms.`),this.config.timeout=3e4}if(void 0===this.config.baseUrl||""===this.config.baseUrl)throw Xt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Xt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Xt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Xt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Xt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Xt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Xt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Hn("string"==typeof e||"number"==typeof e?e:String(e),Ju.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Ju.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ju.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Hn("string"==typeof e||"number"==typeof e?e:String(e),Ju.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: ${Ju.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ju.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==qi.COMPLETED)throw new Wu(e,n.status,n.message);let a;try{a=t(n)}catch(t){if(t instanceof Ku)throw t;throw new Ku(`Failed to transform WebSocket response for transaction ${e}`,Ut(t)?t:new Error(Pt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,a),a}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Wu||t instanceof Ku)throw t;throw new Ku(`WebSocket confirmation failed for transaction ${e}`,Ut(t)?t:new Error(Pt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return rh});e.forEach(e=>{if(!n(e))return;const a=t(e,this.logger);a&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,a)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,a=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 s=t?.creatorAddress,r=new Map;let i=!0,o=null;let c=0;const l=async()=>{if(i){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=>{r.has(t.tokenName)||((e=>{if(r.set(e,!0),r.size>1e3){const e=r.keys().next().value;void 0!==e&&r.delete(e)}})(t.tokenName),void 0!==s&&""!==s&&t.creatorAddress!==s||e(t))})}catch(e){c++;const t=Pt(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(i){const e=Math.min(Math.max(c-1,0),2),t=a*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{i=!1,o&&clearTimeout(o),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw Xt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,a=null;const s=(n,...a)=>{try{if(a.length>0&&"object"==typeof a[0]&&null!==a[0]){const n=a[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const a=n.Data;if("CreateSale"===a.functionName){const n={tokenName:""!==a.tokenName?a.tokenName:"",symbol:""!==a.symbol?a.symbol:"",creatorAddress:""!==a.creatorAddress?a.creatorAddress:"",description:""!==a.description?a.description:"",image:""!==a.image?a.image:"",vaultAddress:""!==a.vaultAddress?a.vaultAddress:"",tokenStringKey:""!==a.tokenStringKey?a.tokenStringKey:"",preBuyQuantity:""!==a.initialBuyQuantity?a.initialBuyQuantity:"0",websiteUrl:""!==a.websiteUrl?a.websiteUrl:"",telegramUrl:""!==a.telegramUrl?a.telegramUrl:"",twitterUrl:""!==a.twitterUrl?a.twitterUrl:"",instagramUrl:""!==a.instagramUrl?a.instagramUrl:"",facebookUrl:""!==a.facebookUrl?a.facebookUrl:"",redditUrl:""!==a.redditUrl?a.redditUrl:"",tiktokUrl:""!==a.tiktokUrl?a.tiktokUrl:"",isFinalized:!1!==a.isFinalized&&null!==a.isFinalized&&void 0!==a.isFinalized&&a.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Pt(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(s),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: ${Pt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(r=this.websocketService.getSocket(),!r&&e<Ju.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(a=setTimeout(()=>i(),Ju.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=Ju.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ju.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Ju.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}r&&(r.onAny(s),n=!0,this.logger.debug("Token creation broadcast listener registered"))};i()}return()=>{try{if(null!==a&&(clearTimeout(a),a=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(s),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}getNftCollectionClaimFee(){return this.nftCollectionService.getCollectionClaimFee()}getNftTokenClassCreateFee(){return this.nftCollectionService.getTokenClassCreateFee()}estimateNftMintFee(e){return this.nftCollectionService.estimateMintFee(e)}estimateNftOperationFees(e){return this.nftCollectionService.estimateNftOperationFees(e)}claimNftCollection(e){return this.nftCollectionService.claimCollection(e)}fetchNftCollections(e){return this.nftCollectionService.fetchUserCollections(e)}isNftCollectionAvailable(e){return this.nftCollectionService.isCollectionAvailable(e)}createNftTokenClass(e){return this.nftCollectionService.createTokenClass(e)}fetchNftTokenClasses(e){return this.nftCollectionService.fetchTokenClasses(e)}mintNft(e){return this.nftCollectionService.mintNft(e)}fetchNftBalances(e,t){return this.nftCollectionService.fetchNftBalances(e,t)}async cleanup(){try{if(this.logger.debug("Starting cleanup..."),void 0!==this._eventsBatcherService)try{await this._eventsBatcherService.shutdown(5e3),this._eventsBatcherService=void 0}catch(e){this.logger.warn("Error during events shutdown:",e)}this.http.cleanup(),null!==this.websocketService&&void 0!==this.websocketService&&this.websocketService.disconnect(),void 0!==this._streamWebSocketService&&(this._streamWebSocketService.disconnect(),this._streamWebSocketService=void 0),this.logger.debug("Cleanup completed")}catch(e){this.logger.error("Error during cleanup:",e)}}static cleanupAll(e=!1){const t=new vn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),su.cleanupAll(e),t.debug("Global cleanup completed")}}function Yu(){const e=globalThis;return e.process?.env??{}}Ju.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ju.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ju.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=gn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ju.DEFAULT_CALCULATE_AMOUNT_MODE="local",Ju.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Ju.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let Zu=0;class eh{constructor(){this.utilityInstance=!0,this.utilityInstance}static generateWallet(){try{const e=n.createRandom();if(null===e.mnemonic?.phrase||void 0===e.mnemonic?.phrase||""===e.mnemonic.phrase)throw jt("mnemonic","Mnemonic phrase");const t=eh.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new n(e.privateKey)}}catch(e){if("test"===Yu().NODE_ENV){const e=`test-wallet-${Date.now()}-${++Zu}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),a=new n(t),s=eh.toGalaAddress(a.address);return{privateKey:a.privateKey,address:a.address,galaAddress:s,mnemonic:"test test test test test test test test test test test junk",wallet:a}}throw e}}static fromPrivateKey(e){const t=new n(e),a=eh.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:a,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const a=l.fromPhrase(e),s=d.fromMnemonic(a,`m/44'/60'/0'/0/${t}`),r=new n(s.privateKey),i=eh.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}catch(a){if("test"===Yu().NODE_ENV){const a=`test-mnemonic-index-${t}-${e}`,s="0x"+Buffer.from(a).toString("hex").padStart(64,"1").slice(0,64),r=new n(s),i=eh.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}throw a}}static toGalaAddress(e){const n=Ea(e);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Vt("address","a valid Ethereum address (40 hex characters)");return`eth|${t(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return Ca(e)}catch(t){const n=Pt(t);if(n.includes("required")||!e?.startsWith("eth|"))throw jt("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Vt("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=Ea(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===Da(e)}static generateMultipleWallets(e=1){Yn(e,1,100,"count");const t=[];if("test"===Yu().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++Zu}`,a="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(eh.fromPrivateKey(a))}else for(let n=0;n<e;n++)t.push(eh.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${null!==e.mnemonic&&void 0!==e.mnemonic&&""!==e.mnemonic?e.mnemonic:"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function th(e){if(void 0===e)return eh.generateWallet();const t=e.trim();if(!aa(t))throw Vt("input","a non-empty string");if(function(e){const t=Ea(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return eh.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 eh.fromMnemonic(t);throw Vt("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function nh(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Vt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new h(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function ah(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Vt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t(u(e))}function sh(e){sa(e)&&(e={});const{wallet:t,env:a,config:s={},...r}=e,i={...{...r,...s}};delete i.wallet,delete i.env,delete i.config;const o=!sa(i.signer)||!sa(i.walletProvider);let c;if(sa(t))c=o?void 0:th().wallet;else if("string"==typeof t){c=th(t).wallet}else{if(!(t instanceof n))throw Xt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");c=t}const l={...void 0!==c?{wallet:c}:{},...void 0!==a?{env:a}:{},debug:!1,timeout:3e4,...i};return new Ju(l)}var rh=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const a=Hn(e.reverseBondingCurveMinFeePortion,NaN);isNaN(a)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=a}if(void 0!==e.reverseBondingCurveMaxFeePortion){const a=Hn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(a)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=a}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{Po as BrowserWalletSigner,mc as EVENT_TYPES,Uo as GalaWalletSigner,Ju as LaunchpadSDK,du as LaunchpadSDKError,Oo as PrivateKeySigner,Vi as SDK_VERSION,Wu as TransactionFailedError,Ku as WebSocketError,Gu as WebSocketTimeoutError,sh as createLaunchpadSDK,th as createWallet,ah as getEthereumAddressFromPrivateKey,nh as getPublicKeyFromPrivateKey};
|
|
1
|
+
import{z as e}from"zod";import{getAddress as t,computeAddress as n,isAddress as s,BrowserProvider as r,Wallet as i}from"ethers";import{PrivateKeyProvider as a,isPrivateKeyProvider as o}from"@gala-chain/gala-core-sdk/providers";import{GALA_CHAIN_ENVIRONMENTS as c,BrowserWalletSigner as l,generateEIP712Types as d,ethereumAddressOfAccount as u,GalaWalletSigner as h,withGalaWalletIdentity as g,PrivateKeySigner as m,isTokenClassKey as f,GatewayReads as p,isGalaError as v,GatewayWrites as A,tokenDetailsOf as E,isWalletUserRejection as y,walletDeclineCode as T,createWallet as S}from"@gala-chain/gala-core-sdk";import{ChainCallDTO as b,TokenClassKey as k}from"@gala-chain/api";import{v4 as w}from"uuid";import{io as N}from"socket.io-client";import _ from"bignumber.js";import I,{AxiosHeaders as C}from"axios";const D={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_CURRENT_USER:"/v1/users/me/profile",UPLOAD_PROFILE_IMAGE:"/v1/users/me/image",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",GET_GALA_BALANCE:"/v1/users/:address/gala-balance",GET_REFERRAL_CODE:"/v1/connect/users/referrals/code",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"},R="/v1/users/referrals/url",O="/v1/users/referrals",M="/v1/users/referrals/summary",U="/v1/tokens/:tokenName/start-stream",L="/v1/tokens/:tokenName/stop-stream",F="/v1/tokens/:tokenName/stream/disable",x="/v1/tokens/:tokenName/stream/enable",P="/v1/tokens/:tokenName/reset-key",B="/v1/tokens/:tokenName/recordings",$="/v1/tokens/:tokenName/recordings/:assetId/download",G="/v1/tokens/:tokenName/recordings/:assetId",K="/v1/tokens/:tokenName/simulcasts",W="/v1/tokens/:tokenName/simulcasts",H="/v1/tokens/:tokenName/simulcasts/:targetId",j="/v1/config",q="/v1/config",V="/v1/config",z="/v1/tokens/:tokenName/role",Q="/v1/roles",X="/v1/permissions",J="/v1/tokens/:tokenName/credentials",Y="/auth/login",Z="/auth/logout",ee="/auth/refresh",te="/auth/session",ne="/v1/tokens/:tokenName/bans",se="/v1/tokens/:tokenName/bans",re="/v1/tokens/:tokenName/bans/:userAddress",ie="/v1/tokens/:tokenName/bans/:userAddress",ae="/v1/tokens/:tokenName/active-users",oe="/v1/user-bans",ce="/v1/user-bans",le="/v1/user-bans/:userAddress",de="/v1/user-bans/:userAddress",ue={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},he="/v1/moderator-invites",ge="/v1/moderator-invites/claim",me="/v1/moderated-tokens",fe="/v1/moderator-invites",pe="/v1/moderator-invites/:id",ve="/v1/moderator-invites/:id/role",Ae="/v1/moderator-invites/:id",Ee="/v1/moderator-invites/code/:code",ye={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Te="/v1/overseer-invites",Se="/v1/overseer-invites",be="/v1/overseer-invites/code/:code",ke="/v1/overseer-invites/claim",we="/v1/overseer-invites/:id",Ne="/v1/overseers",_e="/v1/overseers",Ie="/v1/overseers/:address",Ce="/v1/overseers/me",De="/v1/overseer-summary",Re="/v1/overseer-summary/bans",Oe="/v1/overseer-summary/token-bans",Me="/v1/overseer-summary/invites",Ue="/v1/overseer-summary/flags",Le="/v1/overseer-summary/users",Fe="/v1/users",xe="/v1/users/:address/summary",Pe="/v1/cache/flush/address/:address",Be="/v1/cache/flush/token/:tokenName",$e="/v1/cache/flush/all",Ge="/v1/cache/flush/wallet-aliases/:address",Ke="/v1/cache/flush/wallet-aliases",We="/v1/token-bans",He="/v1/token-bans",je="/v1/token-bans/:tokenName",qe="/v1/token-bans/:tokenName",Ve="/v1/reactions",ze="/v1/reactions",Qe="/v1/trades",Xe={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/pin",GET_MESSAGE_STATS:"/v1/messages/stats"},Je="/v1/restricted-token-names",Ye="/v1/restricted-token-names",Ze="/live/:tokenName/chat",et="/live/:tokenName/chat",tt="/live/:tokenName/chat",nt="/live/:tokenName/chat/slow-mode",st="/v1/events",rt="/v1/events/stats",it="/health",at={GET_SETTINGS:"/v1/ai-moderation/settings",UPDATE_SETTINGS:"/v1/ai-moderation/settings",GET_MODERATION:"/v1/ai-moderation/flags/:flagId",TRIGGER_MODERATION:"/v1/ai-moderation/flags/:flagId/analyze",GET_STATUS:"/v1/ai-moderation/status"},ot="/v1/stats",ct="/v1/trading/fee",lt="/v1/trading/sale-details",dt="/v1/trading/quote",ut="/v1/trading/premint-quote",ht={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},gt="/v1/notifications/register",mt="/v1/notifications/unregister",ft="/v1/notifications/preferences",pt="/v1/notifications/preferences",vt="/v1/config/client-flags",At="native",Et="exact",yt=["RECENT","POPULAR","RECORDINGS","SECONDS_STREAMED"],Tt=["IDLE","ACTIVE","DISABLED"],St=100,bt="REQUIRED",kt="INVALID_TYPE",wt="INVALID_VALUE",Nt="INVALID_FORMAT",_t="TOO_LONG",It="TOO_LARGE",Ct="INVALID_RANGE",Dt="INVALID_PARAMETERS";class Rt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}function Ot(e){return"object"==typeof e&&null!==e}function Mt(e){if(null==e||""===e)return{};if(!Ot(e)||Array.isArray(e))return{body:e};const t=Reflect.get(e,"message"),n="string"==typeof t?t:Array.isArray(t)&&t.every(e=>"string"==typeof e)?t.join(","):void 0,s=Reflect.get(e,"error"),r=Reflect.get(e,"details");return{...void 0===n?{}:{serverMessage:n},..."string"==typeof s&&""!==s?{serverError:s}:{},...void 0===r?{}:{details:r},body:e}}function Ut(e){if(e instanceof Lt)return{...void 0===e.serverMessage?{}:{serverMessage:e.serverMessage},...void 0===e.serverError?{}:{serverError:e.serverError},...void 0===e.details?{}:{details:e.details},...void 0===e.body?{}:{body:e.body}};const t=function(e){if(!Ot(e))return;const t=Reflect.get(e,"response");return Ot(t)?t:void 0}(e);return void 0===t?{}:Mt(Reflect.get(t,"data"))}class Lt extends Error{constructor(e,t,n,s=Ut(n)){super(e),this.name="NetworkError",this.statusCode=t,this.originalError=n,this.serverMessage=s.serverMessage,this.serverError=s.serverError,this.details=s.details,this.body=s.body}}class Ft extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class xt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Pt(e){return e instanceof Error}function Bt(e){return Pt(e)||function(e){return"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message}(e)?e.message:"string"==typeof e?e:String(e)}function $t(e){return Pt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function Gt(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 Kt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Wt(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 s=n.Status;if("number"!=typeof s)throw new Error(`${t}: Response Status must be a number, got ${typeof s}`);if(1!==s)throw new Error(`${t}: Response status indicates failure (Status: ${s})`);return n}function Ht(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)}}}function jt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function qt(e,t){return new Rt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Vt(e,t){const n=jt(e,t);return new Rt(`${n} is required`,e,"REQUIRED")}function zt(e,t,n){const s=jt(e,n);return new Rt(`${s} must be ${t}`,e,"INVALID_FORMAT")}function Qt(e,t,n,s){return new Lt(e,t,n,s)}function Xt(e,t){return new Ft(e,t)}function Jt(e,t,n){return new xt(e,t,n)}function Yt(e,t,n,s,r){const i=jt(e,r);return new Rt(`${i} must be between ${t} and ${n}${void 0!==s?`, received: ${s}`:""}`,e,"OUT_OF_RANGE")}function Zt(e,t,n,s){const r=jt(e,s);return new Rt(`${r} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function en(e,t,n,s){const r=jt(e,s);return new Rt(`${r} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function tn(e,t,n,s){const r=jt(e,s),i=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Rt(`${r} must be ${t}${i}`,e,"INVALID_TYPE")}function nn(e,t,n){const s=jt(e,n);return new Rt(`${s} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function sn(e,t,n,s){const r=jt(e,s);return new Rt(`Invalid ${r}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function rn(e){return null!=e&&"object"==typeof e&&"data"in e}function an(e,t,n=!1){const s=!0===e.error,r=n&&(null===e.data||void 0===e.data);if(s||r){const n=e?.statusCode??e.status??void 0;throw Qt(e?.message??t,n,void 0,s?Mt(e):void 0)}}function on(e){if(rn(e))return e.data}function cn(e,t="No data found in response"){if(!rn(e))throw Qt(t);const n=e.data;if(null==n)throw Qt(t);return n}async function ln(e,t={}){return hn(e,t,e=>{if(void 0===e.data)throw new Rt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function dn(e,t={}){const{errorContext:n="Operation failed",logger:s,debugLogEnabled:r=!1}=t;r&&s&&s.debug(`${n}: starting operation`);try{const t=await e();return r&&s&&s.debug(`${n}: completed successfully`),t}catch(e){throw s&&s.error(n,{error:e}),e}}async function un(e,t={}){return hn(e,t,e=>e)}async function hn(e,t,n){const{errorContext:s="Operation failed",logger:r,debugLogEnabled:i=!1}=t;i&&r&&r.debug(`${s}: starting operation`);try{const t=await e();if(null==t)throw new Rt(`${s}: No response from server`,"response","NO_RESPONSE");return an(t,s,!0),i&&r&&r.debug(`${s}: completed successfully`),n(t)}catch(e){throw r&&r.error(s,{error:e}),e}}const gn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function mn(e){return e.trim().toLowerCase()}function fn(e){return e.trim().toUpperCase()}var pn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(pn||(pn={}));class vn{constructor(e){this.levelPriority={[pn.DEBUG]:0,[pn.INFO]:1,[pn.WARN]:2,[pn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?pn.DEBUG:pn.INFO)}debug(e,t){this.log(pn.DEBUG,e,t)}info(e,t){this.log(pn.INFO,e,t)}warn(e,t){this.log(pn.WARN,e,t)}error(e,t){this.log(pn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===pn.DEBUG&&!this.debugEnabled)return;const s=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,r=this.getConsoleMethod(e);void 0!==n?Pt(n)?r(`${s} ${t}`,n.message,$t(n)??""):r(`${s} ${t}`,n):r(`${s} ${t}`)}getConsoleMethod(e){switch(e){case pn.DEBUG:return console.debug;case pn.INFO:return console.info;case pn.WARN:return console.warn;case pn.ERROR:return console.error;default:return console.log}}child(e){return new vn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[pn.DEBUG]>=this.levelPriority[this.minLevel]}}function An(e){return null==e||""===e}function En(e){return null==e}const yn=new vn({debug:!1,context:"DateUtils"});function Tn(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 Sn(e,t=0){if(An(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 bn(e,t=0){if(En(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Sn(String(e).replace("%","").trim(),t)}function kn(e,t=18){const n=Sn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function wn(e){return kn(e,8)}function Nn(e){return kn(e,18)}function _n(e,t,n,s){if("number"!=typeof e)throw tn(s,"a number",e,s);if(e<t||e>n)throw Yt(s,t,n,e)}function In(e,t,n){if("string"!=typeof e)throw tn(n,"a string",e,n);if(e.length>t)throw en(n,t,e.length)}function Cn(e,t){if("number"!=typeof e)throw tn(t,"a number",e,t);if(!Number.isInteger(e))throw tn(t,"an integer",e,t);if(e<=0)throw Zt(t,1,e,t)}function Dn(e,t,n=!1){if("string"!=typeof e)throw tn(t,"a string",e,t);if(!n&&0===e.trim().length)throw Vt(t,`${t} (non-empty string)`)}const Rn={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},On=function(e){return"string"==typeof e&&e.trim().length>0},Mn=En;function Un(e,t,n=100,s,r){if(void 0!==r&&"string"!=typeof r)throw new Rt("cursor must be a string","cursor",kt);const i=s??t,a=void 0!==s?"pageSize":"limit";if(void 0!==i&&(Cn(i,a),i>n))throw new Rt(`${a} must be at most ${n}`,a,It)}function Ln(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Fn(e){return Object.values(e)}function xn(e,t,n){if(!On(e))throw Vt(t);const s=e.trim();if(0===s.length)throw Vt(t);if(s.length<n.MIN_LENGTH)throw Yt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(s.length>n.MAX_LENGTH)throw Yt(t,n.MIN_LENGTH,n.MAX_LENGTH,s.length,`${t} length`);if(!n.PATTERN.test(s))throw new Rt(`${t} must be ${n.DESCRIPTION}`,t,Nt)}function Pn(e,t,n){if(null==e)throw Vt(t,t);if("string"!=typeof e)throw tn(t,"a string",e);const s=e.trim();if(0===s.length)throw Vt(t,t);if(!n.PATTERN.test(s))throw new Rt(`${t} must be ${n.DESCRIPTION}`,t,Nt)}function Bn(e){return""===e||0===e.trim().length}function $n(e,t,n){if(!Mn(e)){if("string"!=typeof e)throw tn(t,"a string",e,t);if(e.length>n)throw new Rt(`${t} must be at most ${n} characters`,t,It)}}function Gn(e,t){Mn(e)||function(e,t){const n=e instanceof Date?e:"string"==typeof e||"number"==typeof e?new Date(e):void 0;if(void 0===n)throw tn(t,"a date",e,t);if(isNaN(n.getTime()))throw new Rt(`${t} must be a valid date`,t,Nt)}(e,t)}function Kn(e,t,n){try{Cn(e,t)}catch{throw function(e,t,n,s="OPERATION_FAILED"){return new Rt(`${e} failed: ${t}`,n,s)}(n,"must be a positive integer",t)}}function Wn(e,t,n="status"){void 0!==e&&function(e,t,n){const s=Object.values(t);if(!s.includes(e))throw new Rt(`${n} must be one of: ${s.join(", ")}`,n,Nt)}(e,t,n)}class Hn{constructor(e,t=!1,n){this.http=e,this.logger=new vn({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){const e=globalThis;if("test"===e.process?.env?.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new Ft("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=$t(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Kn(e,t,n)}}class jn{constructor(e=!1,t){this.logger=t||new vn({debug:e,context:this.constructor.name})}}class qn extends jn{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 Vn extends qn{constructor(e=!1){super(e)}normalizeKey(e){return mn(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>=Vn.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??gn.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,s)=>{n.lastUpdated<e&&(e=n.lastUpdated);let r=0;r+=2*s.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:${mn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${mn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${mn(e)}`;return this.cache.has(t)}}Vn.MAX_CACHE_SIZE=1e4;const zn={MIN_LENGTH:1,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{1,20}$/,DESCRIPTION:"1-20 letters and digits"},Qn={MIN_LENGTH:1,MAX_LENGTH:255,PATTERN:/^[a-zA-Z0-9]{1,255}$/,DESCRIPTION:"1-255 letters and digits"},Xn={MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[\s\S]{1,50}$/,DESCRIPTION:"1-50 characters"},Jn={MIN_LENGTH:1,MAX_LENGTH:100,PATTERN:/^(?![\s\S]*<[^>]*>)[\s\S]{1,100}$/,DESCRIPTION:"1-100 characters without HTML"},Yn=100,Zn=100,es=50,ts={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},ns=100,ss={COMMENTS_V1:{MAX_LENGTH:2e3},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}},rs={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})$/}},is=60,as=31536e3,os={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},cs=64,ls=1,ds=100,us={FULL_NAME:{MIN_LENGTH:2,MAX_LENGTH:20,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?: [a-zA-Z]+)?$/}},hs={ETHEREUM:Rn.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Rn.BACKEND_ADDRESS,CLIENT:Rn.CLIENT_ADDRESS};class gs{toBackendFormat(e){if(!On(e))throw new Rt("Address is required and must be a string","address","REQUIRED");let n=e;if(e.startsWith("eth|")){if(n=e.slice(4),!/^[a-fA-F0-9]{40}$/.test(n))throw new Rt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=fs(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new Rt(`Invalid Ethereum address format. Expected 40 hex characters (with or without 0x prefix). Got: "${e}"`,"address","INVALID_FORMAT");return`eth|${t(`0x${n}`).slice(2)}`}toEthereumFormat(e){if(!On(e))throw new Rt("Backend address is required and must be a string","address","REQUIRED");const t=e.match(/^eth\|(0x)?([0-9a-fA-F]{40})$/i);if(!t)throw new Rt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],s=void 0!==n&&""!==n?6:4;return`0x${e.substring(s)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!hs.CLIENT.test(e))throw new Rt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!hs.BACKEND.test(e))throw new Rt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!On(e)&&(!!hs.ETHEREUM.test(e)||(!!hs.ETHEREUM_NO_PREFIX.test(e)||(!!hs.BACKEND.test(e)||!!hs.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new Rt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return On(e)?hs.ETHEREUM.test(e)||hs.ETHEREUM_NO_PREFIX.test(e)?"ethereum":hs.BACKEND.test(e)?"backend":hs.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 fs(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new Rt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const ms=new gs;function fs(e){return e.startsWith("0x")?e.slice(2):e}function ps(e){return ms.toBackendFormat(e)}function vs(e){return ms.isValid(e)}const As=/^(eth\|[a-f0-9]{40}|client\|[a-f0-9]{24})$/;function Es(e){if(!On(e))return!1;const t=e.toLowerCase().trim();if(t.startsWith("eth|")||t.startsWith("client|")||t.startsWith("service|"))return As.test(t.replace(/0x/g,""));const n=t.replace(/^0x/,"");return As.test(/^[0-9a-f]{24}$/.test(n)?`client|${n}`:`eth|${n}`)}function ys(e,t){if(!Es(e))throw new Rt(`${t} must be a GalaChain user address (eth|<40 hex>, 0x<40 hex> or client|<24 hex>)`,t,"INVALID_FORMAT")}function Ts(e,t="address"){ms.assertValid(e,t)}var Ss=Object.freeze({__proto__:null,AddressFormatter:gs,assertBackendUserAddress:ys,assertValidWalletAddress:Ts,isBackendUserAddress:Es,isValidAddress:vs,normalizeAddressInput:function(e){return ms.normalizeInput(e)},stripHexPrefix:fs,toBackendAddressFormat:ps});const bs=e.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").regex(/^[a-zA-Z0-9]+$/,"Token name can only contain letters and numbers"),ks=bs.max(20,"Token name must be at most 20 characters"),ws=e.string({message:"Token name is required"}).min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Ns=e.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"),_s=e.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Is=e.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Cs=e.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),Ds=e.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");e.string().regex(Rn.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.string().regex(Rn.ETH_ADDRESS,"Invalid Ethereum address format");const Rs=e.string().refine(e=>Rn.BACKEND_ADDRESS.test(e)||Rn.ETH_ADDRESS.test(e)||Rn.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new gs).normalizeInput(e)??e),Os=e.string().refine(e=>Rn.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Ms=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Sn(e,0)>0,"Amount must be greater than zero"),Us=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Sn(e,0)>=0,"Amount must be zero or greater");e.string().url("Must be a valid URL").regex(/^https?:\/\//,"URL must start with http:// or https://");const Ls=e.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function Fs(t=100){return e.number().int("Limit must be an integer").min(1,"Limit must be at least 1").max(t,`Limit must be at most ${t}`).default(10)}e.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),Fs(100),Fs(20),Fs(20);const xs=e.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"),Ps=e.string().max(255,"Filename must be at most 255 characters"),Bs=e.enum(["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"]);e.string().datetime("Must be a valid ISO 8601 date string"),e.number().int("Timestamp must be an integer").min(0,"Timestamp must be non-negative");const $s=e.string().regex(/^0x[a-fA-F0-9]{64}$/,"Private key must be format: 0x + 64 hex characters");e.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"),e.string().regex(/^galaconnect-operation-[a-z0-9-]+$/,"Unique key must be format: galaconnect-operation-{unique-id}");const Gs=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),name:Ps,size:xs,type:Bs});const Ks=e.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"),Ws=e.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.union([Ks,Ws]),e.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ps.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Gs.includes(t)},`Filename must end with one of: ${Gs.join(", ")}`),e.object({websiteUrl:Ls,telegramUrl:Ls,twitterUrl:Ls,instagramUrl:Ls,facebookUrl:Ls,redditUrl:Ls,tiktokUrl:Ls}).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");const Hs=e.string().min(1,"Token category must not be empty").default("Unit"),js=e.string().min(1,"Token collection must not be empty").default("Token"),qs=e.object({minFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Sn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Sn(e,0)<=.5,"Minimum fee must be <= 0.5").default("0.1"),maxFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Sn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Sn(e,0)<=.5,"Maximum fee must be <= 0.5").default("0.5")}).refine(e=>Sn(e.maxFeePortion,0)>=Sn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Vs=e.object({tokenName:bs,tokenSymbol:Ns,tokenDescription:_s,tokenImage:e.union([e.instanceof(File),e.instanceof(Buffer),e.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Us.default("0"),websiteUrl:Ls,telegramUrl:Ls,twitterUrl:Ls,instagramUrl:Ls,facebookUrl:Ls,redditUrl:Ls,tiktokUrl:Ls,tokenCategory:Hs,tokenCollection:js,reverseBondingCurveConfiguration:qs.optional(),saleStartTime:e.number().int().positive().optional(),privateKey:$s.optional()});e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),tokenName:bs}),e.enum(yt);const zs=e.object({tokenName:ws.optional(),symbol:Ns.optional()}).refine(e=>void 0!==e.tokenName||void 0!==e.symbol,"At least one of tokenName or symbol is required");e.enum(["NATIVE","MEME"]),e.enum(["IN","OUT"]);const Qs=e.object({from:e.number().int("From timestamp must be an integer").min(173e6,"From timestamp must be at least 173000000"),to:e.number().int("To timestamp must be an integer").min(173e6,"To timestamp must be at least 173000000"),resolution:e.number().int("Resolution must be an integer").min(1,"Resolution must be at least 1"),tokenName:ks});e.object({tokenName:ks,slippageToleranceFactor:e.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.number().min(0).max(1).optional(),privateKey:$s.optional()});const Xs=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(100).default(10)}),Js=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)}),Ys=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)});Xs.extend({type:e.enum(["RECENT","POPULAR"]).optional(),tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),Js.extend({tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),Ys.extend({tradeType:e.enum(["BUY","SELL"]).optional(),tokenName:e.string().min(1).max(50).optional(),userAddress:e.string().regex(/^(0x[a-fA-F0-9]{40}|eth\|[a-fA-F0-9]{40})$/).optional(),startDate:e.string().datetime().optional(),endDate:e.string().datetime().optional(),sortOrder:e.enum(["ASC","DESC"]).default("DESC")});const Zs={page:e.number().int().min(1),limit:e.number().int().min(1),total:e.number().int().min(0),totalPages:e.number().int().min(0),hasNext:e.boolean(),hasPrevious:e.boolean()};e.object(Zs);const er=e.enum(["buy","sell"]);e.enum(["BUY","SELL"]),e.object({tradeType:er,tokenAmount:Ms,vaultAddress:Os,userAddress:Rs,slippageTolerance:Ms.optional(),deadline:e.number().int().positive().optional()}),e.object({tokenSymbol:Ns,nativeTokenQuantity:Ms,expectedToken:Ms,maxAcceptableReverseBondingCurveFee:Us.default("0").optional()}),e.object({tokenSymbol:Ns,tokenQuantity:Ms,expectedNativeToken:Ms,maxAcceptableReverseBondingCurveFee:Us.default("0").optional()}),Ys.extend({tokenName:Is.optional()}),e.object({page:e.number().int().min(1).max(1e3).default(1).optional(),limit:e.number().int().min(1).max(20).default(10).optional()});const tr=e.enum(["NATIVE","MEME"]),nr=e.enum(["IN","OUT"]);e.object({type:tr,method:nr,vaultAddress:Os,amount:Ms}),e.object({nativeTokenQuantity:Ms}),e.object({vaultAddress:Os}),e.object({minFeePortion:Ms,maxFeePortion:Ms});const sr=e.enum(["both","held","created"]);function rr(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)}}}Js.extend({type:sr.optional(),address:Rs.optional(),search:Cs.optional(),tokenName:Is.optional()}),e.object({address:Rs.optional(),refresh:e.boolean().optional()}),e.object({profileImage:e.string().nullable().optional(),fullName:Ds.optional(),address:Rs.optional(),privateKey:$s.optional()}),e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),address:Rs.optional(),privateKey:$s.optional()}),e.object({address:Rs,tokenId:e.union([e.string(),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string()}),e.object({collection:e.string(),category:e.string(),type:e.string(),additionalKey:e.string(),instance:e.string()})]).optional(),tokenName:Is.optional(),withExpired:e.boolean().optional()}).refine(e=>void 0!==e.tokenId||void 0!==e.tokenName,"At least one token identifier (tokenId or tokenName) is required");const ir=rr(bs),ar=rr(Vs),or=rr(zs);function cr(e){const t=function(e){const t=ar(e);return t.success?[]:t.errors??["Unknown validation error"]}(e);if(t.length>0)throw new Error(`LaunchTokenData validation failed:\n${t.map(e=>`- ${e}`).join("\n")}`)}function lr(e,t){return"string"==typeof e[t]}function dr(e,t){return void 0===e[t]||"string"==typeof e[t]}function ur(e,t){return void 0===e[t]||"number"==typeof e[t]}function hr(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}}Ln({BUY:"buy",SELL:"sell"});const gr=(mr={nativeTokenQuantity:"string"},e=>{if(null==e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;for(const[e,n]of Object.entries(mr))if(!hr(t[e],n))return!1;return!0});var mr;function fr(e,t="0"){return function(e,t="0"){if(An(e))return new _(t);if(_.isBigNumber(e))return e.isNaN()?new _(t):e;try{const n=new _(e);return n.isNaN()||!n.isFinite()?new _(t):n}catch{return new _(t)}}(e,t)}function pr(e,t){return void 0!==t?fr(e).toFixed(t):fr(e).toFixed()}function vr(e){return fr(e).isZero()}function Ar(e,t){return fr(e).isLessThan(fr(t))}function Er(...e){e.forEach(e=>{if(e.isNaN())throw nn("value","NaN");if(!e.isFinite())throw en("value","finite");if(e.isLessThanOrEqualTo(0))throw Zt("value","0",e.toString())})}function yr(e,t,n="0"){const s=fr(t);return vr(s)?fr(n):fr(e).dividedBy(s)}const Tr={calculateBuyWithExact(e,t){const n=Sn(e),s=Sn(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=gn,c=function(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}(r*(Math.exp((s+n)*i)-Math.exp(s*i))/i,8),l=pr(fr(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=Sn(e),s=Sn(t),{BASE_PRICE:r,PRICE_SCALING_FACTOR:i,TRADING_FEE_FACTOR:a,GAS_FEE:o}=gn,c=Math.log(n*i/r+Math.exp(s*i))/i-s,l=pr(fr(c).multipliedBy(a));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,s,r){const i=Sn(e),a=Sn(t),o=Sn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=gn,h=c*(Math.exp(a*l)-Math.exp((a-i)*l))/l,g=fr(h),m=s+a/o*(r-s),f=pr(g.multipliedBy(m),8),p=pr(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}},calculateSellWithNative(e,t,n,s,r){const i=Sn(e),a=Sn(t),o=Sn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=gn;if(i>=c*(Math.exp(a*l)-1)/l){const e=fr(i),t=s+a/o*(r-s),n=pr(e.multipliedBy(t),8),c=pr(e.multipliedBy(d));return{amount:a.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=a-Math.log(Math.exp(a*l)-i*l/c)/l,g=fr(i),m=s+a/o*(r-s),f=pr(g.multipliedBy(m),8),p=pr(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:f,transactionFee:p,gasFee:u}}};function Sr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function br(e,t){if(!function(e){if(!Sr(e)||"string"!=typeof e.calculatedQuantity)return!1;const t=e.extraFees;return Sr(t)&&"string"==typeof t.reverseBondingCurve&&"string"==typeof t.transactionFees}(e))throw Qt(`Malformed trade quote from the launchpad backend (${t})`);return{amount:e.calculatedQuantity,reverseBondingCurveFee:e.extraFees.reverseBondingCurve,transactionFee:e.extraFees.transactionFees,gasFee:gn.GAS_FEE}}class kr{validate(e,t={}){const{allowZero:n=!0,minimum:s,maximum:r,maxDecimals:i=kr.MAX_DECIMAL_PLACES,fieldName:a="amount"}=t;if(!On(e))throw new Rt(`${a} cannot be empty or whitespace-only. Provide a valid numeric string.`,a,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Rt(`${a} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,a,"INVALID_NUMERIC_STRING");const o=Sn(e,NaN);if(isNaN(o))throw new Rt(`${a} must be a valid numeric string. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new Rt(`${a} must be a finite number. Cannot be Infinity or -Infinity.`,a,"INVALID_NUMERIC_STRING");if(o<0)throw new Rt(`${a} must be non-negative. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new Rt(`${a} must be greater than zero. Received: "${e}"`,a,"INVALID_NUMERIC_STRING");const c=fr(e),l=c.decimalPlaces()??0;if(l>i)throw new Rt(`${a} cannot exceed ${i} decimal places. Received: ${l} decimal places`,a,"PRECISION_EXCEEDED");if(void 0!==s&&Ar(c,s))throw new Rt(`${a} must be at least ${s}. Received: "${e}"`,a,"BELOW_MINIMUM");if(void 0!==r&&(d=r,fr(c).isGreaterThan(fr(d))))throw new Rt(`${a} cannot exceed ${r}. Received: "${e}"`,a,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return fr(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 pr(e,t)}clampAmount(e,t,n){const s=fr(e),r=fr(t),i=fr(n);return function(e,t,n){const s=fr(e),r=fr(t),i=fr(n);return s.isGreaterThanOrEqualTo(r)&&s.isLessThanOrEqualTo(i)}(s,r,i)?pr(s):Ar(s,r)?pr(r):pr(i)}}function wr(e,t){throw new Rt(e.join("; "),t,"VALIDATION_ERROR")}function Nr(e){const t=ir(e);!t.success&&t.errors&&wr(t.errors,"tokenName")}function _r(e){const t=Qs.safeParse(e);var n;t.success||wr((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 Ir(e,t,n=!0){Cr.validate(e,{fieldName:t,allowZero:n})}kr.MAX_DECIMAL_PLACES=18,kr.MIN_POSITIVE="0.00000000000000001";const Cr=new kr;class Dr{constructor(e,t,n,s="local",r){this.http=e,this.logger=t,this.bundleHttp=n,this.defaultCalculateAmountMode=s,this.launchpadWrites=r,this.metadataCache=new Vn}createSale(e){if(void 0===this.launchpadWrites)throw new Error("Launchpad write transport is not configured.");return this.launchpadWrites.createSale(e)}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw zt("options","an options object");const{tokenName:t,amount:n,type:s,currentSupply:r}=e;return"external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[At,Et],'"native" or "exact"')?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:s}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:s},"currentSupply",r))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"OUT"},`Failed to calculate buy amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"IN"},`Failed to calculate buy amount for ${t} (native/GALA budget)`)}async fetchBackendQuote(e,t){return br(await ln(()=>this.http.get(dt,{...e}),{errorContext:t}),t)}async calculateSellAmount(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,s,e.mode,[Et,At],'"exact" or "native"'))return this.calculateSellAmountExternal({tokenName:t,amount:n,type:s});{const e={tokenName:t,amount:n,type:s,...void 0!==r&&{currentSupply:r},...void 0!==i&&{maxSupply:i},...void 0!==a&&{reverseBondingCurveMaxFeeFactor:a},...void 0!==o&&{reverseBondingCurveMinFeeFactor:o}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:s}=e;return this.validateExternalAmountInputs(t,n),"exact"===s?this.fetchBackendQuote({tokenName:t,amount:n,type:"MEME",method:"IN"},`Failed to calculate sell amount for ${t} (exact tokens)`):this.fetchBackendQuote({tokenName:t,amount:n,type:"NATIVE",method:"OUT"},`Failed to calculate sell amount for ${t} (native/GALA target)`)}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r}=e;if(!On(n))throw Vt("amount","Amount");if(s!==At&&s!==Et)throw tn("type",'"native" or "exact"',s);void 0!==r&&Ir(r,"currentSupply");const i=null==r||""===r;if(i&&(null==t||""===t))throw Vt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Nr(t);let a=r;if(i){a=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return s===Et?Tr.calculateBuyWithExact(n,a):Tr.calculateBuyWithNative(n,a)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:s,currentSupply:r,maxSupply:i,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:o}=e;if(!On(n))throw Vt("amount","Amount");if(s!==Et&&s!==At)throw tn("type",'"exact" or "native"',s);void 0!==r&&Ir(r,"currentSupply");const c=null==r||""===r||null==i||""===i||void 0===a||void 0===o;if(c&&(null==t||""===t))throw Vt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Nr(t);let l=r,d=i,u=a,h=o;if(c&&null!=t&&""!==t){const e=this.metadataCache.getByName(t);d=d??this.metadataCache.getMaxSupply(t),u=u??e?.reverseBondingCurveMaxFeeFactor,h=h??e?.reverseBondingCurveMinFeeFactor,null!=l&&""!==l||(l=await this.fetchCurrentSupply(t));if(void 0===u||void 0===h){const e=await this.fetchPoolDetailsForCalculation(t);u=u??e.reverseBondingCurveMaxFeeFactor,h=h??e.reverseBondingCurveMinFeeFactor}}return s===Et?Tr.calculateSellWithExact(n,l,d,h,u):Tr.calculateSellWithNative(n,l,d,h,u)}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 lr(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&dr(t,"currentSupply")}(e))throw tn("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:s,currentSupply:r}=t;Nr(n);const i=await this.fetchSaleDetails(n),a=r??pr(fr(i.maxSupply).minus(i.sellingTokenQuantity)),o=i.sellingTokenQuantity;if("0"===o)throw Vt("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const c={tokenName:n,amount:o,type:"exact",currentSupply:a,...void 0!==s&&{mode:s}};return{...await this.calculateBuyAmount(c),remainingTokens:o}}async launchToken(e){if(void 0!==this.launchpadWrites){return(await this.launchpadWrites.createSale(e)).bundleId}if(!this.bundleHttp)throw Xt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");cr(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Sn(t);if(0===n&&"0"!==t)throw nn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw nn("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const s="string"==typeof e?parseFloat(e):e,r="string"==typeof t?parseFloat(t):t;if(!isFinite(s))throw new Rt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(r))throw new Rt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(s<.1)throw new Rt(`${n} minFee must be >= 0.1, received ${s}`,n,"INVALID_FEE_MINIMUM");if(r>.5)throw new Rt(`${n} maxFee must be <= 0.5, received ${r}`,n,"INVALID_FEE_MAXIMUM");if(s>r)throw new Rt(`${n} minFee (${s}) must be <= maxFee (${r})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}throw new Error("Legacy launchToken signing is unavailable; configure the v6 launchpad write transport.")}async calculateInitialBuyAmount(e){if(!gr(e))throw zt("data","valid pre-mint calculation data");const t="Failed to calculate initial buy amount";return br(await ln(()=>this.http.get(ut,{amount:e.nativeTokenQuantity}),{errorContext:t}),t)}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=pr(fr(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.sellingTokenQuantity,r=t.maxSupply;let i=.5,a=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(i=bn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(a=bn(o.minFeePortion,.1)),void 0===o&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const c=i-a;return this.metadataCache.set(e,{maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}),{currentSupply:n,remainingTokens:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:a,reverseBondingCurveNetFeeFactor:c}}async fetchCurrentSupply(e){Nr(e);const t=await this.fetchSaleDetails(e),n=pr(fr(t.maxSupply).minus(t.sellingTokenQuantity)),s=t.maxSupply;return this.metadataCache.set(e,{maxSupply:s}),n}async fetchPoolDetails(e){Nr(e);const t=await this.fetchSaleDetails(e),{reverseBondingCurveConfiguration:n,...s}=t,r=n?.minFeePortion??"0",i=n?.maxFeePortion??"0";return{...s,reverseBondingCurveMinFeePortion:r,reverseBondingCurveMaxFeePortion:i,hasReverseBondingCurveFee:!vr(r)||!vr(i),isGraduated:"Finished"===t.saleStatus}}async fetchSaleDetails(e){return xn(e,"tokenName",zn),ln(()=>this.http.get(lt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}validateAmountCalculationInputs(e,t,n,s,r,i){const a=s??this.defaultCalculateAmountMode;if("local"!==a&&"external"!==a)throw tn("mode",'"local" or "external"',a);if(!On(e))throw Vt("tokenName","Token name");if(!On(t))throw Vt("amount","Amount");if("string"!=typeof n||!r.includes(n))throw tn("type",i,n);return a}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Rt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Rt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return ps(e)}validateTokenName(e){return Nr(e)}validatePagination(e){void 0!==e.pageSize&&Un(0,void 0,100,e.pageSize)}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const Rr=3e5,Or="Sign in to Launchpad t:",Mr="Authorization",Ur="Bearer ";class Lr{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 Fr;!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"}(Fr||(Fr={}));class xr extends Error{constructor(e,t,n,s){super(t),this.type=e,this.originalError=n,this.statusCode=s,this.name="AuthError"}}class Pr{constructor(e,t=Rr){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 Lr,this.refreshThresholdMs=t}setToken(e,t){if(!On(e))throw new xr(Fr.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new xr(Fr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new xr(Fr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new xr(Fr.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,s){if(this.setToken(e,t),n){const e=Date.now()+1e3*(s??7776e3);if(!this.tokenState)throw new xr(Fr.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:`${Ur}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new xr(Fr.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Mr]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!==this.tokenState.refreshExpiresAt&&void 0!==this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const s=Date.now();this.tokenState={token:e,issuedAt:s,expiresAt:n};const r=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),i=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(r&&i){const e=Number(i);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=r,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}}}class Br extends Pr{getJwtHeaders(){return{}}}async function $r(e,t,n,s){try{return await e()}catch(e){throw s?(s(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),function(e,t,n){n&&n.error(`${t}:`,e);const s=(Kt(e)?e.response?.status:void 0)??(e instanceof Lt?e.statusCode:void 0);return Qt(`${t}: ${Bt(e)}`,s,Pt(e)?e:void 0)}(e,t,n))}}function Gr(e,t){return t instanceof xr?t:new xr(Fr.SIGNATURE_FAILED,`${e}: ${Bt(t)}`,Pt(t)?t:void 0,function(e){if("object"==typeof e&&null!==e){if("statusCode"in e&&"number"==typeof e.statusCode)return e.statusCode;if("response"in e&&"object"==typeof e.response&&null!==e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}}}(t))}class Kr{constructor(e,t,n,s=!1,r){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.session=r,this.refreshPromise=null,this.loginPromise=null,this.logger=new vn({debug:s,context:"SessionAuthService"})}async loginWithSignature(e){if(Ts(e.address,"address"),!On(e.message)||!On(e.signature))throw new xr(Fr.SIGNATURE_FAILED,"A login needs the signed message and its signature.");const t={address:e.address,message:e.message,signature:e.signature,...void 0!==e.publicKey&&{publicKey:e.publicKey},...void 0!==this.session&&{cookieSession:!0}};return this.postLogin(t)}async loginWithDevBypass(e){return Ts(e,"address"),this.postLogin({address:e,...void 0!==this.session&&{cookieSession:!0}})}async postLogin(e){try{const t=await this.http.request({method:"POST",url:Y,data:e,withSession:!1}),n=this.extractLoginData(t);return void 0===this.session&&await this.jwtAuth.setTokens(n.accessToken,n.expiresIn,n.refreshToken,n.refreshExpiresIn),n}catch(e){throw Gr("Login failed",e)}}async login(){if(this.loginPromise)return this.logger.debug("Login already in progress, reusing existing promise"),this.loginPromise;if(!this.signatureAuth.hasWallet())throw new xr(Fr.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 $r(async()=>{const e=Date.now(),t=`${Or}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),s=this.signatureAuth.getAddress();Ts(s,"address");const r={address:s,message:t,signature:n.signature};this.logger.debug("Sending login request",{address:s,message:t});const i=await this.http.post(Y,r),a=this.extractLoginData(i);return await this.jwtAuth.setTokens(a.accessToken,a.expiresIn,a.refreshToken,a.refreshExpiresIn),this.logger.debug("Login successful",{address:a.address,expiresIn:a.expiresIn,hasRefreshToken:!!a.refreshToken}),a},"SessionAuthService.performLogin",this.logger,e=>{if(e instanceof xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,`Login failed: ${Bt(e)}`,Pt(e)?e:void 0)})}async refresh(){if(this.refreshPromise)return this.logger.debug("Refresh already in progress, reusing existing promise"),this.refreshPromise;if(void 0!==this.session){this.refreshPromise=this.performCookieRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}if(!this.jwtAuth.hasToken())throw new xr(Fr.WALLET_NOT_CONNECTED,"No token to refresh. Call login() first.");this.refreshPromise=this.performRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performCookieRefresh(){try{const e=await this.http.request({method:"POST",url:ee,data:{},withSession:!1});return this.extractLoginData(e)}catch(e){throw Gr("Token refresh failed",e)}}async performRefresh(){return $r(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(ee,{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(ee,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,e=>{if(e instanceof xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,`Token refresh failed: ${Bt(e)}`,Pt(e)?e:void 0)})}async logout(e){this.logger.debug("Logging out",{allDevices:e?.allDevices});const t=e?.allDevices??!1;if(void 0!==this.session){const n=e?.accessToken??null;try{await this.http.request({method:"POST",url:Z,data:{allDevices:t},withSession:!1,...null!==n&&""!==n&&{headers:{Authorization:`${Ur}${n}`}}})}catch(e){throw Gr("Logout failed",e)}return}if(t&&this.jwtAuth.hasToken()&&!this.jwtAuth.isExpired())try{await this.http.post(Z,{allDevices:!0},this.jwtAuth.getJwtHeaders()),this.logger.debug("Logged out from all devices")}catch(e){this.logger.warn(`Failed to revoke all-device sessions (server-side revocation may be incomplete): ${Bt(e)}`)}else t&&this.logger.debug("Skipping server-side revocation: no valid local token available");await this.jwtAuth.clear()}async getSession(){if(!this.jwtAuth.hasToken())throw new xr(Fr.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return $r(async()=>{const e=await this.http.get(te,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,`Failed to get session: ${Bt(e)}`,Pt(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(void 0!==this.session){const e=await this.session.accessToken();if(null===e||""===e)throw new xr(Fr.WALLET_NOT_CONNECTED,"The app session has no access token.");return e}if(!this.jwtAuth.hasToken())throw new xr(Fr.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");if(this.jwtAuth.isExpired()){if(await this.jwtAuth.getRefreshToken()){this.logger.debug("Token expired - refresh token available, attempting refresh");try{return(await this.refresh()).accessToken}catch(e){this.logger.warn(`Refresh failed after expiry: ${Bt(e)} - attempting re-login`)}}else this.logger.debug("Token expired - no refresh token available, attempting re-login");return(await this.login()).accessToken}if(this.jwtAuth.shouldRefresh(e)){this.logger.debug("Token near expiry - refreshing");return(await this.refresh()).accessToken}return this.jwtAuth.getToken()}extractLoginData(e){if(e.error)throw new xr(Fr.SIGNATURE_FAILED,""!==Bt(e)?Bt(e):"Authentication failed");const t=cn(e,"No data in authentication response"),{accessToken:n,expiresIn:s,address:r,refreshToken:i,refreshExpiresIn:a}=t;if(!On(n))throw new xr(Fr.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof s||s<=0)throw new xr(Fr.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:s,address:r,...void 0!==i&&{refreshToken:i},...void 0!==a&&{refreshExpiresIn:a}}}extractSessionData(e){if(e.error)throw new xr(Fr.SIGNATURE_FAILED,""!==Bt(e)?Bt(e):"Failed to get session");return cn(e,"No data in session response")}}class Wr{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{Dn(e.messagePrefix,"messagePrefix",!1)}catch{throw new xr(Fr.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=a.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=ps(this.wallet.address)}catch(e){if(e instanceof xr)throw e;if(e instanceof Rt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new xr(Fr.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new xr(Fr.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new xr(Fr.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new xr(Fr.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=a.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=ps(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;const t=void 0!==e&&o(e)?n(e.exportPrivateKey()):void 0;this.cachedAddress=t,this.cachedGalaAddress=void 0===t?void 0:ps(t)}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 xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,"Failed to generate signature for authentication",Pt(e)?e:new Error(Bt(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new xr(Fr.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 xr(Fr.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null===this.wallet.privateKey||void 0===this.wallet.privateKey)throw new xr(Fr.WALLET_NOT_CONNECTED,"Wallet private key not available for @gala-chain signing");return this.wallet.privateKey}if(void 0!==this.walletProvider&&o(this.walletProvider))return this.walletProvider.exportPrivateKey();throw new xr(Fr.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 xr(Fr.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new xr(Fr.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Pt(e)?e:void 0)}}formatAddress(e){try{return ps(e)}catch{throw new xr(Fr.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 xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,Bt(e),Pt(e)?e:new Error(Bt(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),s=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,r=await this.walletProvider.signMessage(s);return{"x-signature":r,"x-address":await this.walletProvider.getGalaAddress(),"x-message":s,"x-timestamp":n.toString()}}catch(e){if(e instanceof xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,"Failed to generate authentication headers",Pt(e)?e:new Error(Bt(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const s={};for(const[e,n]of Object.entries(t))s[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,s,n)}catch(e){if(e instanceof xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,"Failed to sign typed data",Pt(e)?e:new Error(Bt(e)))}}async generateCustomSignature(e){if(!On(e))throw new xr(Fr.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 xr)throw e;throw new xr(Fr.SIGNATURE_FAILED,"Failed to generate custom message signature",Pt(e)?e:new Error(Bt(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new xr(Fr.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new xr(Fr.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new xr(Fr.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Hr={prod:{...c.prod,bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},stage:{...c.stage,bundleBaseUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadBaseUrl:"https://lpad-backend.stage.defi.ovh.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",webSocketUrl:"https://bundle-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function jr(e){return Hr[e]}var qr,Vr;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(qr||(qr={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Vr||(Vr={}));const zr={[qr.PROCESSED]:Vr.COMPLETED,[qr.COMPLETED]:Vr.COMPLETED,[qr.SUCCESS]:Vr.COMPLETED,[qr.FAILED]:Vr.FAILED,[qr.ERROR]:Vr.FAILED,[qr.PROCESSING]:Vr.PROCESSING,[qr.PENDING]:Vr.PENDING},Qr="9.0.0-rc.1",Xr={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Jr(e){return"string"==typeof e||null===e?e:void 0}function Yr(e){if("object"!=typeof e||null===e)return{hasNextPage:!1};const t=Reflect.get(e,"hasNextPage"),n=Reflect.get(e,"hasPreviousPage"),s=Jr(Reflect.get(e,"endCursor")),r=Jr(Reflect.get(e,"startCursor"));return{hasNextPage:!0===t,...void 0===s?{}:{endCursor:s},..."boolean"==typeof n?{hasPreviousPage:n}:{},...void 0===r?{}:{startCursor:r}}}function Zr(e,t){const{hasNextPage:n,endCursor:s}=e;if(n&&"string"==typeof s&&""!==s&&s!==t)return s}function ei(e){return"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e||"bigint"==typeof e?String(e):JSON.stringify(e)??""}function ti(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const s=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(s),n}const ni={tokenName:"lowercase",address:"lowercase",userAddress:"lowercase",assetId:"as given",targetId:"as given",id:"as given",code:"as given"};function si(e,t){let n=e;for(const[e,s]of Object.entries(t)){const t=ni[e];if(void 0===t)throw new Error(`buildEndpoint: path parameter :${e} has no casing in PATH_PARAM_CASING`);n=n.replace(`:${e}`,encodeURIComponent("lowercase"===t?s.toLowerCase():s))}return n}function ri(e,t,n){for(const s of n){const n=t[s];null!=n&&""!==n&&(e[s]=ei(n))}return e}const ii="x-api-key";class ai extends Hn{constructor(e,t,n,s=!1,r){super(e,s),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=r??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!On(e))throw Vt("tokenName","Token name");const n=mn(e);if(!t.PATTERN.test(n))throw zt("tokenName",t.DESCRIPTION,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!On(e))throw Vt(t,n)}(e,t,n)}validateOptionalString(e,t,n,s){!function(e,t,n,s){if(null!=e){if("string"!=typeof e)throw tn(t,"string",typeof e,n);if(e.length>s)throw en(t,s,e.length,n)}}(e,t,n,s)}validateOptionalNumber(e,t,n,s,r,i,a){!function(e,t,n,s,r){if(null!=e){if("number"!=typeof e)throw tn(t,"number",typeof e,n);if(e<s||e>r)throw Yt(t,s,r,e,n)}}(e,t,n,s,r)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Tn(e))throw zt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Kn(e,t,n)}validateStatusFilter(e,t,n="status"){Wn(e,t,n)}buildPaginationParams(e,t){return ti(e,t)}addOptionalFilterParams(e,t,n){return ri(e,t,n)}buildEndpoint(e,t){return si(e,t)}buildEndpointWithId(e,t){return e.replace(":id",encodeURIComponent(t))}validateAndBuildTokenEndpoint(e,t,n){return this.validateTokenName(e,t),this.buildEndpoint(n,{tokenName:e})}getAdminHeaders(){if(void 0===this.adminApiKey||""===this.adminApiKey)throw new Ft("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[ii]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new Ft("JWT authentication required. Call sdk.login() first.");return this.jwtAuth.getJwtHeaders()}hasJwtAuth(){return this.jwtAuth?.isValid()??!1}hasAdminApiKey(){return void 0!==this.adminApiKey&&""!==this.adminApiKey}getDualAuthHeaders(){return void 0!==this.adminApiKey&&""!==this.adminApiKey?this.getAdminHeaders():this.getJwtHeaders()}getMultiAuthHeaders(){return void 0!==this.userApiKey&&""!==this.userApiKey?{[ii]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return an(e,"Backend request failed",!0),cn(e,"No data in backend response")}extractDataOrNull(e){return an(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const s=this.buildEndpoint(t,{tokenName:e}),r=await this.http.post(s,{},this.getAdminHeaders()),i=this.extractData(r);return{enabled:i.enabled,tokenName:i.tokenName??mn(e)}}}class oi extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getSettings(){return{settings:(await this.http.get(at.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(at.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=at.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=at.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(at.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const ci=Fn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function li(e){return ci.includes(e)}function di(e,t,n=!1){const s=t.length;if(Ht(t,()=>{$n(e.description,"description",255)}),t.length>s&&(t[s]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Ht(t,()=>{if(!Array.isArray(e.tokenNames))throw tn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw tn("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n?.includes("array")?t[e]="tokenNames must be an array":n?.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&(!n||null!==e.expiresAt)){const n=t.length;Ht(t,()=>{Gn(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class ui extends Hn{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),an(n,"API key operation failed",!0),e.data}validateApiKeyId(e){this.validatePositiveInteger(e,"id","API key ID")}async create(e){const t=function(e){const t=[];return void 0===e.role||null===e.role?t.push("Role is required"):li(e.role)||t.push(`Invalid role. Must be one of: ${ci.join(", ")}`),di(e,t),t}(e);if(t.length>0)throw new Rt(t.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Creating API key",{role:e.role,delegateAllTokens:e.delegateAllTokens});const n={role:e.role};void 0!==e.description&&(n.description=e.description),void 0!==e.delegateAllTokens&&(n.delegateAllTokens=e.delegateAllTokens),void 0!==e.tokenNames&&e.tokenNames.length>0&&(n.tokenNames=e.tokenNames),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt),void 0!==e.tokenPermissions&&(n.tokenPermissions=e.tokenPermissions);const s=await this.http.post(ue.CREATE,n,this.getJwtHeaders()),r=this.extractData(s);return this.logger.debug("API key created",{id:r.id,keyPrefix:r.keyPrefix}),r}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>Yn))throw tn("pageSize",`number between 1 and ${Yn}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw tn("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=ti(e,Yn),n=await this.http.get(ue.LIST,t,this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Listed API keys",{count:s.apiKeys.length,total:s.pageInfo.totalCount}),s}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=ue.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),s=this.extractData(n);return this.logger.debug("Got API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async update(e,t){this.validateApiKeyId(e);const n=function(e){const t=[];return["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||li(e.role)||t.push(`Invalid role. Must be one of: ${ci.join(", ")}`),di(e,t,!0),t}(t);if(n.length>0)throw new Rt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const s={};void 0!==t.role&&(s.role=t.role),void 0!==t.description&&(s.description=t.description),void 0!==t.delegateAllTokens&&(s.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(s.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(s.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(s.tokenPermissions=t.tokenPermissions);const r=ue.UPDATE.replace(":id",String(e)),i=await this.http.patch(r,s,this.getJwtHeaders()),a=this.extractData(i);return this.logger.debug("Updated API key",{id:a.id,keyPrefix:a.keyPrefix}),a}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=ue.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...ci]}}const hi={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},gi=Ln(hi);function mi(e){if(!On(e.userAddress))throw Vt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!Bn(t)&&t.length<=ss.BAN_REASON.MAX_LENGTH))throw new Rt(`reason must be at most ${ss.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(Mn(n)||"number"==typeof n&&n>=is&&n<=as))throw new Rt(`durationSeconds must be between ${is} and ${as} seconds`,"durationSeconds","OUT_OF_RANGE")}class fi extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createBan(e){!function(e){xn(e.tokenName,"tokenName",Qn),mi(e)}(e);const t=this.buildEndpoint(ne,{tokenName:e.tokenName}),n=pi(e),s=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(s),tokenName:mn(e.tokenName)}}async removeBan(e){!function(e){if(xn(e.tokenName,"tokenName",Qn),!On(e.userAddress))throw Vt("userAddress")}(e);const t=this.buildEndpoint(ie,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(n);return{removed:s?.removed??!0,tokenName:mn(e.tokenName),userAddress:s?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){xn(e.tokenName,"tokenName",Qn),Un(0,void 0,Yn,e.pageSize)}(e);const t=this.buildEndpoint(se,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Yn);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getBanStatus(e){!function(e){if(xn(e.tokenName,"tokenName",Qn),!On(e.userAddress))throw Vt("userAddress")}(e);const t=this.buildEndpoint(re,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:mn(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(xn(e.tokenName,"tokenName",Qn),void 0!==e.type&&!gi(e.type))throw new Rt(`type must be one of: ${Object.values(hi).join(", ")}`,"type",wt)}(e);const t=this.buildEndpoint(ae,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const s=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(s)}async createGlobalBan(e){!function(e){mi(e)}(e);const t=pi(e),n=await this.http.post(oe,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!On(e.userAddress))throw Vt("userAddress")}(e);const t=this.buildEndpoint(de,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{removed:s?.removed??!0,userAddress:s?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Un(0,void 0,Yn,e.pageSize)}(t);const n=this.buildPaginationParams(t,Yn);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const s=await this.http.get(ce,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getGlobalBan(e){!function(e){if(!On(e.userAddress))throw Vt("userAddress")}(e);const t=this.buildEndpoint(le,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},userAddress:e.userAddress.toLowerCase()}}}function pi(e){const t={userAddress:e.userAddress};return void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds),t}function vi(e){return{maxAcceptableReverseBondingCurveFee:wn(e.maxAcceptableReverseBondingCurveFee)}}const Ai={BuyNativeDto:class extends b{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=wn(t),this.expectedToken=Nn(n),this.extraFees=vi(s)}},BuyExactDto:class extends b{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Nn(t),this.expectedNativeToken=wn(n),this.extraFees=vi(s)}},SellExactDto:class extends b{constructor(e,t,n="0",s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=Nn(t),this.expectedNativeToken=wn(n),this.extraFees=vi(s)}},SellNativeDto:class extends b{constructor(e,t,n,s={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=wn(t),this.expectedToken=Nn(n),this.extraFees=vi(s)}}};function Ei(e,t,n){let s;_n(t,0,1,"slippageToleranceFactor");try{s=function(e,t){if(En(e)||""===e)throw Vt(t);if(_.isBigNumber(e)){if(e.isNaN())throw nn(t,"NaN");return e}try{const n=new _(e);if(n.isNaN())throw nn(t,e);if(!n.isFinite())throw nn(t,e);return n}catch(n){if(n instanceof Rt)throw n;throw nn(t,e)}}(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const r=s.multipliedBy(t);let i;switch(n){case"buy-native":case"sell-exact":i=s.minus(r);break;case"buy-exact":case"sell-native":i=s.plus(r);break;default:throw new Error(`Unknown operation type: ${n}`)}return fr(i).isLessThan(0)&&(i=fr(0)),pr(i)}function yi(e,t){if(!On(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);return n}function Ti(e,t,n,s){const r=e?.split?.(t)??[],i=void 0!==n?` (${n})`:"";return new Rt(`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: ${Bt(s)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}function Si(e,t,n){try{const n=yi(e,t),s=n[n.length-1],r=n[n.length-2],i=n[n.length-3],a=n.slice(0,n.length-3).join(t);if(void 0===a||void 0===i||void 0===r||void 0===s||""===s||""===a||""===i||""===r)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:a,category:i,type:r,additionalKey:s}}catch(s){throw Ti(e,t,n,s)}}function bi(e){return function(e,t,n){try{const n=yi(e,t),[s,r,i,...a]=n;if(""===s||""===r||""===i)throw new Error("Collection, category, and type must be non-empty");const o=a.join(t);if(void 0===s||void 0===r||void 0===i||""===o)throw new Error("AdditionalKey must be non-empty");return{collection:s,category:r,type:i,additionalKey:o}}catch(s){throw Ti(e,t,n,s)}}(e,"|","pipe-delimited token")}class ki extends Error{constructor(e,t,n={}){super(e),this.name="LaunchpadSDKError",this.code=t,this.status=n.status,this.chainMessage=n.chainMessage,this.details=n.details}}const wi={name:"GalaChain"},Ni={name:"ethereum",chainId:1};function _i(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Ii(e){const t={};for(const[n,s]of Object.entries(e))void 0!==s&&(t[n]=Ci(s));return t}function Ci(e){return Array.isArray(e)?e.map(Ci):"object"==typeof e&&null!==e?Ii(e):e}function Di(e,t,n,s){return{...e,signature:t,types:n,domain:s}}class Ri extends m{constructor(e){super(e),this.typedDataWallet=new i(e),this.walletAddress=`eth|${this.typedDataWallet.address.slice(2)}`}async signTypedData(e,t){const n=Ii(t),s=d(e,n);return Di(n,await this.typedDataWallet.signTypedData(wi,s,n),s,wi)}}class Oi extends h{constructor(e,t={}){const{verifyActiveAccount:n,...s}=t;if(super(e,s),this.typedDataWallet=t.wallet,!0===n){const e=u(this.walletAddress)??(void 0===this.selectAddress?void 0:u(this.selectAddress));if(void 0===e)throw new ki("verifyActiveAccount needs the Ethereum account of the key (walletAddress or selectAddress as 0x... / eth|...); a client| alias names no key.","INVALID_SIGNER_OPTIONS",{details:{walletAddress:this.walletAddress,selectAddress:this.selectAddress}});this.verifiedKey=e}else this.verifiedKey=void 0}async signTypedData(e,t){const n=Ii(t),s=d(e,n),r={domain:Ni,types:s,message:n,Primary_type:e},i=this.typedDataWallet??function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}();void 0!==this.verifiedKey&&await async function(e,t){let n="address"in e&&"string"==typeof e.address&&""!==e.address?e.address:void 0;if(void 0===n){const t=await e.request({method:"eth_accounts"}),s=Array.isArray(t)?t[0]:void 0;n="string"==typeof s&&""!==s?s:void 0}const s=void 0===n?void 0:u(n);if(void 0===s||s.toLowerCase()!==t.toLowerCase())throw new ki("Your wallet's active account has changed. Please switch back to the connected account or reconnect your wallet.","WALLET_ACCOUNT_CHANGED",{details:{walletAccount:n??null,signerAccount:t}})}(i,this.verifiedKey);const a=await this.typedDataAccount(i);return Di(n,_i(await g(i,this.selectAddress??a,()=>i.request({method:"eth_signTypedData",params:[JSON.stringify(r),a]}))),s,Ni)}async typedDataAccount(e){if(s(this.walletAddress))return this.walletAddress;const t=await e.request({method:"eth_accounts"}),n=Array.isArray(t)?t[0]:void 0,r="string"==typeof n?n.replace(/^eth\|/,"0x"):"";if(!s(r))throw new Error("Gala Wallet did not report an Ethereum account to sign typed data with");return r}}class Mi extends l{constructor(e,t,n){super(e,t,n),this.typedDataProvider=e}async signTypedData(e,n){const r=Ii(n),i=this.typedDataProvider,a=await i.getNetwork(),o={name:a.name,chainId:Number(a.chainId)},c=d(e,r),l=await i.getSigner(),u=t(await l.getAddress());if(s(this.walletAddress)&&u!==t(this.walletAddress))throw new ki(`Wallet account ${u} is not the account this signer was created for (${this.walletAddress}); reconnect before signing.`,"WALLET_ACCOUNT_CHANGED",{details:{walletAccount:u,signerAccount:this.walletAddress}});return Di(r,_i(await l.signTypedData(o,c,r)),c,o)}static fromEip1193(e,t,n){const s=new r(e);return new Mi({request:t=>e.request(t),getNetwork:()=>s.getNetwork(),getSigner:()=>s.getSigner()},u(t)??t,n)}}function Ui(e){const[t,n]=e.split("|",2);if("service"!==t||void 0===n)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);const s=n.split("$"),r=s[s.length-1],i=s.slice(0,-1),a=i.slice(0,-3).join("$"),[o,c,l]=i.slice(-3);if("launchpad"!==r||i.length<4||""===a||void 0===o||void 0===c||void 0===l||""===o||""===c||""===l)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:o,type:c,additionalKey:l}}function Li(e){const{collection:t,category:n,type:s}=Ui(e),r=`${t}$${n}$${s}$none`,i="GALA$Unit$none$none";return[`$service$${r}$launchpad`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${r}$${e}`,`$tokenBalance$${i}$${e}`,`$tokenBalance$${i}$${e}`]}function Fi(e){const t=`${e.tokenName}$Unit$none$none`,n=`$service$${t}$launchpad`;return Number(e.preBuyQuantity??"0")>0?[n,`$token$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$${t}$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`,`$tokenBalance$GALA$Unit$none$none$${n}`]:[n,`token$${t}$${n}`,`tokenBalance$${t}$${n}`]}function xi(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function Pi(e){if("string"==typeof e){if(!On(t=e)||!t.includes("|"))throw new Rt(`Invalid tokenId string format: "${e}". Expected pipe-delimited format: "collection|category|type|additionalKey" or "collection|category|type|additionalKey|instance"`,"tokenId","INVALID_TOKEN_ID_FORMAT");const n=e.split("|");if(n.length>=5){const e=bi(n.slice(0,4).join("|")),t=n[4]??"0";return{...e,instance:t.length>0?t:"0"}}return{...bi(e),instance:"0"}}var t;if("object"==typeof e&&null!==e){if("instance"in e&&void 0!==e.instance&&"string"==typeof e.instance&&e.instance.length>0){if(!f(e))throw new Rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!f(e))throw new Rt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Rt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function Bi(e){return function(e){try{if(!On(e))throw new Error("Vault address must be a non-empty string");const t=e.split("|")[1];if(""===t||void 0===t)throw new Error("Missing token part after service prefix");const n=t.split("$");return Si((n.length>=5&&"launchpad"===n[n.length-1]?n.slice(0,-1):n).join("$"),"$","vault address")}catch(t){throw new Rt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${Bt(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function $i(e){return{...Bi(e),instance:"0"}}function Gi(e){const t=Bi(e);if("Token"!==t.collection)throw new Rt(`Cannot extract a token symbol from vault address "${e}": collection "${t.collection}" is not the launchpad "Token" collection, and a symbol cannot be derived from a class key.`,"vaultAddress","SYMBOL_NOT_DERIVABLE_FROM_KEY");return t.type}var Ki,Wi,Hi,ji,qi=Object.freeze({__proto__:null,extractTokenSymbolFromVault:Gi,normalizeToTokenInstanceKey:Pi,parseVaultAddressToTokenClassKey:Bi,parseVaultAddressToTokenInstance:$i});class Vi extends jn{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=Li(e);return this.logger.debug("✅ Generated stringsInstructions:",t),t}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=Bt(e);throw new Rt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createGalaInstance(){const e=new k;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(!On(e))throw Vt("vaultAddress","Vault address");try{const t=Gi(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Rt)throw zt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!On(e))throw Vt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw zt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw zt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!On(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);if(!t)return null;const n=t[1],s=t[2];return void 0===n||void 0===s?null:{tokenSymbol:n,creatorAddress:s.toLowerCase()}}(e);if(!t)throw zt("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 zt("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,s){return`${e}$${t}$${n}$${s}`}parseTokenClassKeyString(e){try{return Si(e,"$","dollar-delimited token")}catch(e){if(e instanceof Rt)throw zt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function zi(e){return"object"==typeof e&&null!==e?e:void 0}class Qi extends Hn{constructor(e,t,n=!1,s,r,i=.05,a=.01,o){if(super(e,n),this.tokenResolver=t,this._walletProvider=s,this.userAddress=r,this.defaultSlippageToleranceFactor=i,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=a,this.sellFeeCeiling=o,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=r){const e=zi(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Ri(t):function(e){const t=zi(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new Mi(this._walletProvider,this.userAddress)),this.tokenKeyService=new Vi(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 dn(()=>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:rn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Rt)return{success:!1,error:Bt(e)};throw e}}validateBundleData(e){if(null==e)throw Vt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Vt("signedDto","Signed DTO");if(!On(e.method))throw Vt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw zt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Rt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw zt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!On(e))throw new Rt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if("string"!=typeof(n=e)||!n.includes("$"))throw new Rt(`stringsInstructions[${t}] must start with '$': ${e}`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION_FORMAT");var n}),this.logger.debug("✅ Bundle data validation passed")}formatBundleRequest(e){return{signedDto:e.signedDto,stringsInstructions:e.stringsInstructions,method:e.method}}handleBundleResponse(e){const t=on(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(Kt(e)&&null!==e.response&&void 0!==e.response){const t=on(e.response);if(null!=t&&"object"==typeof t){const e=t;if(null!==e.error&&void 0!==e.error)return"string"==typeof e.error?e.error:JSON.stringify(e.error);if(null!==e.message&&void 0!==e.message)return"string"==typeof e.message?e.message:JSON.stringify(e.message)}}return Bt(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!On(e))throw Vt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await dn(()=>this.http.get(`${this.bundleEndpoint}?id=${e}`),{errorContext:"Failed to get bundler transaction result",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from bundler transaction query"}:(this.logger.debug("📊 Bundler transaction result:",t),{success:!0,data:t})}catch(e){if(e instanceof Rt)return{success:!1,error:Bt(e)};throw e}}async cancelTransaction(e){try{if(!On(e))throw Vt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await dn(()=>this.http.delete(`${this.bundleEndpoint}/${e}`),{errorContext:"Failed to cancel transaction",logger:this.logger})}catch(e){return{success:!1,error:this.formatErrorMessage(e)}}return null==t?{success:!1,error:"No response from transaction cancellation"}:(this.logger.debug("🗑️ Transaction cancellation response:",t),{success:!0,data:t})}catch(e){if(e instanceof Rt)return{success:!1,error:Bt(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await dn(()=>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:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===s){if(null==r||""===r)throw new Rt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ei(r,i,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:r,slippageFactor:i,adjustedMinTokens:e});const t=new Ai.BuyNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyWithNative",o)}{if(null==r||""===r)throw new Rt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ei(r,i,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:r,slippageFactor:i,adjustedMaxGalaCost:e});const t=new Ai.BuyExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:a});return await this.executeBundleTransaction(t,"BuyExactToken",o)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:s,expectedAmount:r}=e,{effectiveSlippageFactor:i,effectiveMaxFee:a,vaultAddress:o}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor),c=async()=>void 0===e.maxAcceptableReverseBondingCurveFee?this.defaultSellFeeCeiling(e,o):a;if("exact"===s){if(null==r||""===r)throw new Rt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ei(r,i,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:r,slippageFactor:i,adjustedMinGala:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new Ai.SellExactDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellExactToken",o)}{if(null==r||""===r)throw new Rt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=Ei(r,i,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:r,slippageFactor:i,adjustedMaxTokensToSell:e});const t={maxAcceptableReverseBondingCurveFee:await c()},s=new Ai.SellNativeDto(o,n,e,t);return await this.executeBundleTransaction(s,"SellWithNative",o)}}async prepareTradingOperation(e,t,n,s){const{effectiveSlippageFactor:r,effectiveMaxFee:i}=this.calculateEffectiveSlippage(t,n,s),a=await this.resolveTokenNameToVault(e);if(null==a)throw qt(e);return{effectiveSlippageFactor:r,effectiveMaxFee:i,vaultAddress:a}}async defaultSellFeeCeiling(e,t){if(void 0===this.sellFeeCeiling)throw Xt("Cannot quote the reverse bonding curve fee for this sell. Pass maxAcceptableReverseBondingCurveFee.","maxAcceptableReverseBondingCurveFee");return this.sellFeeCeiling({method:"exact"===e.type?"SellExactToken":"SellWithNative",vaultAddress:t,quantity:e.amount,tokenName:e.tokenName,feeSlippageFactor:e.maxAcceptableReverseBondingCurveFeeSlippageFactor??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor})}calculateEffectiveSlippage(e,t,n){const s=n??this.defaultSlippageToleranceFactor,r=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let i=e??"0";return null!=e&&(i=Ei(e,r,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:r,adjustedMaxFee:i})),{effectiveSlippageFactor:s,effectiveFeeSlippageFactor:r,effectiveMaxFee:i}}ensureTradingServicesAvailable(){if(!this.signer||!this.tokenKeyService)throw Xt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Vt("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap-operation-${Date.now()}_${w().replace(/-/gu,"").substring(0,26)}`;const s=await this.signer.signObject(t,e),r=this.tokenKeyService.generateStringsInstructions(n),i={stringsInstructions:r,method:t,signedDto:s};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:r,dtoKeys:Object.keys(s)});const a=await this.submitTransaction(i);if(a.success){const e=on(a);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const o=a.error;throw new xt("string"==typeof o?o:"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 Xi extends Hn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Client config operation failed";throw new Error(t)}return e.data}async getClientFlags(){this.logger.debug("Fetching client feature flags");const e=await this.http.get(vt),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(Ki||(Ki={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Wi||(Wi={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Hi||(Hi={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(ji||(ji={})),Wi.INAPPROPRIATE_CONTENT,Wi.SPAM,Wi.HARASSMENT,Wi.SCAM,Wi.OTHER,Hi.PENDING,Hi.DISMISSED,Hi.ACTIONED,ji.DELETE_CONTENT,ji.BAN_USER,ji.DELETE_AND_BAN,Ki.CHAT_MESSAGE,Ki.COMMENT,Ki.STREAM,Ki.RECORDING;const Ji=Ln(Ki),Yi=Ln(Wi),Zi=Ln(Hi),ea=Ln(ji),ta={TOKEN_NAME:zn,TOKEN_NAME_FILTER:{MIN_LENGTH:1,MAX_LENGTH:50,PATTERN:/^[a-zA-Z0-9]{1,50}$/,DESCRIPTION:"1-50 letters and digits"},CONTENT_ID:ss.CONTENT_ID,DETAILS:ss.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:Yn}};function na(e,t,n="tokenName"){xn(e,n,t)}function sa(e){if(void 0!==e.contentType&&!Ji(e.contentType))throw zt("contentType",`one of: ${Object.values(Ki).join(", ")}`,"Content type");if(void 0!==e.status&&!Zi(e.status))throw zt("status",`one of: ${Object.values(Hi).join(", ")}`);if(void 0!==e.reason&&!Yi(e.reason))throw zt("reason",`one of: ${Object.values(Wi).join(", ")}`);if(void 0!==e.reporterAddress&&!On(e.reporterAddress))throw tn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&ys(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!On(e.reportedUserAddress))throw tn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&ys(e.reportedUserAddress,"reportedUserAddress"),Un(0,void 0,ta.PAGINATION.MAX_LIMIT,e.pageSize)}class ra extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async createFlag(e){!function(e){if(na(e.tokenName,ta.TOKEN_NAME),void 0===e.contentType)throw Vt("contentType","Content type");if(!Ji(e.contentType))throw zt("contentType",`one of: ${Object.values(Ki).join(", ")}`,"Content type");if(!On(e.contentId))throw Vt("contentId","Content ID");if(e.contentId.length>ta.CONTENT_ID.MAX_LENGTH)throw en("contentId",ta.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!On(e.reportedUserAddress))throw Vt("reportedUserAddress","Reported user address");if(ys(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==Ki.STREAM&&e.contentType!==Ki.RECORDING||void 0!==e.reason&&null!==e.reason))throw Vt("reason","Reason");if(void 0!==e.reason&&!Yi(e.reason))throw zt("reason",`one of: ${Object.values(Wi).join(", ")}`,"Reason");if(void 0!==e.details&&!On(e.details))throw tn("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>ta.DETAILS.MAX_LENGTH)throw en("details",ta.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!==e.reason&&void 0!==e.reason&&(t.reason=e.reason),null!==e.details&&void 0!==e.details&&(t.details=e.details);const n=await this.http.post(ye.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){na(e.tokenName,ta.TOKEN_NAME_FILTER),sa(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&na(e.tokenName,ta.TOKEN_NAME_FILTER),sa(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Vt("flagId","Flag ID");try{Cn(e.flagId,"flagId")}catch{throw zt("flagId","a positive integer","Flag ID")}}(e);const t=ye.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 Vt("flagId","Flag ID");try{Cn(e.flagId,"flagId")}catch{throw zt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Vt("action","Action");if(!ea(e.action))throw zt("action",`one of: ${Object.values(ji).join(", ")}`,"Action")}(e);const t=ye.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async fetchFlagList(e){const t=ti(e,Yn);ri(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(ye.LIST,t,this.getMultiAuthHeaders()),s=this.extractData(n);return{items:s.flags,pageInfo:s.pageInfo}}}const ia=["heart","fire","laugh","wow","thumbs_up"];class aa extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateMessageId(e){if(!On(e))throw Vt("messageId","Message ID");if(In(e,rs.CONTENT_REACTION.MAX_LENGTH,"messageId"),!rs.CONTENT_REACTION.PATTERN.test(e))throw zt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!On(e))throw Vt("reactionType","Reaction type");if(!ia.includes(e))throw zt("reactionType",`one of: ${ia.join(", ")}`,"Reaction type")}async addContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=Ve,n={messageId:e.messageId,reactionType:e.reactionType},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s),{created:i,...a}=r;return{data:a,created:i}}async removeContentReaction(e){this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${ze}?${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)}}const oa="Token name is required and must be a string";const ca="GALA|Unit|none|none";class la extends jn{constructor(e,t,n,s=!1){super(s),this.dexBackendHttp=e,this.cache=t,this.fetchTokenDetails=n}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!On(e))throw new Rt(oa,"tokenName",bt);let s;if(void 0!==n)try{this.logger.debug(`Checking graduation status for token: ${e}`);const t=await n(e);!0===t.isGraduated&&(s=xi(t.sellingToken))}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${Bt(t)}`)}if(void 0!==s)return this.logger.debug(`Token ${e} is graduated, using its swap backend price`),this.fetchMarketUsdPrice(s);try{this.logger.debug(`Using bonding curve calculation for token: ${e}`);const n=await t({tokenName:e,amount:"1",type:"native"}),s=await this.fetchMarketUsdPrice(ca),r=Sn(n.amount,0)/1e18;if(r<=0)throw new Rt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");return{symbol:fn(e),price:s.price/r}}catch(t){throw Qt(`Failed to calculate launchpad token spot price for ${e}: ${Bt(t)}`,void 0,Pt(t)?t:void 0)}}async resolveAuthoritativeSymbol(e){if(e===ca)return"GALA";const t=this.cache?.getByTokenId(e);if(null!=t?.symbol&&""!==t.symbol)return t.symbol;let n;this.logger.debug(`Symbol cache miss for ${e}, reading the token class`);try{if(void 0===this.fetchTokenDetails)throw Qt("GalaChainService not available for token metadata fetch",500);n=(await this.fetchTokenDetails(e)).symbol}catch(t){throw Qt(`Could not resolve the symbol for ${e} from the token class, and a symbol cannot be derived from the class key: ${Bt(t)}`)}if(""===n)throw Qt(`Token class for ${e} has no symbol`);return this.cache?.setByTokenId(e,{symbol:n}),n}async fetchMarketUsdPrice(e){try{const t=function(e){if(!On(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}(e);if(this.logger.debug(`Fetching swap backend price for token: ${t}`),void 0===this.dexBackendHttp)throw Qt("DEX Backend API client not configured");const n=await this.resolveAuthoritativeSymbol(e),s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:t}}),r=null!==s&&"object"==typeof s?s:{},i=Object.keys(r).find(e=>e.toUpperCase()===n.toUpperCase()),a=void 0!==i?r[i]:1===Object.keys(r).length?Object.values(r)[0]:void 0,o=a?.price;if("number"!=typeof o||!Number.isFinite(o))throw new Rt(`Invalid price response: no market price for ${t}`,"data","INVALID_RESPONSE");return this.logger.debug(`Swap backend price for ${n}: $${o}`),{symbol:n,price:o}}catch(e){if(e instanceof Rt)throw e;throw Qt(`Failed to fetch DEX spot price: ${Bt(e)}`)}}}const da=20,ua=3e3,ha=1e3,ga=!0,ma=!0,fa=!1,pa={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 va{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 vn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??da,flushIntervalMs:t.flushIntervalMs??ua,maxQueueSize:t.maxQueueSize??ha,flushOnPageHide:t.flushOnPageHide??ga,flushOnPageUnload:t.flushOnPageUnload??ma,debug:t.debug??fa},this.setupPageLifecycleListeners()}track(e,t,n){if(this.isShuttingDown)return void this.logger.warn("EventsBatcher is shutting down, ignoring track call");const s={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(s),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??""}}const Aa=["createdAt","eventType","userAddress"],Ea=["last_hour","today","yesterday","last_7_days","last_30_days","custom"],ya=["sdk","frontend","backend","mcp"];function Ta(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Sa(e){return"number"==typeof e&&Number.isFinite(e)}function ba(e){return Ta(e)&&Sa(e.id)&&"string"==typeof e.eventType&&Ta(e.payload)&&"string"==typeof e.createdAt&&"string"==typeof e.updatedAt}function ka(e,t,n){if(!t.some(t=>t===e))throw new Rt(`${n} must be one of: ${t.join(", ")}`,n,wt)}class wa extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getEventStats(){return function(e){if(!(Ta(e)&&Sa(e.totalEvents)&&Sa(e.todayEvents)&&Sa(e.uniqueUsers)&&Sa(e.uniqueTokens)&&Ta(e.eventsByType)))throw Qt("Malformed event statistics response");const t={};for(const[n,s]of Object.entries(e.eventsByType)){if(!Sa(s))throw Qt("Malformed event statistics response");t[n]=s}return{totalEvents:e.totalEvents,todayEvents:e.todayEvents,uniqueUsers:e.uniqueUsers,uniqueTokens:e.uniqueTokens,eventsByType:t}}(await this.http.get(rt,void 0,this.getDualAuthHeaders()))}async queryEvents(e={}){!function(e){if(void 0!==e.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>100))throw new Rt("limit must be an integer from 1 to 100","limit",wt);if(void 0!==e.page&&(!Number.isInteger(e.page)||e.page<1))throw new Rt("page must be a positive integer","page",wt);void 0!==e.sortBy&&ka(e.sortBy,Aa,"sortBy"),void 0!==e.sortOrder&&ka(e.sortOrder,["asc","desc"],"sortOrder"),void 0!==e.timePreset&&ka(e.timePreset,Ea,"timePreset"),void 0!==e.source&&ka(e.source,ya,"source")}(e);const t={},n=new URLSearchParams;for(const[s,r]of Object.entries(e))if(void 0!==r&&("string"!=typeof r||""!==r)){if(Array.isArray(r)){const e=r.map(String);if(0===e.length)continue;for(const t of 1===e.length?[...e,...e]:e)n.append(s,t);continue}t[s]=r}const s=n.toString(),r=""===s?st:`${st}?${s}`;return function(e){if(!Ta(e)||!Array.isArray(e.data)||!Ta(e.pagination))throw Qt("Malformed events response");const t=e.pagination,n=e.data;if(!(Sa(t.page)&&Sa(t.limit)&&Sa(t.total)&&Sa(t.totalPages)&&n.every(ba)))throw Qt("Malformed events response");return{data:n,pagination:{page:t.page,limit:t.limit,total:t.total,totalPages:t.totalPages}}}(await this.http.get(r,t,this.getDualAuthHeaders()))}}function Na(e){let t;return{requestor:async(n,s)=>{const r="string"==typeof s?.body?JSON.parse(s.body):void 0,{data:i,status:a,headers:o}=await e(n,r);t=i;const c=void 0===i?"":JSON.stringify(i),l="number"==typeof a?a:200;return{ok:l>=200&&l<300,status:l,json:()=>Promise.resolve(i),text:()=>Promise.resolve(c),headers:o??{}}},answer:()=>t}}const _a=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID"]);class Ia extends Hn{constructor(e,t=!1){super(e,t)}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const{requestor:n}=Na(async(e,t)=>({data:await this.http.post(e,t)})),s=new p({gatewayBaseUrl:"",httpRequestor:n,requestTimeoutMs:1/0}),{owner:r,collection:i,category:a,type:o,additionalKey:c}=e,l=await s.fetchTokenBalance({owner:r,tokenClassKey:{collection:i,category:a,type:o,additionalKey:c},includeExpiredHolds:t});return void 0===l?null:function(e){if("0"===e.quantity)return null;const{collection:t,category:n}=e.tokenClassKey,s={quantity:e.quantity,collection:t,category:n,tokenId:xi(e.tokenClassKey)};return e.inUseHolds.length>0&&(s.inUseHolds=[...e.inUseHolds],s.inUseQuantity=e.inUseQuantity),e.lockedHolds.length>0&&(s.lockedHolds=[...e.lockedHolds],s.lockedQuantity=e.lockedQuantity),void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=e.availableQuantity),s}(l)}catch(e){if(v(e)&&_a.has(e.code))return null;throw Qt(`Failed to fetch token balance from GalaChain: ${Bt(e)}`,void 0,Pt(e)?e:void 0)}}}function Ca(e){if(null==e||"object"!=typeof e)return!1;const t=e;return On(t.amount)&&(void 0!==t.tokenId||On(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 Da(e){if(null==e||"object"!=typeof e)return!1;const t=e;return On(t.amount)&&(void 0!==t.tokenId||On(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Ra,Oa;!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"}(Ra||(Ra={}));class Ma 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"}(Oa||(Oa={}));class Ua extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function La(e){const t=e?.tokens?.[0];if(void 0===t)return;const n={};return void 0!==t.tokenName&&(n.tokenName=t.tokenName),void 0!==t.amount&&(n.amount=t.amount),Object.keys(n).length>0?n:void 0}async function Fa(e,t,n,s="[DEBUG] Token resolution (launchpad)"){const r=await t.resolveTokenToVault(e);if(null!==r){const t=$i(r);return n.debug(s,{tokenName:e,vaultAddress:r,tokenInstance:{collection:t.collection,category:t.category,type:t.type,instance:t.instance}}),t}throw new Rt(`Token "${e}" is not a launchpad token (no vault address found), and a token class key cannot be derived from a name. Pass an explicit tokenId (collection|category|type|additionalKey) for standard GalaChain tokens.`,"tokenName","TOKEN_CLASS_KEY_NOT_DERIVABLE")}class xa extends Hn{constructor(e,t,n,s=!1,r){super(e,s),this.wallet=t,this.tokenResolver=n,this.writer=r,this.nativeSigner=t?new Ri(t.privateKey):void 0}writeIdentity(){return void 0!==this.wallet&&void 0!==this.nativeSigner?{signer:this.nativeSigner,walletAddress:ps(this.wallet.address)}:this.writer}}function Pa(e,t){const{collection:n,category:s,type:r,additionalKey:i,instance:a}=e;return{tokenClassKey:{collection:n,category:s,type:r,additionalKey:i},instance:a,quantity:t}}const Ba=new Set(["GATEWAY_WRITE_REJECTED","GATEWAY_RESPONSE_INVALID","GATEWAY_HTTP_ERROR"]);function $a(e,{signer:t,walletAddress:n}){const{requestor:s,answer:r}=Na((t,n)=>e.postWithMeta(t,n));return{writes:new A({gatewayBaseUrl:"",signer:t,walletAddress:n,httpRequestor:s,requestTimeoutMs:1/0,uniqueKeyPrefix:"galaconnect-operation-"}),answer:r}}async function Ga(e,t,n){let s;try{s=await t(e.writes)}catch(t){throw function(e){return v(e)&&Ba.has(e.code)}(t)&&n(e.answer(),void 0),t}return n(e.answer(),s)}function Ka(e){return void 0===e||""===e?{}:{uniqueKey:e}}const Wa=100,Ha=100;class ja extends xa{async lockTokens(e){this.validateLockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ma("Wallet required for token lock operations",Ra.WALLET_REQUIRED);return $r(async()=>{const n=$a(this.http,t),s=n.writes.walletAddress,r=[],i=[];let a=s;const o=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==o?.lockAuthority&&(a=ps(o.lockAuthority));const c=e.tokens.find(e=>void 0!==e.expires),l=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);i.push(Pa(e,t.amount)),r.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount,lockAuthority:void 0!==t.lockAuthority?ps(t.lockAuthority):a})}return Ga(n,t=>t.lockTokens({tokens:i,lockAuthority:a,...void 0!==c?.expires&&{expires:c.expires},...void 0!==l?.name&&{name:l.name},...Ka(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token lock failed"),this.extractLockResult(e,t,r)))},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){this.validateUnlockTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ma("Wallet required for token unlock operations",Ra.WALLET_REQUIRED);return $r(async()=>{const n=[],s=[],r=e.tokens.find(e=>void 0!==e.name);for(const t of e.tokens){const e=await this.resolveTokenEntry(t);s.push(Pa(e,t.amount)),n.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:t.amount})}return Ga($a(this.http,t),t=>t.unlockTokens({tokens:s,...void 0!==r?.name&&{name:r.name},...Ka(e.uniqueKey)}),(e,t)=>(this.assertLockAnswer(e,"Token unlock failed"),this.extractUnlockResult(e,t,n)))},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}assertLockAnswer(e,t){try{Wt(e,t)}catch(t){const n=function(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}(e);throw new Ma(`${Bt(t)}${n}`,Ra.NETWORK_ERROR)}}validateSharedTokenEntry(e,t,n){if(void 0===e.tokenId&&void 0===e.tokenName)throw new Ma("Must provide either tokenId or tokenName for token identification",Ra.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{Pn(e.tokenName,"tokenName",Qn)}catch{throw new Ma("Invalid token name format",Ra.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{Er(fr(e.amount))}catch{throw new Ma(zt(t,"a positive number",n).message,Ra.INVALID_AMOUNT,{amount:e.amount})}}validateLockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Ca)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ma("Invalid lock data: missing required fields",Ra.VALIDATION_ERROR);if(e.tokens.length>Wa)throw new Ma(`Batch size exceeds maximum limit of ${Wa} tokens per lock operation`,Ra.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!vs(t.lockAuthority))throw new Ma("Invalid lock authority address format",Ra.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Cn(t.expires,"expires")}catch{throw new Ma(zt("expires","a positive integer (epoch milliseconds)","Expires").message,Ra.VALIDATION_ERROR)}}}validateUnlockTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Da)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ma("Invalid unlock data: missing required fields",Ra.VALIDATION_ERROR);if(e.tokens.length>Ha)throw new Ma(`Batch size exceeds maximum limit of ${Ha} tokens per unlock operation`,Ra.VALIDATION_ERROR);for(const t of e.tokens)this.validateSharedTokenEntry(t,"unlockAmount","Unlock amount")}transactionIdOf(e,t){const n=Array.isArray(e.Data)?e.Data[0]:void 0;return t?.transactionId??n?.transactionId??n?.txnId??n?.TxnId??n?.id??void 0}extractLockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},locked:n}}extractUnlockResult(e,t,n){const s=this.transactionIdOf(e,t),r=t?.blockNumber;return{...void 0!==s&&{transactionId:s},...void 0!==r&&{blockNumber:r},unlocked:n}}handleLockError(e,t,n){if(e instanceof Ma)return e;if(v(e)&&"pre_send"===e.phase)return new Ma(`${t}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?Ra.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?Ra.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?Ra.INVALID_AMOUNT:Ra.VALIDATION_ERROR,La(n));var s;let r=t,i=Ra.NETWORK_ERROR;if(Kt(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n.Message;"string"==typeof e&&e.length>0&&(r=`${t}: ${e}`);const s="string"==typeof e?e.toLowerCase():"";s.includes("insufficient")||s.includes("balance")?i=Ra.INSUFFICIENT_BALANCE:s.includes("lock")&&s.includes("not found")?i=Ra.LOCK_NOT_FOUND:s.includes("not found")||s.includes("token")?i=Ra.TOKEN_NOT_FOUND:s.includes("authority")?i=Ra.NOT_LOCK_AUTHORITY:s.includes("expired")&&(i=Ra.LOCK_EXPIRED)}}else Pt(e)&&(r=`${t}: ${Bt(e)}`);return new Ma(r,i,La(n))}async resolveTokenInstance(e){return $r(async()=>Fa(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Ua)throw new Ma(Bt(t),Ra.TOKEN_NOT_FOUND);throw new Ma(`Failed to resolve token '${e}': ${Bt(t)}`,Ra.TOKEN_NOT_FOUND,{tokenName:e})})}async resolveTokenEntry(e){if(void 0!==e.tokenId){const t=Pi(e.tokenId);return this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),t}if(void 0!==e.tokenName)return this.resolveTokenInstance(e.tokenName);throw new Ma("Must provide either tokenId or tokenName for token identification",Ra.TOKEN_NOT_FOUND)}}const qa=new Set(["GATEWAY_READ_REJECTED","GATEWAY_READ_RESPONSE_INVALID","TOKEN_CLASS_NOT_FOUND"]);function Va(e){const t=e?.Data;return Array.isArray(t)?t:void 0}class za extends Hn{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?Pi(e):e,{collection:n,category:s,type:r,additionalKey:i}=t,a={collection:n,category:s,type:r,additionalKey:i},o="Failed to fetch token class from GalaChain";return await this.readPublic(e=>e.fetchTokenClass(a),e=>{if(Wt(e,o),void 0===Va(e)?.[0])throw Qt(`Token not found on GalaChain: ${xi(a)}`,404)},()=>Qt(`Token not found on GalaChain: ${xi(a)}`,404))}catch(e){return this.handleTokenServiceError(e,"Token not found on GalaChain","Failed to fetch token class from GalaChain")}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw Vt("tokenClasses","Token classes array");return await this.readPublic(t=>t.fetchTokenClassesWithSupply(e),e=>{if(Wt(e,"Failed to fetch token classes with supply from GalaChain"),0===(Va(e)?.length??0))throw Qt("No token supply data found for requested token classes",404)},void 0)}catch(e){return this.handleTokenServiceError(e,"Token supply data not found on GalaChain","Failed to fetch token classes with supply from GalaChain")}}async readPublic(e,t,n){if(!this.publicAxios)throw Vt("publicAxios","Public Axios instance");const s=this.publicAxios,{requestor:r,answer:i}=Na(async(e,t)=>{const n=await s.post(e,t);return{data:n.data,status:n.status}});try{return await e(new p({gatewayBaseUrl:"",httpRequestor:r,requestTimeoutMs:1/0}))}catch(e){if(v(e)&&qa.has(e.code)&&(t(i()),"TOKEN_CLASS_NOT_FOUND"===e.code&&void 0!==n))throw n();throw e}}handleTokenServiceError(e,t,n){if(e instanceof Rt)throw e;if(Kt(e)&&404===e.response?.status)throw Qt(t,404,Pt(e)?e:void 0);if(Pt(e)&&"Error"===e.name&&Bt(e).includes("status indicates failure"))throw Qt(Bt(e),400,Pt(e)?e:void 0);const s=Bt(e);if(s.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(s)}throw Qt(`${n}: ${s}`,void 0,Pt(e)?e:void 0)}}function Qa(e){if(null==e||"object"!=typeof e)return!1;const t=e;return On(t.amount)&&(void 0!==t.tokenId||On(t.tokenName))}var Xa;!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"}(Xa||(Xa={}));class Ja extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Ya={validateAmount(e){const t=fr(e);try{!function(e,t){if(e.isNaN())throw nn(t,"NaN");if(!e.isFinite())throw en(t,"finite");if(e.isLessThanOrEqualTo(0))throw Zt(t,"0",e.toString())}(t,"amount")}catch(t){throw new Ua(t.message,Oa.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!Mn(e)&&On(e)){if(e.length>os.MAX_LENGTH)throw new Rt(`Unique key too long. Maximum length: ${os.MAX_LENGTH}`);if(!os.PATTERN.test(e))throw new Ua('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Oa.INVALID_AMOUNT,{uniqueKey:e})}}},Za="gala-transfer-successful",eo="token-transfer-successful",to="token-locked-successfully",no="token-unlocked-successfully",so="transfer-successful-no-id",ro=50;class io extends xa{async transferGala(e){this.validateTransferGalaData(e);const t=this.writeIdentity();if(void 0===t)throw new Ua("Wallet required for GALA transfer operations",Oa.WALLET_REQUIRED);try{const n=ps(e.recipientAddress),s=$a(this.http,t);return await Ga(s,t=>t.transferGala({to:n,quantity:e.amount,...Ka(e.uniqueKey)}),(e,t)=>this.extractTransferResult(e,t,"gala"))}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){this.validateTransferTokenData(e);const t=this.writeIdentity();if(void 0===t)throw new Ua("Wallet required for token transfer operations",Oa.WALLET_REQUIRED);try{const n=ps(e.to),s=await this.tokenInstanceOf(e.tokenId,e.tokenName,()=>new Ua("Must provide either tokenId or tokenName for token identification",Oa.TOKEN_NOT_FOUND)),r=$a(this.http,t);return await Ga(r,t=>t.transferToken({to:n,...Pa(s,e.amount),...Ka(e.uniqueKey)}),(e,t)=>this.extractTransferResult(e,t,"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 Ua)throw t;throw new Ua(`Failed to resolve token class key for '${e}': ${Bt(t)}`,Oa.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){this.validateBurnTokensData(e);const t=this.writeIdentity();if(void 0===t)throw new Ja("Wallet required for token burn operations",Xa.WALLET_REQUIRED);try{const n=[];for(const t of e.tokens){const e=await this.tokenInstanceOf(t.tokenId,t.tokenName,()=>new Ja("Must provide either tokenId or tokenName for token identification",Xa.TOKEN_NOT_FOUND));n.push(Pa(e,t.amount))}const s=$a(this.http,t);return await Ga(s,t=>t.burnTokens({tokens:n,...Ka(e.uniqueKey)}),(e,t)=>this.burnResultOf(e,t))}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 On(t.recipientAddress)&&On(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Rt("Invalid GALA transfer data: missing required fields");if(!vs(e.recipientAddress))throw new Ua("Invalid recipient address format",Oa.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Ya.validateAmount(e.amount),Ya.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return On(t.to)&&On(t.amount)&&(void 0!==t.tokenId||On(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Rt("Invalid token transfer data: missing required fields");if(!vs(e.to))throw new Ua("Invalid recipient address format",Oa.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Ua("Must provide either tokenId or tokenName for token identification",Oa.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{Pn(e.tokenName,"tokenName",Qn)}catch{throw new Ua("Invalid token name format",Oa.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Ya.validateAmount(e.amount),Ya.validateUniqueKey(e.uniqueKey)}validateBurnTokensData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Array.isArray(t.tokens)&&t.tokens.length>0&&t.tokens.every(Qa)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ja("Invalid burn data: missing required fields",Xa.VALIDATION_ERROR);if(e.tokens.length>ro)throw new Ja(`Batch size exceeds maximum limit of ${ro} tokens per burn operation`,Xa.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 Ja("Must provide either tokenId or tokenName for token identification",Xa.TOKEN_NOT_FOUND);const e=fr(t.amount);try{Er(e)}catch{throw new Ja("Burn amount must be a positive number",Xa.INVALID_AMOUNT,{amount:t.amount})}}}async tokenInstanceOf(e,t,n){if(null!=e){const t=Pi(e);return this.logger.debug("[DEBUG] Using provided tokenId:",e),t}if(null!=t)return this.resolveTokenInstance(t);throw n()}async resolveTokenInstance(e){try{return await Fa(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Ua)throw t;throw new Ua(`Failed to resolve token '${e}': ${Bt(t)}`,Oa.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){if(null==e)throw new Ua("No response from GalaChain transfer service",Oa.NETWORK_ERROR);const s=t?.blockNumber,r="object"==typeof e&&"Status"in e;r&&Wt(e,"Extract transaction ID");const i=r&&"Data"in e,a=t?.transactionId;if(void 0!==a)return{transactionId:a,...void 0!==s?{blockNumber:s}:{}};if(i){const t=e;if(Array.isArray(t.Data)){for(const e of t.Data)if(null!=e&&"object"==typeof e){const t=e;for(const e of["transactionId","txnId","TxnId","id","txId"]){const n=t[e];if("string"==typeof n&&n.length>0)return{transactionId:n,...void 0!==s?{blockNumber:s}:{}}}}let e=so;if(t.Data.length>0)switch(n){case"gala":e=Za;break;case"token":e=eo;break;case"lock":e=to;break;case"unlock":e=no}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}throw new Ua("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Oa.NETWORK_ERROR)}burnResultOf(e,t){if(null==e)throw new Ja("No response from GalaChain burn service",Xa.NETWORK_ERROR);try{Wt(e,"Token burn operation")}catch(e){throw new Lt(Bt(e),500)}return this.extractBurnResult(e,t)}extractBurnResult(e,t){const n=[];if(null!==e.Data&&void 0!==e.Data&&Array.isArray(e.Data))for(const t of e.Data)n.push({collection:t.collection??"",category:t.category??"",type:t.type??"",additionalKey:t.additionalKey??"",instance:t.instance??"0",quantity:t.quantity??"0",burnedBy:t.burnedBy??""});const s=Array.isArray(e.Data)?e.Data[0]:void 0,r=t?.transactionId??s?.transactionId??s?.txnId??s?.TxnId??s?.id??void 0,i=t?.blockNumber;return{...void 0!==r&&{transactionId:r},...void 0!==i&&{blockNumber:i},burned:n}}handleTransferError(e,t,n){if(e instanceof Ua)return e;if(e instanceof Rt)return new Ua(Bt(e),Oa.INVALID_AMOUNT);if(v(e)&&"pre_send"===e.phase)return new Ua(e.message,"SIGNING_FAILED"===(s=e.code)?Oa.SIGNATURE_FAILED:"INVALID_WALLET_ADDRESS"===s?Oa.INVALID_RECIPIENT:"INVALID_TOKEN_REFERENCE"===s?Oa.TOKEN_NOT_FOUND:Oa.INVALID_AMOUNT);var s;if(Kt(e)&&e.response){const t=e.response.status,s=e.response.data;if(400===t){const e=s?.message;return new Ua(("string"==typeof e?e:void 0)??"Invalid transfer request",Oa.INVALID_AMOUNT)}if(403===t)return new Ua("Insufficient balance for transfer",Oa.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Ua("Token not found",Oa.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===Gt(e)||"ETIMEDOUT"===Gt(e)))return new Ua("Transfer request timed out",Oa.NETWORK_ERROR);const r=""!==Bt(e)?Bt(e):t;return new Ua(r,Oa.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof Ja)return e;if(v(e)&&"pre_send"===e.phase)return new Ja(`${t}: ${e.message}`,"SIGNING_FAILED"===(s=e.code)?Xa.SIGNATURE_FAILED:"INVALID_TOKEN_REFERENCE"===s?Xa.TOKEN_NOT_FOUND:"INVALID_QUANTITY"===s?Xa.INVALID_AMOUNT:Xa.VALIDATION_ERROR,La(n));var s;let r=t,i=Xa.NETWORK_ERROR;if(Kt(e)){const n=e.response?.data;if("object"==typeof n){const e=n.Message;if("string"==typeof e&&e.length>0){r=`${t}: ${e}`;const n=e.toLowerCase();n.includes("insufficient")||n.includes("balance")?i=Xa.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(i=Xa.TOKEN_NOT_FOUND)}}}else Pt(e)&&(r=`${t}: ${Bt(e)}`);return new Ja(r,i,La(n))}}class ao extends Hn{constructor(e,t,n,s=!1,r,i){super(e,s),this.balanceService=new Ia(e,s),this.tokenService=new za(e,s,r),this.lockService=new ja(e,t,n,s,i),this.transferService=new io(e,t,n,s,i)}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 fetchTokenDetails(e){try{return E(await this.fetchTokenClassFromChain(e))}catch(t){if(Pt(t)&&("NetworkError"===t.name||Bt(t).includes("Token not found")))throw t;throw Qt(`Failed to fetch token details from GalaChain for ${"string"==typeof e?e:xi(e)}: ${Bt(t)}`,500)}}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 oo extends Hn{async getHealth(){const e=(await this.http.get(it)).data;if(null==e)throw Qt("Health check answered no data");return e}}class co extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function lo(e,t,n){if(null==e)throw new co("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Ks.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new co(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new co("Filename is required when uploading Buffer objects",t,n);const s=Ws.safeParse(e);if(!s.success){const e=s.error.issues.map(e=>e.message).join("; ");throw new co(e,t,n)}try{In(t,255,"filename")}catch(e){throw new co(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 co(`Invalid file type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,t,n);const i=function(e){if(null==e||""===e)return"";const t=e.lastIndexOf(".");if(-1===t)return"";return e.substring(t).toLowerCase()}(t),a=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!a.includes(i))throw new co(`File extension "${i}" is not allowed. Allowed extensions: ${a.join(", ")}`,t,n);const o=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(i);if(o!==n&&"application/octet-stream"!==o)throw new co(`File extension "${i}" does not match MIME type "${n}"`,t,n);return}throw new co("File must be a File object (browser) or Buffer (Node.js)",t,n)}function uo(e,t="image",n){const s=new FormData;if("undefined"!=typeof File&&e instanceof File)s.append(t,e);else{if(!Buffer.isBuffer(e))throw zt("file","a File object (browser) or Buffer (Node.js)");{const r=new Blob([e],{type:"image/png"});s.append(t,r,n)}}return s}class ho extends Hn{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;xn(t,"tokenName",Qn);const s=`${t}.png`;lo(n.file,s,"image/png");try{const e=uo(n.file,"image",s),r=await ln(()=>this.http.request({method:"POST",url:si(D.UPLOAD_IMAGE,{tokenName:t}),data:e,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof r?r:""}catch(e){if(e instanceof Ft)throw e;if(Pt(e)&&Bt(e).includes("FormData"))throw Xt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}function go(e){if(Mn(e)||"object"!=typeof e)return{};const t={};for(const[n,s]of Object.entries(e))Mn(s)||(On(s)?t[n]=s:"number"==typeof s||"boolean"==typeof s?t[n]=s.toString():Array.isArray(s)?t[n]=s.join(","):t[n]="object"==typeof s?JSON.stringify(s):String(s));return t}function mo(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}function fo(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function po(e){return"string"==typeof e.quantity&&""!==e.quantity}class vo extends Hn{constructor(e,t,n=!1){super(e,n,t)}async fetchPools(e={}){const t=function(e){const t=e.pageSize??Xr.DEFAULT_LIMIT;if(!Number.isInteger(t)||t<1||t>St)throw Yt("pageSize",1,St,t);const n={pageSize:String(t)};On(e.cursor)&&(n.cursor=e.cursor);void 0!==e.type&&(n.type=To("type",e.type,yt));On(e.tokenName)&&(xn(e.tokenName,"tokenName",zn),n.tokenName=e.tokenName);if(On(e.search)){if(e.search.length>Ao)throw function(e,t,n,s){const r=jt(e,s);return new Rt(`${r} must be at most ${t} characters${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LONG")}("search",Ao,e.search.length);n.search=e.search}!0===e.hasUpcomingShows&&(n.hasUpcomingShows="true");if(On(e.language)){if(!yo.test(e.language))throw zt("language",'an ISO 639-1 code such as "en" or "zh-CN"');n.language=e.language}if(void 0!==e.recentlyStreamed){const t=e.recentlyStreamed;if(!Number.isInteger(t)||t<1||t>Eo)throw Yt("recentlyStreamed",1,Eo,t);n.recentlyStreamed=String(t)}!0===e.hasRecordings&&(n.hasRecordings="true");void 0!==e.streamStatus&&(n.streamStatus=To("streamStatus",e.streamStatus,Tt));return n}(e),n=on(await un(()=>this.http.get(D.FETCH_POOLS,t),{errorContext:"Failed to fetch pools"}));return{items: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}(n),pageInfo:Yr(n?.pageInfo)}}async fetchAllPools(e){const t=[];let n;for(;;){const s={...e,pageSize:100,...void 0!==n&&{cursor:n}},r=await this.fetchPools(s);if(t.push(...r.items),0===r.items.length)break;const i=Zr(r.pageInfo,n);if(void 0===i)break;n=i}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){!function(e){const t=or(e);!t.success&&t.errors&&wr(t.errors,"options")}(e),On(e.tokenName)&&xn(e.tokenName,"tokenName",Xn);try{const t=await this.http.post(D.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===On(e.symbol)){return!n.symbolAvailable}if(!0===On(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,s="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||s.includes("404")||s.includes("Pool not found"))return!1;const r="number"==typeof n.statusCode?n.statusCode:null;if(404===r)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||s.includes("400")||s.includes("Missing required pool identifier"))return!1;if(400===r&&s.includes("Missing required pool identifier"))return!1;throw e}}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async fetchVolumeData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return lr(t,"tokenName")&&ur(t,"from")&&ur(t,"to")&&ur(t,"resolution")}(e))throw new Rt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:s,resolution:r}=e;if(xn(t,"tokenName",zn),null==n||null==s||null==r)throw new Rt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const i={tokenName:t,from:n,to:s,resolution:r};_r(i);const a=go(i),o=await ln(()=>this.http.get(D.CHART,a),{errorContext:"Failed to fetch graph data"});if(!Array.isArray(o.data)||"boolean"!=typeof o.isPreviousData)throw new Lt("Invalid chart response: expected { data: candles, isPreviousData }");return{dataPoints:o.data,isPreviousData:o.isPreviousData,..."number"==typeof o.nextTime&&{nextTime:o.nextTime}}}async fetchTokenDistribution(e){if(""===e||null==e)throw Vt("tokenName","Token name");let t;xn(e,"tokenName",zn);try{t=await un(()=>this.http.get(`${D.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(Kt(t)&&500===t.response?.status)throw Qt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500,Pt(t)?t:void 0);throw t}return function(e,t,n=pr){if(!Array.isArray(e))throw Qt("Invalid API response: expected array of holders",t);for(const n of e){if(!fo(n))throw Qt("Invalid holder data: missing or invalid owner field",t);if(!po(n))throw Qt("Invalid holder data: missing or invalid quantity field",t);const e=Sn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Qt(`Invalid holder quantity: "${n.quantity}"`,t)}const s=e,r=s.reduce((e,t)=>e.plus(t.quantity),fr(0));return{holders:s.map(e=>({address:e.owner,balance:e.quantity,percentage:yr(fr(e.quantity),r,fr(0)).multipliedBy(100).toNumber()})),totalSupply:n(r),totalHolders:s.length,lastUpdated:new Date}}(on(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Vt("tokenName","Token name");if(""===t||null==t)throw Vt("userAddress","User address");return xn(e,"tokenName",zn),ln(()=>this.http.get(`${D.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async resolveTokenNameToVault(e){const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0]?.vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");xn(e,"tokenName",Qn);try{const t=D.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=on(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 t instanceof Lt?new Lt(`Token not found: ${e}`,t.statusCode,t):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&&xn(e.tokenName,"tokenName",Xn);try{const t=await this.http.post(D.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(!On(e))throw Vt("tokenName","Token name");xn(e,"tokenName",Qn);const t=D.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=on(await this.http.get(t));if(!function(e){if("object"!=typeof e||null===e)return!1;const t=new Map(Object.entries(e));return["holdersCount","chatMessageCount","commentCount","roomCount"].every(e=>{const n=t.get(e);return"number"==typeof n&&Number.isFinite(n)})}(e))throw new Error("Invalid response: missing stats data");return{success:!0,data:{holdersCount:e.holdersCount,chatMessageCount:e.chatMessageCount,commentCount:e.commentCount,roomCount:e.roomCount}}}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 Vt("tokenName","Token name");xn(e,"tokenName",Qn),function(e){if(void 0===e.chatEnabled&&void 0===e.commentsEnabled&&void 0===e.streamingEnabled&&void 0===e.nextLiveStreamAt&&void 0===e.streamLanguage&&void 0===e.websiteUrl&&void 0===e.telegramUrl&&void 0===e.twitterUrl&&void 0===e.instagramUrl&&void 0===e.facebookUrl&&void 0===e.redditUrl&&void 0===e.tiktokUrl)throw new Rt("At least one config option must be provided (chatEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",bt);if(void 0!==e.chatEnabled&&"boolean"!=typeof e.chatEnabled)throw tn("chatEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw tn("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw tn("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw tn("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 tn(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw tn("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Rt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Nt)}}(t);const n=D.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),s={};void 0!==t.chatEnabled&&(s.chatEnabled=t.chatEnabled),void 0!==t.commentsEnabled&&(s.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(s.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(s.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(s.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(s.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(s.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(s.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(s.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(s.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(s.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(s.tiktokUrl=t.tiktokUrl),await this.http.patch(n,s,this.getJwtHeaders())}async getTokenConfig(e){if(!On(e))throw Vt("tokenName","Token name");xn(e,"tokenName",Qn);const t=D.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),n=on(await this.http.get(t));if(void 0===n)throw new Error(`Invalid response: missing token config data for "${e}"`);return n}}const Ao=255,Eo=720,yo=/^[a-z]{2}(-[A-Z]{2})?$/u;function To(e,t,n){const s="string"==typeof t?t.toUpperCase():void 0,r=n.find(e=>e===s);if(void 0===r)throw sn(e,t,n);return r}function So(e){if(void 0!==e.tokenName){if(!On(e.tokenName))throw tn("tokenName","a non-empty string",typeof e.tokenName);Pn(e.tokenName,"tokenName",zn)}if(void 0!==e.userAddress){if(!On(e.userAddress))throw tn("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>ns)throw en("userAddress",ns,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw tn("search","a string",typeof e.search);if(e.search.length>256)throw en("search",256,e.search.length)}if(Un(0,void 0,es,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw zt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!On(e.startDate))throw tn("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw zt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!On(e.endDate))throw tn("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw zt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{_n(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw zt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{_n(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw zt("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&function(e,t,n="range"){const s="number"==typeof e?e:Number(e),r="number"==typeof t?t:Number(t);if(isNaN(s)||isNaN(r))throw tn(n,"numeric values",void 0,n);if(s>r)throw new Rt(`Minimum value (${s}) must be less than or equal to maximum value (${r}) for ${n}`,n,Ct)}(e.minAmount,e.maxAmount,"amountRange")}class bo extends Hn{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 lr(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&dr(t,"userAddress")&&ur(t,"offset")&&ur(t,"pageSize")&&ur(t,"page")&&ur(t,"limit")}(e))throw new Rt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,cursor:n,pageSize:s=Xr.DEFAULT_LIMIT}=e;if(!On(t))throw Vt("tokenName","Token name");const r={pageSize:String(Math.min(s,Zn))};void 0!==n&&(r.cursor=n);const i=await this.http.get(si(D.GET_TRADES,{tokenName:t}),r);if(null==i)throw new Rt("No response from trade service","response","NO_RESPONSE");const a=on(i),o=mo(a,"trades"),c=a?.pageInfo;return{items:o,pageInfo:c??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=mn(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?function(e,t=1,n=Xr.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}(e.pageSize,1,es):es;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){So(e);const t=this.buildTradesQueryParams(e);return ln(()=>this.http.get(Qe,t),{errorContext:"Failed to fetch trades"})}}Qn.MIN_LENGTH,Qn.MAX_LENGTH;function ko(e){return!!On(e)&&ts.PATTERN.test(e)}function wo(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const s=e.trim();return s.length<n?null:s}Ln({BOTH:"both",HELD:"held",CREATED:"created"});function No(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _o(e){return"number"==typeof e&&Number.isFinite(e)}function Io(e){return null===e||"string"==typeof e}function Co(e){return Array.isArray(e)&&e.every(e=>No(e)&&"string"==typeof e.badgeName&&"boolean"==typeof e.isActive)}function Do(e){return No(e)&&"string"==typeof e.address&&Io(e.fullName)&&Io(e.profileImage)&&Io(e.bio)&&function(e){return No(e)&&_o(e.tokensCreated)&&_o(e.tokensGraduated)&&_o(e.graduationRate)&&_o(e.totalTrades)&&"string"==typeof e.totalVolumeGala&&Io(e.totalVolumeUsd)&&(null===e.holdingsCount||_o(e.holdingsCount))&&Io(e.accountCreatedAt)&&_o(e.accountAgeDays)}(e.stats)&&Co(e.launchBadge)&&Co(e.successBadge)&&Co(e.volumeBadge)&&Co(e.engagementBadge)&&"boolean"==typeof e.isLiveStreaming&&Io(e.liveStreamToken)}class Ro extends Hn{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!ko(t))throw zt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e){const e=await ln(()=>this.http.get(D.GET_CURRENT_USER,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch profile"});if(!(No(n=e)&&"string"==typeof n.address&&Io(n.fullName)&&Io(n.profileImage)&&"string"==typeof n.bio&&Co(n.launchBadge)&&Co(n.successBadge)))throw Qt("Malformed profile response");return e}var n;const s=await ln(()=>this.http.get(D.GET_PROFILE.replace(":address",t)),{errorContext:"Failed to fetch profile"});if(!Do(s))throw Qt("Malformed profile response");return s}async updateProfile(e){this.validateUpdateProfileData(e);const t={};void 0!==e.fullName&&(t.fullName=e.fullName.trim()),void 0!==e.profileImage&&(t.profileImage=e.profileImage),await ln(()=>this.http.put(D.UPDATE_PROFILE,t,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);try{const t=void 0===e.address?"profile-image.png":`profile-image-${e.address}.png`,n=uo(e.file,"image",t),s=await ln(()=>this.http.request({method:"POST",url:D.UPLOAD_PROFILE_IMAGE,data:n,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Rt||e instanceof Ft)throw e;if(e instanceof Lt)throw new Lt(`Profile image upload failed: ${Bt(e)}`,e.statusCode,e);throw new Rt(`Profile image upload failed: ${Bt(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){if(void 0!==e.status&&"created"!==e.type)throw new Rt("status filters only apply when type=created","status","INVALID_FILTER");const t=e.tokenName,n={...e},s="created"===e.type;s&&(delete n.tokenName,void 0!==t&&void 0===n.search&&(n.search=t));const r=await this.buildFetchRequest(D.GET_TOKEN_LIST,n,{includeType:!0,requestType:e.type??"both",responseKey:s?"launches":"token",errorMessage:"Failed to fetch token list"});return s&&void 0!==t?{...r,tokens:r.tokens.filter(e=>e.tokenName===t||e.name===t)}:r}async fetchTokensHeld(e){if(void 0!==e.type&&"held"!==e.type)throw new Rt("fetchTokensHeld only supports type=held","type","INVALID_TYPE");if(void 0!==e.status)throw new Rt("status filters only apply when type=created","status","INVALID_FILTER");return this.buildFetchRequest(D.GET_TOKENS_HELD,e,{includeType:!0,requestType:"held",responseKey:"token",errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:s,tokenName:r,status:i}=e??{};if(void 0!==e?.type&&"created"!==e.type)throw new Rt("fetchTokensCreated only supports type=created","type","INVALID_TYPE");const a=e?.address??this.http.getAddress();if(null==a||""===a)throw new Rt("Wallet address not available - wallet not configured","address","NO_WALLET");const o={type:"created",address:a,pageSize:n??Xr.DEFAULT_LIMIT};return void 0!==t&&(o.cursor=t),void 0!==s&&(o.search=s),void 0!==r&&void 0===s&&(o.search=r),void 0!==r&&(o.tokenName=r),void 0!==i&&(o.status=i),this.fetchTokenList(o)}async getManagedTokens(e={}){const t={};return void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=String(Math.min(e.pageSize,Zn))),ln(()=>this.http.get(D.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async getUserGalaBalance(e){if("string"!=typeof e||""===e.trim())throw Vt("address","Address");return ln(()=>this.http.get(si(D.GET_GALA_BALANCE,{address:e.trim()})),{errorContext:"Failed to fetch GALA balance"})}async fetchReferralCode(){return ln(()=>this.http.get(D.GET_REFERRAL_CODE,void 0,this.getJwtHeaders()),{errorContext:"Failed to fetch referral code"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const s=ti({pageSize:t.pageSize??Xr.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},Zn);ri(s,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(s.type=n.requestType);let r=e;const i=t.address??this.http.getAddress();if(e.includes(":address")){if(0===i.length)throw Vt("address","User address");r=e.replace(":address",i),delete s.address}const a=on(await un(()=>this.http.get(r,s),{errorContext:n.errorMessage}));return{tokens:mo(a,n.responseKey).map(e=>{const t="string"==typeof e.tokenName?e.tokenName:"",s="string"==typeof e.name?e.name:t,r="string"==typeof e.createdAt?e.createdAt:"",a=e.metadata,o={...e};return delete o.metadata,{...o,id:"string"==typeof e.id?e.id:t,name:s,symbol:"string"==typeof e.symbol?e.symbol:"",type:n.requestType,address:i,balance:"string"==typeof e.balance?e.balance:"string"==typeof e.quantity?e.quantity:"0",decimals:"number"==typeof e.decimals?e.decimals:0,...null!==a&&"object"==typeof a?{metadata:a}:{},createdAt:r,updatedAt:"string"==typeof e.updatedAt?e.updatedAt:r}}),pageInfo:Yr(a?.pageInfo)}}validateGetTokenListOptions(e){const t=e.pageSize??Xr.DEFAULT_LIMIT;if(t<1||t>Zn)throw new Rt(`pageSize must be between 1 and ${Zn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!ko(e.address))throw zt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=wo(e.search);if(null!==n&&!(On(s=n)&&s.length>=ls&&s.length<=ds))throw Yt("search",ls,ds,n.length,"Search query");var s;const r=wo(e.tokenName);if(!(null===r||On(i=r)&&Qn.PATTERN.test(i)))throw zt("tokenName",Qn.DESCRIPTION,"Token name");var i}validateUpdateProfileData(e){if(void 0!==e.address&&!ko(e.address))throw zt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(void 0===e.fullName&&void 0===e.profileImage)throw new Rt("At least one of fullName and profileImage must be provided","options","REQUIRED");if(void 0!==e.fullName&&(t=e.fullName.trim(),!(On(t)&&t.length>=us.FULL_NAME.MIN_LENGTH&&t.length<=us.FULL_NAME.MAX_LENGTH&&us.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t))))throw Yt("fullName",us.FULL_NAME.MIN_LENGTH,us.FULL_NAME.MAX_LENGTH,e.fullName.trim().length,"Full name");var t;if("string"==typeof e.profileImage&&e.profileImage.trim().length>2048)throw new Rt("profileImage must not exceed 2048 characters","profileImage","TOO_LONG")}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!ko(e.address))throw zt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Oo{constructor(e,t,n=!1){this.http=e,this.poolService=new vo(e,t,n),this.tradeService=new bo(e,n),this.userService=new Ro(e,t,n),this.imageService=new ho(e,t,n)}setJwtAuth(e){this.poolService.setJwtAuth(e),this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async getTrades(e){return this.tradeService.getTrades(e)}async fetchProfile(e){return void 0===e?this.userService.fetchProfile():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)}async getUserGalaBalance(e){return this.userService.getUserGalaBalance(e)}async fetchReferralCode(){return this.userService.fetchReferralCode()}getAddress(){return this.http.getAddress()}validateTokenName(e){return Nr(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 getTokenConfig(e){return this.poolService.getTokenConfig(e)}}const Mo={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};class Uo extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateContent(e,t){if(!On(e))throw Vt("content","Message content");if(0===e.trim().length)throw Vt("content","Message content");In(e,t===Mo.CHAT_MESSAGE?ss.CHAT_MESSAGES_V1.MAX_LENGTH:ss.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!On(e))throw Vt("id","Message ID");if(e.length<10||e.length>64)throw zt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Mo.CHAT_MESSAGE&&e!==Mo.COMMENT)throw new Rt(`type must be one of: ${Object.values(Mo).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,zn);const s={};void 0!==e.cursor&&(s.cursor=e.cursor),s.pageSize=e.pageSize??Xr.DEFAULT_LIMIT;const r=ti(s,es),i={};void 0!==r.pageSize&&(i.pageSize=r.pageSize),void 0!==r.cursor&&(i.cursor=r.cursor),t&&(i.type=e.type.toUpperCase()),n&&(i.tokenName=mn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(i.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(i.search=e.search);const a=await this.http.get(Xe.GET_MESSAGES,i),o=this.extractData(a);return{messages:o.messages,pageInfo:o.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,zn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:mn(e.tokenName),content:e.content.trim()},n=await this.http.post(Xe.CREATE_MESSAGE,t,this.getJwtHeaders());return{message:this.extractData(n)}}async updateMessage(e,t){this.validateMessageId(e),this.validateContent(t.content,t.type);const n=this.buildEndpointWithId(Xe.UPDATE_MESSAGE,e),s={content:t.content.trim()},r=await this.http.put(n,s,this.getJwtHeaders());return{message:this.extractData(r)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(Xe.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Qn);const t=await this.http.get(Xe.GET_PINNED,{tokenName:mn(e)});return{message:this.extractDataOrNull(t)}}async pinMessage(e){this.validateMessageId(e);const t=Xe.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=Xe.UNPIN_MESSAGE.replace(":id",e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){return function(e){const t=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!n(e))throw Qt("Malformed message statistics response");const s=e.totalMessages,r=e.todayMessages,i=e.uniqueUsers,a=e.uniqueTokens,o=e.messagesByType;if(!(t(s)&&t(r)&&t(i)&&t(a)&&n(o)))throw Qt("Malformed message statistics response");const c={};for(const[e,n]of Object.entries(o)){if(!t(n))throw Qt("Malformed message statistics response");c[e]=n}return{totalMessages:s,todayMessages:r,uniqueUsers:i,uniqueTokens:a,messagesByType:c}}(await this.http.get(Xe.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders()))}}const Lo=Fn({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),Fo={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},xo=Fn(Fo),Po={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};Fn(Po);class Bo extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateRole(e){if(!On(e))throw Vt("role","Role");if(!function(e){return Lo.includes(e)}(e))throw zt("role",`one of: ${Lo.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!On(e))throw Vt("inviteCode","Invite code");if(e.length>cs)throw zt("inviteCode",`at most ${String(cs)} characters`,"Invite code")}validateInviteScope(e){if(void 0!==e&&(t=e,!xo.includes(t)))throw new Rt(`Invalid invite scope. Must be one of: ${xo.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??Fo.TOKEN;if(t===Fo.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Rt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,zn)}else if(t===Fo.ALL_OWNER_TOKENS&&e.tokenName)throw new Rt("Token name should not be provided for ALL_OWNER_TOKENS scope invites","tokenName","INVALID_VALUE");this.validateRole(e.role),this.validateOptionalString(e.description,"description","Description",ss.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=he,s={inviteScope:t,role:e.role};t===Fo.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(s.tokenName=mn(e.tokenName)),void 0!==e.description&&(s.description=e.description),void 0!==e.expiresAt&&(s.expiresAt=e.expiresAt);const r=await this.http.post(n,s,this.getMultiAuthHeaders());return{invite:this.extractData(r)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,zn),this.validateStatusFilter(e.status,Po);const t=fe,n={...this.buildPaginationParams(e,es)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=mn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(pe,{id:String(e)});an(await this.http.delete(t,void 0,this.getMultiAuthHeaders()),"Failed to revoke invite")}async updateInviteRole(e){this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),this.validateRole(e.role);const t=this.buildEndpoint(ve,{id:String(e.inviteId)}),n={role:e.role},s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&void 0===e.description)throw new Rt("At least one of role or description must be provided","options","REQUIRED");void 0!==e.role&&this.validateRole(e.role),void 0!==e.description&&this.validateOptionalString(e.description,"description","Description",ss.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Ae,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const s=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(s)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=ge,n={inviteCode:e.inviteCode},s=await this.http.post(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return"tokenName"in r&&void 0!==r.tokenName?{token:r}:{blanketAccess:r}}async getModeratedTokens(e){const t=me,n=this.buildPaginationParams(e??{},es),s=await this.http.get(t,n,this.getMultiAuthHeaders()),r=this.extractData(s);return{items:r.tokens,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ee,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const $o="10000",Go="1000";function Ko(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function Wo(){return Date.now()+6e4}function Ho(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function jo(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function qo(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Vo extends Hn{constructor(e){super(e)}getCollectionClaimFee(){return $o}getTokenClassCreateFee(){return Go}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(!qo(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=$o;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const s=Go,r=String(BigInt(s)*BigInt(e.createTokenClasses));n.tokenClassCreate=s,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),!Ho(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:Wo(),uniqueKey:Ko("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),!qo(e))throw new Error(`Invalid wallet address format: ${e}`);const t=e.toLowerCase(),n=(await this.allAuthorizations()).filter(e=>e.authorizedUsers.some(e=>e.toLowerCase()===t)).map(t=>({authorizedUser:e,collection:t.collection}));return this.logger.debug(`Found ${n.length} collections for user`),n}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),!Ho(e))throw new Error(`Invalid collection name format: ${e}`);const t=!(await this.allAuthorizations()).some(t=>t.collection===e);return this.logger.debug(`Collection ${e} available:`,t),t}catch(e){throw this.logger.error("Failed to check collection availability",e),e}}async createTokenClass(e){try{if(this.logger.debug("Creating NFT token class",e),null===e.collection||void 0===e.collection||0===e.collection.length||null===e.type||void 0===e.type||0===e.type.length||null===e.category||void 0===e.category||0===e.category.length)throw new Error("Missing required parameters: collection, type, category");if(!Ho(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?jo(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?jo(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:Wo(),uniqueKey:Ko("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),!Ho(e.collection))throw new Error(`Invalid collection name: ${e.collection}`);const t=(await this.reads().fetchAllTokenClasses({collection:e.collection,category:e.category,type:e.type},{pageSize:1e3})).map(e=>({collection:e.collection,type:e.type,category:e.category,additionalKey:e.additionalKey,totalSupply:e.totalSupply,maxSupply:e.maxSupply,isNonFungible:e.isNonFungible,name:e.name,description:e.description,image:e.image,symbol:e.symbol,...void 0===e.rarity?{}:{rarity:e.rarity}}));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(!qo(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 s={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:Wo(),uniqueKey:Ko("mint")};this.logger.debug("Built mint DTO",s);const r=`mint-${Date.now()}`,i=Array.from({length:t},(e,t)=>t+1);return{transactionId:r,mintedQuantity:e.quantity,owner:e.ownerAddress,tokenInstances:i,tokenClass:{collection:e.collection,type:e.type,category:e.category}}}catch(e){throw this.logger.error("Failed to mint NFT",e),e}}async fetchNftBalances(e,t){try{if(this.logger.debug("Fetching NFT balances for",{ownerAddress:e,collectionFilter:t}),!qo(e))throw new Error(`Invalid owner address: ${e}`);const n=(await this.reads().fetchNftBalances({owner:e,collection:t})).map(e=>({owner:e.owner,collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instanceIds:[...e.instanceIds],totalOwned:e.instanceIds.length}));return this.logger.debug(`Found ${n.length} NFT balances`),n}catch(e){throw this.logger.error("Failed to fetch NFT balances",e),e}}reads(){const{requestor:e}=Na(async(e,t)=>({data:await this.http.post(e,t)}));return new p({gatewayBaseUrl:"",httpRequestor:e,requestTimeoutMs:1/0})}allAuthorizations(){return this.reads().fetchAllNftCollectionAuthorizations({pageSize:1e3})}}class zo extends Hn{constructor(e,t=!1,n){super(e,t,n)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Notification operation failed";throw new Error(t)}return e.data}async registerPushToken(e){this.logger.debug("Registering push token",{platform:e.platform});const t=this.getJwtHeaders(),n=await this.http.post(gt,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),s=this.extractData(n);return this.logger.debug("Push token registered",{registered:s.registered}),s}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:mt,data:{token:e},headers:t}),s=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:s.unregistered}),s}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(ft,void 0,e),n=this.extractData(t);return this.logger.debug("Fetched notification preferences",{tradesEnabled:n.tradesEnabled,streamsEnabled:n.streamsEnabled}),{preferences:n}}async updatePreferences(e){this.logger.debug("Updating notification preferences",e);const t=this.getJwtHeaders(),n=await this.http.put(pt,e,t),s=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:s.tradesEnabled,streamsEnabled:s.streamsEnabled}),{preferences:s}}}class Qo extends Hn{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(D.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(D.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=D.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:s.title}),{oembed:s}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=D.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:s}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=D.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),s=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:s.title}),{oembed:s}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Rt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=D.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),s=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:s}}}function Xo(e){if(!On(e))throw Vt("address","Address")}const Jo={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Yo={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Zo=Ln(Jo),ec=Ln(Yo);function tc(e){try{$n(e.description,"description",255)}catch(e){if(e instanceof Rt){throw e.message.includes("255")?new Error("description must be at most 255 characters"):new Error("description must be a string")}throw e}if(void 0!==e.expiresAt){if(!On(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Gn(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Rt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Tn(e.expiresAt)){if(function(e){if(null==e)return new Date;if(e instanceof Date)return isNaN(e.getTime())?new Date:e;try{const t=new Date(e);return isNaN(t.getTime())?(yn.warn(`Invalid date string received: "${e}". Using fallback.`),new Date):t}catch(t){return yn.warn(`Date parsing error for "${e}":`,t),new Date}}(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}}function nc(e){if(!On(e))throw new Error("Address must be a non-empty string");try{Ts(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function sc(e){try{Cn(e,"id")}catch(e){if(e instanceof Rt)throw new Error("Invite ID must be a positive integer");throw e}}class rc extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}validateInviteCodeFormat(e){if(!On(e))throw Vt("inviteCode","Invite code");!function(e){if(!On(e))throw new Error("Invite code must be a non-empty string");In(e,cs,"code")}(e)}validateWalletAddressFormat(e){if(!On(e))throw Vt("address","Address");nc(e)}async createInvite(e={}){tc(e),this.validateOptionalString(e.description,"description","Description",ss.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Te,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(s)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!Zo(e.status))throw sn("status",e.status,Object.values(Jo),"status");Un(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Jo);const t=Se,n={...this.buildPaginationParams(e,es)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.invites,pageInfo:r.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(be,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){sc(e);const t=this.buildEndpoint(we,{id:String(e)});an(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ke,n={inviteCode:e},s=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(s)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!ec(e.status))throw sn("status",e.status,Object.values(Yo),"status");Un(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Yo);const t=Ne,n={...this.buildPaginationParams(e,es)};void 0!==e.status&&(n.status=e.status);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.overseers,pageInfo:r.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new Rt("Options are required");if(!On(e.userAddress))throw new Rt("userAddress is required and must be a non-empty string");try{Ts(e.userAddress,"userAddress")}catch{throw new Rt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Rt("description must be a string");if(e.description.length>255)throw new Rt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",ss.DESCRIPTION.MAX_LENGTH);const t=_e,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const s=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(s)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Ie,{address:e});an(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Ce,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=De,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Re,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Oe,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=Me,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=Ue,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=Le,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async listOverseerUsers(e){const t=e??{};Object.keys(t).length>0&&function(e){if(null==e||"object"!=typeof e)throw new Rt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Rt("Search must be a string");if(0===e.search.length)throw new Rt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Rt("Sort field must be a string");if(0===e.sortBy.length)throw new Rt("Sort field cannot be empty string")}if(void 0!==e.sortOrder){const t="string"==typeof e.sortOrder?e.sortOrder.toLowerCase():"";if("asc"!==t&&"desc"!==t)throw new Rt('Sort order must be "asc" or "desc"')}}(t);const n=Fe,s=this.buildPaginationParams(t,es);void 0!==t.search&&""!==t.search&&(s.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(s.sortBy=t.sortBy),void 0!==t.sortOrder&&(s.sortOrder=t.sortOrder);const r=await this.http.get(n,s,this.getDualAuthHeaders()),i=this.extractData(r);return{items:i.users,pageInfo:i.pageInfo}}async getOverseerUserSummary(e){if(!On(e))throw Vt("address","User address");nc(e);const t=this.buildEndpoint(xe,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Xo(e);const t=this.buildEndpoint(Pe,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!On(e))throw Vt("tokenName","Token name")}(e);const t=this.buildEndpoint(Be,{tokenName:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushAllCache(e){!function(e){if(!0!==e)throw new Rt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=$e,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Xo(e);const t=this.buildEndpoint(Ge,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Ke,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class ic extends Hn{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),an(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(j);return this.extractData(e)}async updatePlatformConfig(e){const t=function(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}(e);if(t.length>0)throw new Rt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(q,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(Q);return this.extractData(e)}}class ac extends Hn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Platform stats operation failed";throw new Error(t)}return e.data}async getStats(){this.logger.debug("Fetching platform stats");const e=await this.http.get(ot),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class oc extends ai{constructor(e,t,n,s){super(e,t,n,!1,s)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(Je,void 0,this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if("string"!=typeof e.content)throw new Rt("Content is required");return{success:!0,data:(await this.http.put(Ye,{content:e.content},this.getJwtHeaders())).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class cc extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async getChatStatus(e){if(null==e||""===e)throw Vt("tokenName","Token name");return this.validateTokenName(e,Qn),$r(async()=>{const t=this.buildEndpoint(Ze,{tokenName:e}),n=await this.http.get(t);return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw Vt("tokenName","Token name");return this.validateTokenName(e,Qn),$r(async()=>{const t=this.buildEndpoint(tt,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw Vt("tokenName","Token name");return this.validateTokenName(e,Qn),$r(async()=>{const t=this.buildEndpoint(et,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders());return this.buildChatStatusResponse(e,this.extractData(n))},`Failed to enable chat for token: ${e}`,this.logger)}buildChatStatusResponse(e,t){const n={enabled:t.enabled,tokenName:t.tokenName??mn(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),"global"!==t.reason&&"token"!==t.reason||(n.reason=t.reason),"number"==typeof t.slowModeSeconds&&(n.slowModeSeconds=t.slowModeSeconds),n}async setSlowMode(e,t){if(null==e||""===e)throw Vt("tokenName","Token name");if(this.validateTokenName(e,Qn),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return $r(async()=>{const n=this.buildEndpoint(nt,{tokenName:e}),s=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(s)},`Failed to set slow mode for token: ${e}`,this.logger)}}Ln({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),Ln({PREPARING:"preparing",READY:"ready",ERRORED:"errored"});const lc=Ln({YOUTUBE:"youtube",TWITCH:"twitch",FACEBOOK:"facebook",CUSTOM:"custom"});const dc={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};Ln(dc),Ln({OWNER:"OWNER",MODERATOR:"MODERATOR"});function uc(e,t="tokenName"){xn(e,t,Qn)}Ln({...dc,OVERSEER:"OVERSEER"});const hc=/^rtmps?:\/\/\S+$/u,gc=255;function mc(e){if(uc(e.tokenName),!On(e.language))throw Vt("language");if(t=e.language,!On(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Rt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Nt);var t}class fc extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async startStream(e){this.validateTokenName(e,Qn);const t=this.buildEndpoint(U,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,Qn);const t=this.buildEndpoint(L,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,F,Qn)}async enableStream(e){return this.toggleFeature(e,x,Qn)}async resetStreamKey(e){this.validateTokenName(e,Qn);const t=this.buildEndpoint(P,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,Qn);const t=this.buildEndpoint(J,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){uc(e.tokenName)}(e);const t=this.buildEndpoint(B,{tokenName:e.tokenName}),n=await this.http.get(t),s=this.extractData(n);if(!Array.isArray(s))throw Qt("Invalid recordings response: expected an array of recordings");return{recordings:s,tokenName:mn(e.tokenName)}}async getRecordingDownload(e,t){this.validateTokenName(e,Qn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint($,{tokenName:e,assetId:t}),s=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(s)}async deleteRecording(e,t){this.validateTokenName(e,Qn),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(G,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,Qn);const t=this.buildEndpoint(K,{tokenName:e}),n=await this.http.get(t,void 0,this.getJwtHeaders()),s=this.extractData(n);if(!Array.isArray(s))throw Qt("Invalid simulcast response: expected an array of targets");return{targets:s,tokenName:mn(e)}}async addSimulcastTarget(e){!function(e){if(uc(e.tokenName),!On(e.platform))throw Vt("platform");if(!lc(e.platform))throw new Rt("platform must be one of: 'youtube', 'twitch', 'facebook', 'custom'","platform",wt);if(!On(e.url))throw Vt("url");if(!hc.test(e.url))throw new Rt("url must be a valid RTMP or RTMPS URL","url",Nt);if(e.url.length>2048)throw new Rt(`url must not exceed ${String(2048)} characters`,"url",_t);if(!On(e.streamKey))throw Vt("streamKey");if(e.streamKey.length>gc)throw new Rt(`streamKey must not exceed ${String(gc)} characters`,"streamKey",_t);if(void 0!==e.passthrough){if("string"!=typeof e.passthrough)throw new Rt("passthrough must be a string","passthrough",kt);if(e.passthrough.length>gc)throw new Rt(`passthrough must not exceed ${String(gc)} characters`,"passthrough",_t)}}(e);const t=this.buildEndpoint(W,{tokenName:e.tokenName}),n=await this.http.post(t,{platform:e.platform,url:e.url,streamKey:e.streamKey,...void 0!==e.passthrough&&{passthrough:e.passthrough}},this.getJwtHeaders());return{target:this.extractData(n),tokenName:mn(e.tokenName)}}async removeSimulcastTarget(e,t){this.validateTokenName(e,Qn),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(H,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(j);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(q,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(V,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(uc(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||On(e.nextLiveStreamAt)))throw new Rt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",kt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Rt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Nt)}}}(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,Qn);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){mc(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){uc(e.tokenName)}(e);const t=this.buildEndpoint(z,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},s=await this.http.get(t,{},n);return this.extractData(s)}async getAvailableRoles(){const e=await this.http.get(Q);return this.extractData(e)}async getTokenAccess(e){!function(e){uc(e.tokenName)}(e);const t=await this.http.get(X,{tokenName:mn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const pc="subscribe_token",vc="unsubscribe_token",Ac="subscribe_comment",Ec="unsubscribe_comment",yc="subscribe_global_feed",Tc="unsubscribe_global_feed",Sc="subscribe_events_firehose",bc="unsubscribe_events_firehose",kc="authenticate",wc="send_stream_chat",Nc="SEND_STREAM_REACTION",_c="typing_start",Ic="typing_stop",Cc=e=>Dc(e.flagId);function Dc(e){return"string"==typeof e||"number"==typeof e?String(e):void 0}function Rc(e,t){const n=t.map(t=>Dc(e[t]));return n.every(e=>void 0!==e)?n.join("|"):void 0}const Oc={STREAM_STATUS:{},RECORDING_STATUS:{},RECORDINGS_COUNT_UPDATED:{},SIMULCAST_STATUS:{},DOWNLOAD_READY:{},STREAM_COUNTDOWN_UPDATED:{},STREAM_LANGUAGE_UPDATED:{},VIEWER_COUNT:{},STREAM_CONTROL_STATUS_CHANGED:{},STREAM_GLOBAL_STATUS:{token:"none"},ENGAGEMENT_STATS_UPDATED:{},STREAM_CHAT_MESSAGE:{},STREAM_CHAT_SENT:{},STREAM_CHAT_UPDATED:{},STREAM_CHAT_DELETED:{},STREAM_CHAT_PINNED:{},STREAM_CHAT_UNPINNED:{},CHAT_STATUS_CHANGED:{},SLOW_MODE_CHANGED:{},STREAM_CHAT_GLOBAL_STATUS:{token:"none"},USER_TYPING:{},stream_chat_error:{},STREAM_REACTION:{},stream_reaction_error:{},CONTENT_REACTION_ADDED:{},CONTENT_REACTION_REMOVED:{},COMMENT_CREATED:{},COMMENT_UPDATED:{},COMMENT_DELETED:{},TRADE_EXECUTED:{},TRADE_UPDATE_NOTIFY:{token:"none"},BALANCE_UPDATED:{},STATS_UPDATED:{},USER_BANNED:{},USER_UNBANNED:{},BAN_ENFORCEMENT:{},TOKEN_BANNED:{},TOKEN_UNBANNED:{},CONTENT_FLAGGED:{duplicateKey:e=>Dc(e.id)},FLAG_RESOLVED:{duplicateKey:e=>Rc(e,["id","status","reviewedAt"])},AI_MODERATION_COMPLETE:{duplicateKey:Cc},AI_MODERATION_FAILED:{duplicateKey:Cc},MODERATOR_INVITE_CREATED:{},MODERATOR_ADDED:{},MODERATOR_REMOVED:{},MODERATOR_ROLE_UPDATED:{},OVERSEER_ADDED:{token:"none",duplicateKey:e=>Rc(e,["userAddress","addedAt"])},OVERSEER_REMOVED:{token:"none",duplicateKey:e=>Rc(e,["userAddress","removedAt"])},POOL_CREATED:{duplicateKey:e=>Rc(e,["tokenName","createdAt"])},POOL_METADATA_UPDATED:{},POOL_SOCIAL_LINKS_UPDATED:{},POOL_BADGE_ASSIGNED:{},TOKEN_CONFIG_UPDATED:{},HOLDER_COUNT_UPDATED:{},USER_PROFILE_UPDATED:{token:"none"},API_KEY_CREATED:{token:"none"},API_KEY_UPDATED:{token:"none"},API_KEY_REVOKED:{token:"none"},SITE_CONFIG_CHANGED:{token:"none"},COMMENTS_GLOBAL_STATUS:{token:"none"},WEBHOOKS_GLOBAL_STATUS:{token:"none"},AI_MODERATION_GLOBAL_STATUS:{token:"none"},EVENT:{token:"none"},connection:{token:"none"},authenticated:{token:"none"},stream_chat_auth_error:{token:"none"},exception:{token:"none"},token_subscribed:{},token_unsubscribed:{token:"room"},room_subscribed:{token:"none"},room_left:{token:"none"},global_feed_subscribed:{token:"none"},global_feed_unsubscribed:{token:"none"},events_firehose_subscribed:{token:"none"},events_firehose_unsubscribed:{token:"none"}};function Mc(e){return Oc[e]}const Uc=Object.keys(Oc);const Lc="token:",Fc="comment:",xc="global:feed",Pc="global:events_firehose";function Bc(e){if(e.startsWith(Lc)){const t={tokenName:e.slice(Lc.length)};return{join:{event:pc,payload:t},leave:{event:vc,payload:t}}}if(e.startsWith(Fc)){const t={tokenName:e.slice(8)};return{join:{event:Ac,payload:t},leave:{event:Ec,payload:t}}}return e===Pc?{join:{event:Sc},leave:{event:bc}}:{join:{event:yc},leave:{event:Tc}}}const $c=new Set(["token_subscribed","room_subscribed","global_feed_subscribed","events_firehose_subscribed"]);const Gc={STREAM_CHAT_GLOBAL_STATUS:"chatEnabled",STREAM_GLOBAL_STATUS:"streamingEnabled",COMMENTS_GLOBAL_STATUS:"commentsEnabled",WEBHOOKS_GLOBAL_STATUS:"webhooksEnabled",AI_MODERATION_GLOBAL_STATUS:"aiModerationEnabled"},Kc=["STREAM_STATUS","TRADE_EXECUTED","HOLDER_COUNT_UPDATED","POOL_BADGE_ASSIGNED","VIEWER_COUNT","TOKEN_CONFIG_UPDATED","STATS_UPDATED","POOL_CREATED"],Wc=new Set(["STREAM_STATUS","RECORDING_STATUS","RECORDINGS_COUNT_UPDATED","SIMULCAST_STATUS","DOWNLOAD_READY","STREAM_COUNTDOWN_UPDATED","STREAM_LANGUAGE_UPDATED","VIEWER_COUNT","STREAM_CONTROL_STATUS_CHANGED","ENGAGEMENT_STATS_UPDATED","STREAM_CHAT_MESSAGE","STREAM_CHAT_SENT","STREAM_CHAT_UPDATED","STREAM_CHAT_DELETED","STREAM_CHAT_PINNED","STREAM_CHAT_UNPINNED","CHAT_STATUS_CHANGED","SLOW_MODE_CHANGED","USER_TYPING","stream_chat_error","STREAM_REACTION","stream_reaction_error","CONTENT_REACTION_ADDED","CONTENT_REACTION_REMOVED","TRADE_EXECUTED","BALANCE_UPDATED","STATS_UPDATED","TOKEN_BANNED","TOKEN_UNBANNED","CONTENT_FLAGGED","FLAG_RESOLVED","MODERATOR_INVITE_CREATED","MODERATOR_ADDED","MODERATOR_REMOVED","MODERATOR_ROLE_UPDATED","POOL_METADATA_UPDATED","POOL_SOCIAL_LINKS_UPDATED","POOL_BADGE_ASSIGNED","TOKEN_CONFIG_UPDATED","HOLDER_COUNT_UPDATED","token_subscribed","token_unsubscribed"]),Hc=new Set(["COMMENT_CREATED","COMMENT_UPDATED","COMMENT_DELETED"]);const jc={onStreamStatus:"STREAM_STATUS",onStreamSubscribed:"token_subscribed",onStreamUnsubscribed:"token_unsubscribed",onViewerCount:"VIEWER_COUNT",onStreamGlobalStatus:"STREAM_GLOBAL_STATUS",onCountdownUpdated:"STREAM_COUNTDOWN_UPDATED",onLanguageUpdated:"STREAM_LANGUAGE_UPDATED",onRecordingStatus:"RECORDING_STATUS",onRecordingsCountUpdated:"RECORDINGS_COUNT_UPDATED",onSimulcastStatus:"SIMULCAST_STATUS",onDownloadReady:"DOWNLOAD_READY",onStreamControlStatusChanged:"STREAM_CONTROL_STATUS_CHANGED",onChatMessage:"STREAM_CHAT_MESSAGE",onChatSent:"STREAM_CHAT_SENT",onChatUpdated:"STREAM_CHAT_UPDATED",onChatDeleted:"STREAM_CHAT_DELETED",onChatError:"stream_chat_error",onChatStatus:"CHAT_STATUS_CHANGED",onChatSlowMode:"SLOW_MODE_CHANGED",onChatGlobalStatus:"STREAM_CHAT_GLOBAL_STATUS",onChatAuthenticated:"authenticated",onChatAuthError:"stream_chat_auth_error",onChatPinned:"STREAM_CHAT_PINNED",onChatUnpinned:"STREAM_CHAT_UNPINNED",onTypingIndicator:"USER_TYPING",onReaction:"STREAM_REACTION",onReactionError:"stream_reaction_error",onContentReactionAdded:"CONTENT_REACTION_ADDED",onContentReactionRemoved:"CONTENT_REACTION_REMOVED",onCommentCreated:"COMMENT_CREATED",onCommentUpdated:"COMMENT_UPDATED",onCommentDeleted:"COMMENT_DELETED",onUserBanned:"USER_BANNED",onUserUnbanned:"USER_UNBANNED",onBanEnforcement:"BAN_ENFORCEMENT",onTokenBanned:"TOKEN_BANNED",onTokenUnbanned:"TOKEN_UNBANNED",onContentFlagged:"CONTENT_FLAGGED",onFlagResolved:"FLAG_RESOLVED",onAIModerationComplete:"AI_MODERATION_COMPLETE",onAIModerationFailed:"AI_MODERATION_FAILED",onModeratorInviteCreated:"MODERATOR_INVITE_CREATED",onModeratorAdded:"MODERATOR_ADDED",onModeratorRemoved:"MODERATOR_REMOVED",onModeratorRoleUpdated:"MODERATOR_ROLE_UPDATED",onOverseerAdded:"OVERSEER_ADDED",onOverseerRemoved:"OVERSEER_REMOVED",onTradeExecuted:"TRADE_EXECUTED",onTradeUpdateNotify:"TRADE_UPDATE_NOTIFY",onBalanceUpdated:"BALANCE_UPDATED",onStatsUpdated:"STATS_UPDATED",onEngagementStatsUpdated:"ENGAGEMENT_STATS_UPDATED",onPoolCreated:"POOL_CREATED",onPoolMetadataUpdated:"POOL_METADATA_UPDATED",onPoolSocialLinksUpdated:"POOL_SOCIAL_LINKS_UPDATED",onPoolBadgeAssigned:"POOL_BADGE_ASSIGNED",onHolderCountUpdated:"HOLDER_COUNT_UPDATED",onTokenConfigUpdated:"TOKEN_CONFIG_UPDATED",onUserProfileUpdated:"USER_PROFILE_UPDATED",onApiKeyCreated:"API_KEY_CREATED",onApiKeyUpdated:"API_KEY_UPDATED",onApiKeyRevoked:"API_KEY_REVOKED",onException:"exception"},qc={onGlobalFeedSubscribed:"global_feed_subscribed",onGlobalFeedUnsubscribed:"global_feed_unsubscribed",onStreamStatus:"STREAM_STATUS",onTradeExecuted:"TRADE_EXECUTED",onHolderCountUpdated:"HOLDER_COUNT_UPDATED",onPoolBadgeAssigned:"POOL_BADGE_ASSIGNED",onViewerCount:"VIEWER_COUNT",onTokenConfigUpdated:"TOKEN_CONFIG_UPDATED",onStatsUpdated:"STATS_UPDATED",onPoolCreated:"POOL_CREATED",onSiteConfigChanged:"SITE_CONFIG_CHANGED",onStreamGlobalStatus:"STREAM_GLOBAL_STATUS",onStreamChatGlobalStatus:"STREAM_CHAT_GLOBAL_STATUS",onCommentsGlobalStatus:"COMMENTS_GLOBAL_STATUS",onWebhooksGlobalStatus:"WEBHOOKS_GLOBAL_STATUS",onAIModerationGlobalStatus:"AI_MODERATION_GLOBAL_STATUS"},Vc=()=>{};function zc(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Qc(e,t){return t}function Xc(e){return`${Lc}${e}`}function Jc(e){return`${Fc}${e}`}function Yc(e){const t=mn(e);if(""===t)throw Vt("tokenName","Token name");return t}class Zc extends jn{constructor(e,t=!1){if(super(t),this.socket=null,this.disposed=!1,this.epoch=0,this.connectionGeneration=0,this.hasConnected=!1,this.connectAttempt=null,this.reconnectExhausted=!1,this.managerCleanups=[],this.connectionStateListeners=new Set,this.reconnectListeners=new Set,this.subscribers=new Map,this.roomRefs=new Map,this.roomStates=new Map,this.roomWaiters=new Map,this.explicitHolds=new Map,this.recentOccurrences=new Map,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authSequence=0,this.inFlight=null,this.lastEmitted=null,this.pendingAuthenticate=null,""===e.url)throw new Ft("Stream WebSocket URL is required. Set streamWebSocketUrl in SDK config.");this.config={url:e.url,reconnectAttempts:e.reconnectAttempts??5,reconnectDelay:e.reconnectDelay??2e3,reconnectDelayMax:e.reconnectDelayMax,subscriptionTimeout:e.subscriptionTimeout??1e4,tokenProvider:e.tokenProvider,autoConnect:e.autoConnect??!0},this.isSocketIOAvailable="function"==typeof N}register(e,t,n={}){if(this.disposed)return Vc;const s={name:e,deliver:t,token:n.token,filter:n.filter,room:n.room,active:!0};let r=this.subscribers.get(e);return void 0===r&&(r=new Set,this.subscribers.set(e,r)),r.add(s),void 0!==n.room&&this.acquireRoom(n.room),this.openIfNeeded(),()=>{this.release(s)}}release(e){if(!e.active)return;e.active=!1;const t=this.subscribers.get(e.name);t?.delete(e),0===t?.size&&this.subscribers.delete(e.name),void 0!==e.room&&this.releaseRoom(e.room)}hold(e){if(this.disposed)return Vc;let t=!0;return this.acquireRoom(e),this.openIfNeeded(),()=>{t&&(t=!1,this.releaseRoom(e))}}openIfNeeded(){this.config.autoConnect&&!this.disposed&&(null===this.socket||this.reconnectExhausted)&&this.connect().catch(e=>{this.logger.warn(`Stream WebSocket connect failed: ${Bt(e)}`)})}acquireRoom(e){this.roomRefs.set(e,(this.roomRefs.get(e)??0)+1),this.syncRoom(e)}releaseRoom(e){const t=(this.roomRefs.get(e)??1)-1;t<=0?this.roomRefs.delete(e):this.roomRefs.set(e,t),this.syncRoom(e)}syncRoom(e){const t=this.liveSocket();if(null===t)return;const n=(this.roomRefs.get(e)??0)>0,s=this.roomStates.get(e);if(n&&void 0===s){if(function(e){return e===Pc}(e)&&!this.authenticated)return;this.joinRoom(t,e)}else n||"joined"!==s?.phase||(t.emit(Bc(e).leave.event,Bc(e).leave.payload),this.roomStates.delete(e))}syncAllRooms(){for(const e of new Set([...this.roomRefs.keys(),...this.roomStates.keys()]))this.syncRoom(e)}joinRoom(e,t){const n=setTimeout(()=>{const e=this.roomStates.get(t);"joining"===e?.phase&&(this.roomStates.delete(t),this.rejectWaiters(t,new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`)))},this.config.subscriptionTimeout);this.roomStates.set(t,{phase:"joining",timer:n});const s=Bc(t).join;e.emit(s.event,s.payload)}onRoomAcknowledged(e){const t=this.roomStates.get(e);void 0!==t?.timer&&clearTimeout(t.timer),this.roomStates.set(e,{phase:"joined",timer:void 0});const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);const t=e.startsWith(Lc)?e.slice(Lc.length):e;for(const s of n)clearTimeout(s.timer),s.resolve({room:e,tokenName:t})}this.syncRoom(e)}rejectWaiters(e,t){const n=this.roomWaiters.get(e);if(void 0!==n){this.roomWaiters.delete(e);for(const e of n)clearTimeout(e.timer),e.reject(t)}}clearRoomStates(){for(const e of this.roomStates.values())void 0!==e.timer&&clearTimeout(e.timer);this.roomStates.clear()}onServerEvent(e,t){try{this.applyEffects(e,t)}catch(t){this.logger.error(`Error handling ${e}:`,t)}if((!zc(t)||!this.isDuplicate(e,t))&&(this.deliver(e,t,zc(t)?function(e,t){const n=Mc(e).token??"payload";if("none"===n)return;if("room"===n){const e=t.room;return"string"==typeof e&&e.startsWith(Lc)?e.slice(Lc.length):void 0}const s=t.tokenName;return"string"==typeof s&&""!==s?s:void 0}(e,t):void 0),zc(t)))for(const n of function(e,t){if("TOKEN_CONFIG_UPDATED"!==e)return[];const n=t.tokenName;if("string"!=typeof n)return[];const s=[];if("nextLiveStreamAt"in t){const e=t.nextLiveStreamAt;s.push({name:"STREAM_COUNTDOWN_UPDATED",payload:{tokenName:n,nextLiveStreamAt:"string"==typeof e?e:null}})}const r=t.streamLanguage;return"string"==typeof r&&s.push({name:"STREAM_LANGUAGE_UPDATED",payload:{tokenName:n,language:r}}),s}(e,t))this.deliver(n.name,n.payload,n.payload.tokenName)}isDuplicate(e,t){const n=Mc(e).duplicateKey?.(t);if(void 0===n)return!1;const s=Date.now(),r=`${e}:${n}`,i=this.recentOccurrences.get(r);if(void 0!==i&&s-i<5e3)return!0;if(this.recentOccurrences.set(r,s),this.recentOccurrences.size>256)for(const[e,t]of this.recentOccurrences)s-t>=5e3&&this.recentOccurrences.delete(e);return!1}deliver(e,t,n){const s=this.subscribers.get(e);if(void 0===s)return;const r=void 0===n?void 0:mn(n);for(const n of[...s])n.active&&(void 0!==n.token&&n.token!==r||(void 0===n.filter||this.passes(n,t))&&this.invoke(e,n.deliver,t))}passes(e,t){try{return e.filter?.(t)??!0}catch(t){return this.logger.error(`Error in a ${e.name} filter:`,t),!1}}invoke(e,t,n){try{const s=t(n);s instanceof Promise&&s.catch(t=>{this.logger.error(`Error in a ${e} subscriber:`,t)})}catch(t){this.logger.error(`Error in a ${e} subscriber:`,t)}}applyEffects(e,t){if("authenticated"===e)null!==this.inFlight?this.inFlight.settle(!0):this.adoptLateAuthentication();else if("stream_chat_auth_error"===e)this.authenticated=!1,this.inFlight?.settle(!1);else if("exception"===e)this.inFlight?.settle(!1);else if(function(e){return $c.has(e)}(e))zc(t)&&"string"==typeof t.room&&this.onRoomAcknowledged(t.room);else{const n=Gc[e];void 0!==n&&(this.siteConfig={...this.siteConfig,[n]:el(t)})}}liveSocket(){return null!==this.socket&&this.socket.connected?this.socket:null}connect(){if(this.disposed)return Promise.reject(new Ft("The stream WebSocket service has been disposed."));if(!this.isSocketIOAvailable)return Promise.reject(new Ft('Socket.IO not available. Install "socket.io-client" package.'));const e=this.socket??this.createSocket();if(e.connected)return Promise.resolve();if(null===this.connectAttempt){let e=()=>{},t=()=>{};const n=new Promise((n,s)=>{e=n,t=s});this.connectAttempt={promise:n,resolve:e,reject:t}}return e.connect(),this.connectAttempt.promise}createSocket(){this.logger.debug(`🔌 Connecting to Stream WebSocket: ${this.config.url}`);const e=N(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,...void 0!==this.config.reconnectDelayMax&&{reconnectionDelayMax:this.config.reconnectDelayMax}});return this.socket=e,this.attachListeners(e),e}attachListeners(e){e.on("connect",()=>{this.onSocketConnect()}),e.on("disconnect",e=>{this.onSocketDisconnect(e)}),e.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),this.settleConnectWaiters(e)}),e.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)});for(const t of Uc)e.on(t,e=>{this.onServerEvent(t,e)});const t=e=>{this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${String(e)}`)},n=()=>{this.reconnectExhausted=!0,this.logger.error("❌ Stream WebSocket max reconnection attempts reached")};e.io.on("reconnect_attempt",t),e.io.on("reconnect_failed",n),this.managerCleanups.push(()=>e.io.off("reconnect_attempt",t),()=>e.io.off("reconnect_failed",n))}onSocketConnect(){this.connectionGeneration+=1;const e=this.connectionGeneration,t=this.hasConnected;this.hasConnected=!0,this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectExhausted=!1,this.clearRoomStates(),this.authenticated=!1,this.notifyConnectionState(!0),this.settleConnectWaiters(void 0),this.wantsAuthentication?this.restoreAfterReconnect(e):(this.syncAllRooms(),t&&this.notifyReconnect())}async restoreAfterReconnect(e){try{await this.authenticate()}catch(e){this.logger.warn(`Re-authentication after reconnect failed: ${Bt(e)}`)}e!==this.connectionGeneration||this.disposed||(this.syncAllRooms(),this.notifyReconnect())}onSocketDisconnect(e){this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.authenticated=!1,this.inFlight?.settle(!1),this.clearRoomStates(),this.notifyConnectionState(!1),"io server disconnect"!==e||null===this.socket||this.disposed||this.socket.connect()}settleConnectWaiters(e){const t=this.connectAttempt;this.connectAttempt=null,null!==t&&(void 0===e?t.resolve():t.reject(e))}notifyConnectionState(e){for(const t of[...this.connectionStateListeners])this.invoke("connection state",t,e)}notifyReconnect(){for(const e of[...this.reconnectListeners])this.invoke("reconnect",e,void 0)}onConnectionStateChange(e){return this.disposed?Vc:(this.connectionStateListeners.add(e),()=>{this.connectionStateListeners.delete(e)})}onReconnect(e){return this.disposed?Vc:(this.reconnectListeners.add(e),()=>{this.reconnectListeners.delete(e)})}async resolveToken(){const e=this.config.tokenProvider;if(void 0===e)return this.lastExplicitToken;try{const t=await e();return null!==t&&""!==t?t:null}catch(e){return this.logger.warn(`The token provider failed: ${Bt(e)}`),null}}authenticate(e){if(""===e)return Promise.reject(Vt("token","Authentication token"));const t=this.pendingAuthenticate;if(null!==t&&t.token===e&&t.generation===this.connectionGeneration)return t.promise;this.authSequence+=1;const n=this.authSequence,s=this.runAuthenticate(e,n).finally(()=>{this.pendingAuthenticate?.promise===s&&(this.pendingAuthenticate=null)});return this.pendingAuthenticate={token:e,generation:this.connectionGeneration,promise:s},s}async runAuthenticate(e,t){if(this.disposed)return!1;const n=e??await this.resolveToken();if(t!==this.authSequence||null===n)return!1;void 0!==e&&(this.lastExplicitToken=e);try{await this.connect()}catch(e){return this.logger.warn(`Cannot authenticate, the connection failed: ${Bt(e)}`),!1}for(;null!==this.inFlight;)if(await this.inFlight.settled,t!==this.authSequence)return!1;const s=this.liveSocket();if(t!==this.authSequence||null===s)return!1;if(this.authenticated&&this.authenticatedToken===n&&this.authenticatedGeneration===this.connectionGeneration)return!0;const r=this.beginAuthentication(t,n);this.lastEmitted={seq:t,token:n,generation:this.connectionGeneration},this.logger.debug("📡 Authenticating with stream server"),s.emit(kc,{token:n});return await r.result&&t===this.authSequence}beginAuthentication(e,t){let n=()=>{};const s=new Promise(e=>{n=e}),r={seq:e,token:t,generation:this.connectionGeneration,result:s,settled:s.then(()=>{}),timer:void 0,settle:e=>{this.finishAuthentication(r,e,n)}};return r.timer=setTimeout(()=>{this.logger.warn("Stream WebSocket authentication timed out"),r.settle(!1)},this.config.subscriptionTimeout),this.inFlight=r,r}finishAuthentication(e,t,n){if(this.inFlight!==e)return;void 0!==e.timer&&clearTimeout(e.timer),this.inFlight=null;const s=e.seq===this.authSequence&&e.generation===this.connectionGeneration;t&&s&&this.markAuthenticated(e.token,e.generation),n(t&&s)}markAuthenticated(e,t){this.authenticated=!0,this.authenticatedToken=e,this.authenticatedGeneration=t,this.wantsAuthentication=!0,this.syncAllRooms()}adoptLateAuthentication(){const e=this.lastEmitted;null===e||this.authenticated||e.seq===this.authSequence&&e.generation===this.connectionGeneration&&this.markAuthenticated(e.token,e.generation)}deauthenticate(){this.authSequence+=1;const e=this.authenticated||null!==this.inFlight;this.inFlight?.settle(!1),this.pendingAuthenticate=null,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,e&&null!==this.socket&&!this.disposed&&(this.socket.disconnect(),this.socket.connect())}isAuthenticatedForChat(){return this.authenticated}isConnected(){return this.socket?.connected??!1}requireReady(){const e=this.liveSocket();if(null===e)throw new Rt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.authenticated)throw new Rt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");return e}sendChatMessage(e,t){if(""===e)throw Vt("tokenName","Token name");if(""===t)throw Vt("content","Message content");const n=this.requireReady(),s=mn(e);this.logger.debug(`📡 Sending chat message to ${s}: ${t.slice(0,30)}...`),n.emit(wc,{tokenName:s,content:t})}sendReaction(e,t,n=0){if(""===e)throw Vt("tokenName","Token name");if(""===t)throw Vt("emoji");const s=this.requireReady(),r=mn(e);this.logger.debug(`📡 Sending reaction to ${r}: ${t}`),s.emit(Nc,{tokenName:r,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,_c)}sendTypingStop(e){this.sendTypingEvent(e,Ic)}sendTypingEvent(e,t){if(""===e)throw Vt("tokenName","Token name");this.requireReady().emit(t,{tokenName:mn(e)})}subscribeToken(e,t,n){const s=Yc(t);return this.register(e,e=>n(Qc(0,e)),{token:s,room:Xc(s)})}joinTokenRoom(e){return this.hold(Xc(Yc(e)))}subscribeComment(e,t,n){const s=Yc(t);return this.register(e,e=>n(Qc(0,e)),{token:s,room:Jc(s)})}subscribeFeed(e,t){return this.register(e,e=>t(Qc(0,e)),{room:xc})}subscribeEvent(e,t){return this.register(e,e=>t(Qc(0,e)))}subscribeEventsFirehose(e,t){const n=function(e){if(void 0===e)return;const t=e.eventTypes?.map(e=>e.toLowerCase()),n=void 0===e.tokenName?void 0:mn(e.tokenName),s=e.userAddress?.toLowerCase();return void 0!==t||void 0!==n||void 0!==s?e=>{if(!zc(e))return!1;const r=e.eventType;if(void 0!==t&&("string"!=typeof r||!t.includes(r.toLowerCase())))return!1;const i=e.tokenName;if(void 0!==n&&("string"!=typeof i||mn(i)!==n))return!1;const a=e.userAddress;return void 0===s||"string"==typeof a&&a.toLowerCase()===s}:void 0}(t);return this.register("EVENT",t=>e(Qc(0,t)),{room:Pc,...void 0!==n&&{filter:n}})}subscribeFeedTokenEvents(e){const t=Kc.map(t=>this.register(t,n=>e(function(e,t){return{event:e,data:Qc(0,t)}}(t,n)),{room:xc}));return()=>{for(const e of t)e()}}subscribeToGlobalFeed(e={}){const t=this.registerCallbacks(e,qc,()=>({})),n=this.hold(xc);return()=>{t(),n()}}addCallbacks(e){return this.registerCallbacks(e,jc,()=>({}))}registerCallbacks(e,t,n){const s=[],r={...e};for(const[e,i]of Object.entries(t)){const t=r[e];"function"==typeof t&&s.push(this.register(i,e=>Reflect.apply(t,void 0,[e]),n(i)))}return()=>{for(const e of s)e()}}async subscribeToStream(e,t={}){const n=Yc(e),s=Xc(n),r=this.epoch;if(await this.connect(),r!==this.epoch||this.disposed)throw new Error("WebSocket disconnected");const i=this.registerCallbacks(t,jc,e=>{return t=e,Wc.has(t)?{token:n}:function(e){return Hc.has(e)}(e)?{token:n,room:Jc(n)}:{};var t}),a=this.hold(s),o={release:()=>{i(),a()}},c=this.explicitHolds.get(n)??[];c.push(o),this.explicitHolds.set(n,c);try{return await this.waitForRoom(s,n)}catch(e){throw this.dropExplicitHold(n,o),e}}waitForRoom(e,t){return"joined"===this.roomStates.get(e)?.phase?Promise.resolve({room:e,tokenName:t}):new Promise((n,s)=>{const r={resolve:n,reject:s,timer:setTimeout(()=>{this.roomWaiters.get(e)?.delete(r),s(new Error(`Subscription to ${t} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout)},i=this.roomWaiters.get(e)??new Set;i.add(r),this.roomWaiters.set(e,i)})}dropExplicitHold(e,t){t.release();const n=(this.explicitHolds.get(e)??[]).filter(e=>e!==t);0===n.length?this.explicitHolds.delete(e):this.explicitHolds.set(e,n)}unsubscribeFromStream(e){const t=mn(e),n=this.explicitHolds.get(t);if(void 0!==n){this.explicitHolds.delete(t);for(const e of n)e.release()}else this.logger.debug(`📡 Not subscribed to ${t} through subscribeToStream, skipping unsubscribe`)}subscribeStreamStatus(e,t){return this.subscribeToken("STREAM_STATUS",e,t)}subscribeViewerCount(e,t){return this.subscribeToken("VIEWER_COUNT",e,t)}subscribeRecordingStatus(e,t){return this.subscribeToken("RECORDING_STATUS",e,t)}subscribeRecordingsCountUpdated(e,t){return this.subscribeToken("RECORDINGS_COUNT_UPDATED",e,t)}subscribeSimulcastStatus(e,t){return this.subscribeToken("SIMULCAST_STATUS",e,t)}subscribeDownloadReady(e,t){return this.subscribeToken("DOWNLOAD_READY",e,t)}subscribeCountdownUpdated(e,t){return this.subscribeToken("STREAM_COUNTDOWN_UPDATED",e,t)}subscribeLanguageUpdated(e,t){return this.subscribeToken("STREAM_LANGUAGE_UPDATED",e,t)}subscribeStreamControlStatusChanged(e,t){return this.subscribeToken("STREAM_CONTROL_STATUS_CHANGED",e,t)}subscribeEngagementStatsUpdated(e,t){return this.subscribeToken("ENGAGEMENT_STATS_UPDATED",e,t)}subscribeChatMessages(e,t){return this.subscribeToken("STREAM_CHAT_MESSAGE",e,t)}subscribeChatSent(e,t){return this.subscribeToken("STREAM_CHAT_SENT",e,t)}subscribeChatUpdated(e,t){return this.subscribeToken("STREAM_CHAT_UPDATED",e,t)}subscribeChatDeleted(e,t){return this.subscribeToken("STREAM_CHAT_DELETED",e,t)}subscribeChatPinned(e,t){return this.subscribeToken("STREAM_CHAT_PINNED",e,t)}subscribeChatUnpinned(e,t){return this.subscribeToken("STREAM_CHAT_UNPINNED",e,t)}subscribeChatStatus(e,t){return this.subscribeToken("CHAT_STATUS_CHANGED",e,t)}subscribeChatSlowMode(e,t){return this.subscribeToken("SLOW_MODE_CHANGED",e,t)}subscribeTypingIndicator(e,t){return this.subscribeToken("USER_TYPING",e,t)}subscribeReactions(e,t){return this.subscribeToken("STREAM_REACTION",e,t)}subscribeContentReactionAdded(e,t){return this.subscribeToken("CONTENT_REACTION_ADDED",e,t)}subscribeContentReactionRemoved(e,t){return this.subscribeToken("CONTENT_REACTION_REMOVED",e,t)}subscribeTradeExecuted(e,t){return this.subscribeToken("TRADE_EXECUTED",e,t)}subscribeBalanceUpdated(e,t){return this.subscribeToken("BALANCE_UPDATED",e,t)}subscribeTokenBanned(e,t){return this.subscribeToken("TOKEN_BANNED",e,t)}subscribeTokenUnbanned(e,t){return this.subscribeToken("TOKEN_UNBANNED",e,t)}subscribeModeratorInviteCreated(e,t){return this.subscribeToken("MODERATOR_INVITE_CREATED",e,t)}subscribeModeratorAdded(e,t){return this.subscribeToken("MODERATOR_ADDED",e,t)}subscribeModeratorRemoved(e,t){return this.subscribeToken("MODERATOR_REMOVED",e,t)}subscribeModeratorRoleUpdated(e,t){return this.subscribeToken("MODERATOR_ROLE_UPDATED",e,t)}subscribePoolMetadataUpdated(e,t){return this.subscribeToken("POOL_METADATA_UPDATED",e,t)}subscribePoolSocialLinksUpdated(e,t){return this.subscribeToken("POOL_SOCIAL_LINKS_UPDATED",e,t)}subscribePoolBadgeAssigned(e,t){return this.subscribeToken("POOL_BADGE_ASSIGNED",e,t)}subscribeHolderCountUpdated(e,t){return this.subscribeToken("HOLDER_COUNT_UPDATED",e,t)}subscribeTokenConfigUpdated(e,t){return this.subscribeToken("TOKEN_CONFIG_UPDATED",e,t)}subscribeCommentCreated(e,t){return this.subscribeComment("COMMENT_CREATED",e,t)}subscribeCommentUpdated(e,t){return this.subscribeComment("COMMENT_UPDATED",e,t)}subscribeCommentDeleted(e,t){return this.subscribeComment("COMMENT_DELETED",e,t)}subscribeStatsUpdated(e){return this.subscribeFeed("STATS_UPDATED",e)}subscribePoolCreated(e){return this.subscribeFeed("POOL_CREATED",e)}subscribeStreamGlobalStatus(e){return this.subscribeFeed("STREAM_GLOBAL_STATUS",e)}subscribeChatGlobalStatus(e){return this.subscribeFeed("STREAM_CHAT_GLOBAL_STATUS",e)}subscribeCommentsGlobalStatus(e){return this.subscribeFeed("COMMENTS_GLOBAL_STATUS",e)}subscribeWebhooksGlobalStatus(e){return this.subscribeFeed("WEBHOOKS_GLOBAL_STATUS",e)}subscribeAIModerationGlobalStatus(e){return this.subscribeFeed("AI_MODERATION_GLOBAL_STATUS",e)}subscribeSiteConfigChanged(e){return this.subscribeFeed("SITE_CONFIG_CHANGED",e)}getSiteConfigState(){return{...this.siteConfig}}subscribeOverseerAdded(e){return this.subscribeEvent("OVERSEER_ADDED",e)}subscribeOverseerRemoved(e){return this.subscribeEvent("OVERSEER_REMOVED",e)}subscribeUserProfileUpdated(e){return this.subscribeEvent("USER_PROFILE_UPDATED",e)}subscribeApiKeyCreated(e){return this.subscribeEvent("API_KEY_CREATED",e)}subscribeApiKeyUpdated(e){return this.subscribeEvent("API_KEY_UPDATED",e)}subscribeApiKeyRevoked(e){return this.subscribeEvent("API_KEY_REVOKED",e)}subscribeGlobalTokenBanned(e){return this.subscribeEvent("TOKEN_BANNED",e)}subscribeGlobalTokenUnbanned(e){return this.subscribeEvent("TOKEN_UNBANNED",e)}subscribeGlobalModeratorAdded(e){return this.subscribeEvent("MODERATOR_ADDED",e)}subscribeGlobalModeratorRemoved(e){return this.subscribeEvent("MODERATOR_REMOVED",e)}subscribeGlobalModeratorRoleUpdated(e){return this.subscribeEvent("MODERATOR_ROLE_UPDATED",e)}subscribeGlobalModeratorInviteCreated(e){return this.subscribeEvent("MODERATOR_INVITE_CREATED",e)}subscribeContentFlagged(e){return this.subscribeEvent("CONTENT_FLAGGED",e)}subscribeFlagResolved(e){return this.subscribeEvent("FLAG_RESOLVED",e)}subscribeAIModerationComplete(e){return this.subscribeEvent("AI_MODERATION_COMPLETE",e)}subscribeAIModerationFailed(e){return this.subscribeEvent("AI_MODERATION_FAILED",e)}subscribeUserBanned(e){return this.subscribeEvent("USER_BANNED",e)}subscribeUserUnbanned(e){return this.subscribeEvent("USER_UNBANNED",e)}subscribeBanEnforcement(e){return this.subscribeEvent("BAN_ENFORCEMENT",e)}subscribeTradeUpdateNotify(e){return this.subscribeEvent("TRADE_UPDATE_NOTIFY",e)}subscribeReactionErrors(e){return this.subscribeEvent("stream_reaction_error",e)}subscribeChatErrors(e){return this.subscribeEvent("stream_chat_error",e)}subscribeException(e){return this.subscribeEvent("exception",e)}getSubscribedTokens(){const e=[];for(const t of this.roomRefs.keys())t.startsWith(Lc)&&e.push(t.slice(Lc.length));return e}isSubscribedToGlobalFeed(){return(this.roomRefs.get(xc)??0)>0}getSocket(){return this.socket}disconnect(){this.epoch+=1,this.authSequence+=1,this.pendingAuthenticate=null,this.inFlight?.settle(!1);const e=new Error("WebSocket disconnected");this.settleConnectWaiters(e);for(const t of[...this.roomWaiters.keys()])this.rejectWaiters(t,e);this.clearRoomStates();for(const e of this.subscribers.values())for(const t of e)t.active=!1;this.subscribers.clear(),this.roomRefs.clear(),this.explicitHolds.clear(),this.recentOccurrences.clear(),this.connectionStateListeners.clear(),this.reconnectListeners.clear();const t=this.socket;if(this.socket=null,null!==t){this.logger.debug("🔌 Disconnecting from Stream WebSocket");for(const e of this.managerCleanups)e();t.removeAllListeners();try{t.disconnect()}catch(e){this.logger.error("Error disconnecting socket:",e)}}this.managerCleanups=[],this.authenticated=!1,this.authenticatedToken=null,this.authenticatedGeneration=-1,this.wantsAuthentication=!1,this.lastExplicitToken=null,this.lastEmitted=null,this.reconnectExhausted=!1,this.hasConnected=!1,this.connectionGeneration+=1,this.siteConfig={chatEnabled:void 0,streamingEnabled:void 0,commentsEnabled:void 0,webhooksEnabled:void 0,aiModerationEnabled:void 0},this.logger.debug("✅ Stream WebSocket disconnected and cleaned up")}dispose(){this.disposed=!0,this.disconnect()}}function el(e){if(!zc(e))return;const t=e.enabled;return"boolean"==typeof t?t:void 0}function tl(e){if(xn(e.tokenName,"tokenName",zn),!(null==(t=e.reason)||""===t||"string"==typeof t&&!Bn(t)&&t.length<=ss.BAN_REASON.MAX_LENGTH))throw new Rt(`reason must be at most ${ss.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class nl extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async banToken(e){tl(e);const t=We,n={tokenName:mn(e.tokenName)};if(void 0!==e.reason)try{Dn(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const s=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(s),tokenName:mn(e.tokenName)}}async unbanToken(e){!function(e){xn(e.tokenName,"tokenName",Qn)}(e);const t=this.buildEndpoint(qe,{tokenName:e.tokenName});return an(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:mn(e.tokenName)}}async listTokenBans(e={}){!function(e){Un(0,void 0,Yn,e.pageSize)}(e);const t=He,n=this.buildPaginationParams(e,Yn);this.addOptionalFilterParams(n,e,["search"]);const s=await this.http.get(t,n,this.getDualAuthHeaders()),r=this.extractData(s);return{items:r.bans,pageInfo:r.pageInfo}}async getTokenBan(e){!function(e){xn(e.tokenName,"tokenName",Qn)}(e);const t=this.buildEndpoint(je,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),s=this.extractDataOrNull(n);return{banned:null!==s,...null!==s&&{ban:s},tokenName:mn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class sl extends jn{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(!On(e))throw Vt("tokenName","Token name");const t=mn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null!==s&&""!==s){const e=this.parseVaultAddressToTokenClassKey(s);this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:e,cachedAt:Date.now()})}return s}async resolveTokenClassKey(e){if(!On(e))throw Vt("tokenName","Token name");const t=mn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const s=await this.poolService.resolveTokenNameToVault(e);if(null===s||""===s)throw qt(e);const r=this.parseVaultAddressToTokenClassKey(s);return this.setCacheEntry(t,{vaultAddress:s,tokenClassKey:r,cachedAt:Date.now()}),r}get(e){const t=this.getCacheEntry(mn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=sl.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=mn(e),s=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:s,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:sl.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(mn(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:s}of e){const e=mn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:s,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return Bi(e)}catch(e){if(e instanceof Rt)throw zt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}sl.MAX_CACHE_SIZE=1e4;class rl extends Hn{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){const e=await ln(()=>this.http.get(ct),{errorContext:"Failed to fetch launchpad fee"});if("number"!=typeof e.feeAmount||!Number.isFinite(e.feeAmount))throw new Rt("Failed to fetch launchpad fee: no feeAmount in the response","feeAmount","INVALID_RESPONSE");return e.feeAmount}async fetchSaleDetails(e){return ln(()=>this.http.get(lt,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){const t={tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method},{signal:n}=e;return br(await ln(()=>void 0===n?this.http.get(dt,t):this.http.request({method:"GET",url:dt,params:t,signal:n}),{errorContext:`Failed to get trade quote for ${e.tokenName}`}),`trade quote for ${e.tokenName}`)}async getPremintQuote(e){return br(await ln(()=>this.http.get(ut,{amount:e}),{errorContext:"Failed to get premint quote"}),"premint quote")}}class il extends ai{constructor(e,t,n,s=!1,r){super(e,t,n,s,r)}async emitTradeExecuted(e,t){this.validateTokenName(e,Jn);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,Jn);const s={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(s)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Jn);const s={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Jn);const s={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Jn);const s={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Jn);const s={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Jn);const s={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Jn);const s={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitTokenBanned(e,t){this.validateTokenName(e,Jn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Jn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Jn);const s={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Jn);const s={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(s)}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 s=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(s)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return void 0===n?{online:!1}:{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new Ft("userAddresses must be a non-empty array");const t=await this.getConnectedClients({userAddresses:e.join(","),limit:e.length}),n=t.clients.filter(e=>"string"==typeof e.address&&""!==e.address).map(e=>e.address);return{online:n,offline:e.filter(e=>!n.includes(e)),clients:t.clients.map(e=>{const t={socketId:e.socketId,rooms:e.rooms};return"string"==typeof e.address&&(t.address=e.address),t})}}async getTokenViewers(e,t){this.validateTokenName(e,Jn);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const s=await this.getConnectedClients(n);return{clients:s.clients,count:s.summary.totalConnected,authenticatedCount:s.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,Jn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Jn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Jn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class al{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 ol{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 s=n??this.defaultTtlMs,r={value:t};s>0&&(r.expiresAt=Date.now()+s),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}}class cl extends jn{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 al({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new ol(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),cl.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof N||(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)=>{$r(async()=>{if(!this.isSocketIOAvailable){const e=new Error('Socket.IO not available in current environment. Install "socket.io-client" package.');throw this.logger.error("❌ Socket.IO connection failed:",Bt(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=N(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],s=n.status??n.Status;"string"==typeof s&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${s}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{this.logger.error("Socket.IO connection failed:",e);const n=Pt(e)?e:new Error(Bt(e));throw t(n),n}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${String(this.socket?.connected??!1)}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const s=this.config.timeout??3e5,r=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(s/1e3),r={transactionId:e,status:Vr.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)}},s);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: ${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:Vr.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}await Promise.resolve()}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const s=t,r=s?.data,i=s?.status??s?.Status??r?.status??r?.Status;let a=s?.message??s?.Message??r?.message??r?.Message??s?.error??r?.error;On(a)||(a=i===qr.FAILED||i===qr.ERROR?"Transaction failed - check transaction details":i===qr.COMPLETED||i===qr.PROCESSED||i===qr.SUCCESS?"Transaction completed successfully":null!=i?`Transaction status: ${String(i)}`:"Unknown transaction status");const o=s?.blockHash??r?.blockHash,c=s?.gasUsed??r?.gasUsed,l=s?.Data??r?.Data,d={transactionId:e,status:this.mapSocketStatus(i),message:"string"==typeof a?a:"Transaction update received",timestamp:Date.now(),...null!=o?{blockHash:o}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(i)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(a)}"`),n(d),d.status===Vr.COMPLETED||d.status===Vr.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} (${d.status})`)}}async waitForTransaction(e){return new Promise((t,n)=>{this.monitorTransaction(e,e=>{e.status===Vr.COMPLETED?t(e):e.status!==Vr.FAILED&&e.status!==Vr.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return zr[t]??Vr.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")),cl.instances.delete(this)}static cleanupAll(e=!1){for(const e of cl.instances)e.disconnect();cl.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}cl.instances=new Set;class ll extends Hn{constructor(e,t=!1){super(e,t)}extractData(e){if(e.error||void 0===e.data){const t=e.message??"Weekly challenge operation failed";throw new Error(t)}return e.data}async getLeaderboard(e={}){const{limit:t=10}=e;if(t<1||t>50)throw new Rt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},s=await this.http.get(ht.GET_LEADERBOARD,n),r=this.extractData(s);return this.logger.debug("Fetched weekly challenge leaderboard",{count:r.count}),{leaderboard:r}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Rt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=ht.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),s=await this.http.get(n),r=this.extractData(s);return this.logger.debug("Fetched token weekly history",{count:r.length}),{snapshots:r}}}const dl=["CreateSale","BuyWithNative","BuyExactToken","SellWithNative","SellExactToken"];class ul{constructor(e){this.bundleId=e.bundleId,this.uniqueKey=e.uniqueKey,this.method=e.method,this.waitForResult=e.wait}wait(e){return this.waitForResult(e)}}class hl{constructor(e){this.bundleBaseUrl=Sl(e.bundleBaseUrl),this.launchpadBaseUrl=Sl(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>N(e,{transports:["websocket"]})),this.bundleSocketFactory=e.bundleSocketFactory}attach(e){const{bundleId:t,method:n,uniqueKey:s,tokenName:r}=e;if("string"!=typeof t||""===t)throw ml("bundleId");if(i=n,!dl.some(e=>e===i))throw ml("method");var i;if("string"!=typeof s||""===s)throw ml("uniqueKey");if(void 0!==r&&("string"!=typeof r||""===r))throw ml("tokenName");if("CreateSale"===n&&void 0===r)throw ml("tokenName");const a={method:n,dto:{uniqueKey:s,...void 0===r?{}:{tokenName:r}},stringsInstructions:[]};return new ul({bundleId:t,uniqueKey:s,method:n,wait:e=>this.waitForResult(a,t,e)})}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){throw function(e){if(e instanceof ki)return e;if(y(e)){const t=e instanceof Error?e.message:"The signature was rejected in the wallet.",n=T(e);return new ki(t,"WALLET_USER_REJECTED",{details:void 0===n?{}:{walletCode:n}})}const t=e instanceof Error?e.message:"Launchpad signing failed.";return new ki(t,"LAUNCHPAD_SIGNING_FAILED",{chainMessage:t})}(e)}const n=function(e){return Object.fromEntries(Object.entries(e).filter(([e])=>"prefix"!==e))}(t),s=`${this.bundleBaseUrl}/bundle`,r=await this.requestor(s,{method:"POST",headers:{"content-type":"application/json","X-Wallet-Address":this.walletAddress},body:JSON.stringify({stringsInstructions:e.stringsInstructions,method:e.method,signedDto:n})}),i=await yl(r);if(!r.ok)throw pl(r.status,i,s);const a=function(e){if("string"==typeof e&&""!==e)return e;if(!Tl(e))throw new ki("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(Tl(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new ki("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(i),o=El(e.dto,"uniqueKey");return new ul({bundleId:a,uniqueKey:o,method:e.method,wait:t=>this.waitForResult(e,a,t)})}waitForResult(e,t,n={}){const s=n.timeoutMs??6e4,r=n.pollIntervalMs??2500,i=n.signal;return new Promise((n,a)=>{const o=this.confirmationUrl(e,t);if(!0===i?.aborted)return void a(gl(e.method,t));const c=Date.now(),l=new AbortController,d=void 0===this.bundleSocketFactory;let u,h,g,m=!1;const f=()=>{p(()=>a(gl(e.method,t)))},p=e=>{m||(m=!0,clearTimeout(A),i?.removeEventListener("abort",f),l.abort(),void 0!==u&&(void 0!==h&&u.off(t,h),d&&u.disconnect()),e())},v=()=>{p(()=>a(function(e,t){const n="string"==typeof e.dto.uniqueKey?e.dto.uniqueKey:"";return new ki(`Timed out waiting for bundle ${n}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method,...void 0===t?{}:{lastReadFailure:{message:t.message,...void 0===t.status?{}:{status:t.status}}}}})}(e,g)))};i?.addEventListener("abort",f,{once:!0});const A=setTimeout(v,s);try{u=(this.bundleSocketFactory??this.socketFactory)(this.bundleBaseUrl),h=e=>{const t=function(e){if(!Tl(e))return;const t=e.status;return"PROCESSED"!==t&&"FAILED"!==t?void 0:{status:t,data:e.data}}(e);void 0!==t&&p(()=>{"FAILED"===t.status?a(fl(t.data)):n(t)})},u.on(t,h)}catch{u=void 0,h=void 0}this.pollConfirmation({request:e,confirmationUrl:o,startedAt:c,timeoutMs:s,pollIntervalMs:r,signal:l.signal,onReadFailure:e=>{g=e}}).then(e=>{void 0===e?v():p(()=>n(e))},e=>p(()=>a(e instanceof Error?e:new Error(String(e)))))})}confirmationUrl(e,t){return"CreateSale"===e.method?function(e,t){const n=El(t,"tokenName");return`${e}/v1/tokens/${encodeURIComponent(n)}`}(this.launchpadBaseUrl,e.dto):`${this.bundleBaseUrl}/bundle?id=${encodeURIComponent(t)}`}async pollConfirmation(e){const{request:t,confirmationUrl:n,startedAt:s,timeoutMs:r,pollIntervalMs:i,signal:a,onReadFailure:o}=e;for(;!a.aborted&&Date.now()-s<=r;){const e=await this.readConfirmation(t,n,a);if(a.aborted)return;if("processed"===e.kind)return e.result;if("failed"===e.kind)throw fl(e.data);o("read-failed"===e.kind?e.error:void 0);const c=r-(Date.now()-s);if(c<=0)break;await bl(Math.min(Math.max(0,i),c),a)}}async readConfirmation(e,t,n){try{const s=await this.requestor(t,{method:"GET",signal:n}),r=await yl(s);if("CreateSale"===e.method)return s.ok?{kind:"processed",result:{status:"PROCESSED",data:Al(r)}}:404===s.status||202===s.status?{kind:"pending"}:{kind:"read-failed",error:pl(s.status,r,t)};if(!s.ok)return{kind:"read-failed",error:pl(s.status,r,t)};const i=Tl(r)?r.status:void 0;return"COMPLETED"===i||"PROCESSED"===i?{kind:"processed",result:{status:"PROCESSED",data:r}}:"FAILED"===i?{kind:"failed",data:r}:{kind:"pending"}}catch(e){const n=e instanceof Error?e.message:"The bundle confirmation read failed.";return{kind:"read-failed",error:new ki(n,"BUNDLE_REQUEST_FAILED",{details:{url:t}})}}}}function gl(e,t){return new ki("Waiting for the launchpad bundle was aborted. The bundle itself may still be processed: `attach` resumes it.","BUNDLE_WAIT_ABORTED",{details:{method:e,bundleId:t}})}function ml(e){return new ki(`Cannot attach to a launchpad bundle: ${e} is missing or not accepted.`,"INVALID_BUNDLE_ATTACHMENT",{details:{field:e}})}function fl(e){const t=vl(e)??"Launchpad bundle failed on chain.";return new ki(t,"BUNDLE_FAILED",{chainMessage:t})}function pl(e,t,n){const s=vl(t)??`Bundle request failed with HTTP ${e}`;return new ki(s,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:s,details:{body:t,url:n}})}function vl(e){if("string"==typeof e&&""!==e)return e;if(Tl(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(Tl(n)){const e=vl(n);if(void 0!==e)return e}}}function Al(e){return Tl(e)?e.data??e.Data??e:e}function El(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new ki(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function yl(e){try{return await e.json()}catch{return e.text()}}function Tl(e){return"object"==typeof e&&null!==e}function Sl(e){return e.replace(/\/$/u,"")}function bl(e,t){return new Promise(n=>{if(t.aborted)return void n();const s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t.removeEventListener("abort",s),n()},e);t.addEventListener("abort",s,{once:!0})})}function kl(e){return async t=>{const n=t.tokenName??await async function(e,t){const n=Ui(t).type,s=await e.findTokenNameByVault(t,n);if(void 0===s)throw new Rt(`Could not find the launchpad token for vault ${t}, so the reverse bonding curve fee ceiling cannot be quoted. Pass tokenName, or pass extraFees.maxAcceptableReverseBondingCurveFee explicitly.`,"tokenName","TOKEN_NOT_FOUND_FOR_VAULT");return s}(e,t.vaultAddress);return function(e,t){if(!/^\d+(\.\d+)?$/.test(e))throw new Rt(`Quoted reverse bonding curve fee is not a non-negative number: ${e}`,"extraFees","INVALID_QUOTED_FEE");if(!Number.isFinite(t)||t<0)throw new Rt(`Fee slippage factor must be a non-negative number, got ${String(t)}`,"maxAcceptableReverseBondingCurveFeeSlippageFactor","INVALID_FEE_SLIPPAGE_FACTOR");return new _(e).multipliedBy(new _(1).plus(new _(String(t)))).decimalPlaces(8,_.ROUND_UP).toFixed()}((await e.getTradeQuote("SellExactToken"===t.method?{tokenName:n,amount:t.quantity,type:"MEME",method:"IN"}:{tokenName:n,amount:t.quantity,type:"NATIVE",method:"OUT"})).reverseBondingCurveFee,t.feeSlippageFactor??e.defaultFeeSlippageFactor())}}const wl="0.1",Nl="0.5",_l=/^(?:\d+\.?\d*|\.\d+)$/u,Il=/^[0-9A-Z]+$/u,Cl=/^[A-Za-z0-9]+$/u,Dl=new _("0.1"),Rl=new _("0.5");function Ol(e){if("string"!=typeof e||!_l.test(e))return;const t=new _(e);return t.isFinite()?t.toFixed():void 0}function Ml(e){return"string"==typeof e&&""!==e}function Ul(e,t,n){void 0!==n&&"string"!=typeof n&&e.push(`${t} must be a string`)}function Ll(e,t,n){void 0===n||Ml(n)||e.push(`${t} must be a non-empty string`)}function Fl(e){const t=[];if("object"!=typeof e||null===e)throw new Rt("CreateSale input must be an object","data","VALIDATION_ERROR");const n={...e},s=n.tokenName;Ml(s)?Cl.test(s)||t.push("Token name can only contain letters and numbers"):t.push("Token name is required");const r=n.tokenSymbol;Ml(r)?Il.test(r.toUpperCase())||t.push("Token symbol can only contain letters and numbers"):t.push("Token symbol is required");const i=n.tokenDescription;Ml(i)?i.length>1e3&&t.push("Token description must be at most 1000 characters"):t.push("Token description is required");const a=n.tokenImage;Ml(a)?a.length>500&&t.push("Token image must be at most 500 characters"):t.push("Token image is required");const o=n.preBuyQuantity;void 0!==o&&void 0===Ol(o)&&t.push("preBuyQuantity must be a non-negative decimal number");for(const e of["websiteUrl","telegramUrl","twitterUrl","instagramUrl","facebookUrl","redditUrl","tiktokUrl"])Ul(t,e,n[e]);Ll(t,"tokenCategory",n.tokenCategory),Ll(t,"tokenCollection",n.tokenCollection);const c=n.saleStartTime;if(void 0===c||Number.isInteger(c)||t.push("saleStartTime must be an integer"),function(e,t){if(void 0!==t&&("object"!=typeof t||null===t))return void e.push("reverseBondingCurveConfiguration must be an object");const n=t??{},s=n.minFeePortion??wl,r=n.maxFeePortion??Nl,i=Ol(s),a=Ol(r);if(void 0===i&&e.push("minFeePortion must be a decimal number"),void 0===a&&e.push("maxFeePortion must be a decimal number"),void 0===i||void 0===a)return;const o=new _(i),c=new _(a);o.isLessThan(Dl)&&e.push("minFeePortion must be greater than or equal to 0.1"),c.isGreaterThan(Rl)&&e.push("maxFeePortion must be less than or equal to 0.5"),o.isGreaterThan(c)&&e.push("minFeePortion must be less than or equal to maxFeePortion")}(t,n.reverseBondingCurveConfiguration),t.length>0)throw new Rt(t.join("; "),"data","VALIDATION_ERROR")}class xl{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress,this.sellFeeCeiling=e.sellFeeCeiling}createSale(e){Fl(e);const t=function(e,t){const n={tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,tokenDescription:e.tokenDescription,tokenImage:e.tokenImage,preBuyQuantity:Ol(e.preBuyQuantity??"0"),websiteUrl:e.websiteUrl??"",telegramUrl:e.telegramUrl??"",twitterUrl:e.twitterUrl??"",instagramUrl:e.instagramUrl??"",facebookUrl:e.facebookUrl??"",redditUrl:e.redditUrl??"",tiktokUrl:e.tiktokUrl??"",tokenCategory:e.tokenCategory??"Unit",tokenCollection:e.tokenCollection??"Token",uniqueKey:e.uniqueKey??Pl(t)},s=e.reverseBondingCurveConfiguration;n.reverseBondingCurveConfiguration={minFeePortion:Ol(s?.minFeePortion??wl),maxFeePortion:Ol(s?.maxFeePortion??Nl)},void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:Fi(e)})}attach(e){return this.transport.attach(e)}buyWithNative(e){return this.submitTrade("BuyWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}buyExactToken(e){return this.submitTrade("BuyExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}sellWithNative(e){return this.submitTrade("SellWithNative",e,{nativeTokenQuantity:e.quantity,expectedToken:e.expectedAmount})}sellExactToken(e){return this.submitTrade("SellExactToken",e,{tokenQuantity:e.quantity,expectedNativeToken:e.expectedAmount})}async submitTrade(e,t,n){const s={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??await this.defaultExtraFees(e,t),uniqueKey:t.uniqueKey??Pl(this.walletAddress)};return this.transport.submit({method:e,dto:s,stringsInstructions:Li(t.vaultAddress)})}async defaultExtraFees(e,t){if("BuyWithNative"===e||"BuyExactToken"===e)return{maxAcceptableReverseBondingCurveFee:"0"};if(void 0===this.sellFeeCeiling)throw new Rt("A sell needs a reverse bonding curve fee ceiling and no quote source is configured: pass extraFees.maxAcceptableReverseBondingCurveFee.","extraFees","FEE_CEILING_REQUIRED");return{maxAcceptableReverseBondingCurveFee:await this.sellFeeCeiling({method:e,vaultAddress:t.vaultAddress,quantity:t.quantity,...void 0===t.tokenName?{}:{tokenName:t.tokenName}})}}}function Pl(e){return`galaswap-operation-${w()}-${Date.now()}-${e}`}function Bl(e,t=3e4){return I.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const $l=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Gl(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Gl(e,t+1));if(e instanceof Map){const n={};for(const[s,r]of e.entries()){const e=String(s);n[e]=$l.has(e.toLowerCase())?"[REDACTED]":Gl(r,t+1)}return n}if("object"==typeof e){const n={};for(const[s,r]of Object.entries(e))n[s]=$l.has(s.toLowerCase())?"[REDACTED]":Gl(r,t+1);return n}return e}class Kl{constructor(e,t={},n={signRequests:!0}){this.auth=e,this.signRequests=n.signRequests,this.session=n.session,this.debug=t.debug??!1,this.logger=new vn({debug:this.debug,context:"HttpClient"});const s=t.baseUrl??jr("stage").launchpadBaseUrl,r=t.timeout??6e4;this.axios=Bl(s,r),t.headers&&(this.axios.defaults.headers.common={...this.axios.defaults.headers.common,...t.headers}),void 0!==this.session&&"omit"!==this.session.credentials&&(this.axios.defaults.withCredentials=!0),this.setupInterceptors()}async request(e){return(await this.requestWithMeta(e)).data}async requestWithMeta(e){return $r(async()=>{const t=void 0!==this.session&&!1!==e.withSession&&!function(e){return void 0!==e&&Object.keys(e).some(e=>"authorization"===e.toLowerCase())}(e.headers),n=t&&void 0!==this.session?await this.session.accessToken():null,s=this.toAxiosConfig(e,n);e.headers&&this.logger.debug("Custom headers provided:",Object.keys(s.headers??{}));const r=e.data instanceof FormData?"[FormData object - multipart/form-data]":Gl(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Gl(s.params),data:r,isFormData:e.data instanceof FormData,contentType:s.headers?.["Content-Type"]??"not set"});const i=await this.sendWithSession(e,s,t,n),a=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,s]of Object.entries(e))"string"==typeof s?t[n.toLowerCase()]=s:"number"!=typeof s&&"boolean"!=typeof s||(t[n.toLowerCase()]=String(s));return t}(i.headers);return this.logger.debug("Response:",{status:i.status,data:Gl(i.data),transactionId:a["x-transaction-id"],blockNumber:a["x-block-number"]}),{data:i.data,headers:a,status:i.status}},`HTTP ${e.method} ${e.url}`,this.logger)}toAxiosConfig(e,t){const n=null===t?e.headers:{...e.headers,Authorization:`Bearer ${t}`},s={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:go(e.params)},...void 0!==n&&{headers:{...n}},...void 0!==e.timeout&&{timeout:e.timeout},...void 0!==e.signal&&{signal:e.signal}};if(e.data instanceof FormData){const e=new C(n);e.set("Content-Type",void 0),s.headers=e,this.logger.debug("FormData detected - clearing the JSON Content-Type default for the multipart upload")}return s}async sendWithSession(e,t,n,s){try{return await this.axios.request(t)}catch(t){if(!n||void 0===this.session||!function(e){if("object"!=typeof e||null===e||!("response"in e))return!1;const t=e.response;return"object"==typeof t&&null!==t&&"status"in t&&401===t.status}(t))throw t;const r=await this.session.onUnauthorized(s);if(null===r)throw t;return this.logger.debug("Retrying once with the refreshed session token"),await this.axios.request(this.toAxiosConfig(e,r))}}async get(e,t,n){return this.request({method:"GET",url:e,...t&&{params:t},...n&&{headers:n}})}async post(e,t,n){return this.request({method:"POST",url:e,data:t,...n&&{headers:n}})}async postWithMeta(e,t,n){return this.requestWithMeta({method:"POST",url:e,data:t,...n&&{headers:n}})}async put(e,t,n){return this.request({method:"PUT",url:e,data:t,...n&&{headers:n}})}async delete(e,t,n){return this.request({method:"DELETE",url:e,...t&&{params:t},...n&&{headers:n}})}async patch(e,t,n){return this.request({method:"PATCH",url:e,data:t,...n&&{headers:n}})}getAddress(){return this.auth.getAddress()}getEthereumAddress(){return this.auth.getEthereumAddress()}async signMessage(e){return(await this.auth.signMessage(e)).signature}async signTypedData(e,t,n){return await this.auth.signTypedData(e,t,n)}async signCustomMessage(e){return $r(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.signRequests&&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("Skipping signature header (no wallet, or signRequests is off)");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e instanceof Error?e:new Error(String(e)))),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,s={message:n?.message??Bt(e),...n&&"string"==typeof n.error&&""!==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=s,this.logger.error("Backend error:",s)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e instanceof Error?e:new Error(String(e)))})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class Wl extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Hl extends Wl{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class jl 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 ql(e,t){if(Mn(e))throw new Wl(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Wl(`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 Wl(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function Vl(e,t,n,s){ql(e,t);const r=e,i=r.data??{};if(!function(e){if(Mn(e)||"object"!=typeof e)return!1;const t=e;return!(void 0!==t.inputQuantity&&"string"!=typeof t.inputQuantity||void 0!==t.outputQuantity&&"string"!=typeof t.outputQuantity||void 0!==t.totalFees&&"string"!=typeof t.totalFees||void 0!==t.vaultAddress&&"string"!=typeof t.vaultAddress)}(i))throw new Wl(`Invalid trade data received for transaction ${t}`);const a={transactionId:t,type:n,method:"native"===s.type?"native":"exact",inputAmount:i.inputQuantity??s.amount,outputAmount:i.outputQuantity??s.expectedAmount??"0",totalFees:i.totalFees??"0",tokenName:s.tokenName,vaultAddress:i.vaultAddress??"",timestamp:Date.now()};return void 0!==r.blockHash&&(a.blockHash=r.blockHash),void 0!==r.gasUsed&&(a.gasUsed=r.gasUsed),void 0!==s.slippageToleranceFactor&&(a.slippageTolerance=s.slippageToleranceFactor),a}function zl(e){return void 0!==e&&o(e)?new i(e.exportPrivateKey()):void 0}const Ql={MUSIC:"$MUSIC",GMUSIC:"$GMUSIC"};function Xl(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}const Jl=/^(?:eth\||0x)([0-9a-fA-F]{40})$/;function Yl(e,t,n){if(void 0===e||void 0===t)return;const s=Jl.exec(e)?.[1],r=Jl.exec(t)?.[1];if(void 0!==s&&void 0!==r&&s.toLowerCase()!==r.toLowerCase())throw Xt(`${n} ${t} is not the identity of the configured signing key (${e}); writes would be signed as the key, not as ${n}.`,n)}class Zl{constructor(e){let t,n;this.walletGeneration=0,e.walletProvider?(t=e.walletProvider,n=zl(e.walletProvider)):e.wallet&&(n=e.wallet,t=a.fromWallet(e.wallet)),this.wallet=n;const s=e.env??"prod",r=jr(s);this.environment=s,this.config={baseUrl:e.launchpadBaseUrl??r.launchpadBaseUrl,gatewayBaseUrl:r.gatewayBaseUrl,bundleBaseUrl:r.bundleBaseUrl,webSocketUrl:r.webSocketUrl,dexApiBaseUrl:r.dexApiBaseUrl,dexBackendBaseUrl:r.dexBackendBaseUrl,launchpadFrontendUrl:r.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const i=e.signer??(void 0!==n?new Ri(n.privateKey):void 0),o=void 0!==n?`eth|${n.address.slice(2)}`:Xl(i);Yl(o,e.walletAddress,"walletAddress"),Yl(o,e.galaChainAddress,"galaChainAddress");const c=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.address.slice(2)}`:Xl(i)),l=i??{signObject:()=>Promise.reject(new Error("A signer is required for token writes.")),signTypedData:()=>Promise.reject(new Error("A signer is required for launchpad writes."))},d=c??"";this.tokenWriter=void 0===n&&void 0!==e.signer&&void 0!==c?{signer:e.signer,walletAddress:c}:void 0;const u=new hl({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:l,walletAddress:d,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor},bundleSocketFactory:e.bundleSocketFactory}),h=kl({getTradeQuote:e=>this.tradingQuotesService.getTradeQuote(e),findTokenNameByVault:(e,t)=>this.findTokenNameByVault(e,t),defaultFeeSlippageFactor:()=>this.maxAcceptableReverseBondingCurveFeeSlippageFactor});this.sellFeeCeiling=h,this.launchpad=new xl({transport:u,walletAddress:d,sellFeeCeiling:h}),this.logger=new vn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Zl.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Zl.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Zl.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.signerWalletAddress=e.walletAddress??(void 0===n?c:void 0),this.auth=new Wr({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"});const g=e.session;if(void 0!==g){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.credentials;return"function"==typeof t.accessToken&&"function"==typeof t.onUnauthorized&&(void 0===n||"include"===n||"omit"===n)}(g))throw Xt("session must provide accessToken() and onUnauthorized()","session");if(void 0!==e.accessToken&&""!==e.accessToken)throw Xt("Pass either session or accessToken, not both: the session owns the token.","accessToken")}if(this.jwtAuth=void 0===g?new Pr:new Br,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Kl(this.auth,this.config,{signRequests:!0,session:g}),this.sessionAuth=new Kr(this.http,this.auth,this.jwtAuth,e.debug??!1,g);const m={signRequests:!1};this.galaChainHttp=new Kl(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl},m),this.bundleHttp=new Kl(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl},m),this.dexApiHttp=new Kl(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl},m),this.dexBackendHttp=new Kl(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl},m),this.galaChainPublicAxios=Bl(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Vn(e.debug??!1),this.launchpadService=new Oo(this.http,this.jwtAuth),this.tokenResolverService=new sl(this.launchpadService.poolService),this.launchpadAPI=new Dr(this.http,this.logger,this.bundleHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new ao(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios,this.tokenWriter),this.priceService=new la(this.dexBackendHttp,this.cache,e=>this.galaChainService.fetchTokenDetails(e),e.debug??!1),this.bundleService=this.createBundleService(),this.websocketService=new cl({url:this.config.webSocketUrl},this.config.debug),this.nftCollectionService=new Vo(this.galaChainHttp),this.tradingQuotesService=new rl(this.http,e.debug??!1)}createOverrideSdk(e){if(!On(e))throw Xt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Xt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new i(e),n={...this.config,wallet:t};return new Zl(n)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:void 0!==this.signerWalletAddress&&""!==this.signerWalletAddress?this.signerWalletAddress:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Vt("wallet","Wallet");return this.wallet}assertTokenWriter(){if(void 0===this.wallet&&void 0===this.tokenWriter)throw Vt("wallet","Wallet")}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Rt("Invalid wallet: must be an ethers Wallet instance, received "+typeof e,"wallet","INVALID_WALLET");this.wallet=e,this.auth.setWallet(e),this.onWalletChanged()}onWalletChanged(){this.walletGeneration+=1,this.galaChainAddressOverride=void 0,this.signerWalletAddress=void 0,this.rebuildTokenWrites(),this.bundleService=this.createBundleService(),this._bridgeService=void 0,this._wrapService=void 0,this._galaConnectClient=void 0,this._streamWebSocketService?.deauthenticate()}createBundleService(){return new Qi(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,this.wallet,this.wallet?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor,this.sellFeeCeiling)}rebuildTokenWrites(){this.tokenWriter=void 0,this.galaChainService=new ao(this.galaChainHttp,this.wallet,this.tokenResolverService,this.config.debug??!1,this.galaChainPublicAxios)}setWalletProvider(e){this.auth.setWalletProvider(e),this.wallet=e?zl(e):void 0,this.onWalletChanged()}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,signer:n,httpRequestor:s,streamAdminApiKey:r,userApiKey:i,accessToken:a,headers:o,...c}=this.config;return{...c,...void 0!==r&&{streamAdminApiKey:"[REDACTED]"},...void 0!==i&&{userApiKey:"[REDACTED]"},...void 0!==a&&{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:gn.GAS_FEE}}getVersion(){return Qr}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Xt("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),s=Math.min(t,100);return n.holders.slice(0,s).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),s=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());if(-1===s)return null;const r=n.holders[s];return void 0===r?null:{rank:s+1,balance:r.balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),s=t?.minBalance??0,r=t?.maxBalance??1/0,i=Math.min(t?.limit??100,1e3),a=new Map;return n.holders.forEach((e,t)=>{a.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=s&&t<=r}).map(e=>({...e,rank:a.get(e.address)??0})).slice(0,i)}async getHolderHistory(e,t,n=20){return this.getTrades({tokenName:e,userAddress:t,pageSize:Math.min(n,100)})}async fetchUserHolderContext(e,t){return this.launchpadService.fetchUserHolderContext(e,t)}async fetchTokenPrice(e){const t="object"==typeof e&&null!==e?e:{};if(void 0!==t.tokenId)throw new Rt("fetchTokenPrice prices a launchpad token by tokenName; a token by class key is priced by gswap-sdk (gSwap.market.getPrice)","tokenId",Dt);const n=t.tokenName;return this.priceService.fetchLaunchpadTokenSpotPrice("string"==typeof n?n:"",e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}async fetchTokenDetails(e){return this.galaChainService.fetchTokenDetails(e)}async fetchLaunchTokenFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.launchpadAPI.fetchPoolDetails(e),n=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return t.currentSupply=n.currentSupply,t.reverseBondingCurveMaxFeeFactor=n.reverseBondingCurveMaxFeeFactor,t.reverseBondingCurveMinFeeFactor=n.reverseBondingCurveMinFeeFactor,t.reverseBondingCurveNetFeeFactor=n.reverseBondingCurveNetFeeFactor,t.tokenName=e,t}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 Ss}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none"})}loadCoreBridge(){const e=this.config.bridge;return void 0===e?Promise.reject(Xt("The bridge and wrap methods need gala-core-sdk's ./bridge: create the SDK with `bridge: () => import('@gala-chain/gala-core-sdk/bridge')` (it needs the optional peers ethers, @solana/web3.js and @solana/spl-token).","bridge")):(this.coreBridgeLoad??(this.coreBridgeLoad=Promise.resolve().then(()=>e()).then(e=>{if("object"!=typeof(t=e)||null===t||"function"!=typeof t.BridgeService)throw new Error("the module has no BridgeService export");var t;return e}).catch(e=>{throw this.coreBridgeLoad=void 0,Xt(`The bridge and wrap methods use @gala-chain/gala-core-sdk/bridge, which needs its optional peers ethers, @solana/web3.js and @solana/spl-token installed: ${Bt(e)}`,"bridge")})),this.coreBridgeLoad)}async coreBridge(){const e=this.walletGeneration,t=await this.loadCoreBridge();if(e!==this.walletGeneration)throw Xt("The wallet changed while this bridge or wrap call was starting; nothing was sent. Call it again.","wallet");return t}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=globalThis.process?.env.SOLANA_PRIVATE_KEY;this._bridgeService=new e.BridgeService({galaConnectBaseUrl:this.config.dexApiBaseUrl,galaChainWalletAddress:this.getAddress(),ethereumPrivateKey:t.privateKey,...void 0!==n&&""!==n?{solanaPrivateKey:n}:{},bridgeableTokenService:this.getBridgeableTokenService(e),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(e){return this._bridgeableTokenService??(this._bridgeableTokenService=new e.BridgeableTokenService(this.dexApiHttp)),this._bridgeableTokenService}getWrappableTokenService(e){return this._wrappableTokenService??(this._wrappableTokenService=new e.WrappableTokenService(this.dexApiHttp)),this._wrappableTokenService}getGalaConnectClient(e){if(void 0===this._galaConnectClient){const t=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 e.GalaConnectClient({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl?{galachainBaseUrl:this.config.gatewayBaseUrl}:{},walletAddress:t})}return this._galaConnectClient}getWrapService(e){if(!this._wrapService){const t=this.getWallet();this._wrapService=new e.WrapService({galaConnectClient:this.getGalaConnectClient(e),wrappableTokenService:this.getWrappableTokenService(e),...void 0!==t&&{walletAddress:this.getAddress(),signer:new Ri(t.privateKey)}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new fc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new cc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new fi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new nl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new oi(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new ll(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new Qo(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new ac(this.http,this.config.debug??!1)),this._platformStatsService}getHealthService(){return this._healthService??(this._healthService=new oo(this.http,this.config.debug??!1)),this._healthService}getEventsQueryService(){return this._eventsQueryService??(this._eventsQueryService=new wa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._eventsQueryService}getNotificationService(){return this._notificationService??(this._notificationService=new zo(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new Xi(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new ui(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Bo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ra(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new rc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new il(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new aa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}buildMessageFetchOptions(e,t){return{type:t,...void 0!==e.tokenName&&{tokenName:e.tokenName},...void 0!==e.userAddress&&{userAddress:e.userAddress},...void 0!==e.cursor&&{cursor:e.cursor},...void 0!==e.pageSize&&{pageSize:e.pageSize}}}async resolveReferralAddress(e){if(void 0===e||""===e)return this.getAddress();if(e.startsWith("client|"))return e;const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n=t(e);if(void 0===n)throw new Rt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new Uo(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new oc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new ic(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new va(this.http,this.config.events)),this._eventsBatcherService}getStreamWebSocketService(){if(null===this._streamWebSocketService||void 0===this._streamWebSocketService){if(void 0===this.config.streamWebSocketUrl||""===this.config.streamWebSocketUrl)throw new Error('Stream WebSocket URL is required for real-time streaming features.\n\nConfigure SDK:\n const sdk = createLaunchpadSDK({\n wallet: yourWallet,\n streamWebSocketUrl: getEnvironmentConfig("stage").launchpadBaseUrl\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new Zc({url:this.config.streamWebSocketUrl,tokenProvider:()=>this.streamSocketToken(),...void 0!==this.config.streamReconnectAttempts&&{reconnectAttempts:this.config.streamReconnectAttempts},...void 0!==this.config.streamReconnectDelay&&{reconnectDelay:this.config.streamReconnectDelay},...void 0!==this.config.streamReconnectDelayMax&&{reconnectDelayMax:this.config.streamReconnectDelayMax}},this.config.debug??!1)}return this._streamWebSocketService}async streamSocketToken(){const e=this.config.session;return void 0!==e?e.accessToken():this.ensureValidToken()}get realtime(){return this.getStreamWebSocketService()}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService(await this.coreBridge()).requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService(await this.coreBridge()).getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService(await this.coreBridge()).fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService(await this.coreBridge()).fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService(await this.coreBridge()).isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService(await this.coreBridge()).fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService(await this.coreBridge()).fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService(await this.coreBridge()).getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService(await this.coreBridge()).getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService(await this.coreBridge()).isTokenWrappable(e)}async wrapToken(e){return this.getWrapService(await this.coreBridge()).wrapToken(e)}async unwrapToken(e){return this.getWrapService(await this.coreBridge()).unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService(await this.coreBridge()).estimateUnwrapFee(e,t)}async login(){return this.sessionAuth.login()}async loginWithSignature(e){return this.sessionAuth.loginWithSignature(e)}async loginWithDevBypass(e){return this.sessionAuth.loginWithDevBypass(e)}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 getChatStatus(e){return this.getStreamChatService().getChatStatus(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getPinnedChatMessage(e){const t=this.getMessagesService();return{tokenName:e,pinnedMessage:(await t.getPinnedMessage(e)).message}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);return{tokenName:e,pinnedMessage:(await n.getPinnedMessage(e)).message}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.messageId),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.messageId}):{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 getActiveModerators(e){return(await this.listModeratorInvites({tokenName:e,status:"CLAIMED"})).items.filter(e=>null!==e.claimedBy).map(e=>({address:e.claimedBy,role:e.role,joinedAt:e.claimedAt,inviteId:e.id}))}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 emitWebSocketEvent(e){return this.getWebSocketAdminService().emitEvent(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 getHealth(){return this.getHealthService().getHealth()}async getEventStats(){return this.getEventsQueryService().getEventStats()}async queryEvents(e={}){return this.getEventsQueryService().queryEvents(e)}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=this.buildMessageFetchOptions(e,"COMMENT"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content,type:"COMMENT"})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t=this.buildMessageFetchOptions(e,"CHAT_MESSAGE"),n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content,type:"CHAT_MESSAGE"})).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 getTokenConfig(e){return this.launchpadService.poolService.getTokenConfig(e)}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 getPoolRealtimeState(e){const[t,n,s,r]=await Promise.allSettled([this.getHolderCount(e),this.getTokenConfig(e),this.getRecentTrades(e,10),this.fetchTokenPrice({tokenName:e})]);return{tokenName:e,holderCount:"fulfilled"===t.status?t.value:null,..."rejected"===t.status&&{holderCountError:String(t.reason)},chatConfig:"fulfilled"===n.status?n.value:null,..."rejected"===n.status&&{chatConfigError:String(n.reason)},recentTrades:"fulfilled"===s.status?s.value:null,..."rejected"===s.status&&{recentTradesError:String(s.reason)},price:"fulfilled"===r.status?r.value:null,..."rejected"===r.status&&{priceError:String(r.reason)}}}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.addCallbacks(e)}async authenticateStreamWebSocket(e){return this.getStreamWebSocketService().authenticate(e)}deauthenticateStreamWebSocket(){this._streamWebSocketService?.deauthenticate()}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.getStreamWebSocketService().subscribeEvent("STREAM_STATUS",e)}onUserBanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_BANNED",e)}onUserUnbanned(e){return this.getStreamWebSocketService().subscribeEvent("USER_UNBANNED",e)}onBanEnforcement(e){return this.getStreamWebSocketService().subscribeEvent("BAN_ENFORCEMENT",e)}watchBanEnforcement(e,t={}){const n=(e,n,s,r)=>(void 0===t.actionType||t.actionType===e)&&((void 0===t.userAddress||t.userAddress===n)&&((void 0===t.tokenName||t.tokenName===s)&&!!(void 0===t.reason||null!==r&&r.includes(t.reason)))),s=this.onUserBanned(t=>{const s=t.userAddress??null,r=t.reason??null;n("BANNED",s,t.tokenName,r)&&e({actionType:"BANNED",userAddress:s,tokenName:t.tokenName,reason:r,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})}),r=this.onUserUnbanned(t=>{const s=t.userAddress??null;n("UNBANNED",s,t.tokenName,null)&&e({actionType:"UNBANNED",userAddress:s,tokenName:t.tokenName,reason:null})}),i=this.onBanEnforcement(t=>{const s=t.reason??null;n("ENFORCEMENT",null,t.tokenName,s)&&e({actionType:"ENFORCEMENT",userAddress:null,tokenName:t.tokenName,reason:s,...void 0!==t.expiresAt&&{expiresAt:t.expiresAt}})});return()=>{s(),r(),i()}}watchTokenRoomEvent(e,t,n,s){const r=s.tokenName;if(void 0===r||""===r)throw new Error(`${e} requires a tokenName filter - these are per-token stream events with no way to watch every token at once.`);return t(r,n)}watchCommentCreated(e,t={}){return this.watchTokenRoomEvent("watchCommentCreated",(e,t)=>this.getStreamWebSocketService().subscribeCommentCreated(e,t),n=>{void 0!==t.authorAddress&&t.authorAddress!==n.userAddress||void 0!==t.minLength&&n.content.length<t.minLength||e(n)},t)}watchHolderCountUpdated(e,t={}){return this.watchTokenRoomEvent("watchHolderCountUpdated",(e,t)=>this.getStreamWebSocketService().subscribeHolderCountUpdated(e,t),n=>{void 0!==t.minThreshold&&Math.abs(n.change??0)<t.minThreshold||e(n)},t)}watchModeratorAdded(e,t={}){return this.watchTokenRoomEvent("watchModeratorAdded",(e,t)=>this.getStreamWebSocketService().subscribeModeratorAdded(e,t),e,t)}watchPoolMetadataUpdated(e,t={}){return this.watchTokenRoomEvent("watchPoolMetadataUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolMetadataUpdated(e,t),e,t)}watchTradeExecuted(e,t={}){return this.watchTokenRoomEvent("watchTradeExecuted",(e,t)=>this.getStreamWebSocketService().subscribeTradeExecuted(e,t),n=>{void 0!==t.tradeType&&t.tradeType!==n.tradeType||void 0!==t.userAddress&&t.userAddress!==n.userAddress||void 0!==t.minAmount&&Number(n.inputAmount)<t.minAmount||e(n)},t)}watchTokenBanned(e,t={}){return this.watchTokenRoomEvent("watchTokenBanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenBanned(e,t),e,t)}watchModeratorChanged(e,t={}){const n=(e,n)=>(void 0===t.eventType||t.eventType===e)&&(void 0===t.moderatorAddress||t.moderatorAddress===n),s=this.watchModeratorAdded(t=>{n("ADDED",t.userAddress)&&e({actionType:"ADDED",tokenName:t.tokenName,moderatorAddress:t.userAddress,role:t.role})},t),r=this.watchTokenRoomEvent("watchModeratorRemoved",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRemoved(e,t),t=>{n("REMOVED",t.userAddress)&&e({actionType:"REMOVED",tokenName:t.tokenName,moderatorAddress:t.userAddress})},t),i=this.watchTokenRoomEvent("watchModeratorRoleUpdated",(e,t)=>this.getStreamWebSocketService().subscribeModeratorRoleUpdated(e,t),t=>{n("ROLE_UPDATED",t.userAddress)&&e({actionType:"ROLE_UPDATED",tokenName:t.tokenName,moderatorAddress:t.userAddress,oldRole:t.oldRole,newRole:t.newRole})},t);return()=>{s(),r(),i()}}watchPoolUpdated(e,t={}){const n=e=>void 0===t.updateType||t.updateType===e,s=this.watchPoolMetadataUpdated(t=>{n("METADATA")&&e({updateType:"METADATA",tokenName:t.tokenName,details:t})},t),r=this.watchTokenRoomEvent("watchPoolSocialLinksUpdated",(e,t)=>this.getStreamWebSocketService().subscribePoolSocialLinksUpdated(e,t),t=>{n("SOCIAL_LINKS")&&e({updateType:"SOCIAL_LINKS",tokenName:t.tokenName,details:t})},t),i=this.watchTokenRoomEvent("watchPoolBadgeAssigned",(e,t)=>this.getStreamWebSocketService().subscribePoolBadgeAssigned(e,t),t=>{n("BADGE_ASSIGNED")&&e({updateType:"BADGE_ASSIGNED",tokenName:t.tokenName,details:t})},t);return()=>{s(),r(),i()}}watchTokenBanChanged(e,t={}){const n=e=>void 0===t.banStatus||t.banStatus===e,s=this.watchTokenBanned(t=>{n("BANNED")&&e({banStatus:"BANNED",tokenName:t.tokenName,reason:t.reason})},t),r=this.watchTokenRoomEvent("watchTokenUnbanned",(e,t)=>this.getStreamWebSocketService().subscribeTokenUnbanned(e,t),t=>{n("UNBANNED")&&e({banStatus:"UNBANNED",tokenName:t.tokenName})},t);return()=>{s(),r()}}onContentFlagged(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_FLAGGED",e)}onFlagResolved(e){return this.getStreamWebSocketService().subscribeEvent("FLAG_RESOLVED",e)}onStreamChatMessage(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_MESSAGE",e)}onStreamChatUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UPDATED",e)}onStreamChatDeleted(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_DELETED",e)}onStreamChatPinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_PINNED",e)}onStreamChatUnpinned(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CHAT_UNPINNED",e)}onChatStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("CHAT_STATUS_CHANGED",e)}onViewerCountChanged(e){return this.getStreamWebSocketService().subscribeEvent("VIEWER_COUNT",e)}onRecordingStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("RECORDING_STATUS",e)}onSimulcastStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("SIMULCAST_STATUS",e)}onDownloadReady(e){return this.getStreamWebSocketService().subscribeEvent("DOWNLOAD_READY",e)}onRecordingsCountUpdated(e){return this.getStreamWebSocketService().subscribeEvent("RECORDINGS_COUNT_UPDATED",e)}onUserTyping(e){return this.getStreamWebSocketService().subscribeEvent("USER_TYPING",e)}onStreamReaction(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_REACTION",e)}onContentReactionAdded(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_ADDED",e)}onContentReactionRemoved(e){return this.getStreamWebSocketService().subscribeEvent("CONTENT_REACTION_REMOVED",e)}onStreamCountdownUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_COUNTDOWN_UPDATED",e)}onStreamLanguageUpdated(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_LANGUAGE_UPDATED",e)}onStreamControlStatusChanged(e){return this.getStreamWebSocketService().subscribeEvent("STREAM_CONTROL_STATUS_CHANGED",e)}onConnection(e){return this.getStreamWebSocketService().subscribeEvent("connection",e)}onAuthenticated(e){return this.getStreamWebSocketService().subscribeEvent("authenticated",e)}onTokenSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_subscribed",e)}onTokenUnsubscribed(e){return this.getStreamWebSocketService().subscribeEvent("token_unsubscribed",e)}onRoomSubscribed(e){return this.getStreamWebSocketService().subscribeEvent("room_subscribed",e)}onRoomLeft(e){return this.getStreamWebSocketService().subscribeEvent("room_left",e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEvent("ENGAGEMENT_STATS_UPDATED",e)}async estimateBridgeFee(e){return this.getBridgeService(await this.coreBridge()).estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService(await this.coreBridge()).bridgeOut(e)}async bridgeIn(e){return this.getBridgeService(await this.coreBridge()).bridgeIn(e)}async getBridgeStatus(e){return this.getBridgeService(await this.coreBridge()).getBridgeStatus(e)}async getSupportedBridgeTokens(){const e=this.getBridgeService(await this.coreBridge()),t=e.getSupportedBridgeTokens();return{tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()}}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return qi}),s=t(e.tokenId),{collection:r,category:i,type:a,additionalKey:o}=s;return this.galaChainService.fetchTokenBalance({owner:n,collection:r,category:i,additionalKey:o,type:a},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=fn(e.tokenName),s=Ql[t];if(void 0!==s)return this.galaChainService.fetchTokenBalance({owner:n,collection:s,category:"Unit",additionalKey:"none",type:"none"},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 s=await this.resolveTokenClassKey(e.tokenName);return{quantity:t.balance,collection:s.collection,category:s.category,tokenId:xi(s)}}throw Vt("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:s,privateKey:r,calculateAmountMode:i,currentSupply:a}=e;let o=t;void 0===i&&void 0===a||(o={tokenName:t,...void 0!==i&&{calculateAmountMode:i},...void 0!==a&&{currentSupply:a}});const c=await this.calculateBuyAmountForGraduation(o),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!==s&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=s),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,...s}=e;return t.buy(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Jt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>Vl(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.sell(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Jt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>Vl(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,...s}=e;return t.launchToken(s)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{ql(n,t);const s=n.data??{};if(!function(e){if(Mn(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)}(s))throw new Wl(`Invalid launch data received for transaction ${t}`);const r={transactionId:t,vaultAddress:s.vaultAddress??"",tokenStringKey:s.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:s.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&&(r.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(r.preBuyQuantity=e.preBuyQuantity),""!==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,...s}=e;return t.uploadTokenImage(s)}return this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(R,void 0,{"x-wallet-address":e})}async fetchReferrals(e){const t=await this.resolveReferralAddress(e?.address),n=e?.page??1,s=e?.limit??10,r={pageNumber:n,limit:s,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},i=await this.dexApiHttp.get(O,r,{"x-wallet-address":t});if(!Array.isArray(i))throw new Lt("Unexpected API response: expected array, got "+typeof i);return{referrals:i,page:n,limit:s,hasMore:i.length===s}}async fetchAllReferrals(e){const t=await async function(e,t={}){const{maxPages:n=1e4,logger:s,pageSize:r=20,concurrency:i=1,startPage:a=1}=t,o=[];let c=a;const l=a+n-1;let d=!0,u=0;if(i<=1)for(;d&&c<=l;){s&&s.debug(`Auto-pagination: fetching page ${c} with limit ${r}`);const t=await e(c,r);if(null==t||!Array.isArray(t.items)){s&&s.warn("Auto-pagination: received invalid result structure, stopping");break}if(o.push(...t.items),u=t.total,s&&s.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${String(t.hasNext)}`),0===t.items.length){s&&s.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(s&&s.debug(`Auto-pagination: using concurrent mode with concurrency=${i}`);d&&c<=l;){const t=[];for(let e=0;e<i&&c+e<=l;e++)t.push(c+e);s&&s.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,r).catch(e=>{const n=e,i=n.statusCode??n.response?.status??n.originalError?.response?.status??n.status??n.launchpadError?.statusCode;if(400===i||404===i)return s&&s.debug(`Auto-pagination: page ${t} returned ${i} (end of pagination)`,{statusCode:i}),{items:[],total:0,totalPages:0,page:t,limit:r,hasNext:!1,hasPrevious:!1};throw e})),a=await Promise.all(n);for(const e of a){if(null==e||!Array.isArray(e.items)){s&&s.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){s&&s.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(o.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,s&&s.debug(`Auto-pagination: batch complete, total items so far: ${o.length}`)}return c>l&&s&&s.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),s&&s.debug(`Auto-pagination: completed with total items: ${o.length}, total count: ${u}`),{items:o,total:u}}((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){const t=await this.resolveReferralAddress(e?.address),n=await this.dexApiHttp.get(M,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Lt(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),{address:n,...s}=e,r=void 0===n?void 0:t(n),i={...s,...void 0!==r&&{address:r}};if(void 0!==i.privateKey&&""!==i.privateKey){const e=this.createOverrideSdk(i.privateKey),{privateKey:t,...n}=i;return e.updateProfile(n)}return this.launchpadService.updateProfile(i)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n=void 0===e.address?void 0:t(e.address)??e.address,s={...e,...void 0!==n&&{address:n}};if(void 0!==s.privateKey&&""!==s.privateKey){const e=this.createOverrideSdk(s.privateKey),{privateKey:t,...n}=s;return e.uploadProfileImage(n)}return this.launchpadService.uploadProfileImage(s)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n=t(e?.address)??this.getAddress(),s={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(s.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(s.search=e.search),this.launchpadService.fetchTokensHeld(s)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n={type:"created",address:t(e?.address)??this.getAddress(),pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(n.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(n.search=e.search),void 0!==e?.status&&(n.status=e.status),this.launchpadService.fetchTokenList(n)}async getManagedTokens(e){return this.launchpadService.getManagedTokens(e??{})}async getUserGalaBalance(e){return this.launchpadService.getUserGalaBalance(e)}async fetchReferralCode(){return this.launchpadService.fetchReferralCode()}async transferGala(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferGala(s)}return this.assertTokenWriter(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Ss}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...s}=n;return e.transferToken(s)}return this.assertTokenWriter(),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 Ss});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,...s}=n;return e.lockTokens(s)}return this.assertTokenWriter(),this.galaChainService.lockTokens(n)}async unlockTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.unlockTokens(s)}return this.assertTokenWriter(),this.galaChainService.unlockTokens(e)}async burnTokens(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...s}=e;return t.burnTokens(s)}return this.assertTokenWriter(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}async findTokenNameByVault(e,t){let n;for(let s=0;s<10;s+=1){const s=await this.launchpadService.poolService.fetchPools({search:t,pageSize:100,...void 0===n?{}:{cursor:n}}),r=s.items.find(t=>t.vaultAddress===e);if(void 0!==r)return r.tokenName;const i=Zr(s.pageInfo,n);if(void 0===i)return;n=i}}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{_n(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 Xt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Xt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Xt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Xt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Xt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Xt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Xt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Sn("string"==typeof e||"number"==typeof e?e:String(e),Zl.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Zl.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Zl.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Sn("string"==typeof e||"number"==typeof e?e:String(e),Zl.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: ${Zl.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Zl.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if(n.status!==Vr.COMPLETED)throw new jl(e,n.status,n.message);let s;try{s=t(n)}catch(t){if(t instanceof Wl)throw t;throw new Wl(`Failed to transform WebSocket response for transaction ${e}`,Pt(t)?t:new Error(Bt(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,s),s}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof jl||t instanceof Wl)throw t;throw new Wl(`WebSocket confirmation failed for transaction ${e}`,Pt(t)?t:new Error(Bt(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return td});e.forEach(e=>{if(!n(e))return;const s=t(e,this.logger);s&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,s)})}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onLaunchpadTokenCreation(e,t){const n=1e3,s=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,i=new Map;let a=!0,o=null;let c=0;const l=async()=>{if(a){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{i.has(t.tokenName)||((e=>{if(i.set(e,!0),i.size>1e3){const e=i.keys().next().value;void 0!==e&&i.delete(e)}})(t.tokenName),void 0!==r&&""!==r&&t.creatorAddress!==r||e(t))})}catch(e){c++;const t=Bt(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(a){const e=Math.min(Math.max(c-1,0),2),t=s*Math.pow(2,e);o=setTimeout(()=>{l()},t)}}};return l(),()=>{a=!1,o&&clearTimeout(o),this.logger.debug("Stopped watching for launchpad token creation")}}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw Xt("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,s=null;const r=(n,...s)=>{try{if(s.length>0&&"object"==typeof s[0]&&null!==s[0]){const n=s[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const s=n.Data;if("CreateSale"===s.functionName){const n=(e,t="")=>{const n=s[e];return"string"==typeof n&&""!==n?n:t},r={tokenName:n("tokenName"),symbol:n("symbol"),creatorAddress:n("creatorAddress"),description:n("description"),image:n("image"),vaultAddress:n("vaultAddress"),tokenStringKey:n("tokenStringKey"),preBuyQuantity:n("initialBuyQuantity","0"),websiteUrl:n("websiteUrl"),telegramUrl:n("telegramUrl"),twitterUrl:n("twitterUrl"),instagramUrl:n("instagramUrl"),facebookUrl:n("facebookUrl"),redditUrl:n("redditUrl"),tiktokUrl:n("tiktokUrl"),isFinalized:!0===s.isFinalized};this.matchesCreatorFilter(r,t?.creatorFilter)&&e(r)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${Bt(e)}`)}};let i=this.websocketService.getSocket();if(i)i.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: ${Bt(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const a=()=>{if(i=this.websocketService.getSocket(),!i&&e<Zl.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(s=setTimeout(()=>a(),Zl.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!i&&e>=Zl.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Zl.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Zl.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("Token creation broadcast subscription timeout:",e.message),void(t?.onError&&t.onError(e))}i&&(i.onAny(r),n=!0,this.logger.debug("Token creation broadcast listener registered"))};a()}return()=>{try{if(null!==s&&(clearTimeout(s),s=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)}}}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.dispose(),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 vn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),cl.cleanupAll(e),t.debug("Global cleanup completed")}}function ed(e){Mn(e)&&(e={});const{wallet:t,env:n,config:s={},...r}=e,a={...{...r,...s}};delete a.wallet,delete a.env,delete a.config;const o=!Mn(a.signer)||!Mn(a.walletProvider);let c;if(Mn(t))c=o?void 0:new i(S().privateKey);else if("string"==typeof t)c=new i(S(t).privateKey);else{if(!(t instanceof i))throw Xt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");c=t}const l={...void 0!==c?{wallet:c}:{},...void 0!==n?{env:n}:{},debug:!1,timeout:3e4,...a};return new Zl(l)}Zl.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Zl.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Zl.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=gn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Zl.DEFAULT_CALCULATE_AMOUNT_MODE="local",Zl.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Zl.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;var td=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const s=Sn(e.reverseBondingCurveMinFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=s}if(void 0!==e.reverseBondingCurveMaxFeePortion){const s=Sn(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(s)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=s}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{Mi as BrowserWalletSigner,pa as EVENT_TYPES,Oi as GalaWalletSigner,Zl as LaunchpadSDK,ki as LaunchpadSDKError,Ri as PrivateKeySigner,Qr as SDK_VERSION,jl as TransactionFailedError,Wl as WebSocketError,Hl as WebSocketTimeoutError,ed as createLaunchpadSDK};
|