@gala-chain/launchpad-sdk 6.0.0 → 7.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EXAMPLES.md +159 -156
- package/LICENSE +21 -0
- package/README.md +56 -3338
- package/dist/LaunchpadSDK.d.ts +113 -1811
- package/dist/LaunchpadSDK.d.ts.map +1 -1
- package/dist/api/LaunchpadAPI.d.ts +21 -69
- package/dist/api/LaunchpadAPI.d.ts.map +1 -1
- package/dist/api/dto/BondingCurveDTOs.d.ts +8 -8
- package/dist/api/dto/BondingCurveDTOs.d.ts.map +1 -1
- package/dist/api/dto/BurnTokensDto.d.ts +2 -14
- package/dist/api/dto/BurnTokensDto.d.ts.map +1 -1
- package/dist/api/dto/LockTokenDto.d.ts +2 -14
- package/dist/api/dto/LockTokenDto.d.ts.map +1 -1
- package/dist/api/dto/TransferTokenDto.d.ts +2 -14
- package/dist/api/dto/TransferTokenDto.d.ts.map +1 -1
- package/dist/api/dto/UnlockTokenDto.d.ts +2 -14
- package/dist/api/dto/UnlockTokenDto.d.ts.map +1 -1
- package/dist/bridge/BridgeService.d.ts.map +1 -1
- package/dist/bridge/constants/tokens.d.ts +1 -1
- package/dist/bridge/index.d.ts +1 -1
- package/dist/bridge/index.d.ts.map +1 -1
- package/dist/bridge/public-types.d.ts +2 -0
- package/dist/bridge/public-types.d.ts.map +1 -0
- package/dist/bridge/strategies/BridgeStrategy.d.ts +44 -0
- package/dist/bridge/strategies/BridgeStrategy.d.ts.map +1 -1
- package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts +4 -26
- package/dist/bridge/strategies/EthereumBridgeStrategy.d.ts.map +1 -1
- package/dist/bridge/strategies/SolanaBridgeStrategy.d.ts +4 -26
- package/dist/bridge/strategies/SolanaBridgeStrategy.d.ts.map +1 -1
- package/dist/bridge/utils/bridgePayload.d.ts.map +1 -1
- package/dist/bridge/utils/bridgeStatusParser.d.ts +5 -4
- package/dist/bridge/utils/bridgeStatusParser.d.ts.map +1 -1
- package/dist/bridge/utils/strategyDelegation.d.ts +57 -0
- package/dist/bridge/utils/strategyDelegation.d.ts.map +1 -1
- package/dist/config/environments.d.ts +19 -33
- package/dist/config/environments.d.ts.map +1 -1
- package/dist/constants/bondingCurve.d.ts +10 -10
- package/dist/constants/bondingCurve.d.ts.map +1 -1
- package/dist/constants/endpoints.d.ts +23 -58
- package/dist/constants/endpoints.d.ts.map +1 -1
- package/dist/constants/sdk-defaults.d.ts +0 -2
- package/dist/constants/sdk-defaults.d.ts.map +1 -1
- package/dist/constants/version.generated.d.ts +3 -3
- package/dist/constants/version.generated.d.ts.map +1 -1
- package/dist/errors/LaunchpadSDKError.d.ts +28 -0
- package/dist/errors/LaunchpadSDKError.d.ts.map +1 -0
- package/dist/errors/index.d.ts +3 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/helpers/sdk.d.ts +8 -8
- package/dist/helpers/sdk.d.ts.map +1 -1
- package/dist/index.browser.d.ts +21 -23
- 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.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/launchpad/bundle-submission.d.ts +88 -0
- package/dist/launchpad/bundle-submission.d.ts.map +1 -0
- package/dist/launchpad/strings-instructions.d.ts +15 -0
- package/dist/launchpad/strings-instructions.d.ts.map +1 -0
- package/dist/launchpad/transport.d.ts +28 -0
- package/dist/launchpad/transport.d.ts.map +1 -0
- package/dist/launchpad/writes.d.ts +74 -0
- package/dist/launchpad/writes.d.ts.map +1 -0
- package/dist/native.cjs +1 -1
- package/dist/native.d.ts +3 -0
- package/dist/native.d.ts.map +1 -1
- package/dist/native.esm.js +1 -1
- package/dist/polyfills/file-global.d.ts +4 -0
- package/dist/polyfills/file-global.d.ts.map +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.esm.js +1 -1
- package/dist/schemas/files.d.ts +2 -2
- package/dist/schemas/files.d.ts.map +1 -1
- package/dist/schemas/pagination.d.ts +0 -3
- package/dist/schemas/pagination.d.ts.map +1 -1
- package/dist/services/BanService.d.ts.map +1 -1
- package/dist/services/BaseService.d.ts +1 -1
- package/dist/services/BaseService.d.ts.map +1 -1
- package/dist/services/BatchedCacheService.d.ts.map +1 -1
- package/dist/services/BundleService.d.ts +1 -1
- package/dist/services/BundleService.d.ts.map +1 -1
- package/dist/services/BundlerClientFactory.d.ts +3 -3
- package/dist/services/BundlerClientFactory.d.ts.map +1 -1
- package/dist/services/ContentFlagService.d.ts +1 -0
- package/dist/services/ContentFlagService.d.ts.map +1 -1
- package/dist/services/DexService.d.ts +1 -1
- package/dist/services/DexService.d.ts.map +1 -1
- package/dist/services/GalaChainLockService.d.ts +4 -1
- package/dist/services/GalaChainLockService.d.ts.map +1 -1
- package/dist/services/GalaChainTokenService.d.ts +1 -0
- package/dist/services/GalaChainTokenService.d.ts.map +1 -1
- package/dist/services/GalaChainTransferService.d.ts +10 -5
- package/dist/services/GalaChainTransferService.d.ts.map +1 -1
- package/dist/services/GdexStreamService.d.ts +3 -1
- package/dist/services/GdexStreamService.d.ts.map +1 -1
- package/dist/services/HolderService.d.ts.map +1 -1
- package/dist/services/LaunchpadService.d.ts +3 -35
- package/dist/services/LaunchpadService.d.ts.map +1 -1
- package/dist/services/OEmbedService.d.ts +2 -2
- package/dist/services/OEmbedService.d.ts.map +1 -1
- package/dist/services/PoolService.d.ts +9 -20
- package/dist/services/PoolService.d.ts.map +1 -1
- package/dist/services/PriceHistoryService.d.ts +6 -4
- package/dist/services/PriceHistoryService.d.ts.map +1 -1
- package/dist/services/StreamChatService.d.ts +3 -101
- package/dist/services/StreamChatService.d.ts.map +1 -1
- package/dist/services/StreamTokenServiceBase.d.ts.map +1 -1
- package/dist/services/StreamWebSocketService.d.ts +5 -2
- package/dist/services/StreamWebSocketService.d.ts.map +1 -1
- package/dist/services/StreamingEventService.d.ts +1 -1
- package/dist/services/StreamingEventService.d.ts.map +1 -1
- package/dist/services/StreamingService.d.ts +4 -20
- package/dist/services/StreamingService.d.ts.map +1 -1
- package/dist/services/TokenMetadataCache.d.ts.map +1 -1
- package/dist/services/TokenMetadataService.d.ts +1 -1
- package/dist/services/TokenMetadataService.d.ts.map +1 -1
- package/dist/services/TokenResolverService.d.ts +5 -0
- package/dist/services/TokenResolverService.d.ts.map +1 -1
- package/dist/services/TradeService.d.ts.map +1 -1
- package/dist/services/UserService.d.ts +1 -62
- package/dist/services/UserService.d.ts.map +1 -1
- package/dist/services/WebSocketAdminService.d.ts.map +1 -1
- package/dist/services/WebSocketService.d.ts +1 -1
- package/dist/services/WebSocketService.d.ts.map +1 -1
- package/dist/services/WrapService.d.ts +10 -11
- package/dist/services/WrapService.d.ts.map +1 -1
- package/dist/services/WrappableTokenCache.d.ts.map +1 -1
- package/dist/services/WrappableTokenService.d.ts +1 -1
- package/dist/services/WrappableTokenService.d.ts.map +1 -1
- package/dist/services/__mocks__/logger.mock.d.ts.map +1 -1
- package/dist/services/shared/http-helpers.d.ts +1 -1
- package/dist/services/shared/http-helpers.d.ts.map +1 -1
- package/dist/services/shared/pagination-helpers.d.ts.map +1 -1
- package/dist/services/shared/service-validators.d.ts +1 -1
- package/dist/services/shared/service-validators.d.ts.map +1 -1
- package/dist/services/shared/websocket-helpers.d.ts.map +1 -1
- package/dist/signing/eip712.d.ts +13 -0
- package/dist/signing/eip712.d.ts.map +1 -0
- package/dist/signing/index.d.ts +5 -0
- package/dist/signing/index.d.ts.map +1 -0
- package/dist/signing/signers.d.ts +81 -0
- package/dist/signing/signers.d.ts.map +1 -0
- package/dist/signing/types.d.ts +31 -0
- package/dist/signing/types.d.ts.map +1 -0
- package/dist/tokens/transfers.d.ts +91 -0
- package/dist/tokens/transfers.d.ts.map +1 -0
- package/dist/types/api-key.dto.d.ts.map +1 -1
- package/dist/types/backend-responses.d.ts +8 -31
- package/dist/types/backend-responses.d.ts.map +1 -1
- package/dist/types/ban.dto.d.ts +14 -23
- package/dist/types/ban.dto.d.ts.map +1 -1
- package/dist/types/chat-messages.dto.d.ts.map +1 -1
- package/dist/types/comments.dto.d.ts +5 -26
- package/dist/types/comments.dto.d.ts.map +1 -1
- package/dist/types/common.d.ts +4 -3
- package/dist/types/common.d.ts.map +1 -1
- package/dist/types/content-flag.dto.d.ts.map +1 -1
- package/dist/types/dto.d.ts +6 -0
- package/dist/types/dto.d.ts.map +1 -1
- package/dist/types/engagement-stats.dto.d.ts +2 -3
- package/dist/types/engagement-stats.dto.d.ts.map +1 -1
- package/dist/types/galachain-api.types.d.ts.map +1 -1
- package/dist/types/launchpad.dto.d.ts +7 -73
- package/dist/types/launchpad.dto.d.ts.map +1 -1
- package/dist/types/messages.dto.d.ts.map +1 -1
- package/dist/types/moderator.dto.d.ts +10 -18
- package/dist/types/moderator.dto.d.ts.map +1 -1
- package/dist/types/options.dto.d.ts +2 -13
- package/dist/types/options.dto.d.ts.map +1 -1
- package/dist/types/overseer.dto.d.ts +1 -2
- package/dist/types/overseer.dto.d.ts.map +1 -1
- package/dist/types/priceHistory.dto.d.ts +15 -46
- package/dist/types/priceHistory.dto.d.ts.map +1 -1
- package/dist/types/session-auth.dto.d.ts +4 -8
- package/dist/types/session-auth.dto.d.ts.map +1 -1
- package/dist/types/stream-chat.dto.d.ts +14 -105
- package/dist/types/stream-chat.dto.d.ts.map +1 -1
- package/dist/types/streaming.dto.d.ts +30 -119
- package/dist/types/streaming.dto.d.ts.map +1 -1
- package/dist/types/token-ban.dto.d.ts +5 -9
- package/dist/types/token-ban.dto.d.ts.map +1 -1
- package/dist/types/token-config.dto.d.ts +2 -3
- package/dist/types/token-config.dto.d.ts.map +1 -1
- package/dist/types/token.types.d.ts +50 -27
- package/dist/types/token.types.d.ts.map +1 -1
- package/dist/types/trade.dto.d.ts +2 -3
- package/dist/types/trade.dto.d.ts.map +1 -1
- package/dist/types/transfer.dto.d.ts +2 -16
- package/dist/types/transfer.dto.d.ts.map +1 -1
- package/dist/types/user.dto.d.ts +4 -6
- package/dist/types/user.dto.d.ts.map +1 -1
- package/dist/utils/ReconnectionManager.d.ts +0 -1
- package/dist/utils/ReconnectionManager.d.ts.map +1 -1
- package/dist/utils/adapters.d.ts +1 -1
- package/dist/utils/adapters.d.ts.map +1 -1
- package/dist/utils/agent-config.d.ts +17 -14
- package/dist/utils/agent-config.d.ts.map +1 -1
- package/dist/utils/amount-validator.d.ts +1 -1
- package/dist/utils/api-patterns.d.ts.map +1 -1
- package/dist/utils/async-patterns.d.ts.map +1 -1
- package/dist/utils/auto-pagination.d.ts +2 -2
- package/dist/utils/auto-pagination.d.ts.map +1 -1
- package/dist/utils/bignumber-helpers.d.ts +7 -4
- package/dist/utils/bignumber-helpers.d.ts.map +1 -1
- package/dist/utils/bondingCurveCalculations.d.ts +6 -19
- package/dist/utils/bondingCurveCalculations.d.ts.map +1 -1
- package/dist/utils/crypto-compat.d.ts.map +1 -1
- package/dist/utils/data-transform-patterns.d.ts +2 -8
- package/dist/utils/data-transform-patterns.d.ts.map +1 -1
- package/dist/utils/delimiter-parser.d.ts.map +1 -1
- package/dist/utils/error-factories.d.ts.map +1 -1
- package/dist/utils/error-handling-patterns.d.ts +2 -4
- package/dist/utils/error-handling-patterns.d.ts.map +1 -1
- package/dist/utils/error-patterns.d.ts +3 -2
- package/dist/utils/error-patterns.d.ts.map +1 -1
- package/dist/utils/error-utils.d.ts +0 -4
- package/dist/utils/error-utils.d.ts.map +1 -1
- package/dist/utils/errors.d.ts +8 -7
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/http.d.ts +8 -19
- package/dist/utils/http.d.ts.map +1 -1
- package/dist/utils/message-validators.d.ts +13 -0
- package/dist/utils/message-validators.d.ts.map +1 -0
- package/dist/utils/object-extractors.d.ts +1 -1
- package/dist/utils/object-patterns.d.ts +1 -1
- package/dist/utils/object-patterns.d.ts.map +1 -1
- package/dist/utils/pagination-helpers.d.ts +1 -1
- package/dist/utils/pagination-helpers.d.ts.map +1 -1
- package/dist/utils/service-validators.d.ts.map +1 -1
- package/dist/utils/string-transforms.d.ts +1 -1
- package/dist/utils/token-format-converter.d.ts +3 -3
- package/dist/utils/token-format-converter.d.ts.map +1 -1
- package/dist/utils/token-holder-transformer.d.ts +30 -0
- package/dist/utils/token-holder-transformer.d.ts.map +1 -0
- package/dist/utils/token-instance-key.d.ts +57 -0
- package/dist/utils/token-instance-key.d.ts.map +1 -0
- package/dist/utils/token-instance-resolver.d.ts +29 -0
- package/dist/utils/token-instance-resolver.d.ts.map +1 -0
- package/dist/utils/token-operation-details.d.ts +23 -0
- package/dist/utils/token-operation-details.d.ts.map +1 -0
- package/dist/utils/token-stringification.d.ts +0 -1
- package/dist/utils/token-stringification.d.ts.map +1 -1
- package/dist/utils/transfer-validation.d.ts +4 -4
- package/dist/utils/transfer-validation.d.ts.map +1 -1
- package/dist/utils/unique-key-generator.d.ts +31 -32
- package/dist/utils/unique-key-generator.d.ts.map +1 -1
- package/dist/utils/validation-patterns.d.ts +1 -6
- package/dist/utils/validation-patterns.d.ts.map +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/utils/wallet.d.ts +2 -21
- package/dist/utils/wallet.d.ts.map +1 -1
- package/dist/utils/websocket-patterns.d.ts +3 -4
- package/dist/utils/websocket-patterns.d.ts.map +1 -1
- package/dist/wallet/ExternalWalletProvider.d.ts +2 -21
- package/dist/wallet/ExternalWalletProvider.d.ts.map +1 -1
- package/dist/wallet/GalaChainConnectProvider.d.ts +1 -1
- package/dist/wallet/GalaChainConnectProvider.d.ts.map +1 -1
- package/dist/wallet/GalaWalletProvider.d.ts +2 -21
- package/dist/wallet/GalaWalletProvider.d.ts.map +1 -1
- package/dist/wallet/detection.d.ts.map +1 -1
- package/dist/wallet/event-handlers.d.ts +50 -0
- package/dist/wallet/event-handlers.d.ts.map +1 -0
- package/dist/wallet/signing-operation.d.ts +19 -0
- package/dist/wallet/signing-operation.d.ts.map +1 -0
- package/dist/wallet/typed-data-helpers.d.ts +68 -0
- package/dist/wallet/typed-data-helpers.d.ts.map +1 -0
- package/dist/wallet.cjs +1 -1
- package/dist/wallet.esm.js +1 -1
- package/package.json +189 -186
- package/README.md.bak +0 -3174
- package/dist/ai-docs.json +0 -11904
- package/dist/examples/admin/api-key-advanced.d.ts +0 -43
- package/dist/examples/admin/api-key-advanced.d.ts.map +0 -1
- package/dist/examples/admin/moderator-invite-complete.d.ts +0 -41
- package/dist/examples/admin/moderator-invite-complete.d.ts.map +0 -1
- package/dist/examples/admin/overseer-management-advanced.d.ts +0 -38
- package/dist/examples/admin/overseer-management-advanced.d.ts.map +0 -1
- package/dist/examples/admin/overseer-page-stats.d.ts +0 -26
- package/dist/examples/admin/overseer-page-stats.d.ts.map +0 -1
- package/dist/examples/admin/token-ban-complete.d.ts +0 -44
- package/dist/examples/admin/token-ban-complete.d.ts.map +0 -1
- package/dist/examples/ai-moderation/ai-moderation-demo.d.ts +0 -32
- package/dist/examples/ai-moderation/ai-moderation-demo.d.ts.map +0 -1
- package/dist/examples/ai-moderation/flag-ai-verdicts-demo.d.ts +0 -30
- package/dist/examples/ai-moderation/flag-ai-verdicts-demo.d.ts.map +0 -1
- package/dist/examples/analytics/index.d.ts +0 -23
- package/dist/examples/analytics/index.d.ts.map +0 -1
- package/dist/examples/analytics/market-analysis-tools.d.ts +0 -28
- package/dist/examples/analytics/market-analysis-tools.d.ts.map +0 -1
- package/dist/examples/analytics/portfolio-performance-tracking.d.ts +0 -25
- package/dist/examples/analytics/portfolio-performance-tracking.d.ts.map +0 -1
- package/dist/examples/analytics/trading-analytics-advanced.d.ts +0 -27
- package/dist/examples/analytics/trading-analytics-advanced.d.ts.map +0 -1
- package/dist/examples/api-keys/advanced-configuration.d.ts +0 -19
- package/dist/examples/api-keys/advanced-configuration.d.ts.map +0 -1
- package/dist/examples/api-keys/complete-lifecycle.d.ts +0 -18
- package/dist/examples/api-keys/complete-lifecycle.d.ts.map +0 -1
- package/dist/examples/api-keys/crud.d.ts +0 -22
- package/dist/examples/api-keys/crud.d.ts.map +0 -1
- package/dist/examples/api-keys/token-delegation.d.ts +0 -24
- package/dist/examples/api-keys/token-delegation.d.ts.map +0 -1
- package/dist/examples/api-keys/user-api-key-auth.d.ts +0 -24
- package/dist/examples/api-keys/user-api-key-auth.d.ts.map +0 -1
- package/dist/examples/auth/auth-permissions-checking.d.ts +0 -32
- package/dist/examples/auth/auth-permissions-checking.d.ts.map +0 -1
- package/dist/examples/auth/auth-token-management.d.ts +0 -32
- package/dist/examples/auth/auth-token-management.d.ts.map +0 -1
- package/dist/examples/auth/auth-validation-workflows.d.ts +0 -32
- package/dist/examples/auth/auth-validation-workflows.d.ts.map +0 -1
- package/dist/examples/bans/ban-management.d.ts +0 -24
- package/dist/examples/bans/ban-management.d.ts.map +0 -1
- package/dist/examples/bans/demo-global-user-bans.d.ts +0 -27
- package/dist/examples/bans/demo-global-user-bans.d.ts.map +0 -1
- package/dist/examples/bonding/token-graduation-workflow.d.ts +0 -21
- package/dist/examples/bonding/token-graduation-workflow.d.ts.map +0 -1
- package/dist/examples/bonding-curve/basic-trading.d.ts +0 -20
- package/dist/examples/bonding-curve/basic-trading.d.ts.map +0 -1
- package/dist/examples/bonding-curve/graduation-workflow.d.ts +0 -18
- package/dist/examples/bonding-curve/graduation-workflow.d.ts.map +0 -1
- package/dist/examples/bonding-curve/pagination-variants.d.ts +0 -17
- package/dist/examples/bonding-curve/pagination-variants.d.ts.map +0 -1
- package/dist/examples/bonding-curve/pool-analysis.d.ts +0 -18
- package/dist/examples/bonding-curve/pool-analysis.d.ts.map +0 -1
- package/dist/examples/bonding-curve/pool-creator-filtering.d.ts +0 -17
- package/dist/examples/bonding-curve/pool-creator-filtering.d.ts.map +0 -1
- package/dist/examples/bonding-curve/pool-discovery.d.ts +0 -19
- package/dist/examples/bonding-curve/pool-discovery.d.ts.map +0 -1
- package/dist/examples/bonding-curve/price-impact.d.ts +0 -18
- package/dist/examples/bonding-curve/price-impact.d.ts.map +0 -1
- package/dist/examples/bonding-curve/token-launch.d.ts +0 -18
- package/dist/examples/bonding-curve/token-launch.d.ts.map +0 -1
- package/dist/examples/bonding-curve/user-holder-context.d.ts +0 -18
- package/dist/examples/bonding-curve/user-holder-context.d.ts.map +0 -1
- package/dist/examples/bonding-curve/volume-trading.d.ts +0 -18
- package/dist/examples/bonding-curve/volume-trading.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-ethereum-specific.d.ts +0 -18
- package/dist/examples/bridge/bridge-ethereum-specific.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-generic-operations.d.ts +0 -18
- package/dist/examples/bridge/bridge-generic-operations.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-multi-chain-routing.d.ts +0 -31
- package/dist/examples/bridge/bridge-multi-chain-routing.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-network-methods.d.ts +0 -31
- package/dist/examples/bridge/bridge-network-methods.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-network-tokens.d.ts +0 -18
- package/dist/examples/bridge/bridge-network-tokens.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-network-validation.d.ts +0 -33
- package/dist/examples/bridge/bridge-network-validation.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-operations.d.ts +0 -27
- package/dist/examples/bridge/bridge-operations.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-solana-specific.d.ts +0 -18
- package/dist/examples/bridge/bridge-solana-specific.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-status-monitoring.d.ts +0 -30
- package/dist/examples/bridge/bridge-status-monitoring.d.ts.map +0 -1
- package/dist/examples/bridge/bridge-wrapped-token-operations.d.ts +0 -30
- package/dist/examples/bridge/bridge-wrapped-token-operations.d.ts.map +0 -1
- package/dist/examples/bridge/bridgeable-tokens.d.ts +0 -27
- package/dist/examples/bridge/bridgeable-tokens.d.ts.map +0 -1
- package/dist/examples/bridge/check-balances.d.ts +0 -13
- package/dist/examples/bridge/check-balances.d.ts.map +0 -1
- package/dist/examples/bridge/ethereum-in.d.ts +0 -17
- package/dist/examples/bridge/ethereum-in.d.ts.map +0 -1
- package/dist/examples/bridge/ethereum-out.d.ts +0 -17
- package/dist/examples/bridge/ethereum-out.d.ts.map +0 -1
- package/dist/examples/bridge/ethereum-roundtrip.d.ts +0 -20
- package/dist/examples/bridge/ethereum-roundtrip.d.ts.map +0 -1
- package/dist/examples/bridge/external-balances.d.ts +0 -29
- package/dist/examples/bridge/external-balances.d.ts.map +0 -1
- package/dist/examples/bridge/fee-estimation.d.ts +0 -14
- package/dist/examples/bridge/fee-estimation.d.ts.map +0 -1
- package/dist/examples/bridge/solana-in.d.ts +0 -18
- package/dist/examples/bridge/solana-in.d.ts.map +0 -1
- package/dist/examples/bridge/solana-out.d.ts +0 -18
- package/dist/examples/bridge/solana-out.d.ts.map +0 -1
- package/dist/examples/bridge/solana-roundtrip.d.ts +0 -21
- package/dist/examples/bridge/solana-roundtrip.d.ts.map +0 -1
- package/dist/examples/bridge/status-tracking.d.ts +0 -16
- package/dist/examples/bridge/status-tracking.d.ts.map +0 -1
- package/dist/examples/bridge/supported-tokens.d.ts +0 -14
- package/dist/examples/bridge/supported-tokens.d.ts.map +0 -1
- package/dist/examples/bridge/test-debug-unwrap.d.ts +0 -13
- package/dist/examples/bridge/test-debug-unwrap.d.ts.map +0 -1
- package/dist/examples/bridge/test-unwrap-execution.d.ts +0 -13
- package/dist/examples/bridge/test-unwrap-execution.d.ts.map +0 -1
- package/dist/examples/bridge/test-wrap-debug.d.ts +0 -13
- package/dist/examples/bridge/test-wrap-debug.d.ts.map +0 -1
- package/dist/examples/bridge/test-wrap-execution.d.ts +0 -13
- package/dist/examples/bridge/test-wrap-execution.d.ts.map +0 -1
- package/dist/examples/bridge/test-wrap-roundtrip.d.ts +0 -13
- package/dist/examples/bridge/test-wrap-roundtrip.d.ts.map +0 -1
- package/dist/examples/bridge/transaction-status.d.ts +0 -26
- package/dist/examples/bridge/transaction-status.d.ts.map +0 -1
- package/dist/examples/bridge/wallet-balances.d.ts +0 -24
- package/dist/examples/bridge/wallet-balances.d.ts.map +0 -1
- package/dist/examples/bridge/wrap-discovery.d.ts +0 -16
- package/dist/examples/bridge/wrap-discovery.d.ts.map +0 -1
- package/dist/examples/bridge/wrap-fee-estimation.d.ts +0 -16
- package/dist/examples/bridge/wrap-fee-estimation.d.ts.map +0 -1
- package/dist/examples/bridge/wrap-unwrap.d.ts +0 -18
- package/dist/examples/bridge/wrap-unwrap.d.ts.map +0 -1
- package/dist/examples/bridge/wrap-utilities.d.ts +0 -21
- package/dist/examples/bridge/wrap-utilities.d.ts.map +0 -1
- package/dist/examples/calculations/calculation-methods-comprehensive.d.ts +0 -24
- package/dist/examples/calculations/calculation-methods-comprehensive.d.ts.map +0 -1
- package/dist/examples/calculations/external-calculations-demo.d.ts +0 -23
- package/dist/examples/calculations/external-calculations-demo.d.ts.map +0 -1
- package/dist/examples/calculations/local-calculations-demo.d.ts +0 -24
- package/dist/examples/calculations/local-calculations-demo.d.ts.map +0 -1
- package/dist/examples/calculations/pool-calculation-context.d.ts +0 -19
- package/dist/examples/calculations/pool-calculation-context.d.ts.map +0 -1
- package/dist/examples/chat/basic-chat.d.ts +0 -17
- package/dist/examples/chat/basic-chat.d.ts.map +0 -1
- package/dist/examples/chat/chat-admin-controls.d.ts +0 -41
- package/dist/examples/chat/chat-admin-controls.d.ts.map +0 -1
- package/dist/examples/chat/chat-demo.d.ts +0 -25
- package/dist/examples/chat/chat-demo.d.ts.map +0 -1
- package/dist/examples/chat/chat-engagement-stats.d.ts +0 -44
- package/dist/examples/chat/chat-engagement-stats.d.ts.map +0 -1
- package/dist/examples/chat/chat-lifecycle.d.ts +0 -26
- package/dist/examples/chat/chat-lifecycle.d.ts.map +0 -1
- package/dist/examples/chat/chat-message-management.d.ts +0 -18
- package/dist/examples/chat/chat-message-management.d.ts.map +0 -1
- package/dist/examples/chat/chat-pinning-workflow.d.ts +0 -37
- package/dist/examples/chat/chat-pinning-workflow.d.ts.map +0 -1
- package/dist/examples/chat/demo-pin-messages.d.ts +0 -17
- package/dist/examples/chat/demo-pin-messages.d.ts.map +0 -1
- package/dist/examples/chat/multi-user-chat-test.d.ts +0 -19
- package/dist/examples/chat/multi-user-chat-test.d.ts.map +0 -1
- package/dist/examples/chat/quick-reaction-test.d.ts +0 -4
- package/dist/examples/chat/quick-reaction-test.d.ts.map +0 -1
- package/dist/examples/chat/typing-indicators.d.ts +0 -23
- package/dist/examples/chat/typing-indicators.d.ts.map +0 -1
- package/dist/examples/chat/websocket-chat.d.ts +0 -21
- package/dist/examples/chat/websocket-chat.d.ts.map +0 -1
- package/dist/examples/comments/basic-comments.d.ts +0 -19
- package/dist/examples/comments/basic-comments.d.ts.map +0 -1
- package/dist/examples/comments/comments-demo.d.ts +0 -34
- package/dist/examples/comments/comments-demo.d.ts.map +0 -1
- package/dist/examples/comments/comments-lifecycle.d.ts +0 -24
- package/dist/examples/comments/comments-lifecycle.d.ts.map +0 -1
- package/dist/examples/comments/comments-update-workflow.d.ts +0 -35
- package/dist/examples/comments/comments-update-workflow.d.ts.map +0 -1
- package/dist/examples/content/content-categorization.d.ts +0 -51
- package/dist/examples/content/content-categorization.d.ts.map +0 -1
- package/dist/examples/content/content-publishing-workflow.d.ts +0 -45
- package/dist/examples/content/content-publishing-workflow.d.ts.map +0 -1
- package/dist/examples/content/content-versioning.d.ts +0 -52
- package/dist/examples/content/content-versioning.d.ts.map +0 -1
- package/dist/examples/content-flags/comprehensive-flag-workflow.d.ts +0 -40
- package/dist/examples/content-flags/comprehensive-flag-workflow.d.ts.map +0 -1
- package/dist/examples/content-flags/flag-management.d.ts +0 -28
- package/dist/examples/content-flags/flag-management.d.ts.map +0 -1
- package/dist/examples/content-reactions/advanced-reactions.d.ts +0 -24
- package/dist/examples/content-reactions/advanced-reactions.d.ts.map +0 -1
- package/dist/examples/content-reactions/basic-reactions.d.ts +0 -21
- package/dist/examples/content-reactions/basic-reactions.d.ts.map +0 -1
- package/dist/examples/content-reactions/comprehensive-reactions-workflow.d.ts +0 -41
- package/dist/examples/content-reactions/comprehensive-reactions-workflow.d.ts.map +0 -1
- package/dist/examples/content-reactions/content-reactions-advanced.d.ts +0 -40
- package/dist/examples/content-reactions/content-reactions-advanced.d.ts.map +0 -1
- package/dist/examples/core/authenticated-operations.d.ts +0 -14
- package/dist/examples/core/authenticated-operations.d.ts.map +0 -1
- package/dist/examples/core/complete-sdk-demo.d.ts +0 -22
- package/dist/examples/core/complete-sdk-demo.d.ts.map +0 -1
- package/dist/examples/core/image-uploads.d.ts +0 -28
- package/dist/examples/core/image-uploads.d.ts.map +0 -1
- package/dist/examples/core/privatekey-override-pattern.d.ts +0 -16
- package/dist/examples/core/privatekey-override-pattern.d.ts.map +0 -1
- package/dist/examples/core/read-only-operations.d.ts +0 -16
- package/dist/examples/core/read-only-operations.d.ts.map +0 -1
- package/dist/examples/core/session-auth-demo.d.ts +0 -15
- package/dist/examples/core/session-auth-demo.d.ts.map +0 -1
- package/dist/examples/core/session-auth-lifecycle.d.ts +0 -19
- package/dist/examples/core/session-auth-lifecycle.d.ts.map +0 -1
- package/dist/examples/core/test-pagination-fix.d.ts +0 -14
- package/dist/examples/core/test-pagination-fix.d.ts.map +0 -1
- package/dist/examples/core/token-refresh-utilities.d.ts +0 -18
- package/dist/examples/core/token-refresh-utilities.d.ts.map +0 -1
- package/dist/examples/core/token-validation.d.ts +0 -18
- package/dist/examples/core/token-validation.d.ts.map +0 -1
- package/dist/examples/core/wallet-management.d.ts +0 -23
- package/dist/examples/core/wallet-management.d.ts.map +0 -1
- package/dist/examples/debug/check-recorded-bridge-tx.d.ts +0 -8
- package/dist/examples/debug/check-recorded-bridge-tx.d.ts.map +0 -1
- package/dist/examples/debug/debug-comment.d.ts +0 -2
- package/dist/examples/debug/debug-comment.d.ts.map +0 -1
- package/dist/examples/debug/test-volume-data-bounds-prod.d.ts +0 -15
- package/dist/examples/debug/test-volume-data-bounds-prod.d.ts.map +0 -1
- package/dist/examples/debug/test-volume-data-bounds.d.ts +0 -14
- package/dist/examples/debug/test-volume-data-bounds.d.ts.map +0 -1
- package/dist/examples/debug/websocket-event-discovery.d.ts +0 -26
- package/dist/examples/debug/websocket-event-discovery.d.ts.map +0 -1
- package/dist/examples/debug/websocket-monitor.d.ts +0 -15
- package/dist/examples/debug/websocket-monitor.d.ts.map +0 -1
- package/dist/examples/debug-single-trade.d.ts +0 -6
- package/dist/examples/debug-single-trade.d.ts.map +0 -1
- package/dist/examples/demo-librarian.d.ts +0 -18
- package/dist/examples/demo-librarian.d.ts.map +0 -1
- package/dist/examples/demo-runner.d.ts +0 -22
- package/dist/examples/demo-runner.d.ts.map +0 -1
- package/dist/examples/dex/demo-roundtrip-liquidity.d.ts +0 -16
- package/dist/examples/dex/demo-roundtrip-liquidity.d.ts.map +0 -1
- package/dist/examples/dex/dex-impermanent-loss-analysis.d.ts +0 -28
- package/dist/examples/dex/dex-impermanent-loss-analysis.d.ts.map +0 -1
- package/dist/examples/dex/dex-liquidity-management-advanced.d.ts +0 -27
- package/dist/examples/dex/dex-liquidity-management-advanced.d.ts.map +0 -1
- package/dist/examples/dex/dex-multi-hop-swaps.d.ts +0 -32
- package/dist/examples/dex/dex-multi-hop-swaps.d.ts.map +0 -1
- package/dist/examples/dex/dex-pool-pricing.d.ts +0 -20
- package/dist/examples/dex/dex-pool-pricing.d.ts.map +0 -1
- package/dist/examples/dex/dex-quote-calculations.d.ts +0 -21
- package/dist/examples/dex/dex-quote-calculations.d.ts.map +0 -1
- package/dist/examples/dex/dex-seasons-leaderboard.d.ts +0 -22
- package/dist/examples/dex/dex-seasons-leaderboard.d.ts.map +0 -1
- package/dist/examples/dex/dex-slippage-protection.d.ts +0 -28
- package/dist/examples/dex/dex-slippage-protection.d.ts.map +0 -1
- package/dist/examples/dex/dex-tokens-discovery.d.ts +0 -20
- package/dist/examples/dex/dex-tokens-discovery.d.ts.map +0 -1
- package/dist/examples/dex/dex-volume-analytics.d.ts +0 -19
- package/dist/examples/dex/dex-volume-analytics.d.ts.map +0 -1
- package/dist/examples/dex/leaderboard.d.ts +0 -12
- package/dist/examples/dex/leaderboard.d.ts.map +0 -1
- package/dist/examples/dex/pool-discovery.d.ts +0 -25
- package/dist/examples/dex/pool-discovery.d.ts.map +0 -1
- package/dist/examples/dex/pools-with-pricing.d.ts +0 -28
- package/dist/examples/dex/pools-with-pricing.d.ts.map +0 -1
- package/dist/examples/dex/quote-comparison.d.ts +0 -16
- package/dist/examples/dex/quote-comparison.d.ts.map +0 -1
- package/dist/examples/dex/swap-user-assets-comprehensive.d.ts +0 -20
- package/dist/examples/dex/swap-user-assets-comprehensive.d.ts.map +0 -1
- package/dist/examples/dex/swap-workflow.d.ts +0 -20
- package/dist/examples/dex/swap-workflow.d.ts.map +0 -1
- package/dist/examples/dex/token-discovery.d.ts +0 -27
- package/dist/examples/dex/token-discovery.d.ts.map +0 -1
- package/dist/examples/dex/volume-summary.d.ts +0 -12
- package/dist/examples/dex/volume-summary.d.ts.map +0 -1
- package/dist/examples/error-handling/error-recovery-patterns.d.ts +0 -42
- package/dist/examples/error-handling/error-recovery-patterns.d.ts.map +0 -1
- package/dist/examples/error-handling/timeout-management.d.ts +0 -43
- package/dist/examples/error-handling/timeout-management.d.ts.map +0 -1
- package/dist/examples/events/event-aggregation-analysis.d.ts +0 -40
- package/dist/examples/events/event-aggregation-analysis.d.ts.map +0 -1
- package/dist/examples/events/event-emission-patterns.d.ts +0 -35
- package/dist/examples/events/event-emission-patterns.d.ts.map +0 -1
- package/dist/examples/events/subscription-management-advanced.d.ts +0 -38
- package/dist/examples/events/subscription-management-advanced.d.ts.map +0 -1
- package/dist/examples/fees/complete-fee-test.d.ts +0 -13
- package/dist/examples/fees/complete-fee-test.d.ts.map +0 -1
- package/dist/examples/fees/demo-fee-generation-and-collection.d.ts +0 -27
- package/dist/examples/fees/demo-fee-generation-and-collection.d.ts.map +0 -1
- package/dist/examples/fees/demo-fees-high-volume.d.ts +0 -13
- package/dist/examples/fees/demo-fees-high-volume.d.ts.map +0 -1
- package/dist/examples/fees/demo-multi-wallet-fee-generation.d.ts +0 -13
- package/dist/examples/fees/demo-multi-wallet-fee-generation.d.ts.map +0 -1
- package/dist/examples/fees/trade-and-collect-fees.d.ts +0 -13
- package/dist/examples/fees/trade-and-collect-fees.d.ts.map +0 -1
- package/dist/examples/galachain/bundler-transactions.d.ts +0 -28
- package/dist/examples/galachain/bundler-transactions.d.ts.map +0 -1
- package/dist/examples/galachain/galachain-token-resolution.d.ts +0 -28
- package/dist/examples/galachain/galachain-token-resolution.d.ts.map +0 -1
- package/dist/examples/galachain/galachain-tokens.d.ts +0 -28
- package/dist/examples/galachain/galachain-tokens.d.ts.map +0 -1
- package/dist/examples/galachain/galachain-transfers.d.ts +0 -25
- package/dist/examples/galachain/galachain-transfers.d.ts.map +0 -1
- package/dist/examples/global-feed-demo.d.ts +0 -17
- package/dist/examples/global-feed-demo.d.ts.map +0 -1
- package/dist/examples/global-feed-filtering-demo.d.ts +0 -20
- package/dist/examples/global-feed-filtering-demo.d.ts.map +0 -1
- package/dist/examples/launchpad/demo-socials.d.ts +0 -16
- package/dist/examples/launchpad/demo-socials.d.ts.map +0 -1
- package/dist/examples/launchpad/fetch-token-stats.d.ts +0 -18
- package/dist/examples/launchpad/fetch-token-stats.d.ts.map +0 -1
- package/dist/examples/launchpad/update-token-config.d.ts +0 -17
- package/dist/examples/launchpad/update-token-config.d.ts.map +0 -1
- package/dist/examples/liquidity/apr-calculator.d.ts +0 -18
- package/dist/examples/liquidity/apr-calculator.d.ts.map +0 -1
- package/dist/examples/liquidity/demo-bundler-operations.d.ts +0 -15
- package/dist/examples/liquidity/demo-bundler-operations.d.ts.map +0 -1
- package/dist/examples/liquidity/demo-fetch-all-positions.d.ts +0 -2
- package/dist/examples/liquidity/demo-fetch-all-positions.d.ts.map +0 -1
- package/dist/examples/liquidity/demo-position-direct.d.ts +0 -14
- package/dist/examples/liquidity/demo-position-direct.d.ts.map +0 -1
- package/dist/examples/liquidity/demo-positions-with-chunked-pricing.d.ts +0 -26
- package/dist/examples/liquidity/demo-positions-with-chunked-pricing.d.ts.map +0 -1
- package/dist/examples/liquidity/demo-roundtrip-remove.d.ts +0 -21
- package/dist/examples/liquidity/demo-roundtrip-remove.d.ts.map +0 -1
- package/dist/examples/liquidity/detailed.d.ts +0 -21
- package/dist/examples/liquidity/detailed.d.ts.map +0 -1
- package/dist/examples/liquidity/errors.d.ts +0 -18
- package/dist/examples/liquidity/errors.d.ts.map +0 -1
- package/dist/examples/liquidity/fee-collection.d.ts +0 -22
- package/dist/examples/liquidity/fee-collection.d.ts.map +0 -1
- package/dist/examples/liquidity/liquidity-position-details.d.ts +0 -21
- package/dist/examples/liquidity/liquidity-position-details.d.ts.map +0 -1
- package/dist/examples/liquidity/liquidity-removal-estimation.d.ts +0 -19
- package/dist/examples/liquidity/liquidity-removal-estimation.d.ts.map +0 -1
- package/dist/examples/liquidity/multi-position.d.ts +0 -22
- package/dist/examples/liquidity/multi-position.d.ts.map +0 -1
- package/dist/examples/liquidity/positions-cli.d.ts +0 -41
- package/dist/examples/liquidity/positions-cli.d.ts.map +0 -1
- package/dist/examples/liquidity/ticks.d.ts +0 -18
- package/dist/examples/liquidity/ticks.d.ts.map +0 -1
- package/dist/examples/locks/burn-tokens.d.ts +0 -25
- package/dist/examples/locks/burn-tokens.d.ts.map +0 -1
- package/dist/examples/locks/lock-unlock-workflow.d.ts +0 -20
- package/dist/examples/locks/lock-unlock-workflow.d.ts.map +0 -1
- package/dist/examples/messages/messages-lifecycle.d.ts +0 -37
- package/dist/examples/messages/messages-lifecycle.d.ts.map +0 -1
- package/dist/examples/messages/messages-pinning.d.ts +0 -37
- package/dist/examples/messages/messages-pinning.d.ts.map +0 -1
- package/dist/examples/moderators/claim-invite.d.ts +0 -28
- package/dist/examples/moderators/claim-invite.d.ts.map +0 -1
- package/dist/examples/moderators/invite-management.d.ts +0 -30
- package/dist/examples/moderators/invite-management.d.ts.map +0 -1
- package/dist/examples/moderators/moderated-tokens-portfolio.d.ts +0 -18
- package/dist/examples/moderators/moderated-tokens-portfolio.d.ts.map +0 -1
- package/dist/examples/monitoring/demo-stream-events.d.ts +0 -17
- package/dist/examples/monitoring/demo-stream-events.d.ts.map +0 -1
- package/dist/examples/monitoring/demo-watch-pools.d.ts +0 -18
- package/dist/examples/monitoring/demo-watch-pools.d.ts.map +0 -1
- package/dist/examples/monitoring/demo-watch-tokens.d.ts +0 -18
- package/dist/examples/monitoring/demo-watch-tokens.d.ts.map +0 -1
- package/dist/examples/monitoring/fees-collection-e2e.d.ts +0 -36
- package/dist/examples/monitoring/fees-collection-e2e.d.ts.map +0 -1
- package/dist/examples/monitoring/fees-collection-guaranteed.d.ts +0 -49
- package/dist/examples/monitoring/fees-collection-guaranteed.d.ts.map +0 -1
- package/dist/examples/monitoring/liquidity-e2e-test.d.ts +0 -15
- package/dist/examples/monitoring/liquidity-e2e-test.d.ts.map +0 -1
- package/dist/examples/monitoring/liquidity-monitor.d.ts +0 -17
- package/dist/examples/monitoring/liquidity-monitor.d.ts.map +0 -1
- package/dist/examples/monitoring/pool-creation-integration.d.ts +0 -27
- package/dist/examples/monitoring/pool-creation-integration.d.ts.map +0 -1
- package/dist/examples/monitoring/pool-liquidity-tracker.d.ts +0 -15
- package/dist/examples/monitoring/pool-liquidity-tracker.d.ts.map +0 -1
- package/dist/examples/monitoring/subscribe-liquidity-added.d.ts +0 -30
- package/dist/examples/monitoring/subscribe-liquidity-added.d.ts.map +0 -1
- package/dist/examples/monitoring/subscribe-liquidity-removed.d.ts +0 -30
- package/dist/examples/monitoring/subscribe-liquidity-removed.d.ts.map +0 -1
- package/dist/examples/monitoring/subscribe-pool-creations.d.ts +0 -29
- package/dist/examples/monitoring/subscribe-pool-creations.d.ts.map +0 -1
- package/dist/examples/monitoring/subscribe-token-creations.d.ts +0 -21
- package/dist/examples/monitoring/subscribe-token-creations.d.ts.map +0 -1
- package/dist/examples/monitoring/token-creation-integration.d.ts +0 -32
- package/dist/examples/monitoring/token-creation-integration.d.ts.map +0 -1
- package/dist/examples/monitoring/websocket-event-handlers.d.ts +0 -22
- package/dist/examples/monitoring/websocket-event-handlers.d.ts.map +0 -1
- package/dist/examples/nft/demo-collection-management.d.ts +0 -13
- package/dist/examples/nft/demo-collection-management.d.ts.map +0 -1
- package/dist/examples/nft/demo-fee-calculations.d.ts +0 -14
- package/dist/examples/nft/demo-fee-calculations.d.ts.map +0 -1
- package/dist/examples/nft/demo-minting.d.ts +0 -13
- package/dist/examples/nft/demo-minting.d.ts.map +0 -1
- package/dist/examples/nft/demo-portfolio-query.d.ts +0 -14
- package/dist/examples/nft/demo-portfolio-query.d.ts.map +0 -1
- package/dist/examples/nft/nft-collection-lifecycle.d.ts +0 -22
- package/dist/examples/nft/nft-collection-lifecycle.d.ts.map +0 -1
- package/dist/examples/nft/nft-data-queries.d.ts +0 -22
- package/dist/examples/nft/nft-data-queries.d.ts.map +0 -1
- package/dist/examples/nft/nft-fee-estimation.d.ts +0 -23
- package/dist/examples/nft/nft-fee-estimation.d.ts.map +0 -1
- package/dist/examples/nft/nft-token-creation.d.ts +0 -22
- package/dist/examples/nft/nft-token-creation.d.ts.map +0 -1
- package/dist/examples/nft/nft-utilities.d.ts +0 -23
- package/dist/examples/nft/nft-utilities.d.ts.map +0 -1
- package/dist/examples/orchestrator-master.d.ts +0 -22
- package/dist/examples/orchestrator-master.d.ts.map +0 -1
- package/dist/examples/orchestrator-tasks.d.ts +0 -38
- package/dist/examples/orchestrator-tasks.d.ts.map +0 -1
- package/dist/examples/overseers/claim-invite.d.ts +0 -31
- package/dist/examples/overseers/claim-invite.d.ts.map +0 -1
- package/dist/examples/overseers/demo-list-users.d.ts +0 -19
- package/dist/examples/overseers/demo-list-users.d.ts.map +0 -1
- package/dist/examples/overseers/direct-promotion.d.ts +0 -39
- package/dist/examples/overseers/direct-promotion.d.ts.map +0 -1
- package/dist/examples/overseers/invite-management.d.ts +0 -38
- package/dist/examples/overseers/invite-management.d.ts.map +0 -1
- package/dist/examples/overseers/restricted-names-management.d.ts +0 -27
- package/dist/examples/overseers/restricted-names-management.d.ts.map +0 -1
- package/dist/examples/performance/caching-strategies-advanced.d.ts +0 -28
- package/dist/examples/performance/caching-strategies-advanced.d.ts.map +0 -1
- package/dist/examples/performance/performance-optimization-patterns.d.ts +0 -28
- package/dist/examples/performance/performance-optimization-patterns.d.ts.map +0 -1
- package/dist/examples/persistence/data-backup-recovery.d.ts +0 -119
- package/dist/examples/persistence/data-backup-recovery.d.ts.map +0 -1
- package/dist/examples/persistence/local-storage-patterns.d.ts +0 -86
- package/dist/examples/persistence/local-storage-patterns.d.ts.map +0 -1
- package/dist/examples/queries/advanced-sorting.d.ts +0 -28
- package/dist/examples/queries/advanced-sorting.d.ts.map +0 -1
- package/dist/examples/queries/complex-filtering.d.ts +0 -27
- package/dist/examples/queries/complex-filtering.d.ts.map +0 -1
- package/dist/examples/security/security-audit-trail.d.ts +0 -42
- package/dist/examples/security/security-audit-trail.d.ts.map +0 -1
- package/dist/examples/security/security-content-moderation-advanced.d.ts +0 -42
- package/dist/examples/security/security-content-moderation-advanced.d.ts.map +0 -1
- package/dist/examples/security/security-token-safety-checks.d.ts +0 -41
- package/dist/examples/security/security-token-safety-checks.d.ts.map +0 -1
- package/dist/examples/security/security-user-restrictions-advanced.d.ts +0 -42
- package/dist/examples/security/security-user-restrictions-advanced.d.ts.map +0 -1
- package/dist/examples/site-config-demo.d.ts +0 -20
- package/dist/examples/site-config-demo.d.ts.map +0 -1
- package/dist/examples/streaming/admin-controls.d.ts +0 -30
- package/dist/examples/streaming/admin-controls.d.ts.map +0 -1
- package/dist/examples/streaming/advanced-stream-demo.d.ts +0 -28
- package/dist/examples/streaming/advanced-stream-demo.d.ts.map +0 -1
- package/dist/examples/streaming/basic-stream.d.ts +0 -17
- package/dist/examples/streaming/basic-stream.d.ts.map +0 -1
- package/dist/examples/streaming/demo-countdown.d.ts +0 -16
- package/dist/examples/streaming/demo-countdown.d.ts.map +0 -1
- package/dist/examples/streaming/demo-get-stream-credentials.d.ts +0 -29
- package/dist/examples/streaming/demo-get-stream-credentials.d.ts.map +0 -1
- package/dist/examples/streaming/demo-platform-config.d.ts +0 -20
- package/dist/examples/streaming/demo-platform-config.d.ts.map +0 -1
- package/dist/examples/streaming/engagement-stats.d.ts +0 -25
- package/dist/examples/streaming/engagement-stats.d.ts.map +0 -1
- package/dist/examples/streaming/recordings.d.ts +0 -16
- package/dist/examples/streaming/recordings.d.ts.map +0 -1
- package/dist/examples/streaming/simulcast.d.ts +0 -19
- package/dist/examples/streaming/simulcast.d.ts.map +0 -1
- package/dist/examples/streaming/stream-access-control.d.ts +0 -30
- package/dist/examples/streaming/stream-access-control.d.ts.map +0 -1
- package/dist/examples/streaming/stream-control.d.ts +0 -25
- package/dist/examples/streaming/stream-control.d.ts.map +0 -1
- package/dist/examples/streaming/stream-countdown.d.ts +0 -31
- package/dist/examples/streaming/stream-countdown.d.ts.map +0 -1
- package/dist/examples/streaming/stream-enable-disable.d.ts +0 -31
- package/dist/examples/streaming/stream-enable-disable.d.ts.map +0 -1
- package/dist/examples/streaming/stream-key-management.d.ts +0 -21
- package/dist/examples/streaming/stream-key-management.d.ts.map +0 -1
- package/dist/examples/streaming/stream-recording-management.d.ts +0 -29
- package/dist/examples/streaming/stream-recording-management.d.ts.map +0 -1
- package/dist/examples/streaming/stream-simulcast-multi-platform.d.ts +0 -38
- package/dist/examples/streaming/stream-simulcast-multi-platform.d.ts.map +0 -1
- package/dist/examples/streaming/stream-viewer-analytics.d.ts +0 -43
- package/dist/examples/streaming/stream-viewer-analytics.d.ts.map +0 -1
- package/dist/examples/streaming/streaming-lifecycle.d.ts +0 -26
- package/dist/examples/streaming/streaming-lifecycle.d.ts.map +0 -1
- package/dist/examples/streaming-premium/stream-monetization-setup.d.ts +0 -47
- package/dist/examples/streaming-premium/stream-monetization-setup.d.ts.map +0 -1
- package/dist/examples/streaming-premium/stream-revenue-analytics.d.ts +0 -56
- package/dist/examples/streaming-premium/stream-revenue-analytics.d.ts.map +0 -1
- package/dist/examples/streaming-premium/stream-vip-management.d.ts +0 -56
- package/dist/examples/streaming-premium/stream-vip-management.d.ts.map +0 -1
- package/dist/examples/swap-monitoring/arbitrage-monitor.d.ts +0 -20
- package/dist/examples/swap-monitoring/arbitrage-monitor.d.ts.map +0 -1
- package/dist/examples/swap-monitoring/e2e-trading-demo.d.ts +0 -50
- package/dist/examples/swap-monitoring/e2e-trading-demo.d.ts.map +0 -1
- package/dist/examples/swap-monitoring/health-monitor.d.ts +0 -10
- package/dist/examples/swap-monitoring/health-monitor.d.ts.map +0 -1
- package/dist/examples/swap-monitoring/volume-monitor.d.ts +0 -20
- package/dist/examples/swap-monitoring/volume-monitor.d.ts.map +0 -1
- package/dist/examples/testing/demo-test-runner.d.ts +0 -33
- package/dist/examples/testing/demo-test-runner.d.ts.map +0 -1
- package/dist/examples/testing/error-classifier.d.ts +0 -23
- package/dist/examples/testing/error-classifier.d.ts.map +0 -1
- package/dist/examples/testing/index.d.ts +0 -14
- package/dist/examples/testing/index.d.ts.map +0 -1
- package/dist/examples/testing/memory-manager.d.ts +0 -31
- package/dist/examples/testing/memory-manager.d.ts.map +0 -1
- package/dist/examples/testing/report-generator.d.ts +0 -31
- package/dist/examples/testing/report-generator.d.ts.map +0 -1
- package/dist/examples/testing/test-result-types.d.ts +0 -158
- package/dist/examples/testing/test-result-types.d.ts.map +0 -1
- package/dist/examples/token-bans/token-ban-management.d.ts +0 -32
- package/dist/examples/token-bans/token-ban-management.d.ts.map +0 -1
- package/dist/examples/token-creation/token-launch-complete.d.ts +0 -20
- package/dist/examples/token-creation/token-launch-complete.d.ts.map +0 -1
- package/dist/examples/token-creation/token-validation-comprehensive.d.ts +0 -22
- package/dist/examples/token-creation/token-validation-comprehensive.d.ts.map +0 -1
- package/dist/examples/token-info/token-name-resolution.d.ts +0 -30
- package/dist/examples/token-info/token-name-resolution.d.ts.map +0 -1
- package/dist/examples/token-info/token-operations-comprehensive.d.ts +0 -22
- package/dist/examples/token-info/token-operations-comprehensive.d.ts.map +0 -1
- package/dist/examples/token-metadata/token-description-versioning.d.ts +0 -33
- package/dist/examples/token-metadata/token-description-versioning.d.ts.map +0 -1
- package/dist/examples/token-metadata/token-image-management.d.ts +0 -34
- package/dist/examples/token-metadata/token-image-management.d.ts.map +0 -1
- package/dist/examples/token-metadata/token-social-links-management.d.ts +0 -34
- package/dist/examples/token-metadata/token-social-links-management.d.ts.map +0 -1
- package/dist/examples/trading/buy-sell-aliases.d.ts +0 -20
- package/dist/examples/trading/buy-sell-aliases.d.ts.map +0 -1
- package/dist/examples/trading/volume-data-demo.d.ts +0 -20
- package/dist/examples/trading/volume-data-demo.d.ts.map +0 -1
- package/dist/examples/trading-advanced/dollar-cost-averaging.d.ts +0 -35
- package/dist/examples/trading-advanced/dollar-cost-averaging.d.ts.map +0 -1
- package/dist/examples/trading-advanced/limit-orders-advanced.d.ts +0 -34
- package/dist/examples/trading-advanced/limit-orders-advanced.d.ts.map +0 -1
- package/dist/examples/trading-advanced/stop-loss-orders.d.ts +0 -34
- package/dist/examples/trading-advanced/stop-loss-orders.d.ts.map +0 -1
- package/dist/examples/trading-advanced/trading-history-analysis.d.ts +0 -35
- package/dist/examples/trading-advanced/trading-history-analysis.d.ts.map +0 -1
- package/dist/examples/users/balance-queries.d.ts +0 -28
- package/dist/examples/users/balance-queries.d.ts.map +0 -1
- package/dist/examples/users/fetch-user-balances.d.ts +0 -19
- package/dist/examples/users/fetch-user-balances.d.ts.map +0 -1
- package/dist/examples/users/fetch-user-report.d.ts +0 -21
- package/dist/examples/users/fetch-user-report.d.ts.map +0 -1
- package/dist/examples/users/profile-images.d.ts +0 -24
- package/dist/examples/users/profile-images.d.ts.map +0 -1
- package/dist/examples/users/profile-management.d.ts +0 -22
- package/dist/examples/users/profile-management.d.ts.map +0 -1
- package/dist/examples/users/referrals-comprehensive.d.ts +0 -26
- package/dist/examples/users/referrals-comprehensive.d.ts.map +0 -1
- package/dist/examples/users/wallet-balances-external.d.ts +0 -28
- package/dist/examples/users/wallet-balances-external.d.ts.map +0 -1
- package/dist/examples/utilities/account.d.ts +0 -19
- package/dist/examples/utilities/account.d.ts.map +0 -1
- package/dist/examples/utilities/balance.d.ts +0 -5
- package/dist/examples/utilities/balance.d.ts.map +0 -1
- package/dist/examples/utilities/balances.d.ts +0 -7
- package/dist/examples/utilities/balances.d.ts.map +0 -1
- package/dist/examples/utilities/demo-cache.d.ts +0 -13
- package/dist/examples/utilities/demo-cache.d.ts.map +0 -1
- package/dist/examples/utilities/demo-token-supply.d.ts +0 -14
- package/dist/examples/utilities/demo-token-supply.d.ts.map +0 -1
- package/dist/examples/utilities/key-derivation.d.ts +0 -12
- package/dist/examples/utilities/key-derivation.d.ts.map +0 -1
- package/dist/examples/utilities/multi-token-portfolio.d.ts +0 -18
- package/dist/examples/utilities/multi-token-portfolio.d.ts.map +0 -1
- package/dist/examples/utilities/pool-discovery-advanced.d.ts +0 -36
- package/dist/examples/utilities/pool-discovery-advanced.d.ts.map +0 -1
- package/dist/examples/utilities/pool-pair-analysis.d.ts +0 -37
- package/dist/examples/utilities/pool-pair-analysis.d.ts.map +0 -1
- package/dist/examples/utilities/price-history.d.ts +0 -22
- package/dist/examples/utilities/price-history.d.ts.map +0 -1
- package/dist/examples/utilities/referrals.d.ts +0 -21
- package/dist/examples/utilities/referrals.d.ts.map +0 -1
- package/dist/examples/utilities/token-classification.d.ts +0 -38
- package/dist/examples/utilities/token-classification.d.ts.map +0 -1
- package/dist/examples/utilities/token-discovery.d.ts +0 -26
- package/dist/examples/utilities/token-discovery.d.ts.map +0 -1
- package/dist/examples/utilities/token-metadata-advanced.d.ts +0 -37
- package/dist/examples/utilities/token-metadata-advanced.d.ts.map +0 -1
- package/dist/examples/utilities/token-validation-complete.d.ts +0 -41
- package/dist/examples/utilities/token-validation-complete.d.ts.map +0 -1
- package/dist/examples/utilities/trade-history.d.ts +0 -19
- package/dist/examples/utilities/trade-history.d.ts.map +0 -1
- package/dist/examples/utilities/transfers.d.ts +0 -29
- package/dist/examples/utilities/transfers.d.ts.map +0 -1
- package/dist/examples/utilities/validation-and-error-handling.d.ts +0 -27
- package/dist/examples/utilities/validation-and-error-handling.d.ts.map +0 -1
- package/dist/examples/utilities/wrappable-tokens.d.ts +0 -27
- package/dist/examples/utilities/wrappable-tokens.d.ts.map +0 -1
- package/dist/examples/utility/auth-utilities.d.ts +0 -30
- package/dist/examples/utility/auth-utilities.d.ts.map +0 -1
- package/dist/examples/utility/pool-utilities.d.ts +0 -29
- package/dist/examples/utility/pool-utilities.d.ts.map +0 -1
- package/dist/examples/utility/sdk-configuration.d.ts +0 -29
- package/dist/examples/utility/sdk-configuration.d.ts.map +0 -1
- package/dist/examples/utility/wallet-management-advanced.d.ts +0 -32
- package/dist/examples/utility/wallet-management-advanced.d.ts.map +0 -1
- package/dist/examples/utils/auth-bootstrap.d.ts +0 -123
- package/dist/examples/utils/auth-bootstrap.d.ts.map +0 -1
- package/dist/examples/utils/balance-checking.d.ts +0 -158
- package/dist/examples/utils/balance-checking.d.ts.map +0 -1
- package/dist/examples/utils/bridge-formatters.d.ts +0 -188
- package/dist/examples/utils/bridge-formatters.d.ts.map +0 -1
- package/dist/examples/utils/bridge-setup.d.ts +0 -235
- package/dist/examples/utils/bridge-setup.d.ts.map +0 -1
- package/dist/examples/utils/bridge-transaction-logger.d.ts +0 -42
- package/dist/examples/utils/bridge-transaction-logger.d.ts.map +0 -1
- package/dist/examples/utils/cli-input.d.ts +0 -41
- package/dist/examples/utils/cli-input.d.ts.map +0 -1
- package/dist/examples/utils/demo-config.d.ts +0 -155
- package/dist/examples/utils/demo-config.d.ts.map +0 -1
- package/dist/examples/utils/demo-registry.d.ts +0 -155
- package/dist/examples/utils/demo-registry.d.ts.map +0 -1
- package/dist/examples/utils/error-handler.d.ts +0 -85
- package/dist/examples/utils/error-handler.d.ts.map +0 -1
- package/dist/examples/utils/formatting.d.ts +0 -195
- package/dist/examples/utils/formatting.d.ts.map +0 -1
- package/dist/examples/utils/get-environment.d.ts +0 -17
- package/dist/examples/utils/get-environment.d.ts.map +0 -1
- package/dist/examples/utils/index.d.ts +0 -44
- package/dist/examples/utils/index.d.ts.map +0 -1
- package/dist/examples/utils/indexing.d.ts +0 -48
- package/dist/examples/utils/indexing.d.ts.map +0 -1
- package/dist/examples/utils/load-env.d.ts +0 -90
- package/dist/examples/utils/load-env.d.ts.map +0 -1
- package/dist/examples/utils/logger.d.ts +0 -52
- package/dist/examples/utils/logger.d.ts.map +0 -1
- package/dist/examples/utils/pool-helpers.d.ts +0 -226
- package/dist/examples/utils/pool-helpers.d.ts.map +0 -1
- package/dist/examples/utils/punchlist.d.ts +0 -104
- package/dist/examples/utils/punchlist.d.ts.map +0 -1
- package/dist/examples/utils/sdk-setup.d.ts +0 -423
- package/dist/examples/utils/sdk-setup.d.ts.map +0 -1
- package/dist/examples/utils/suppress-logging.d.ts +0 -11
- package/dist/examples/utils/suppress-logging.d.ts.map +0 -1
- package/dist/examples/utils/token-naming.d.ts +0 -117
- package/dist/examples/utils/token-naming.d.ts.map +0 -1
- package/dist/examples/utils/trade-helpers.d.ts +0 -195
- package/dist/examples/utils/trade-helpers.d.ts.map +0 -1
- package/dist/examples/utils/transaction-helpers.d.ts +0 -92
- package/dist/examples/utils/transaction-helpers.d.ts.map +0 -1
- package/dist/examples/wallet/wallet-initialization-complete.d.ts +0 -31
- package/dist/examples/wallet/wallet-initialization-complete.d.ts.map +0 -1
- package/dist/examples/wallet/wallet-key-rotation.d.ts +0 -28
- package/dist/examples/wallet/wallet-key-rotation.d.ts.map +0 -1
- package/dist/examples/wallet/wallet-recovery-patterns.d.ts +0 -29
- package/dist/examples/wallet/wallet-recovery-patterns.d.ts.map +0 -1
- package/dist/examples/wallet/wallet-signature-operations.d.ts +0 -28
- package/dist/examples/wallet/wallet-signature-operations.d.ts.map +0 -1
- package/dist/examples/wallet-tracking/wallet-balance-monitoring.d.ts +0 -21
- package/dist/examples/wallet-tracking/wallet-balance-monitoring.d.ts.map +0 -1
- package/dist/examples/wallet-tracking/wallet-portfolio-alerts.d.ts +0 -21
- package/dist/examples/wallet-tracking/wallet-portfolio-alerts.d.ts.map +0 -1
- package/dist/examples/wallet-tracking/wallet-transaction-tracking.d.ts +0 -21
- package/dist/examples/wallet-tracking/wallet-transaction-tracking.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-chat-advanced.d.ts +0 -26
- package/dist/examples/websocket/websocket-chat-advanced.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-chat-events-detailed.d.ts +0 -28
- package/dist/examples/websocket/websocket-chat-events-detailed.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-chat-events.d.ts +0 -26
- package/dist/examples/websocket/websocket-chat-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-combined-events.d.ts +0 -28
- package/dist/examples/websocket/websocket-combined-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-comprehensive.d.ts +0 -25
- package/dist/examples/websocket/websocket-comprehensive.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-connected-clients.d.ts +0 -30
- package/dist/examples/websocket/websocket-connected-clients.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-connection-management.d.ts +0 -28
- package/dist/examples/websocket/websocket-connection-management.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-content-events.d.ts +0 -28
- package/dist/examples/websocket/websocket-content-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-core-events.d.ts +0 -27
- package/dist/examples/websocket/websocket-core-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-dex-events.d.ts +0 -40
- package/dist/examples/websocket/websocket-dex-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-dex-pools.d.ts +0 -23
- package/dist/examples/websocket/websocket-dex-pools.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-download-recording.d.ts +0 -26
- package/dist/examples/websocket/websocket-download-recording.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-interactions.d.ts +0 -25
- package/dist/examples/websocket/websocket-interactions.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-moderation-events.d.ts +0 -26
- package/dist/examples/websocket/websocket-moderation-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-recording-events.d.ts +0 -24
- package/dist/examples/websocket/websocket-recording-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-room-events.d.ts +0 -27
- package/dist/examples/websocket/websocket-room-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-room-management.d.ts +0 -27
- package/dist/examples/websocket/websocket-room-management.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-simulcast-events.d.ts +0 -26
- package/dist/examples/websocket/websocket-simulcast-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-stream-auth.d.ts +0 -23
- package/dist/examples/websocket/websocket-stream-auth.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-stream-countdown.d.ts +0 -38
- package/dist/examples/websocket/websocket-stream-countdown.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-stream-events.d.ts +0 -26
- package/dist/examples/websocket/websocket-stream-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-stream-status.d.ts +0 -39
- package/dist/examples/websocket/websocket-stream-status.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-subscription-management.d.ts +0 -27
- package/dist/examples/websocket/websocket-subscription-management.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-token-creation-events.d.ts +0 -22
- package/dist/examples/websocket/websocket-token-creation-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-token-events.d.ts +0 -24
- package/dist/examples/websocket/websocket-token-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-token-subscription.d.ts +0 -26
- package/dist/examples/websocket/websocket-token-subscription.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-token-viewers.d.ts +0 -29
- package/dist/examples/websocket/websocket-token-viewers.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-unsubscribe.d.ts +0 -25
- package/dist/examples/websocket/websocket-unsubscribe.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-user-events.d.ts +0 -40
- package/dist/examples/websocket/websocket-user-events.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-user-presence.d.ts +0 -29
- package/dist/examples/websocket/websocket-user-presence.d.ts.map +0 -1
- package/dist/examples/websocket/websocket-viewer-analytics.d.ts +0 -38
- package/dist/examples/websocket/websocket-viewer-analytics.d.ts.map +0 -1
- package/dist/examples/wrap/wrap-status-tracking.d.ts +0 -19
- package/dist/examples/wrap/wrap-status-tracking.d.ts.map +0 -1
- package/dist/examples/wrap/wrap-token-discovery.d.ts +0 -20
- package/dist/examples/wrap/wrap-token-discovery.d.ts.map +0 -1
- package/dist/scripts/derive-public-key-from-private-key.d.ts +0 -8
- package/dist/scripts/derive-public-key-from-private-key.d.ts.map +0 -1
- package/dist/scripts/eslint-fixer.d.ts +0 -7
- package/dist/scripts/eslint-fixer.d.ts.map +0 -1
- package/dist/scripts/final-fixer.d.ts +0 -7
- package/dist/scripts/final-fixer.d.ts.map +0 -1
- package/dist/scripts/fix-all-remaining-boolean.d.ts +0 -7
- package/dist/scripts/fix-all-remaining-boolean.d.ts.map +0 -1
- package/dist/scripts/fix-boolean-expressions-advanced.d.ts +0 -7
- package/dist/scripts/fix-boolean-expressions-advanced.d.ts.map +0 -1
- package/dist/scripts/fix-boolean-expressions-ast.d.ts +0 -9
- package/dist/scripts/fix-boolean-expressions-ast.d.ts.map +0 -1
- package/dist/scripts/fix-boolean-expressions-auto.d.ts +0 -7
- package/dist/scripts/fix-boolean-expressions-auto.d.ts.map +0 -1
- package/dist/scripts/fix-final-aggressive.d.ts +0 -6
- package/dist/scripts/fix-final-aggressive.d.ts.map +0 -1
- package/dist/scripts/fix-final-boolean.d.ts +0 -7
- package/dist/scripts/fix-final-boolean.d.ts.map +0 -1
- package/dist/scripts/fix-remaining-boolean.d.ts +0 -7
- package/dist/scripts/fix-remaining-boolean.d.ts.map +0 -1
- package/dist/scripts/fix-strict-boolean-comprehensive.d.ts +0 -3
- package/dist/scripts/fix-strict-boolean-comprehensive.d.ts.map +0 -1
- package/dist/scripts/fix-strict-boolean-expressions.d.ts +0 -2
- package/dist/scripts/fix-strict-boolean-expressions.d.ts.map +0 -1
- package/dist/scripts/fix-strict-boolean-final.d.ts +0 -13
- package/dist/scripts/fix-strict-boolean-final.d.ts.map +0 -1
- package/dist/scripts/fixer-aggressive.d.ts +0 -7
- package/dist/scripts/fixer-aggressive.d.ts.map +0 -1
- package/dist/scripts/fixer-conservative.d.ts +0 -7
- package/dist/scripts/fixer-conservative.d.ts.map +0 -1
- package/dist/scripts/fixer-direct.d.ts +0 -7
- package/dist/scripts/fixer-direct.d.ts.map +0 -1
- package/dist/scripts/generate-demo-registry.d.ts +0 -14
- package/dist/scripts/generate-demo-registry.d.ts.map +0 -1
- package/dist/scripts/inject-version.d.ts +0 -8
- package/dist/scripts/inject-version.d.ts.map +0 -1
- package/dist/scripts/strict-boolean-fixer.d.ts +0 -9
- package/dist/scripts/strict-boolean-fixer.d.ts.map +0 -1
- package/dist/scripts/validate-demo-registry.d.ts +0 -17
- package/dist/scripts/validate-demo-registry.d.ts.map +0 -1
- package/dist/services/DexBackendClient.d.ts +0 -225
- package/dist/services/DexBackendClient.d.ts.map +0 -1
- package/dist/services/DexBackendTradeClient.d.ts +0 -34
- package/dist/services/DexBackendTradeClient.d.ts.map +0 -1
- package/dist/services/DexPoolService.d.ts +0 -152
- package/dist/services/DexPoolService.d.ts.map +0 -1
- package/dist/services/DexQuoteService.d.ts +0 -446
- package/dist/services/DexQuoteService.d.ts.map +0 -1
- package/dist/services/GSwapAssetService.d.ts +0 -96
- package/dist/services/GSwapAssetService.d.ts.map +0 -1
- package/dist/services/GSwapLiquidityMutationService.d.ts +0 -138
- package/dist/services/GSwapLiquidityMutationService.d.ts.map +0 -1
- package/dist/services/GSwapLiquidityQueryService.d.ts +0 -75
- package/dist/services/GSwapLiquidityQueryService.d.ts.map +0 -1
- package/dist/services/GSwapPoolCalculationService.d.ts +0 -187
- package/dist/services/GSwapPoolCalculationService.d.ts.map +0 -1
- package/dist/services/GSwapPoolQueryService.d.ts +0 -114
- package/dist/services/GSwapPoolQueryService.d.ts.map +0 -1
- package/dist/services/GSwapService.d.ts +0 -1207
- package/dist/services/GSwapService.d.ts.map +0 -1
- package/dist/services/GSwapSwapService.d.ts +0 -66
- package/dist/services/GSwapSwapService.d.ts.map +0 -1
- package/dist/services/MultiPoolStateManager.d.ts +0 -289
- package/dist/services/MultiPoolStateManager.d.ts.map +0 -1
- package/dist/services/PoolCacheManager.d.ts +0 -258
- package/dist/services/PoolCacheManager.d.ts.map +0 -1
- package/dist/services/PoolStateManager.d.ts +0 -176
- package/dist/services/PoolStateManager.d.ts.map +0 -1
- package/dist/services/SignatureService.d.ts +0 -113
- package/dist/services/SignatureService.d.ts.map +0 -1
- package/dist/services/SwapEventQueue.d.ts +0 -192
- package/dist/services/SwapEventQueue.d.ts.map +0 -1
- package/dist/src/LaunchpadSDK.d.ts +0 -10746
- package/dist/src/LaunchpadSDK.d.ts.map +0 -1
- package/dist/src/api/LaunchpadAPI.d.ts +0 -930
- package/dist/src/api/LaunchpadAPI.d.ts.map +0 -1
- package/dist/src/api/dto/BondingCurveDTOs.d.ts +0 -145
- package/dist/src/api/dto/BondingCurveDTOs.d.ts.map +0 -1
- package/dist/src/api/dto/BurnTokensDto.d.ts +0 -89
- package/dist/src/api/dto/BurnTokensDto.d.ts.map +0 -1
- package/dist/src/api/dto/LockTokenDto.d.ts +0 -97
- package/dist/src/api/dto/LockTokenDto.d.ts.map +0 -1
- package/dist/src/api/dto/TransferTokenDto.d.ts +0 -76
- package/dist/src/api/dto/TransferTokenDto.d.ts.map +0 -1
- package/dist/src/api/dto/UnlockTokenDto.d.ts +0 -86
- package/dist/src/api/dto/UnlockTokenDto.d.ts.map +0 -1
- package/dist/src/auth/JwtAuth.d.ts +0 -183
- package/dist/src/auth/JwtAuth.d.ts.map +0 -1
- package/dist/src/auth/SessionAuthService.d.ts +0 -151
- package/dist/src/auth/SessionAuthService.d.ts.map +0 -1
- package/dist/src/auth/SignatureAuth.d.ts +0 -181
- package/dist/src/auth/SignatureAuth.d.ts.map +0 -1
- package/dist/src/auth/storage.d.ts +0 -66
- package/dist/src/auth/storage.d.ts.map +0 -1
- package/dist/src/auth/types.d.ts +0 -50
- package/dist/src/auth/types.d.ts.map +0 -1
- package/dist/src/bridge/BridgeService.d.ts +0 -484
- package/dist/src/bridge/BridgeService.d.ts.map +0 -1
- package/dist/src/bridge/GalaConnectClient.d.ts +0 -170
- package/dist/src/bridge/GalaConnectClient.d.ts.map +0 -1
- package/dist/src/bridge/constants/index.d.ts +0 -7
- package/dist/src/bridge/constants/index.d.ts.map +0 -1
- package/dist/src/bridge/constants/tokens.d.ts +0 -212
- package/dist/src/bridge/constants/tokens.d.ts.map +0 -1
- package/dist/src/bridge/index.d.ts +0 -24
- package/dist/src/bridge/index.d.ts.map +0 -1
- package/dist/src/bridge/strategies/BridgeStrategy.d.ts +0 -160
- package/dist/src/bridge/strategies/BridgeStrategy.d.ts.map +0 -1
- package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts +0 -200
- package/dist/src/bridge/strategies/EthereumBridgeStrategy.d.ts.map +0 -1
- package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts +0 -258
- package/dist/src/bridge/strategies/SolanaBridgeStrategy.d.ts.map +0 -1
- package/dist/src/bridge/types/bridge.dto.d.ts +0 -772
- package/dist/src/bridge/types/bridge.dto.d.ts.map +0 -1
- package/dist/src/bridge/types/bridgeable-token.dto.d.ts +0 -205
- package/dist/src/bridge/types/bridgeable-token.dto.d.ts.map +0 -1
- package/dist/src/bridge/types/eip712.d.ts +0 -66
- package/dist/src/bridge/types/eip712.d.ts.map +0 -1
- package/dist/src/bridge/types/index.d.ts +0 -8
- package/dist/src/bridge/types/index.d.ts.map +0 -1
- package/dist/src/bridge/utils/RateLimiter.d.ts +0 -34
- package/dist/src/bridge/utils/RateLimiter.d.ts.map +0 -1
- package/dist/src/bridge/utils/address-formatter.d.ts +0 -25
- package/dist/src/bridge/utils/address-formatter.d.ts.map +0 -1
- package/dist/src/bridge/utils/addressValidation.d.ts +0 -200
- package/dist/src/bridge/utils/addressValidation.d.ts.map +0 -1
- package/dist/src/bridge/utils/balanceHelpers.d.ts +0 -215
- package/dist/src/bridge/utils/balanceHelpers.d.ts.map +0 -1
- package/dist/src/bridge/utils/bridgeErrors.d.ts +0 -98
- package/dist/src/bridge/utils/bridgeErrors.d.ts.map +0 -1
- package/dist/src/bridge/utils/bridgeOutHelpers.d.ts +0 -68
- package/dist/src/bridge/utils/bridgeOutHelpers.d.ts.map +0 -1
- package/dist/src/bridge/utils/bridgePayload.d.ts +0 -98
- package/dist/src/bridge/utils/bridgePayload.d.ts.map +0 -1
- package/dist/src/bridge/utils/bridgeStatusParser.d.ts +0 -75
- package/dist/src/bridge/utils/bridgeStatusParser.d.ts.map +0 -1
- package/dist/src/bridge/utils/eip712Helpers.d.ts +0 -66
- package/dist/src/bridge/utils/eip712Helpers.d.ts.map +0 -1
- package/dist/src/bridge/utils/index.d.ts +0 -19
- package/dist/src/bridge/utils/index.d.ts.map +0 -1
- package/dist/src/bridge/utils/retry.d.ts +0 -112
- package/dist/src/bridge/utils/retry.d.ts.map +0 -1
- package/dist/src/bridge/utils/strategyDelegation.d.ts +0 -69
- package/dist/src/bridge/utils/strategyDelegation.d.ts.map +0 -1
- package/dist/src/bridge/utils/tokenIdUtils.d.ts +0 -86
- package/dist/src/bridge/utils/tokenIdUtils.d.ts.map +0 -1
- package/dist/src/bridge/utils/tokenMath.d.ts +0 -39
- package/dist/src/bridge/utils/tokenMath.d.ts.map +0 -1
- package/dist/src/bridge/utils/tokenMetadataResolver.d.ts +0 -97
- package/dist/src/bridge/utils/tokenMetadataResolver.d.ts.map +0 -1
- package/dist/src/config/environments.d.ts +0 -51
- package/dist/src/config/environments.d.ts.map +0 -1
- package/dist/src/constants/bondingCurve.d.ts +0 -102
- package/dist/src/constants/bondingCurve.d.ts.map +0 -1
- package/dist/src/constants/config.d.ts +0 -30
- package/dist/src/constants/config.d.ts.map +0 -1
- package/dist/src/constants/decimals.d.ts +0 -63
- package/dist/src/constants/decimals.d.ts.map +0 -1
- package/dist/src/constants/endpoints.d.ts +0 -820
- package/dist/src/constants/endpoints.d.ts.map +0 -1
- package/dist/src/constants/enums.d.ts +0 -65
- package/dist/src/constants/enums.d.ts.map +0 -1
- package/dist/src/constants/error-messages.d.ts +0 -61
- package/dist/src/constants/error-messages.d.ts.map +0 -1
- package/dist/src/constants/events.d.ts +0 -53
- package/dist/src/constants/events.d.ts.map +0 -1
- package/dist/src/constants/jwt.d.ts +0 -41
- package/dist/src/constants/jwt.d.ts.map +0 -1
- package/dist/src/constants/nft-fees.d.ts +0 -30
- package/dist/src/constants/nft-fees.d.ts.map +0 -1
- package/dist/src/constants/pagination.d.ts +0 -66
- package/dist/src/constants/pagination.d.ts.map +0 -1
- package/dist/src/constants/query-fields.d.ts +0 -51
- package/dist/src/constants/query-fields.d.ts.map +0 -1
- package/dist/src/constants/sdk-defaults.d.ts +0 -37
- package/dist/src/constants/sdk-defaults.d.ts.map +0 -1
- package/dist/src/constants/version.d.ts +0 -6
- package/dist/src/constants/version.d.ts.map +0 -1
- package/dist/src/constants/version.generated.d.ts +0 -7
- package/dist/src/constants/version.generated.d.ts.map +0 -1
- package/dist/src/helpers/sdk.d.ts +0 -87
- package/dist/src/helpers/sdk.d.ts.map +0 -1
- package/dist/src/helpers/wallet.d.ts +0 -151
- package/dist/src/helpers/wallet.d.ts.map +0 -1
- package/dist/src/index.browser.d.ts +0 -149
- package/dist/src/index.browser.d.ts.map +0 -1
- package/dist/src/index.d.ts +0 -12
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/index.node.d.ts +0 -13
- package/dist/src/index.node.d.ts.map +0 -1
- package/dist/src/native.d.ts +0 -22
- package/dist/src/native.d.ts.map +0 -1
- package/dist/src/polyfills/file-global.d.ts +0 -12
- package/dist/src/polyfills/file-global.d.ts.map +0 -1
- package/dist/src/react/WalletContext.d.ts +0 -60
- package/dist/src/react/WalletContext.d.ts.map +0 -1
- package/dist/src/react/index.d.ts +0 -65
- package/dist/src/react/index.d.ts.map +0 -1
- package/dist/src/react/types.d.ts +0 -76
- package/dist/src/react/types.d.ts.map +0 -1
- package/dist/src/react/useWallet.d.ts +0 -123
- package/dist/src/react/useWallet.d.ts.map +0 -1
- package/dist/src/react/useWalletConnection.d.ts +0 -89
- package/dist/src/react/useWalletConnection.d.ts.map +0 -1
- package/dist/src/react/useWalletDetection.d.ts +0 -81
- package/dist/src/react/useWalletDetection.d.ts.map +0 -1
- package/dist/src/schemas/files.d.ts +0 -83
- package/dist/src/schemas/files.d.ts.map +0 -1
- package/dist/src/schemas/index.d.ts +0 -83
- package/dist/src/schemas/index.d.ts.map +0 -1
- package/dist/src/schemas/launchpad.d.ts +0 -135
- package/dist/src/schemas/launchpad.d.ts.map +0 -1
- package/dist/src/schemas/pagination.d.ts +0 -107
- package/dist/src/schemas/pagination.d.ts.map +0 -1
- package/dist/src/schemas/primitives.d.ts +0 -142
- package/dist/src/schemas/primitives.d.ts.map +0 -1
- package/dist/src/schemas/trade.d.ts +0 -140
- package/dist/src/schemas/trade.d.ts.map +0 -1
- package/dist/src/schemas/user.d.ts +0 -99
- package/dist/src/schemas/user.d.ts.map +0 -1
- package/dist/src/schemas/validators.d.ts +0 -332
- package/dist/src/schemas/validators.d.ts.map +0 -1
- package/dist/src/services/AIModerationService.d.ts +0 -217
- package/dist/src/services/AIModerationService.d.ts.map +0 -1
- package/dist/src/services/AbstractCacheService.d.ts +0 -227
- package/dist/src/services/AbstractCacheService.d.ts.map +0 -1
- package/dist/src/services/AbstractTokenFetchService.d.ts +0 -150
- package/dist/src/services/AbstractTokenFetchService.d.ts.map +0 -1
- package/dist/src/services/ApiKeyService.d.ts +0 -211
- package/dist/src/services/ApiKeyService.d.ts.map +0 -1
- package/dist/src/services/BanService.d.ts +0 -312
- package/dist/src/services/BanService.d.ts.map +0 -1
- package/dist/src/services/BaseService.d.ts +0 -116
- package/dist/src/services/BaseService.d.ts.map +0 -1
- package/dist/src/services/BatchedCacheService.d.ts +0 -133
- package/dist/src/services/BatchedCacheService.d.ts.map +0 -1
- package/dist/src/services/BridgeableTokenCache.d.ts +0 -120
- package/dist/src/services/BridgeableTokenCache.d.ts.map +0 -1
- package/dist/src/services/BridgeableTokenService.d.ts +0 -218
- package/dist/src/services/BridgeableTokenService.d.ts.map +0 -1
- package/dist/src/services/BundleService.d.ts +0 -245
- package/dist/src/services/BundleService.d.ts.map +0 -1
- package/dist/src/services/BundlerClientFactory.d.ts +0 -32
- package/dist/src/services/BundlerClientFactory.d.ts.map +0 -1
- package/dist/src/services/ChartService.d.ts +0 -106
- package/dist/src/services/ChartService.d.ts.map +0 -1
- package/dist/src/services/ClientConfigService.d.ts +0 -61
- package/dist/src/services/ClientConfigService.d.ts.map +0 -1
- package/dist/src/services/ContentFlagService.d.ts +0 -218
- package/dist/src/services/ContentFlagService.d.ts.map +0 -1
- package/dist/src/services/ContentReactionService.d.ts +0 -175
- package/dist/src/services/ContentReactionService.d.ts.map +0 -1
- package/dist/src/services/DexBackendClient.d.ts +0 -225
- package/dist/src/services/DexBackendClient.d.ts.map +0 -1
- package/dist/src/services/DexBackendTradeClient.d.ts +0 -34
- package/dist/src/services/DexBackendTradeClient.d.ts.map +0 -1
- package/dist/src/services/DexPoolService.d.ts +0 -152
- package/dist/src/services/DexPoolService.d.ts.map +0 -1
- package/dist/src/services/DexQuoteService.d.ts +0 -446
- package/dist/src/services/DexQuoteService.d.ts.map +0 -1
- package/dist/src/services/DexService.d.ts +0 -433
- package/dist/src/services/DexService.d.ts.map +0 -1
- package/dist/src/services/EventsBatcherService.d.ts +0 -111
- package/dist/src/services/EventsBatcherService.d.ts.map +0 -1
- package/dist/src/services/GSwapAssetService.d.ts +0 -96
- package/dist/src/services/GSwapAssetService.d.ts.map +0 -1
- package/dist/src/services/GSwapLiquidityMutationService.d.ts +0 -138
- package/dist/src/services/GSwapLiquidityMutationService.d.ts.map +0 -1
- package/dist/src/services/GSwapLiquidityQueryService.d.ts +0 -75
- package/dist/src/services/GSwapLiquidityQueryService.d.ts.map +0 -1
- package/dist/src/services/GSwapPoolCalculationService.d.ts +0 -187
- package/dist/src/services/GSwapPoolCalculationService.d.ts.map +0 -1
- package/dist/src/services/GSwapPoolQueryService.d.ts +0 -114
- package/dist/src/services/GSwapPoolQueryService.d.ts.map +0 -1
- package/dist/src/services/GSwapService.d.ts +0 -1207
- package/dist/src/services/GSwapService.d.ts.map +0 -1
- package/dist/src/services/GSwapSwapService.d.ts +0 -66
- package/dist/src/services/GSwapSwapService.d.ts.map +0 -1
- package/dist/src/services/GalaChainBalanceService.d.ts +0 -155
- package/dist/src/services/GalaChainBalanceService.d.ts.map +0 -1
- package/dist/src/services/GalaChainLockService.d.ts +0 -144
- package/dist/src/services/GalaChainLockService.d.ts.map +0 -1
- package/dist/src/services/GalaChainService.d.ts +0 -400
- package/dist/src/services/GalaChainService.d.ts.map +0 -1
- package/dist/src/services/GalaChainTokenService.d.ts +0 -108
- package/dist/src/services/GalaChainTokenService.d.ts.map +0 -1
- package/dist/src/services/GalaChainTransferService.d.ts +0 -211
- package/dist/src/services/GalaChainTransferService.d.ts.map +0 -1
- package/dist/src/services/GdexStreamService.d.ts +0 -133
- package/dist/src/services/GdexStreamService.d.ts.map +0 -1
- package/dist/src/services/HolderService.d.ts +0 -181
- package/dist/src/services/HolderService.d.ts.map +0 -1
- package/dist/src/services/ImageService.d.ts +0 -173
- package/dist/src/services/ImageService.d.ts.map +0 -1
- package/dist/src/services/IntervalRegistry.d.ts +0 -79
- package/dist/src/services/IntervalRegistry.d.ts.map +0 -1
- package/dist/src/services/LaunchpadService.d.ts +0 -343
- package/dist/src/services/LaunchpadService.d.ts.map +0 -1
- package/dist/src/services/MessagesService.d.ts +0 -251
- package/dist/src/services/MessagesService.d.ts.map +0 -1
- package/dist/src/services/ModeratorService.d.ts +0 -311
- package/dist/src/services/ModeratorService.d.ts.map +0 -1
- package/dist/src/services/MultiPoolStateManager.d.ts +0 -289
- package/dist/src/services/MultiPoolStateManager.d.ts.map +0 -1
- package/dist/src/services/NetworkKeyedCacheService.d.ts +0 -185
- package/dist/src/services/NetworkKeyedCacheService.d.ts.map +0 -1
- package/dist/src/services/NftCollectionService.d.ts +0 -121
- package/dist/src/services/NftCollectionService.d.ts.map +0 -1
- package/dist/src/services/NotificationService.d.ts +0 -113
- package/dist/src/services/NotificationService.d.ts.map +0 -1
- package/dist/src/services/OEmbedService.d.ts +0 -152
- package/dist/src/services/OEmbedService.d.ts.map +0 -1
- package/dist/src/services/OverseerService.d.ts +0 -524
- package/dist/src/services/OverseerService.d.ts.map +0 -1
- package/dist/src/services/PlatformConfigService.d.ts +0 -149
- package/dist/src/services/PlatformConfigService.d.ts.map +0 -1
- package/dist/src/services/PlatformStatsService.d.ts +0 -72
- package/dist/src/services/PlatformStatsService.d.ts.map +0 -1
- package/dist/src/services/PoolCacheManager.d.ts +0 -258
- package/dist/src/services/PoolCacheManager.d.ts.map +0 -1
- package/dist/src/services/PoolService.d.ts +0 -316
- package/dist/src/services/PoolService.d.ts.map +0 -1
- package/dist/src/services/PoolStateManager.d.ts +0 -176
- package/dist/src/services/PoolStateManager.d.ts.map +0 -1
- package/dist/src/services/PriceHistoryService.d.ts +0 -207
- package/dist/src/services/PriceHistoryService.d.ts.map +0 -1
- package/dist/src/services/RestrictedNamesService.d.ts +0 -80
- package/dist/src/services/RestrictedNamesService.d.ts.map +0 -1
- package/dist/src/services/SignatureService.d.ts +0 -113
- package/dist/src/services/SignatureService.d.ts.map +0 -1
- package/dist/src/services/StreamChatService.d.ts +0 -259
- package/dist/src/services/StreamChatService.d.ts.map +0 -1
- package/dist/src/services/StreamTokenServiceBase.d.ts +0 -404
- package/dist/src/services/StreamTokenServiceBase.d.ts.map +0 -1
- package/dist/src/services/StreamWebSocketService.d.ts +0 -586
- package/dist/src/services/StreamWebSocketService.d.ts.map +0 -1
- package/dist/src/services/StreamingEventService.d.ts +0 -441
- package/dist/src/services/StreamingEventService.d.ts.map +0 -1
- package/dist/src/services/StreamingService.d.ts +0 -573
- package/dist/src/services/StreamingService.d.ts.map +0 -1
- package/dist/src/services/SwapEventQueue.d.ts +0 -192
- package/dist/src/services/SwapEventQueue.d.ts.map +0 -1
- package/dist/src/services/TokenBanService.d.ts +0 -217
- package/dist/src/services/TokenBanService.d.ts.map +0 -1
- package/dist/src/services/TokenClassKeyService.d.ts +0 -162
- package/dist/src/services/TokenClassKeyService.d.ts.map +0 -1
- package/dist/src/services/TokenMetadataCache.d.ts +0 -310
- package/dist/src/services/TokenMetadataCache.d.ts.map +0 -1
- package/dist/src/services/TokenMetadataService.d.ts +0 -509
- package/dist/src/services/TokenMetadataService.d.ts.map +0 -1
- package/dist/src/services/TokenResolverService.d.ts +0 -329
- package/dist/src/services/TokenResolverService.d.ts.map +0 -1
- package/dist/src/services/TradeService.d.ts +0 -286
- package/dist/src/services/TradeService.d.ts.map +0 -1
- package/dist/src/services/TradingQuotesService.d.ts +0 -162
- package/dist/src/services/TradingQuotesService.d.ts.map +0 -1
- package/dist/src/services/UserService.d.ts +0 -352
- package/dist/src/services/UserService.d.ts.map +0 -1
- package/dist/src/services/WebSocketAdminService.d.ts +0 -587
- package/dist/src/services/WebSocketAdminService.d.ts.map +0 -1
- package/dist/src/services/WebSocketService.d.ts +0 -189
- package/dist/src/services/WebSocketService.d.ts.map +0 -1
- package/dist/src/services/WeeklyChallengeService.d.ts +0 -114
- package/dist/src/services/WeeklyChallengeService.d.ts.map +0 -1
- package/dist/src/services/WrapService.d.ts +0 -172
- package/dist/src/services/WrapService.d.ts.map +0 -1
- package/dist/src/services/WrappableTokenCache.d.ts +0 -100
- package/dist/src/services/WrappableTokenCache.d.ts.map +0 -1
- package/dist/src/services/WrappableTokenService.d.ts +0 -130
- package/dist/src/services/WrappableTokenService.d.ts.map +0 -1
- package/dist/src/services/__mocks__/logger.mock.d.ts +0 -24
- package/dist/src/services/__mocks__/logger.mock.d.ts.map +0 -1
- package/dist/src/services/shared/cache-helpers.d.ts +0 -188
- package/dist/src/services/shared/cache-helpers.d.ts.map +0 -1
- package/dist/src/services/shared/http-helpers.d.ts +0 -146
- package/dist/src/services/shared/http-helpers.d.ts.map +0 -1
- package/dist/src/services/shared/pagination-helpers.d.ts +0 -167
- package/dist/src/services/shared/pagination-helpers.d.ts.map +0 -1
- package/dist/src/services/shared/service-validators.d.ts +0 -137
- package/dist/src/services/shared/service-validators.d.ts.map +0 -1
- package/dist/src/services/shared/websocket-helpers.d.ts +0 -158
- package/dist/src/services/shared/websocket-helpers.d.ts.map +0 -1
- package/dist/src/setup.d.ts +0 -8
- package/dist/src/setup.d.ts.map +0 -1
- package/dist/src/test-constants.d.ts +0 -29
- package/dist/src/test-constants.d.ts.map +0 -1
- package/dist/src/types/ai-moderation.dto.d.ts +0 -294
- package/dist/src/types/ai-moderation.dto.d.ts.map +0 -1
- package/dist/src/types/api-key.dto.d.ts +0 -373
- package/dist/src/types/api-key.dto.d.ts.map +0 -1
- package/dist/src/types/backend-responses.d.ts +0 -235
- package/dist/src/types/backend-responses.d.ts.map +0 -1
- package/dist/src/types/ban.dto.d.ts +0 -577
- package/dist/src/types/ban.dto.d.ts.map +0 -1
- package/dist/src/types/burn.dto.d.ts +0 -170
- package/dist/src/types/burn.dto.d.ts.map +0 -1
- package/dist/src/types/cache-management.dto.d.ts +0 -44
- package/dist/src/types/cache-management.dto.d.ts.map +0 -1
- package/dist/src/types/chat-messages.dto.d.ts +0 -193
- package/dist/src/types/chat-messages.dto.d.ts.map +0 -1
- package/dist/src/types/client-config.dto.d.ts +0 -43
- package/dist/src/types/client-config.dto.d.ts.map +0 -1
- package/dist/src/types/comment.dto.d.ts +0 -176
- package/dist/src/types/comment.dto.d.ts.map +0 -1
- package/dist/src/types/comments.dto.d.ts +0 -198
- package/dist/src/types/comments.dto.d.ts.map +0 -1
- package/dist/src/types/common.d.ts +0 -619
- package/dist/src/types/common.d.ts.map +0 -1
- package/dist/src/types/composite-pool.dto.d.ts +0 -101
- package/dist/src/types/composite-pool.dto.d.ts.map +0 -1
- package/dist/src/types/constraints.d.ts +0 -378
- package/dist/src/types/constraints.d.ts.map +0 -1
- package/dist/src/types/content-flag.dto.d.ts +0 -337
- package/dist/src/types/content-flag.dto.d.ts.map +0 -1
- package/dist/src/types/content-reactions.dto.d.ts +0 -132
- package/dist/src/types/content-reactions.dto.d.ts.map +0 -1
- package/dist/src/types/dex-pool.dto.d.ts +0 -230
- package/dist/src/types/dex-pool.dto.d.ts.map +0 -1
- package/dist/src/types/dto.d.ts +0 -183
- package/dist/src/types/dto.d.ts.map +0 -1
- package/dist/src/types/engagement-stats.dto.d.ts +0 -62
- package/dist/src/types/engagement-stats.dto.d.ts.map +0 -1
- package/dist/src/types/events.dto.d.ts +0 -80
- package/dist/src/types/events.dto.d.ts.map +0 -1
- package/dist/src/types/galachain-api.types.d.ts +0 -297
- package/dist/src/types/galachain-api.types.d.ts.map +0 -1
- package/dist/src/types/global-feed.dto.d.ts +0 -203
- package/dist/src/types/global-feed.dto.d.ts.map +0 -1
- package/dist/src/types/gswap-responses.types.d.ts +0 -369
- package/dist/src/types/gswap-responses.types.d.ts.map +0 -1
- package/dist/src/types/gswap.dto.d.ts +0 -448
- package/dist/src/types/gswap.dto.d.ts.map +0 -1
- package/dist/src/types/holder.types.d.ts +0 -106
- package/dist/src/types/holder.types.d.ts.map +0 -1
- package/dist/src/types/launchpad.dto.d.ts +0 -1263
- package/dist/src/types/launchpad.dto.d.ts.map +0 -1
- package/dist/src/types/launchpad.validation.d.ts +0 -43
- package/dist/src/types/launchpad.validation.d.ts.map +0 -1
- package/dist/src/types/liquidity-monitor.dto.d.ts +0 -177
- package/dist/src/types/liquidity-monitor.dto.d.ts.map +0 -1
- package/dist/src/types/lock.dto.d.ts +0 -261
- package/dist/src/types/lock.dto.d.ts.map +0 -1
- package/dist/src/types/messages.dto.d.ts +0 -386
- package/dist/src/types/messages.dto.d.ts.map +0 -1
- package/dist/src/types/moderator.dto.d.ts +0 -607
- package/dist/src/types/moderator.dto.d.ts.map +0 -1
- package/dist/src/types/nft.dto.d.ts +0 -155
- package/dist/src/types/nft.dto.d.ts.map +0 -1
- package/dist/src/types/notification.dto.d.ts +0 -92
- package/dist/src/types/notification.dto.d.ts.map +0 -1
- package/dist/src/types/oembed.dto.d.ts +0 -160
- package/dist/src/types/oembed.dto.d.ts.map +0 -1
- package/dist/src/types/options.dto.d.ts +0 -485
- package/dist/src/types/options.dto.d.ts.map +0 -1
- package/dist/src/types/overseer.dto.d.ts +0 -530
- package/dist/src/types/overseer.dto.d.ts.map +0 -1
- package/dist/src/types/platform-config.dto.d.ts +0 -89
- package/dist/src/types/platform-config.dto.d.ts.map +0 -1
- package/dist/src/types/platform-stats.dto.d.ts +0 -40
- package/dist/src/types/platform-stats.dto.d.ts.map +0 -1
- package/dist/src/types/pool-state-delta.dto.d.ts +0 -246
- package/dist/src/types/pool-state-delta.dto.d.ts.map +0 -1
- package/dist/src/types/pool.dto.d.ts +0 -111
- package/dist/src/types/pool.dto.d.ts.map +0 -1
- package/dist/src/types/priceHistory.dto.d.ts +0 -165
- package/dist/src/types/priceHistory.dto.d.ts.map +0 -1
- package/dist/src/types/restricted-names.dto.d.ts +0 -50
- package/dist/src/types/restricted-names.dto.d.ts.map +0 -1
- package/dist/src/types/result.types.d.ts +0 -104
- package/dist/src/types/result.types.d.ts.map +0 -1
- package/dist/src/types/session-auth.dto.d.ts +0 -99
- package/dist/src/types/session-auth.dto.d.ts.map +0 -1
- package/dist/src/types/stream-chat.dto.d.ts +0 -810
- package/dist/src/types/stream-chat.dto.d.ts.map +0 -1
- package/dist/src/types/streaming-events.dto.d.ts +0 -605
- package/dist/src/types/streaming-events.dto.d.ts.map +0 -1
- package/dist/src/types/streaming.dto.d.ts +0 -1178
- package/dist/src/types/streaming.dto.d.ts.map +0 -1
- package/dist/src/types/swap-monitor.dto.d.ts +0 -256
- package/dist/src/types/swap-monitor.dto.d.ts.map +0 -1
- package/dist/src/types/token-ban.dto.d.ts +0 -194
- package/dist/src/types/token-ban.dto.d.ts.map +0 -1
- package/dist/src/types/token-config.dto.d.ts +0 -117
- package/dist/src/types/token-config.dto.d.ts.map +0 -1
- package/dist/src/types/token.types.d.ts +0 -336
- package/dist/src/types/token.types.d.ts.map +0 -1
- package/dist/src/types/trade.dto.d.ts +0 -457
- package/dist/src/types/trade.dto.d.ts.map +0 -1
- package/dist/src/types/trades-query.dto.d.ts +0 -133
- package/dist/src/types/trades-query.dto.d.ts.map +0 -1
- package/dist/src/types/transfer.dto.d.ts +0 -186
- package/dist/src/types/transfer.dto.d.ts.map +0 -1
- package/dist/src/types/user.dto.d.ts +0 -880
- package/dist/src/types/user.dto.d.ts.map +0 -1
- package/dist/src/types/websocket-admin.dto.d.ts +0 -390
- package/dist/src/types/websocket-admin.dto.d.ts.map +0 -1
- package/dist/src/types/websocket-data.types.d.ts +0 -35
- package/dist/src/types/websocket-data.types.d.ts.map +0 -1
- package/dist/src/types/websocket-events.dto.d.ts +0 -472
- package/dist/src/types/websocket-events.dto.d.ts.map +0 -1
- package/dist/src/types/websocket.types.d.ts +0 -118
- package/dist/src/types/websocket.types.d.ts.map +0 -1
- package/dist/src/types/weekly-challenge.dto.d.ts +0 -130
- package/dist/src/types/weekly-challenge.dto.d.ts.map +0 -1
- package/dist/src/types/wrappable-token.dto.d.ts +0 -305
- package/dist/src/types/wrappable-token.dto.d.ts.map +0 -1
- package/dist/src/utils/LiquidityEventExtractor.d.ts +0 -106
- package/dist/src/utils/LiquidityEventExtractor.d.ts.map +0 -1
- package/dist/src/utils/Logger.d.ts +0 -136
- package/dist/src/utils/Logger.d.ts.map +0 -1
- package/dist/src/utils/MonitoringMetrics.d.ts +0 -151
- package/dist/src/utils/MonitoringMetrics.d.ts.map +0 -1
- package/dist/src/utils/PoolKeyNormalizer.d.ts +0 -135
- package/dist/src/utils/PoolKeyNormalizer.d.ts.map +0 -1
- package/dist/src/utils/ReconnectionManager.d.ts +0 -142
- package/dist/src/utils/ReconnectionManager.d.ts.map +0 -1
- package/dist/src/utils/SignatureHelper.d.ts +0 -140
- package/dist/src/utils/SignatureHelper.d.ts.map +0 -1
- package/dist/src/utils/SwapEventExtractor.d.ts +0 -152
- package/dist/src/utils/SwapEventExtractor.d.ts.map +0 -1
- package/dist/src/utils/adapters.d.ts +0 -111
- package/dist/src/utils/adapters.d.ts.map +0 -1
- package/dist/src/utils/address-formatter.d.ts +0 -318
- package/dist/src/utils/address-formatter.d.ts.map +0 -1
- package/dist/src/utils/agent-config.d.ts +0 -288
- package/dist/src/utils/agent-config.d.ts.map +0 -1
- package/dist/src/utils/amount-validator.d.ts +0 -268
- package/dist/src/utils/amount-validator.d.ts.map +0 -1
- package/dist/src/utils/api-patterns.d.ts +0 -347
- package/dist/src/utils/api-patterns.d.ts.map +0 -1
- package/dist/src/utils/array-helpers.d.ts +0 -115
- package/dist/src/utils/array-helpers.d.ts.map +0 -1
- package/dist/src/utils/assetUrls.d.ts +0 -450
- package/dist/src/utils/assetUrls.d.ts.map +0 -1
- package/dist/src/utils/async-patterns.d.ts +0 -272
- package/dist/src/utils/async-patterns.d.ts.map +0 -1
- package/dist/src/utils/auto-pagination.d.ts +0 -549
- package/dist/src/utils/auto-pagination.d.ts.map +0 -1
- package/dist/src/utils/bignumber-helpers.d.ts +0 -446
- package/dist/src/utils/bignumber-helpers.d.ts.map +0 -1
- package/dist/src/utils/bignumber-pool-cache.d.ts +0 -169
- package/dist/src/utils/bignumber-pool-cache.d.ts.map +0 -1
- package/dist/src/utils/bondingCurveCalculations.d.ts +0 -144
- package/dist/src/utils/bondingCurveCalculations.d.ts.map +0 -1
- package/dist/src/utils/cacheWarmingHelpers.d.ts +0 -110
- package/dist/src/utils/cacheWarmingHelpers.d.ts.map +0 -1
- package/dist/src/utils/composite-pool-converter.d.ts +0 -121
- package/dist/src/utils/composite-pool-converter.d.ts.map +0 -1
- package/dist/src/utils/crypto-compat.d.ts +0 -40
- package/dist/src/utils/crypto-compat.d.ts.map +0 -1
- package/dist/src/utils/data-transform-patterns.d.ts +0 -393
- package/dist/src/utils/data-transform-patterns.d.ts.map +0 -1
- package/dist/src/utils/date-utils.d.ts +0 -205
- package/dist/src/utils/date-utils.d.ts.map +0 -1
- package/dist/src/utils/delimiter-parser.d.ts +0 -139
- package/dist/src/utils/delimiter-parser.d.ts.map +0 -1
- package/dist/src/utils/error-factories.d.ts +0 -701
- package/dist/src/utils/error-factories.d.ts.map +0 -1
- package/dist/src/utils/error-handling-patterns.d.ts +0 -390
- package/dist/src/utils/error-handling-patterns.d.ts.map +0 -1
- package/dist/src/utils/error-patterns.d.ts +0 -360
- package/dist/src/utils/error-patterns.d.ts.map +0 -1
- package/dist/src/utils/error-utils.d.ts +0 -463
- package/dist/src/utils/error-utils.d.ts.map +0 -1
- package/dist/src/utils/error-wrapper.d.ts +0 -208
- package/dist/src/utils/error-wrapper.d.ts.map +0 -1
- package/dist/src/utils/errors.d.ts +0 -552
- package/dist/src/utils/errors.d.ts.map +0 -1
- package/dist/src/utils/http-factory.d.ts +0 -36
- package/dist/src/utils/http-factory.d.ts.map +0 -1
- package/dist/src/utils/http.d.ts +0 -113
- package/dist/src/utils/http.d.ts.map +0 -1
- package/dist/src/utils/load-env.d.ts +0 -31
- package/dist/src/utils/load-env.d.ts.map +0 -1
- package/dist/src/utils/multipart-helpers.d.ts +0 -38
- package/dist/src/utils/multipart-helpers.d.ts.map +0 -1
- package/dist/src/utils/multipart.d.ts +0 -63
- package/dist/src/utils/multipart.d.ts.map +0 -1
- package/dist/src/utils/nft-helpers.d.ts +0 -62
- package/dist/src/utils/nft-helpers.d.ts.map +0 -1
- package/dist/src/utils/numeric-patterns.d.ts +0 -289
- package/dist/src/utils/numeric-patterns.d.ts.map +0 -1
- package/dist/src/utils/numeric-wrappers.d.ts +0 -149
- package/dist/src/utils/numeric-wrappers.d.ts.map +0 -1
- package/dist/src/utils/object-extractors.d.ts +0 -115
- package/dist/src/utils/object-extractors.d.ts.map +0 -1
- package/dist/src/utils/object-patterns.d.ts +0 -81
- package/dist/src/utils/object-patterns.d.ts.map +0 -1
- package/dist/src/utils/pagination-helpers.d.ts +0 -161
- package/dist/src/utils/pagination-helpers.d.ts.map +0 -1
- package/dist/src/utils/pagination-validation.d.ts +0 -88
- package/dist/src/utils/pagination-validation.d.ts.map +0 -1
- package/dist/src/utils/pool-pair-parser.d.ts +0 -57
- package/dist/src/utils/pool-pair-parser.d.ts.map +0 -1
- package/dist/src/utils/pool-state-validator.d.ts +0 -207
- package/dist/src/utils/pool-state-validator.d.ts.map +0 -1
- package/dist/src/utils/position-filters.d.ts +0 -252
- package/dist/src/utils/position-filters.d.ts.map +0 -1
- package/dist/src/utils/primitives.d.ts +0 -76
- package/dist/src/utils/primitives.d.ts.map +0 -1
- package/dist/src/utils/query-params.d.ts +0 -89
- package/dist/src/utils/query-params.d.ts.map +0 -1
- package/dist/src/utils/response-handlers.d.ts +0 -225
- package/dist/src/utils/response-handlers.d.ts.map +0 -1
- package/dist/src/utils/response-helpers.d.ts +0 -28
- package/dist/src/utils/response-helpers.d.ts.map +0 -1
- package/dist/src/utils/response-normalizers.d.ts +0 -115
- package/dist/src/utils/response-normalizers.d.ts.map +0 -1
- package/dist/src/utils/safe-parsers.d.ts +0 -487
- package/dist/src/utils/safe-parsers.d.ts.map +0 -1
- package/dist/src/utils/service-validators.d.ts +0 -268
- package/dist/src/utils/service-validators.d.ts.map +0 -1
- package/dist/src/utils/slippage-utils.d.ts +0 -70
- package/dist/src/utils/slippage-utils.d.ts.map +0 -1
- package/dist/src/utils/string-patterns.d.ts +0 -404
- package/dist/src/utils/string-patterns.d.ts.map +0 -1
- package/dist/src/utils/string-transforms.d.ts +0 -89
- package/dist/src/utils/string-transforms.d.ts.map +0 -1
- package/dist/src/utils/string-utils.d.ts +0 -108
- package/dist/src/utils/string-utils.d.ts.map +0 -1
- package/dist/src/utils/swap-delta-calculator.d.ts +0 -231
- package/dist/src/utils/swap-delta-calculator.d.ts.map +0 -1
- package/dist/src/utils/tick-crossing-handler.d.ts +0 -250
- package/dist/src/utils/tick-crossing-handler.d.ts.map +0 -1
- package/dist/src/utils/token-format-converter.d.ts +0 -175
- package/dist/src/utils/token-format-converter.d.ts.map +0 -1
- package/dist/src/utils/token-parser.d.ts +0 -235
- package/dist/src/utils/token-parser.d.ts.map +0 -1
- package/dist/src/utils/token-stringification.d.ts +0 -168
- package/dist/src/utils/token-stringification.d.ts.map +0 -1
- package/dist/src/utils/tokenNameNormalizer.d.ts +0 -96
- package/dist/src/utils/tokenNameNormalizer.d.ts.map +0 -1
- package/dist/src/utils/tokenNormalizer.d.ts +0 -167
- package/dist/src/utils/tokenNormalizer.d.ts.map +0 -1
- package/dist/src/utils/trade-transformers.d.ts +0 -28
- package/dist/src/utils/trade-transformers.d.ts.map +0 -1
- package/dist/src/utils/transfer-validation.d.ts +0 -58
- package/dist/src/utils/transfer-validation.d.ts.map +0 -1
- package/dist/src/utils/type-guard-factory.d.ts +0 -260
- package/dist/src/utils/type-guard-factory.d.ts.map +0 -1
- package/dist/src/utils/unique-key-generator.d.ts +0 -148
- package/dist/src/utils/unique-key-generator.d.ts.map +0 -1
- package/dist/src/utils/validation-helpers.d.ts +0 -1074
- package/dist/src/utils/validation-helpers.d.ts.map +0 -1
- package/dist/src/utils/validation-patterns.d.ts +0 -768
- package/dist/src/utils/validation-patterns.d.ts.map +0 -1
- package/dist/src/utils/validation.d.ts +0 -140
- package/dist/src/utils/validation.d.ts.map +0 -1
- package/dist/src/utils/wallet.d.ts +0 -185
- package/dist/src/utils/wallet.d.ts.map +0 -1
- package/dist/src/utils/websocket-errors.d.ts +0 -30
- package/dist/src/utils/websocket-errors.d.ts.map +0 -1
- package/dist/src/utils/websocket-patterns.d.ts +0 -680
- package/dist/src/utils/websocket-patterns.d.ts.map +0 -1
- package/dist/src/utils/websocket-validators.d.ts +0 -30
- package/dist/src/utils/websocket-validators.d.ts.map +0 -1
- package/dist/src/wallet/ExternalWalletProvider.d.ts +0 -109
- package/dist/src/wallet/ExternalWalletProvider.d.ts.map +0 -1
- package/dist/src/wallet/GalaChainConnectProvider.d.ts +0 -125
- package/dist/src/wallet/GalaChainConnectProvider.d.ts.map +0 -1
- package/dist/src/wallet/GalaWalletProvider.d.ts +0 -141
- package/dist/src/wallet/GalaWalletProvider.d.ts.map +0 -1
- package/dist/src/wallet/PrivateKeyProvider.d.ts +0 -90
- package/dist/src/wallet/PrivateKeyProvider.d.ts.map +0 -1
- package/dist/src/wallet/detection.d.ts +0 -107
- package/dist/src/wallet/detection.d.ts.map +0 -1
- package/dist/src/wallet/index.d.ts +0 -52
- package/dist/src/wallet/index.d.ts.map +0 -1
- package/dist/src/wallet/types.d.ts +0 -267
- package/dist/src/wallet/types.d.ts.map +0 -1
- package/dist/src/wallet/utils.d.ts +0 -117
- package/dist/src/wallet/utils.d.ts.map +0 -1
- package/dist/types/composite-pool.dto.d.ts +0 -101
- package/dist/types/composite-pool.dto.d.ts.map +0 -1
- package/dist/types/dex-pool.dto.d.ts +0 -230
- package/dist/types/dex-pool.dto.d.ts.map +0 -1
- package/dist/types/gswap-responses.types.d.ts +0 -369
- package/dist/types/gswap-responses.types.d.ts.map +0 -1
- package/dist/types/gswap.dto.d.ts +0 -448
- package/dist/types/gswap.dto.d.ts.map +0 -1
- package/dist/types/liquidity-monitor.dto.d.ts +0 -177
- package/dist/types/liquidity-monitor.dto.d.ts.map +0 -1
- package/dist/types/pool-state-delta.dto.d.ts +0 -246
- package/dist/types/pool-state-delta.dto.d.ts.map +0 -1
- package/dist/types/swap-monitor.dto.d.ts +0 -256
- package/dist/types/swap-monitor.dto.d.ts.map +0 -1
- package/dist/utils/LiquidityEventExtractor.d.ts +0 -106
- package/dist/utils/LiquidityEventExtractor.d.ts.map +0 -1
- package/dist/utils/MonitoringMetrics.d.ts +0 -151
- package/dist/utils/MonitoringMetrics.d.ts.map +0 -1
- package/dist/utils/PoolKeyNormalizer.d.ts +0 -135
- package/dist/utils/PoolKeyNormalizer.d.ts.map +0 -1
- package/dist/utils/SignatureHelper.d.ts +0 -140
- package/dist/utils/SignatureHelper.d.ts.map +0 -1
- package/dist/utils/SwapEventExtractor.d.ts +0 -152
- package/dist/utils/SwapEventExtractor.d.ts.map +0 -1
- package/dist/utils/bignumber-pool-cache.d.ts +0 -169
- package/dist/utils/bignumber-pool-cache.d.ts.map +0 -1
- package/dist/utils/composite-pool-converter.d.ts +0 -121
- package/dist/utils/composite-pool-converter.d.ts.map +0 -1
- package/dist/utils/pool-pair-parser.d.ts +0 -57
- package/dist/utils/pool-pair-parser.d.ts.map +0 -1
- package/dist/utils/pool-state-validator.d.ts +0 -207
- package/dist/utils/pool-state-validator.d.ts.map +0 -1
- package/dist/utils/position-filters.d.ts +0 -252
- package/dist/utils/position-filters.d.ts.map +0 -1
- package/dist/utils/swap-delta-calculator.d.ts +0 -231
- package/dist/utils/swap-delta-calculator.d.ts.map +0 -1
- package/dist/utils/tick-crossing-handler.d.ts +0 -250
- package/dist/utils/tick-crossing-handler.d.ts.map +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 o,JsonRpcProvider as i,Contract as r,Signature as s,keccak256 as a,toUtf8Bytes as c,ethers as l,Mnemonic as d,HDNodeWallet as u,computeAddress as h,SigningKey as g}from"ethers";import{ChainCallDTO as m,SigningType as p,calculatePersonalSignPrefix as f,SigningClient as y}from"@gala-chain/connect";import{v4 as k}from"uuid";import v from"bignumber.js";import{PublicKey as w,Connection as b,Keypair as S,Transaction as A,ComputeBudgetProgram as T,TransactionInstruction as E,SystemProgram as C,LAMPORTS_PER_SOL as I}from"@solana/web3.js";import N from"json-stringify-deterministic";import{TOKEN_PROGRAM_ID as D,AccountLayout as P,ASSOCIATED_TOKEN_PROGRAM_ID as x}from"@solana/spl-token";import _ from"bs58";import{TokenClassKey as F,TokenBalance as R}from"@gala-chain/api";import{Pool as B,TickData as U,CompositePoolDto as O,GetCompositePoolDto as L,QuoteExactAmountDto as M,quoteExactAmount as $,tickToSqrtPrice as K,getLiquidityForAmounts as q,getAmountsForLiquidity as G,liquidity0 as W,liquidity1 as H,getAmount0Delta as z,getAmount1Delta as j,sqrtPriceToTick as V,computeSwapStep as X}from"@gala-chain/dex";import Q from"axios";import{io as J}from"socket.io-client";const Y={UPLOAD_IMAGE:"/v1/tokens/:tokenName/image",FETCH_POOLS:"/v1/tokens",GET_TOKEN:"/v1/tokens/:tokenName",GET_TOKEN_DISTRIBUTION:"/v1/holders",GET_TOKEN_BADGES:"/v1/tokens/:tokenName/badges",CHART:"/v1/chart",GET_TRADES:"/v1/tokens/:tokenName/trades",GET_PROFILE:"/v1/users/:address",UPDATE_PROFILE:"/v1/users/me",GET_TOKEN_LIST:"/v1/users/:address/tokens",GET_TOKENS_HELD:"/v1/users/:address/tokens",USER_BALANCES:"/v1/users/:address/balances",USER_REPORT:"/v1/users/:address/report",GET_MANAGED_TOKENS:"/v1/users/me/managed-tokens",VALIDATE_TOKEN:"/v1/utils/validate-token",UPDATE_TOKEN_CONFIG:"/v1/tokens/:tokenName",TOKEN_STATS:"/v1/tokens/:tokenName/stats",OEMBED:"/oembed",OEMBED_BUY_SELL:"/oembed/buy-sell/:tokenName",OEMBED_PROFILE:"/oembed/profile/:address"},Z="/v1/users/referrals/url",ee="/v1/users/referrals",te="/v1/users/referrals/summary",ne="/v1/tokens/:tokenName/start-stream",oe="/v1/tokens/:tokenName/stop-stream",ie="/v1/tokens/:tokenName/stream/disable",re="/v1/tokens/:tokenName/stream/enable",se="/v1/tokens/:tokenName/reset-key",ae="/v1/tokens/:tokenName/recordings",ce="/v1/tokens/:tokenName/recordings/:assetId/download",le="/v1/tokens/:tokenName/recordings/:assetId",de="/v1/tokens/:tokenName/stream/simulcast",ue="/v1/tokens/:tokenName/stream/simulcast",he="/v1/tokens/:tokenName/stream/simulcast/:targetId",ge="/v1/config",me="/v1/config",pe="/v1/config",fe="/v1/tokens/:tokenName/role",ye="/v1/roles",ke="/v1/tokens/:tokenName/access",ve="/v1/tokens/:tokenName/credentials",we="/auth/login",be="/auth/logout",Se="/auth/refresh",Ae="/auth/session",Te="/v1/tokens/:tokenName/bans",Ee="/v1/tokens/:tokenName/bans",Ce="/v1/tokens/:tokenName/bans/:userAddress",Ie="/v1/tokens/:tokenName/bans/:userAddress",Ne="/v1/tokens/:tokenName/active-users",De="/v1/user-bans",Pe="/v1/user-bans",xe="/v1/user-bans/:userAddress",_e="/v1/user-bans/:userAddress",Fe={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Re="/v1/moderator-invites",Be="/v1/moderator-invites/claim",Ue="/v1/moderated-tokens",Oe="/v1/moderator-invites",Le="/v1/moderator-invites/:id",Me="/v1/moderator-invites/:id/role",$e="/v1/moderator-invites/:id",Ke="/v1/moderator-invites/code/:code",qe={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},Ge="/v1/overseer-invites",We="/v1/overseer-invites",He="/v1/overseer-invites/code/:code",ze="/v1/overseer-invites/claim",je="/v1/overseer-invites/:id",Ve="/v1/overseers",Xe="/v1/overseers",Qe="/v1/overseers/:address",Je="/v1/overseers/me",Ye="/v1/overseer-summary",Ze="/v1/overseer-summary/bans",et="/v1/overseer-summary/token-bans",tt="/v1/overseer-summary/invites",nt="/v1/overseer-summary/flags",ot="/v1/overseer-summary/users",it="/v1/users",rt="/v1/users/:address/summary",st="/v1/cache/flush/address/:address",at="/v1/cache/flush/token/:tokenName",ct="/v1/cache/flush/all",lt="/v1/cache/flush/wallet-aliases/:address",dt="/v1/cache/flush/wallet-aliases",ut="/v1/token-bans",ht="/v1/token-bans",gt="/v1/token-bans/:tokenName",mt="/v1/token-bans/:tokenName",pt="/v1/reactions",ft="/v1/reactions",yt="/v1/trades",kt={GET_MESSAGES:"/v1/messages",CREATE_MESSAGE:"/v1/messages",UPDATE_MESSAGE:"/v1/messages/:id",DELETE_MESSAGE:"/v1/messages/:id",GET_PINNED:"/v1/messages/pinned",PIN_MESSAGE:"/v1/messages/:id/pin",UNPIN_MESSAGE:"/v1/messages/:id/unpin",GET_MESSAGE_STATS:"/v1/messages/stats"},vt="/v1/restricted-token-names",wt="/v1/restricted-token-names",bt="/live/:tokenName/chat",St="/live/:tokenName/chat",At="/live/:tokenName/chat",Tt="/live/chat",Et="/live/chat",Ct="/live/chat",It="/live/:tokenName/chat/slow-mode",Nt="/live/:tokenName/engagement-stats",Dt={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"},Pt="/v1/stats",xt="/v1/trading/fee",_t="/v1/trading/sale-details",Ft="/v1/trading/quote",Rt="/v1/trading/premint-quote",Bt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},Ut="/v1/notifications/register",Ot="/v1/notifications/unregister",Lt="/v1/notifications/preferences",Mt="/v1/notifications/preferences",$t="/v1/config/client-flags",Kt="native",qt="exact";class Gt extends Error{constructor(e,t,n){super(`API Error [${e}]: ${t}`),this.status=e,this.message=t,this.details=n,this.name="ApiError"}}function Wt(e){return"object"==typeof e&&null!==e&&"collection"in e&&"category"in e&&"type"in e&&"additionalKey"in e&&"string"==typeof e.collection&&"string"==typeof e.category&&"string"==typeof e.type&&"string"==typeof e.additionalKey}function Ht(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.positionId&&Wt(t.token0ClassKey)&&Wt(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickLower&&"number"==typeof t.tickUpper&&"string"==typeof t.liquidity&&"string"==typeof t.feeGrowthInside0Last&&"string"==typeof t.feeGrowthInside1Last&&"string"==typeof t.tokensOwed0&&"string"==typeof t.tokensOwed1}const zt="REQUIRED",jt="INVALID_TYPE",Vt="INVALID_VALUE",Xt="INVALID_FORMAT",Qt="TOO_LARGE",Jt="INVALID_RANGE";class Yt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class Zt extends Yt{constructor(e){super(e,"token","TOKEN_RESTRICTED"),this.name="TokenRestrictedError"}}class en extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class tn extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class nn extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}class on extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapQuoteError"}}class rn extends Error{constructor(e,t,n,o){super(e),this.originalError=t,this.transactionHash=n,this.code=o,this.name="GSwapSwapError"}}class sn extends Error{constructor(e,t,n,o,i){super(e),this.originalError=t,this.tokenA=n,this.tokenB=o,this.code=i,this.name="GSwapPoolError"}}class an extends Error{constructor(e,t,n,o){super(e),this.originalError=t,this.walletAddress=n,this.code=o,this.name="GSwapAssetError"}}class cn extends Error{constructor(e,t,n){super(e),this.originalError=t,this.code=n,this.name="GSwapPositionError"}}class ln extends Yt{constructor(e,t){super(e,"dexQuote","DEX_QUOTE_ERROR"),this.context=t,this.name="DexQuoteError"}}class dn extends Yt{constructor(e){super(e,"dexPool","DEX_POOL_NOT_FOUND"),this.name="DexPoolNotFoundError"}}function un(e){return e instanceof Error}function hn(e){return un(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 gn(e){return"object"==typeof e&&null!==e?e:void 0}function mn(e,t){const n=gn(e),o=gn(n?.launchpadError),i=yn(e)?e.response:void 0,r=gn(i?.data),s=e instanceof Gt?e.status:"number"==typeof o?.statusCode?o.statusCode:i?.status,a="string"==typeof r?.message?r.message:"string"==typeof r?.Message?r.Message:hn(e);if(403===s)return new Zt(""!==a?a:"One or both tokens are restricted (blacklisted or not yet graduated).");if(404===s)return"pool"===t?new dn(""!==a?a:"DEX pool not found"):new Gt(404,""!==a?a:"Position not found",r);if(429===s){const t=i?.headers?.["retry-after"],n="string"==typeof t||"number"==typeof t?String(t):void 0;return new en(`Trade backend per-IP rate limit exceeded (100 requests per 60 seconds).${void 0===n?"":` Retry-After: ${n}.`}`,429,e instanceof Error?e:void 0)}if(502===s)return new en("Trade backend upstream chain unavailable",502,e instanceof Error?e:void 0);if(e instanceof Gt)return e;if(yn(e)){const e=gn(r?.Data)??r;return new Gt(s??500,`${t}: ${a}`,e)}return new Gt(500,`${t}: ${hn(e)}`)}function pn(e){return un(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function fn(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 yn(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function kn(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 o=n.Status;if("number"!=typeof o)throw new Error(`${t}: Response Status must be a number, got ${typeof o}`);if(1!==o)throw new Error(`${t}: Response status indicates failure (Status: ${o})`);return n}function vn(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function wn(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}const bn="Token name is required and must be a string",Sn=e=>`Could not find vault address for token: ${e}`;function An(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function Tn(e,t){return new Yt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function En(e,t){const n=An(e,t);return new Yt(`${n} is required`,e,"REQUIRED")}function Cn(e,t,n){const o=An(e,n);return new Yt(`${o} must be ${t}`,e,"INVALID_FORMAT")}function In(e,t,n){return new en(e,t,n)}function Nn(e,t){return new tn(e,t)}function Dn(e,t,n){return new nn(e,t,n)}function Pn(e,t,n,o){n&&n.error(`${t}:`,e);const i=yn(e)?e.response?.status:void 0;return In(`${t}: ${hn(e)}`,i,un(e)?e:void 0)}function xn(e,t,n,o,i){const r=An(e,i);return new Yt(`${r} must be between ${t} and ${n}${void 0!==o?`, received: ${o}`:""}`,e,"OUT_OF_RANGE")}function _n(e,t,n,o){const i=An(e,o);return new Yt(`${i} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function Fn(e,t,n,o){const i=An(e,o);return new Yt(`${i} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function Rn(e,t,n,o){const i=An(e,o),r=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Yt(`${i} must be ${t}${r}`,e,"INVALID_TYPE")}function Bn(e,t,n){const o=An(e,n);return new Yt(`${o} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function Un(e){return new Yt(`Liquidity position not found: ${e}`,"positionId","POSITION_NOT_FOUND")}function On(e,t,n,o){const i=An(e,o);return new Yt(`Invalid ${i}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function Ln(e){return null!=e&&"object"==typeof e&&"data"in e}function Mn(e,t,n=!1){const o=!0===e.error,i=n&&(null===e.data||void 0===e.data);if(o||i){const n=e?.statusCode??e.status??void 0;throw In(e?.message??t,n)}}function $n(e){if(Ln(e))return e.data}function Kn(e,t="No data found in response"){if(!Ln(e))throw In(t);const n=e.data;if(null==n)throw In(t);return n}async function qn(e,t={}){const{errorContext:n="Operation failed",logger:o,debugLogEnabled:i=!1}=t;i&&o&&o.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new Yt(`${n}: No response from server`,"response","NO_RESPONSE");if(Mn(t,n,!0),i&&o&&o.debug(`${n}: completed successfully`),void 0===t.data)throw new Yt(`${n}: No data returned from API`,"data","NO_DATA");return t.data}catch(e){throw o&&o.error(n,{error:e}),e}}async function Gn(e,t={}){const{errorContext:n="Operation failed",logger:o,debugLogEnabled:i=!1}=t;i&&o&&o.debug(`${n}: starting operation`);try{const t=await e();return i&&o&&o.debug(`${n}: completed successfully`),t}catch(e){throw o&&o.error(n,{error:e}),e}}async function Wn(e,t={}){const{errorContext:n="Operation failed",logger:o,debugLogEnabled:i=!1}=t;i&&o&&o.debug(`${n}: starting operation`);try{const t=await e();if(null==t)throw new Yt(`${n}: No response from server`,"response","NO_RESPONSE");return Mn(t,n,!0),i&&o&&o.debug(`${n}: completed successfully`),t}catch(e){throw o&&o.error(n,{error:e}),e}}class Hn{}function zn(e){return e.trim().toLowerCase()}function jn(e){return e.trim().toUpperCase()}function Vn(e){return e.trim().toUpperCase()}var Xn;Hn.BASE_PRICE=1650667151e-14,Hn.PRICE_SCALING_FACTOR=1166069e-12,Hn.TRADING_FEE_FACTOR=.001,Hn.GAS_FEE="1",Hn.MIN_UNBONDING_FEE_FACTOR=0,Hn.MAX_UNBONDING_FEE_FACTOR=.5,Hn.NET_UNBONDING_FEE_FACTOR=.5,Hn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=1e7,function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(Xn||(Xn={}));class Qn{constructor(e){this.levelPriority={[Xn.DEBUG]:0,[Xn.INFO]:1,[Xn.WARN]:2,[Xn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?Xn.DEBUG:Xn.INFO)}debug(e,t){this.log(Xn.DEBUG,e,t)}info(e,t){this.log(Xn.INFO,e,t)}warn(e,t){this.log(Xn.WARN,e,t)}error(e,t){this.log(Xn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===Xn.DEBUG&&!this.debugEnabled)return;const o=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,i=this.getConsoleMethod(e);void 0!==n?un(n)?i(`${o} ${t}`,n.message,pn(n)??""):i(`${o} ${t}`,n):i(`${o} ${t}`)}getConsoleMethod(e){switch(e){case Xn.DEBUG:return console.debug;case Xn.INFO:return console.info;case Xn.WARN:return console.warn;case Xn.ERROR:return console.error;default:return console.log}}child(e){return new Qn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[Xn.DEBUG]>=this.levelPriority[this.minLevel]}}function Jn(e){return null==e||""===e}function Yn(e){return null==e}const Zn=new Qn({debug:!1,context:"DateUtils"});function eo(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())?(Zn.warn(`Invalid date string received: "${e}". Using fallback.`),t??new Date):n}catch(n){return Zn.warn(`Date parsing error for "${e}":`,n),t??new Date}}function to(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 no(e){return Date.now()-e}const oo={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},io={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},ro={MIN_LENGTH:1,MAX_LENGTH:50},so=100,ao=20,co={MAX_LIMIT:50},lo={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},uo={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}},ho={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})$/}},go=60,mo=31536e3,po={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},fo={PATTERN:/^[a-fA-F0-9]{64}$/},yo={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},ko=50,vo=1,wo=100,bo={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function So(e,t){if(Jn(e))return t;try{return JSON.parse(e)}catch{return t}}function Ao(e,t=0){if(Jn(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 To(e,t,n){if(Yn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const o=Number(e);return isNaN(o)?t:o}function Eo(e,t=0){if(Jn(e))return t;if("bigint"==typeof e)try{return Number(e)}catch{return t}if("number"==typeof e)return isNaN(e)||!isFinite(e)?t:Math.floor(e);const n=parseInt(String(e),10);return isNaN(n)?t:n}function Co(e,t,n){if(Yn(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 o=parseInt(String(e),10);return isNaN(o)?t:o}function Io(e,t="0"){if(Jn(e))return new v(t);if(v.isBigNumber(e))return e.isNaN()?new v(t):e;try{const n=new v(e);return n.isNaN()||!n.isFinite()?new v(t):n}catch{return new v(t)}}function No(e,t){if(Yn(e)||""===e)throw En(t);if(v.isBigNumber(e)){if(e.isNaN())throw Bn(t,"NaN");return e}try{const n=new v(e);if(n.isNaN())throw Bn(t,e);if(!n.isFinite())throw Bn(t,e);return n}catch(n){if(n instanceof Yt)throw n;throw Bn(t,e)}}function Do(e,t=0){if(Yn(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Ao(String(e).replace("%","").trim(),t)}function Po(e,t=18){const n=Ao(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function xo(e){return Po(e,8)}function _o(e){return Po(e,18)}function Fo(e,t,n,o){if("number"!=typeof e)throw Rn(o,"a number",e,o);if(e<t||e>n)throw xn(o,t,n,e)}function Ro(e,t,n){if("string"!=typeof e)throw Rn(n,"a string",e,n);if(e.length>t)throw Fn(n,t,e.length)}function Bo(e,t){if("number"!=typeof e)throw Rn(t,"a number",e,t);if(!Number.isInteger(e))throw Rn(t,"an integer",e,t);if(e<=0)throw _n(t,1,e,t)}function Uo(e,t,n="range"){const o="number"==typeof e?e:Number(e),i="number"==typeof t?t:Number(t);if(isNaN(o)||isNaN(i))throw Rn(n,"numeric values",void 0,n);if(o>i)throw new Yt(`Minimum value (${o}) must be less than or equal to maximum value (${i}) for ${n}`,n,Jt)}function Oo(e,t,n=!1){if("string"!=typeof e)throw Rn(t,"a string",e,t);if(!n&&0===e.trim().length)throw En(t,`${t} (non-empty string)`)}const Lo={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},Mo=function(e){return"string"==typeof e&&e.trim().length>0},$o=Yn;function Ko(e,t,n=100,o,i){if(void 0!==i&&"string"!=typeof i)throw new Yt("cursor must be a string","cursor",jt);const r=o??t,s=void 0!==o?"pageSize":"limit";if(void 0!==r&&(Bo(r,s),r>n))throw new Yt(`${s} must be at most ${n}`,s,Qt)}function qo(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function Go(e){return Object.values(e)}function Wo(e,t,n,o={}){const{description:i="parameter",treatEmptyAsNull:r=!0}=o,s=e[t],a=e[n],c=null!=s&&(!r||""!==s),l=null!=a&&(!r||""!==a);if(!c&&!l)throw Nn(`Either ${t} or ${n} must be provided (${i})`,n);if(c&&l)throw Nn(`Cannot provide both ${t} and ${n}. Provide exactly one (${i}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function Ho(e,t="tokenName",n=oo){if(!Mo(e))throw En(t);const o=e.trim();if(0===o.length)throw En(t);if(o.length<n.MIN_LENGTH)throw xn(t,n.MIN_LENGTH,n.MAX_LENGTH,o.length,`${t} length`);if(o.length>n.MAX_LENGTH)throw xn(t,n.MIN_LENGTH,n.MAX_LENGTH,o.length,`${t} length`);if(!n.PATTERN.test(o))throw new Yt(`${t} must contain only alphanumeric characters`,t,Xt)}function zo(e,t="tokenName",n=oo){if(null==e)throw En(t,t);if("string"!=typeof e)throw Rn(t,"a string",e);const o=e.trim();if(0===o.length)throw En(t,t);if(!n.PATTERN.test(o))throw new Yt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Xt)}function jo(e){return""===e||0===e.trim().length}function Vo(e,t,n){if(!$o(e)){if("string"!=typeof e)throw Rn(t,"a string",e,t);if(e.length>n)throw new Yt(`${t} must be at most ${n} characters`,t,Qt)}}function Xo(e,t){if($o(e))return;let n;if(e instanceof Date)n=e;else if("string"==typeof e)n=new Date(e);else{if("number"!=typeof e)throw Rn(t,"a date",e,t);n=new Date(e)}if(isNaN(n.getTime()))throw new Yt(`${t} must be a valid date`,t,Xt)}function Qo(e,t,n){try{Bo(e,t)}catch{throw function(e,t,n,o="OPERATION_FAILED"){return new Yt(`${e} failed: ${t}`,n,o)}(n,"must be a positive integer",t)}}function Jo(e,t,n="status"){void 0!==e&&function(e,t,n){const o=Object.values(t);if(!o.includes(e))throw new Yt(`${n} must be one of: ${o.join(", ")}`,n,Xt)}(e,t,n)}class Yo{constructor(e,t=!1,n){this.http=e,this.logger=new Qn({debug:t,context:this.constructor.name}),this.jwtAuth=n}setJwtAuth(e){this.jwtAuth=e}getJwtHeaders(){if(!this.jwtAuth){if("test"===process.env.NODE_ENV&&!this.isCalledFromUserCode())return{};throw new tn("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=pn(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){Qo(e,t,n)}}class Zo{constructor(e=!1,t){this.logger=t||new Qn({debug:e,context:this.constructor.name})}}class ei extends Zo{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 ti extends ei{constructor(e=!1){super(e)}normalizeKey(e){return zn(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>=ti.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??Hn.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,o)=>{n.lastUpdated<e&&(e=n.lastUpdated);let i=0;i+=2*o.length,void 0!==n.reverseBondingCurveMinFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveMaxFeeFactor&&(i+=8),void 0!==n.reverseBondingCurveNetFeeFactor&&(i+=8),i+=8,void 0!==n.vaultAddress&&""!==n.vaultAddress&&(i+=2*n.vaultAddress.length),void 0!==n.maxSupply&&""!==n.maxSupply&&(i+=2*n.maxSupply.length),void 0!==n.symbol&&""!==n.symbol&&(i+=2*n.symbol.length),i+=32,t+=i}),{cacheSize:t,oldestEntry:this.cache.size>0?e:0}}getByTokenId(e){const t=`token:${zn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${zn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${zn(e)}`;return this.cache.has(t)}}ti.MAX_CACHE_SIZE=1e4;class ni extends m{constructor(e){super(),this.tokenName=e.tokenName,this.tokenSymbol=e.tokenSymbol,this.tokenDescription=e.tokenDescription,this.tokenImage=e.tokenImage,this.preBuyQuantity=e.preBuyQuantity,void 0!==e.websiteUrl&&(this.websiteUrl=e.websiteUrl),void 0!==e.telegramUrl&&(this.telegramUrl=e.telegramUrl),void 0!==e.twitterUrl&&(this.twitterUrl=e.twitterUrl),void 0!==e.instagramUrl&&(this.instagramUrl=e.instagramUrl),void 0!==e.facebookUrl&&(this.facebookUrl=e.facebookUrl),void 0!==e.redditUrl&&(this.redditUrl=e.redditUrl),void 0!==e.tiktokUrl&&(this.tiktokUrl=e.tiktokUrl),this.tokenCategory=e.tokenCategory,this.tokenCollection=e.tokenCollection,this.uniqueKey=e.uniqueKey,e.reverseBondingCurveConfiguration&&(this.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration),void 0!==e.saleStartTime&&(this.saleStartTime=e.saleStartTime)}}function oi(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}const ii={ETHEREUM:Lo.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:Lo.BACKEND_ADDRESS,CLIENT:Lo.CLIENT_ADDRESS};class ri{toBackendFormat(e){if(!Mo(e))throw new Yt("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 Yt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=oi(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new Yt(`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(!Mo(e))throw new Yt("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 Yt(`Invalid backend address format. Expected "eth|{40-hex-characters}" or "eth|0x{40-hex-characters}". Got: "${e}"`,"address","INVALID_FORMAT");const n=t[1],o=void 0!==n&&""!==n?6:4;return`0x${e.substring(o)}`}normalizeInput(e){if(void 0!==e&&""!==e){if(e.startsWith("client|")){if(!ii.CLIENT.test(e))throw new Yt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!ii.BACKEND.test(e))throw new Yt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!Mo(e)&&(!!ii.ETHEREUM.test(e)||(!!ii.ETHEREUM_NO_PREFIX.test(e)||(!!ii.BACKEND.test(e)||!!ii.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new Yt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return Mo(e)?ii.ETHEREUM.test(e)||ii.ETHEREUM_NO_PREFIX.test(e)?"ethereum":ii.BACKEND.test(e)?"backend":ii.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 oi(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new Yt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const si=new ri,ai=oi;function ci(e){return si.toBackendFormat(e)}function li(e){return si.toEthereumFormat(e)}function di(e){return si.isValid(e)}function ui(e,t="address"){si.assertValid(e,t)}function hi(e){return si.detectFormat(e)}var gi=Object.freeze({__proto__:null,AddressFormatter:ri,assertValidWalletAddress:ui,detectFormat:hi,fromBackendAddressFormat:li,isValidAddress:di,normalizeAddressInput:function(e){return si.normalizeInput(e)},stripHexPrefix:ai,toBackendAddressFormat:ci});const mi=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"),pi=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"),fi=e.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),yi=e.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),ki=e.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),vi=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(Lo.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.string().regex(Lo.ETH_ADDRESS,"Invalid Ethereum address format");const wi=e.string().refine(e=>Lo.BACKEND_ADDRESS.test(e)||Lo.ETH_ADDRESS.test(e)||Lo.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new ri).normalizeInput(e)??e),bi=e.string().refine(e=>Lo.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Si=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Ao(e,0)>0,"Amount must be greater than zero"),Ai=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Ao(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 Ti=e.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function Ei(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),Ei(100),Ei(20),Ei(20);const Ci=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"),Ii=e.string().max(255,"Filename must be at most 255 characters"),Ni=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 Di=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 Pi=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),name:Ii,size:Ci,type:Ni});const xi=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"),_i=e.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.union([xi,_i]),e.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Ii.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Pi.includes(t)},`Filename must end with one of: ${Pi.join(", ")}`),e.object({websiteUrl:Ti,telegramUrl:Ti,twitterUrl:Ti,instagramUrl:Ti,facebookUrl:Ti,redditUrl:Ti,tiktokUrl:Ti}).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 Fi=e.string().min(1,"Token category must not be empty").default("Unit"),Ri=e.string().min(1,"Token collection must not be empty").default("Token"),Bi=e.object({minFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Ao(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Ao(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Ao(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Ao(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>Ao(e.maxFeePortion,0)>=Ao(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),Ui=e.object({tokenName:mi,tokenSymbol:pi,tokenDescription:fi,tokenImage:e.union([e.instanceof(File),e.instanceof(Buffer),e.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Ai.default("0"),websiteUrl:Ti,telegramUrl:Ti,twitterUrl:Ti,instagramUrl:Ti,facebookUrl:Ti,redditUrl:Ti,tiktokUrl:Ti,tokenCategory:Fi,tokenCollection:Ri,reverseBondingCurveConfiguration:Bi.optional(),saleStartTime:e.number().int().positive().optional(),privateKey:Di.optional()});e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),tokenName:mi}),e.enum(["RECENT","POPULAR"]);const Oi=e.object({tokenName:mi.optional(),symbol:pi.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 Li=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:mi});e.object({tokenName:mi,slippageToleranceFactor:e.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.number().min(0).max(1).optional(),privateKey:Di.optional()});const Mi=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(100).default(10)}),$i=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)}),Ki=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)});Mi.extend({type:e.enum(["RECENT","POPULAR"]).optional(),tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),$i.extend({tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),Ki.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")}),e.object({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()});const qi=e.enum(["buy","sell"]);e.enum(["BUY","SELL"]),e.object({tradeType:qi,tokenAmount:Si,vaultAddress:bi,userAddress:wi,slippageTolerance:Si.optional(),deadline:e.number().int().positive().optional()}),e.object({tokenSymbol:pi,nativeTokenQuantity:Si,expectedToken:Si,maxAcceptableReverseBondingCurveFee:Ai.default("0").optional()}),e.object({tokenSymbol:pi,tokenQuantity:Si,expectedNativeToken:Si,maxAcceptableReverseBondingCurveFee:Ai.default("0").optional()}),Ki.extend({tokenName:yi.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 Gi=e.enum(["NATIVE","MEME"]),Wi=e.enum(["IN","OUT"]);e.object({type:Gi,method:Wi,vaultAddress:bi,amount:Si}),e.object({nativeTokenQuantity:Si}),e.object({vaultAddress:bi}),e.object({minFeePortion:Si,maxFeePortion:Si});const Hi=e.enum(["all","DEFI","ASSET"]);function zi(e){return t=>{const n=e.safeParse(t);return{success:n.success,data:n.success?n.data:void 0,errors:n.success?void 0:n.error.issues.map(e=>e.message)}}}$i.extend({type:Hi.optional(),address:wi.optional(),search:ki.optional(),tokenName:yi.optional()}),e.object({address:wi.optional(),refresh:e.boolean().optional()}),e.object({profileImage:e.string(),fullName:vi,address:wi,privateKey:Di.optional()}),e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),address:wi.optional(),privateKey:Di.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:wi,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:yi.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 ji=zi(mi),Vi=zi(Ui),Xi=zi(Oi);function Qi(e){const t=function(e){const t=Vi(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 Ji(e,t){return"string"==typeof e[t]}function Yi(e,t){return void 0===e[t]||"string"==typeof e[t]}function Zi(e,t){return void 0===e[t]||"number"==typeof e[t]}function er(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Ji(t,"tokenName")&&Zi(t,"from")&&Zi(t,"to")&&Zi(t,"resolution")}function tr(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function nr(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,o]of Object.entries(e)){if(!tr(n[t],o))return!1}return!0}}qo({BUY:"buy",SELL:"sell"});const or=nr({vaultAddress:"string"}),ir=nr({nativeTokenQuantity:"string"});function rr(e){if($o(e)||"object"!=typeof e)return{};const t={};for(const[n,o]of Object.entries(e))$o(o)||(Mo(o)?t[n]=o:"number"==typeof o||"boolean"==typeof o?t[n]=o.toString():Array.isArray(o)?t[n]=o.join(","):t[n]="object"==typeof o?JSON.stringify(o):String(o));return t}function sr(e,t="0"){return Io(e,t)}function ar(e,t){return void 0!==t?sr(e).toFixed(t):sr(e).toFixed()}function cr(e){const t=sr(e),n=Math.log(1.0001),o=t.toNumber();return Math.log(o)/n}function lr(e,t=!1){const n=sr(e),o=new v(1).dividedBy(n);return t?o.toFixed():o}function dr(e,t){return v.min(sr(e),sr(t))}function ur(e,t){return v.max(sr(e),sr(t))}function hr(e){return sr(e).isZero()}function gr(e){return sr(e).isLessThan(0)}function mr(e,t){return sr(e).isLessThan(sr(t))}function pr(e,t){return sr(e).multipliedBy(t).dividedBy(100)}function fr(...e){e.forEach(e=>{if(e.isNaN())throw Bn("value","NaN");if(!e.isFinite())throw Fn("value","finite");if(e.isLessThanOrEqualTo(0))throw _n("value","0",e.toString())})}function yr(...e){e.forEach(e=>{if(e.isNaN())throw Bn("value","NaN");if(!e.isFinite())throw Fn("value","finite");if(e.isLessThan(0))throw _n("value","0",e.toString())})}function kr(e,t,n){if(e.isNaN())throw Bn(t,"NaN");if(!e.isFinite())throw Fn(t,"finite");if(e.isLessThanOrEqualTo(0))throw _n(t,"0",e.toString())}function vr(e,t,n="0"){const o=sr(t);return hr(o)?sr(n):sr(e).dividedBy(o)}function wr(e,t){return Math.floor(e/t)*t}class br{static calculateBuyWithExact(e,t){const n=Ao(e),o=Ao(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:a}=Hn,c=this.roundUp(i*(Math.exp((o+n)*r)-Math.exp(o*r))/r,8),l=ar(sr(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateBuyWithNative(e,t){const n=Ao(e),o=Ao(t),{BASE_PRICE:i,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:s,GAS_FEE:a}=Hn,c=Math.log(n*r/i+Math.exp(o*r))/r-o,l=ar(sr(c).multipliedBy(s));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:a}}static calculateSellWithExact(e,t,n,o,i){const r=Ao(e),s=Ao(t),a=Ao(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=Hn,h=c*(Math.exp(s*l)-Math.exp((s-r)*l))/l,g=sr(h),m=o+s/a*(i-o),p=ar(g.multipliedBy(m),8),f=ar(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}static calculateSellWithNative(e,t,n,o,i){const r=Ao(e),s=Ao(t),a=Ao(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=Hn;if(r>=c*(Math.exp(s*l)-1)/l){const e=sr(r),t=o+s/a*(i-o),n=ar(e.multipliedBy(t),8),c=ar(e.multipliedBy(d));return{amount:s.toString(),reverseBondingCurveFee:n,transactionFee:c,gasFee:u}}const h=s-Math.log(Math.exp(s*l)-r*l/c)/l,g=sr(r),m=o+s/a*(i-o),p=ar(g.multipliedBy(m),8),f=ar(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}static roundUp(e,t){const n=Math.pow(10,t);return Math.ceil(e*n)/n}}class Sr extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Ar(e,t,n){if(null==e)throw new Sr("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=xi.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Sr(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Sr("Filename is required when uploading Buffer objects",t,n);const o=_i.safeParse(e);if(!o.success){const e=o.error.issues.map(e=>e.message).join("; ");throw new Sr(e,t,n)}try{Ro(t,255,"filename")}catch(e){throw new Sr(e.message,t,n)}const i=["image/png","image/jpg","image/jpeg","image/gif","image/webp","image/svg+xml"];if(!i.includes(n))throw new Sr(`Invalid file type "${n}" is not allowed. Allowed types: ${i.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),s=[".png",".jpg",".jpeg",".gif",".webp",".svg"];if(!s.includes(r))throw new Sr(`File extension "${r}" is not allowed. Allowed extensions: ${s.join(", ")}`,t,n);const a=function(e){switch(e.toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".svg":return"image/svg+xml";default:return"application/octet-stream"}}(r);if(a!==n&&"application/octet-stream"!==a)throw new Sr(`File extension "${r}" does not match MIME type "${n}"`,t,n);return}throw new Sr("File must be a File object (browser) or Buffer (Node.js)",t,n)}function Tr(e,t,n=1){if(null==e||""===e)return null;if("string"!=typeof e)return null;const o=e.trim();return o.length<n?null:o}function Er(e,t){return e.toLowerCase()===t.toLowerCase()}function Cr(e,t){return e.toLowerCase().includes(t.toLowerCase())}function Ir(e,t,n,o){return e===n&&t===o||e===o&&t===n}class Nr{validate(e,t={}){const{allowZero:n=!0,minimum:o,maximum:i,maxDecimals:r=Nr.MAX_DECIMAL_PLACES,fieldName:s="amount"}=t;if(!Mo(e))throw new Yt(`${s} cannot be empty or whitespace-only. Provide a valid numeric string.`,s,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Yt(`${s} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,s,"INVALID_NUMERIC_STRING");const a=Ao(e,NaN);if(isNaN(a))throw new Yt(`${s} must be a valid numeric string. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!isFinite(a))throw new Yt(`${s} must be a finite number. Cannot be Infinity or -Infinity.`,s,"INVALID_NUMERIC_STRING");if(a<0)throw new Yt(`${s} must be non-negative. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");if(!n&&0===a)throw new Yt(`${s} must be greater than zero. Received: "${e}"`,s,"INVALID_NUMERIC_STRING");const c=sr(e),l=c.decimalPlaces()??0;if(l>r)throw new Yt(`${s} cannot exceed ${r} decimal places. Received: ${l} decimal places`,s,"PRECISION_EXCEEDED");if(void 0!==o&&mr(c,o))throw new Yt(`${s} must be at least ${o}. Received: "${e}"`,s,"BELOW_MINIMUM");if(void 0!==i&&(d=i,sr(c).isGreaterThan(sr(d))))throw new Yt(`${s} cannot exceed ${i}. Received: "${e}"`,s,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return sr(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 ar(e,t)}clampAmount(e,t,n){const o=sr(e),i=sr(t),r=sr(n);return function(e,t,n){const o=sr(e),i=sr(t),r=sr(n);return o.isGreaterThanOrEqualTo(i)&&o.isLessThanOrEqualTo(r)}(o,i,r)?ar(o):mr(o,i)?ar(i):ar(r)}}function Dr(e,t){throw new Yt(e.join("; "),t,"VALIDATION_ERROR")}function Pr(e){const t=ji(e);!t.success&&t.errors&&Dr(t.errors,"tokenName")}function xr(e){const t=Xi(e);!t.success&&t.errors&&Dr(t.errors,"options")}function _r(e){const t=Li.safeParse(e);var n;t.success||Dr((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 Fr(e,t,n=!0){Rr.validate(e,{fieldName:t,allowZero:n})}Nr.MAX_DECIMAL_PLACES=18,Nr.MIN_POSITIVE="0.00000000000000001";const Rr=new Nr;class Br{constructor(e,t,n,o,i,r,s="local"){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=o,this.galaChainHttp=i,this.dexApiHttp=r,this.defaultCalculateAmountMode=s,this.metadataCache=new ti}addIfDefined(e,t,n){return void 0!==n&&(e[t]=n),e}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Pr(t);const o=`${t}.png`;Ar(n.file,o,"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 Cn("file","a File object (browser) or Buffer (Node.js)");{const o=`${void 0!==n.tokenName&&""!==n.tokenName?n.tokenName:t}.png`,i=new Blob([n.file],{type:"image/png"});e.append("image",i,o)}}const o=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===o.error||200!==o.status)throw In(void 0!==o.message&&""!==o.message?o.message:"Image upload failed - no URL returned",o.status);const i=$n(o);if(!i?.imageUrl)throw In("Image upload failed - no URL returned",o.status);return i.imageUrl}catch(e){if(un(e)&&e.message.includes("FormData"))throw Nn("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&&Ko(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&Pr(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=rr(t),o=await this.http.get("/launchpad/fetch-pool",n);if(!0===o.error||200!==o.status)throw In(void 0!==o.message&&""!==o.message?o.message:"Failed to fetch pools",o.status);const i=$n(o);if(null==i)throw In("Failed to fetch pools - no data returned",o.status);let r=[];if(i.tokens)if(Array.isArray(i.tokens))r=i.tokens.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!hr(t)||!hr(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:o,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}});else{const e=i.tokens,t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!hr(t)||!hr(n);r=[{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:o,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}]}else i.pools&&Array.isArray(i.pools)&&(r=i.pools.map(e=>{const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0",o=!hr(t)||!hr(n);return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:o,createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}));const{extractMetadataFromPoolData:s,isValidPoolForCaching:a}=await Promise.resolve().then(function(){return fh});r.forEach(e=>{if(!a(e))return void this.logger.debug("Skipping pool with invalid structure for caching",e);const t=s(e,this.logger);t&&this.warmCacheFromPoolData(e.tokenName,t)});const c=i.count??i.total??0,l={hasNextPage:i.hasNextPage??!1};return void 0!==i.hasPrevPage&&(l.hasPrevPage=i.hasPrevPage),void 0!==i.nextCursor&&(l.nextCursor=i.nextCursor),void 0!==i.prevCursor&&(l.prevCursor=i.prevCursor),c>0&&(l.totalCount=c),{items:r,pageInfo:l}}async checkPool(e){xr(e),void 0!==e.tokenName&&""!==e.tokenName&&Pr(e.tokenName);const t=rr(e),n=await this.http.get("/launchpad/check-pool",t);if(!0===n.error||200!==n.status)throw In(void 0!==n.message&&""!==n.message?n.message:"Failed to check pool",n.status);const o=n.data;return void 0!==e.symbol&&""!==e.symbol?o?.isSymbolExist??!1:void 0!==e.tokenName&&""!==e.tokenName?o?.isNameExist??!1:o?.exists??!1}async fetchVolumeData(e){if(!er(e))throw Cn("options","{ tokenName: string, from?: number, to?: number, resolution?: number }");const{tokenName:t,from:n,to:o,resolution:i}=e;if(Pr(t),null==n||null==o||null==i)throw En("graphOptions","Graph options (from, to, resolution)");const r={tokenName:t,from:n,to:o,resolution:i};_r(r);const s=rr(r),a=await this.http.get("/launchpad/get-graph-data",s);if(!0===a.error||200!==a.status)throw In(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch graph data",a.status);const c=$n(a);if(!c)throw In("Failed to fetch graph data - no data returned",a.status);return{dataPoints:c}}async fetchPools(e={}){let t;"recent"===e.type?t="RECENT":"popular"===e.type&&(t="POPULAR");const n={pageSize:e.pageSize??10};return void 0!==e.cursor&&(n.cursor=e.cursor),void 0!==e.search&&""!==e.search&&(n.search=e.search),void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=e.tokenName),null!=t&&(n.type=t),void 0!==e.hasUpcomingShows&&(n.hasUpcomingShows=e.hasUpcomingShows),void 0!==e.language&&""!==e.language&&(n.language=e.language),void 0!==e.recentlyStreamed&&(n.recentlyStreamed=e.recentlyStreamed),this.fetchPoolsFromAPI(n)}async isTokenNameAvailable(e){try{return!await this.checkPool({tokenName:e})}catch{return!1}}async isTokenSymbolAvailable(e){try{return!await this.checkPool({symbol:e})}catch{return!1}}async calculateBuyAmount(e){if(null==e||"object"!=typeof e)throw Cn("options","an options object");const{tokenName:t,amount:n,type:o,currentSupply:i}=e,r=e.mode??this.defaultCalculateAmountMode;if("local"!==r&&"external"!==r)throw Rn("mode",'"local" or "external"',r);if(!Mo(t))throw En("tokenName","Token name");if(!Mo(n))throw En("amount","Amount");if(o!==Kt&&o!==qt)throw Rn("type",'"native" or "exact"',o);return"external"===r?this.calculateBuyAmountExternal({tokenName:t,amount:n,type:o}):this.calculateBuyAmountLocal(this.addIfDefined({tokenName:t,amount:n,type:o},"currentSupply",i))}async calculateBuyAmountExternal(e){const{tokenName:t,amount:n,type:o}=e;if("string"!=typeof t||""===t)throw new Yt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof n||""===n)throw new Yt("Amount must be a non-empty string","amount","INVALID_AMOUNT");return"exact"===o?qn(()=>this.http.get(Ft,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):qn(()=>this.http.get(Ft,{tokenName:t,amount:n,type:"NATIVE",method:"IN"}),{errorContext:`Failed to calculate buy amount for ${t} (native/GALA budget)`})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:o,currentSupply:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e,c=e.mode??this.defaultCalculateAmountMode;if("local"!==c&&"external"!==c)throw Rn("mode",'"local" or "external"',c);if(!Mo(t))throw En("tokenName","Token name");if(!Mo(n))throw En("amount","Amount");if(o!==qt&&o!==Kt)throw Rn("type",'"exact" or "native"',o);if("external"===c)return this.calculateSellAmountExternal({tokenName:t,amount:n,type:o});{const e={tokenName:t,amount:n,type:o,...void 0!==i&&{currentSupply:i},...void 0!==r&&{maxSupply:r},...void 0!==s&&{reverseBondingCurveMaxFeeFactor:s},...void 0!==a&&{reverseBondingCurveMinFeeFactor:a}};return this.calculateSellAmountLocal(e)}}async calculateSellAmountExternal(e){const{tokenName:t,amount:n,type:o}=e;if("string"!=typeof t||""===t)throw new Yt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof n||""===n)throw new Yt("Amount must be a non-empty string","amount","INVALID_AMOUNT");return"exact"===o?qn(()=>this.http.get(Ft,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):qn(()=>this.http.get(Ft,{tokenName:t,amount:n,type:"NATIVE",method:"OUT"}),{errorContext:`Failed to calculate sell amount for ${t} (native/GALA target)`})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:o,currentSupply:i}=e;if(!Mo(n))throw En("amount","Amount");if(o!==Kt&&o!==qt)throw Rn("type",'"native" or "exact"',o);void 0!==i&&Fr(i,"currentSupply");const r=null==i||""===i;if(r&&(null==t||""===t))throw En("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Pr(t);let s=i;if(r){s=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return o===qt?br.calculateBuyWithExact(n,s):br.calculateBuyWithNative(n,s)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:o,currentSupply:i,maxSupply:r,reverseBondingCurveMaxFeeFactor:s,reverseBondingCurveMinFeeFactor:a}=e;if(!Mo(n))throw En("amount","Amount");if(o!==qt&&o!==Kt)throw Rn("type",'"exact" or "native"',o);void 0!==i&&Fr(i,"currentSupply");const c=null==i||""===i||null==r||""===r||void 0===s||void 0===a;if(c&&(null==t||""===t))throw En("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Pr(t);let l=i,d=r,u=s,h=a;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 o===qt?br.calculateSellWithExact(n,l,d,h,u):br.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 Ji(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&Yi(t,"currentSupply")}(e))throw Rn("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:o,currentSupply:i}=t;Pr(n);const r=await this.tokenResolver.resolveTokenToVault(n);if(null==r||""===r)throw new Yt(Sn(n),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Nn("GalaChain HTTP client not configured");const s=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:r});if(1!==s.Status)throw In(`Failed to fetch pool details: Status ${s.Status}`,s.Status);const a=s.Data,c=i??ar(sr(a.maxSupply).minus(a.sellingTokenQuantity)),l=a.sellingTokenQuantity;if("0"===l)throw En("tokenName",`Token ${n} is already graduated (no tokens remaining in pool)`);const d={tokenName:n,amount:l,type:"exact",currentSupply:c,...void 0!==o&&{mode:o}};return{...await this.calculateBuyAmount(d),remainingTokens:l}}async launchToken(e){if(!this.bundleHttp)throw Nn("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");Qi(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Ao(t);if(0===n&&"0"!==t)throw Bn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw Bn("preBuyQuantity",t,"Pre-buy quantity");if(e.reverseBondingCurveConfiguration){const{minFeePortion:t,maxFeePortion:n}=e.reverseBondingCurveConfiguration;!function(e,t,n){const o="string"==typeof e?parseFloat(e):e,i="string"==typeof t?parseFloat(t):t;if(!isFinite(o))throw new Yt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(i))throw new Yt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(o<.1)throw new Yt(`${n} minFee must be >= 0.1, received ${o}`,n,"INVALID_FEE_MINIMUM");if(i>.5)throw new Yt(`${n} maxFee must be <= 0.5, received ${i}`,n,"INVALID_FEE_MAXIMUM");if(o>i)throw new Yt(`${n} minFee (${o}) must be <= maxFee (${i})`,n,"INVALID_FEE_RANGE")}(t,n,"reverseBondingCurve")}let o="https://via.placeholder.com/200?text=Token";if(void 0!==e.tokenImage&&null!==e.tokenImage)if(e.tokenImage instanceof File||Buffer.isBuffer(e.tokenImage)){const t=await this.uploadImageByTokenName({tokenName:e.tokenName,options:{file:e.tokenImage,tokenName:e.tokenName}});if(null==t||""===t)throw In("Image upload failed: No URL returned");o=t}else"string"==typeof e.tokenImage&&(o=e.tokenImage);const i=`galaswap - operation - ${k()}-${Date.now()}-${this.http.getAddress()}`,r=(void 0!==t&&""!==t?t:"0").toString(),s=void 0!==e.tokenCategory&&""!==e.tokenCategory?e.tokenCategory:"Unit",a=void 0!==e.tokenCollection&&""!==e.tokenCollection?e.tokenCollection:"Token",c={tokenName:e.tokenName.trim(),tokenSymbol:Vn(e.tokenSymbol),tokenDescription:e.tokenDescription.trim(),tokenImage:o.trim(),preBuyQuantity:r,tokenCategory:s,tokenCollection:a,uniqueKey:i},l=Tr(e.websiteUrl);null!==l&&(c.websiteUrl=l);const d=Tr(e.telegramUrl);null!==d&&(c.telegramUrl=d);const u=Tr(e.twitterUrl);null!==u&&(c.twitterUrl=u);const h=Tr(e.instagramUrl);null!==h&&(c.instagramUrl=h);const g=Tr(e.facebookUrl);null!==g&&(c.facebookUrl=g);const m=Tr(e.redditUrl);null!==m&&(c.redditUrl=m);const f=Tr(e.tiktokUrl);null!==f&&(c.tiktokUrl=f);const y=e.reverseBondingCurveConfiguration?.minFeePortion?.toString()??"0.1",v=e.reverseBondingCurveConfiguration?.maxFeePortion?.toString()??"0.5";c.reverseBondingCurveConfiguration={minFeePortion:y,maxFeePortion:v},void 0!==e.saleStartTime&&null!==e.saleStartTime&&(c.saleStartTime=e.saleStartTime);const w=Object.fromEntries(Object.entries(c).filter(([e,t])=>void 0!==t)),b=new ni(w),S=await this.http.signWithGalaChain("CreateSale",b,p.SIGN_TYPED_DATA),{signature:A,types:T,domain:E,prefix:C}=S,I=null!=C?{prefix:C}:{},N=void 0!==b.reverseBondingCurveConfiguration&&null!==b.reverseBondingCurveConfiguration?{reverseBondingCurveConfiguration:b.reverseBondingCurveConfiguration}:{},D=void 0!==b.saleStartTime&&null!==b.saleStartTime?{saleStartTime:b.saleStartTime}:{},P={tokenName:b.tokenName,tokenSymbol:b.tokenSymbol,tokenDescription:b.tokenDescription,tokenImage:b.tokenImage,preBuyQuantity:b.preBuyQuantity,...void 0!==b.websiteUrl&&""!==b.websiteUrl?{websiteUrl:b.websiteUrl}:{},...void 0!==b.telegramUrl&&""!==b.telegramUrl?{telegramUrl:b.telegramUrl}:{},...void 0!==b.twitterUrl&&""!==b.twitterUrl?{twitterUrl:b.twitterUrl}:{},...void 0!==b.instagramUrl&&""!==b.instagramUrl?{instagramUrl:b.instagramUrl}:{},...void 0!==b.facebookUrl&&""!==b.facebookUrl?{facebookUrl:b.facebookUrl}:{},...void 0!==b.redditUrl&&""!==b.redditUrl?{redditUrl:b.redditUrl}:{},...void 0!==b.tiktokUrl&&""!==b.tiktokUrl?{tiktokUrl:b.tiktokUrl}:{},tokenCategory:b.tokenCategory,tokenCollection:b.tokenCollection,uniqueKey:b.uniqueKey,signature:A,types:T,domain:E,...I,...N,...D},x=`${e.tokenName.trim()}$Unit$none$none`,_="GALA$Unit$none$none";let F;if(Ao(t,0)>0){const e=`$service$${x}$launchpad`;F=[e,`$token$${x}$${e}`,`$tokenBalance$${x}$${e}`,`$tokenBalance$${x}$${e}`,`$tokenBalance$${_}$${e}`,`$tokenBalance$${_}$${e}`]}else{const e=`$service$${x}$launchpad`;F=[e,`$token$${x}$${e}`,`$tokenBalance$${x}$${e}`]}const R={signedDto:P,stringsInstructions:F,method:"CreateSale"},B=await this.bundleHttp.post("/bundle",R);if(B.error)throw In(void 0!==B.message&&""!==B.message?B.message:"Token launch failed");const U=$n(B);if(null==U||""===U)throw In("Token launch failed - no transaction ID returned");return U}async fetchTokenDistribution(e){if(null==e||""===e)throw En("tokenName","Token name");Pr(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw In(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=$n(t);if(null==n)throw In("Failed to fetch token distribution - no data returned",t.status);if(!Array.isArray(n))throw In("Invalid API response: expected array of holders",t.status);for(const e of n){if(void 0===e.owner||null===e.owner||""===e.owner||"string"!=typeof e.owner)throw In("Invalid holder data: missing or invalid owner field",t.status);if(void 0===e.quantity||null===e.quantity||""===e.quantity||"string"!=typeof e.quantity)throw In("Invalid holder data: missing or invalid quantity field",t.status);const n=Ao(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw In(`Invalid holder quantity: "${e.quantity}"`,t.status)}const o=n.reduce((e,t)=>e.plus(t.quantity),sr(0));return{holders:n.map(e=>{const t=vr(sr(e.quantity),o,sr(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:ar(o),totalHolders:n.length,lastUpdated:new Date}}async fetchTokenBadges(e){if(null==e||""===e)throw En("tokenName","Token name");Pr(e);const t=await this.http.get("/launchpad/get-badge/",{tokenName:e});if(t.error)throw In(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token badges");const n=$n(t);if(null==n)throw In("Failed to fetch token badges - no data returned");return{volumeBadges:Array.isArray(n.volumeBadge)?n.volumeBadge:[],engagementBadges:Array.isArray(n.engagementBadge)?n.engagementBadge:[]}}async hasTokenBadgeByTokenName(e){const{tokenName:t,badgeType:n,badgeName:o}=e;try{const e=await this.fetchTokenBadges(t);if(null==e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===o);return i?.isActive??!1}catch{return!1}}async calculateInitialBuyAmount(e){if(!ir(e))throw Cn("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw Nn("GalaChain HTTP client not available. Please initialize SDK with galaChainBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return"number"==typeof t.Status&&void 0!==t.Data&&"object"==typeof t.Data&&null!==t.Data&&"string"==typeof t.Data.calculatedQuantity&&void 0!==t.Data.extraFees&&"object"==typeof t.Data.extraFees&&null!==t.Data.extraFees&&"string"==typeof t.Data.extraFees.reverseBondingCurve&&"string"==typeof t.Data.extraFees.transactionFees}(n))throw In("Malformed response data from GalaChain gateway");try{kn(n,"Pre-mint calculation")}catch(e){throw In(hn(e),500)}const{calculatedQuantity:o,extraFees:i}=n.Data;return{amount:o,reverseBondingCurveFee:i.reverseBondingCurve,transactionFee:i.transactionFees,gasFee:"1"}}catch(e){if(un(e)&&e instanceof en)throw e;throw In(hn(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new Yt(Sn(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Nn("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw In(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const o=n.Data,i=ar(sr(o.maxSupply).minus(o.sellingTokenQuantity)),r=o.sellingTokenQuantity,s=o.maxSupply;let a=.5,c=.1;const l=o.reverseBondingCurveConfiguration;null!=l?.maxFeePortion&&(a=Do(l.maxFeePortion,.5)),null!=l?.minFeePortion&&(c=Do(l.minFeePortion,.1)),void 0===l&&this.logger.debug(`Pool details missing reverse bonding curve configuration for token ${e}, using defaults (min: 0.1, max: 0.5)`);const d=a-c;return this.metadataCache.set(e,{maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:d}),{currentSupply:i,remainingTokens:r,maxSupply:s,reverseBondingCurveMaxFeeFactor:a,reverseBondingCurveMinFeeFactor:c,reverseBondingCurveNetFeeFactor:d}}async fetchCurrentSupply(e){Pr(e);const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new Yt(Sn(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Nn("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw In(`Failed to fetch pool details: Status ${n.Status}`,n.Status);const o=n.Data,i=ar(sr(o.maxSupply).minus(o.sellingTokenQuantity)),r=o.maxSupply;return this.metadataCache.set(e,{maxSupply:r}),i}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return ci(e)}validateTokenName(e){return Pr(e)}validatePagination(e){void 0!==e.pageSize&&Ko(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw Nn("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw En("symbols","At least one symbol");const t=Array.isArray(e)?e.join(","):e;try{const e=await this.dexApiHttp.request({method:"GET",url:"/v1/tokens",params:{symbols:t}}),n=[];return void 0!==e.tokens&&null!==e.tokens&&Array.isArray(e.tokens)&&e.tokens.forEach(e=>{void 0!==e.currentPrices&&null!==e.currentPrices&&void 0!==e.symbol&&null!==e.symbol&&n.push({symbol:e.symbol,price:e.currentPrices.usd})}),n}catch(e){throw In(`Failed to fetch token prices: ${hn(e)}`,void 0,un(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const Ur=3e5,Or="Sign in to Launchpad t:",Lr="Authorization",Mr="Bearer ";class $r{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 Kr,qr;!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"}(Kr||(Kr={}));class Gr extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Wr{constructor(e,t=Ur){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 $r,this.refreshThresholdMs=t}setToken(e,t){if(!Mo(e))throw new Gr(Kr.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Gr(Kr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Gr(Kr.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Gr(Kr.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,o){if(this.setToken(e,t),n){const e=Date.now()+1e3*(o??7776e3);if(!this.tokenState)throw new Gr(Kr.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:`${Mr}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Gr(Kr.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Lr]:e}}async getRefreshToken(){if(!this.tokenState?.refreshToken){const e=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(e&&t){const n=Number(t);if(Number.isFinite(n)&&Date.now()<n)return e}return null}return null!=this.tokenState.refreshExpiresAt&&(!Number.isFinite(this.tokenState.refreshExpiresAt)||Date.now()>=this.tokenState.refreshExpiresAt)?null:this.tokenState.refreshToken??null}async restoreFromStorage(){const e=await this.storage.get(this.STORAGE_KEYS.ACCESS_TOKEN),t=await this.storage.get(this.STORAGE_KEYS.ACCESS_EXPIRES);if(!e||!t)return!1;const n=Number(t);if(!Number.isFinite(n)||Date.now()>=n)return!1;const o=Date.now();this.tokenState={token:e,issuedAt:o,expiresAt:n};const i=await this.storage.get(this.STORAGE_KEYS.REFRESH_TOKEN),r=await this.storage.get(this.STORAGE_KEYS.REFRESH_EXPIRES);if(i&&r){const e=Number(r);Number.isFinite(e)&&Date.now()<e&&(this.tokenState.refreshToken=i,this.tokenState.refreshExpiresAt=e)}return!0}async clear(){this.tokenState=null,await this.storage.remove(this.STORAGE_KEYS.ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEYS.ACCESS_EXPIRES),await this.storage.remove(this.STORAGE_KEYS.REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEYS.REFRESH_EXPIRES)}isValid(){return this.hasToken()&&!this.isExpired()}getDebugInfo(){return{hasToken:this.hasToken(),isExpired:this.isExpired(),shouldRefresh:this.shouldRefresh(),timeUntilExpiryMs:this.getTimeUntilExpiry(),expiresAt:this.tokenState?new Date(this.tokenState.expiresAt):null}}}async function Hr(e,t,n,o){try{return await e()}catch(e){throw o?(o(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Pn(e,t,n))}}function zr(e,t,n,o){try{return e()}catch(e){throw o?(o(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),Pn(e,t,n))}}class jr{constructor(e,t,n,o=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new Qn({debug:o,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 Gr(Kr.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 Hr(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),o=this.signatureAuth.getAddress();ui(o,"address");const i={address:o,message:t,signature:n.signature};let r;try{this.logger.debug("Sending login request with refresh token support",{address:o,message:t}),r=await this.http.post(we,{...i,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),r=await this.http.post(we,i)}const s=this.extractLoginData(r);return await this.jwtAuth.setTokens(s.accessToken,s.expiresIn,s.refreshToken,s.refreshExpiresIn),this.logger.debug("Login successful",{address:s.address,expiresIn:s.expiresIn,hasRefreshToken:!!s.refreshToken}),s},"SessionAuthService.performLogin",this.logger,(e,t,n)=>{if(e instanceof Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,`Login failed: ${hn(e)}`,un(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 Gr(Kr.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 Hr(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(Se,{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(Se,{},this.jwtAuth.getJwtHeaders()),n=this.extractLoginData(t);return this.jwtAuth.setToken(n.accessToken,n.expiresIn),this.logger.debug("Token refreshed successfully via access token",{address:n.address,expiresIn:n.expiresIn}),n},"SessionAuthService.performRefresh",this.logger,(e,t,n)=>{if(e instanceof Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,`Token refresh failed: ${hn(e)}`,un(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(be,{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): ${hn(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 Gr(Kr.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return Hr(async()=>{const e=await this.http.get(Ae,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,(e,t,n)=>{if(e instanceof Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,`Failed to get session: ${hn(e)}`,un(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 Gr(Kr.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: ${hn(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 Gr(Kr.SIGNATURE_FAILED,""!==hn(e)?hn(e):"Authentication failed");const t=Kn(e,"No data in authentication response"),{accessToken:n,expiresIn:o,address:i,refreshToken:r,refreshExpiresIn:s}=t;if(!Mo(n))throw new Gr(Kr.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof o||o<=0)throw new Gr(Kr.SIGNATURE_FAILED,"Invalid expiration in response");return{accessToken:n,expiresIn:o,address:i,...void 0!==r&&{refreshToken:r},...void 0!==s&&{refreshExpiresIn:s}}}extractSessionData(e){if(e.error)throw new Gr(Kr.SIGNATURE_FAILED,""!==hn(e)?hn(e):"Failed to get session");return Kn(e,"No data in session response")}}class Vr 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"}(qr||(qr={}));class Xr{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new n(e)}catch(e){throw new Vr("Invalid private key provided",qr.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new Xr(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new Vr("Failed to sign message",qr.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 Vr("Failed to sign typed data",qr.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 Qr{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{Oo(e.messagePrefix,"messagePrefix",!1)}catch{throw new Gr(Kr.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=Xr.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=ci(this.wallet.address)}catch(e){if(e instanceof Gr)throw e;if(e instanceof Yt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Gr(Kr.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Gr(Kr.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Gr(Kr.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Gr(Kr.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=Xr.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=ci(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 Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,"Failed to generate signature for authentication",un(e)?e:new Error(hn(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Gr(Kr.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 Gr(Kr.WALLET_NOT_CONNECTED,"Address not available. For external wallets, call cacheAddress() after connecting.")}async getEthereumAddressAsync(){return await this.validateWalletAsync(),this.walletProvider.getAddress()}getPrivateKey(){if(this.validateWallet(),this.wallet){if(""===this.wallet.privateKey||null==this.wallet.privateKey)throw new Gr(Kr.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 Gr(Kr.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 Gr(Kr.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Gr(Kr.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",un(e)?e:void 0)}}formatAddress(e){try{return ci(e)}catch{throw new Gr(Kr.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 Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,hn(e),un(e)?e:new Error(hn(e)))}}async generateAuthHeaders(e,t){await this.validateWalletAsync();try{const n=Date.now(),o=`${this.messagePrefix} ${t.toUpperCase()} ${e} ${n}`,i=await this.walletProvider.signMessage(o);return{"x-signature":i,"x-address":await this.walletProvider.getGalaAddress(),"x-message":o,"x-timestamp":n.toString()}}catch(e){if(e instanceof Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,"Failed to generate authentication headers",un(e)?e:new Error(hn(e)))}}async signTypedData(e,t,n){await this.validateWalletAsync();try{const o={};for(const[e,n]of Object.entries(t))o[e]=n.map(e=>({name:e.name,type:e.type}));return await this.walletProvider.signTypedData(e,o,n)}catch(e){if(e instanceof Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,"Failed to sign typed data",un(e)?e:new Error(hn(e)))}}async generateCustomSignature(e){if(!Mo(e))throw new Gr(Kr.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 Gr)throw e;throw new Gr(Kr.SIGNATURE_FAILED,"Failed to generate custom message signature",un(e)?e:new Error(hn(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Gr(Kr.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Gr(Kr.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Gr(Kr.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const Jr={PROD:{launchpadBaseUrl:"https://lpad-backend-prod1.defi.gala.com",galaChainBaseUrl:"https://gateway-mainnet.galachain.com",bundleBaseUrl:"https://bundle-backend-prod1.defi.gala.com",webSocketUrl:"https://bundle-backend-prod1.defi.gala.com",gdexWebSocketUrl:"wss://dex-backend-prod1.defi.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-prod-gala.gala.com",dexBackendBaseUrl:"https://dex-backend-prod1.defi.gala.com",launchpadFrontendUrl:"https://lpad-frontend-prod1.defi.gala.com"},STAGE:{launchpadBaseUrl:"https://lpad-backend-dev1.defi.gala.com",galaChainBaseUrl:"https://gateway-testnet.galachain.com",bundleBaseUrl:"https://bundle-backend-dev1.defi.gala.com",webSocketUrl:"https://bundle-backend-dev1.defi.gala.com",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"},QA1:{launchpadBaseUrl:"https://lpad-backend-qa1.defi.gala.com",galaChainBaseUrl:"https://gateway-testnet.galachain.com",bundleBaseUrl:"https://bundle-backend-qa1.defi.gala.com",webSocketUrl:"https://bundle-backend-qa1.defi.gala.com",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",dexBackendBaseUrl:"https://swap-backend.stage.defi.ovh.gala.com",launchpadFrontendUrl:"https://lpad-frontend-qa1.defi.gala.com"}};function Yr(e){return Jr[e]}function Zr(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function es(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}function ts(e){return`$${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const ns=1,os=2,is=1002,rs=1,ss=3,as=[{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}],cs=[{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 ls(e){return"PROD"===e?as:cs}function ds(e){return"PROD"===e?"0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9":"0x6a1734E09f3099a3675645D214ce547080ea67e0"}const us=as,hs=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],gs={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"}},ms=["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)"],ps=["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"],fs={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 ys(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function ks(e){const t=new Map;for(const n of e)t.set(jn(n.symbol),n);return t}function vs(e,t,n){const o=function(e,t){return e.get(jn(t))}(e,t);if(!o){throw Nn(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return o}function ws(e){if(null==e||!ys(e))throw Cn("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function bs(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function Ss(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function As(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function Ts(e,t,n){const o=e.find(e=>e.symbol===t);if(!o){const o=e.map(e=>e.symbol).join(", ");throw En("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${o}`)}return o}const Es={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function Cs(e,t,n){if(void 0===e)throw Nn(n??Es[t],`${t.toLowerCase()}Strategy`);return e}function Is(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 Ns="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",Ds="Bridge request ID missing from RequestTokenBridgeOut response",Ps="BridgeTokenOut response missing transaction hash";function xs(e){if(void 0===e||""===e)throw Nn(Ns,"tokenSymbol");return e}function _s(e,t){if(!o(e)){throw Cn(t??"address","a valid 0x-prefixed Ethereum address",e)}}function Fs(e,t){try{return new w(e)}catch{throw Cn(t??"address","a valid Solana address (base58)",e)}}function Rs(e){try{return new w(e)}catch{throw Cn("address","a valid Solana address (base58)",e)}}function Bs(e){const t={};for(const[n,o]of Object.entries(e))void 0!==o&&(o&&"object"==typeof o&&!Array.isArray(o)?t[n]=Bs(o):t[n]=o);return t}function Us(e,t){const n=Ao(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}function Os(e){const t="string"==typeof e.timestamp?Co(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}}let Ls=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{Ls=require("crypto")}catch{}function Ms(){if(void 0!==Ls?.randomUUID)try{return Ls.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 $s={name:"GalaConnect",chainId:1},Ks=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],qs=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Gs=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Ws=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Hs={GalaTransaction:Ks,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:qs,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:Gs,externalQuoteToken:Ws,tokenInstance:Gs},zs={GalaTransaction:Ks,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:qs,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:Ws,externalQuoteToken:Ws,externalCrossRateToken:Ws,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:Gs,tokenInstance:Gs};const js={GalaTransaction:[{name:"quantity",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"destinationChainId",type:"uint256"},{name:"recipient",type:"string"},{name:"wrap",type:"bool"},{name:"uniqueKey",type:"string"}],tokenInstance:Gs};async function Vs(e,t){const{wallet:n}=t,o=e.uniqueKey??`galaconnect-operation-${Ms()}`,i="string"==typeof e.destinationChainId?Co(e.destinationChainId,1):e.destinationChainId,r=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Co(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Co(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Co(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Co(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Co(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Co(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),s=Boolean(r.galaExchangeCrossRate),a={destinationChainId:i,destinationChainTxFee:Bs(s?{...r,galaExchangeRate:void 0}:{...r,galaExchangeCrossRate:void 0}),quantity:e.quantity,recipient:e.recipient,tokenInstance:e.tokenInstance,uniqueKey:o},c=function(e){return e?zs:Hs}(s),l=await n.signTypedData($s,c,a),d=`Ethereum Signed Message:\n${N({domain:$s,message:a,primaryType:"GalaTransaction",types:c}).length}`;return{...a,signature:l,prefix:d,types:c,domain:$s}}async function Xs(e,t){const{amount:n,recipientAddress:o,tokenSymbol:i}=e,{galaConnectClient:r,tokenMetadataResolver:s,ethereumWallet:a,destinationChainId:c,destinationChain:l,validateRecipientAddress:d}=t,u=xs(i);Us(n,u),d(o,"recipient");const h=await s.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:o,tokenDescriptor:h.descriptor}),p=await Vs(m,{wallet:a}),f=function(e){if(void 0===e||""===e)throw Nn(Ds,"bridgeRequestId");return e}(function(e){if("string"==typeof e.Data)return e.Data;if(null!=e.data){if("string"==typeof e.data)return e.data;if("object"==typeof e.data){const t=e.data;if("string"==typeof t.Data)return t.Data}}}(await 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 Nn(Ps,"transactionHash");return t}(await r.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:f})),tokenSymbol:u,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:r.getBaseUrl()})}const Qs=5,Js=6,Ys=7;function Zs(e){const t=Co(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===Qs,isFailed:t===Js||t===Ys}}class ea{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw _n("requestsPerSecond","1",e,"Requests per second");this.minIntervalMs=1e3/e}async schedule(e){let t,n;const o=new Promise((e,o)=>{t=e,n=o});if(this.pendingPromise=this.pendingPromise.then(async()=>{const o=Date.now()-this.lastTimestamp,i=Math.max(0,this.minIntervalMs-o);i>0&&await new Promise(e=>setTimeout(e,i)),this.lastTimestamp=Date.now();try{const n=await e();t(n)}catch(e){n(un(e)?e:new Error(hn(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return o}}const ta={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},na=new Set([408,429,500,502,503,504]),oa=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function ia(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return na.has(t.status);if("number"==typeof t.statusCode)return na.has(t.statusCode);const n=fn(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=hn(e);return oa.some(e=>e.test(t))}function ra(e,t){const n=t.initialDelayMs*Math.pow(t.backoffMultiplier,e-1),o=Math.min(n,t.maxDelayMs),i=o*t.jitterFactor*Math.random();return Math.floor(o+i)}function sa(e){return new Promise(t=>setTimeout(t,e))}function aa(e,t){return Cs(e.get("Ethereum"),"Ethereum",t)}function ca(e,t){return Cs(e.get("Solana"),"Solana",t)}function la(e,t){return e??t.getWalletAddress()}function da(e,t,n){const o=void 0!==n?` (${n})`:"";try{if(!Mo(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);const[o,i,r,...s]=n;if(""===o||""===i||""===r)throw new Error("Collection, category, and type must be non-empty");const a=s.join(t);if(""===a)throw new Error("AdditionalKey must be non-empty");return{collection:o,category:i,type:r,additionalKey:a}}catch(n){const i=e?.split?.(t)??[];throw new Yt(`Invalid ${"|"===t?"pipe":"dollar"}-delimited token: "${e}" (${i.length} parts)${o}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${hn(n)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}}function ua(e){if("object"==typeof e&&null!==e)return function(e){if(null===e||"object"!=typeof e)throw new Yt("Token object must be a non-null object, got "+typeof e,"token","INVALID_TOKEN_OBJECT");const{collection:t,category:n,type:o,additionalKey:i}=e;if(!Mo(t))throw new Yt("Token.collection must be a non-empty string, got "+typeof t,"token.collection","MISSING_OR_INVALID_COLLECTION");if(!Mo(n))throw new Yt("Token.category must be a non-empty string, got "+typeof n,"token.category","MISSING_OR_INVALID_CATEGORY");if(!Mo(o))throw new Yt("Token.type must be a non-empty string, got "+typeof o,"token.type","MISSING_OR_INVALID_TYPE");if(!Mo(i))throw new Yt("Token.additionalKey must be a non-empty string, got "+typeof i,"token.additionalKey","MISSING_OR_INVALID_ADDITIONAL_KEY");return{collection:t,category:n,type:o,additionalKey:i}}(e);if(null==e)throw new Yt(`Token cannot be null, undefined, or empty. Received: ${JSON.stringify(e)}`,"token","EMPTY_TOKEN");if("string"!=typeof e)throw new Yt("Token must be a string or TokenClassKey object, got "+typeof e,"token","INVALID_TOKEN_TYPE");if(ga(e))return ha(e);if(ma(e))return function(e){return function(e,t,n){const o=` (${n})`;try{if(!Mo(e))throw new Error("Input must be a non-empty string");const n=e.split(t);if(n.length<4)throw new Error(`Invalid dollar-delimited token format. Expected 4+ parts separated by ${t}, got ${n.length}`);const o=n[n.length-1],i=n[n.length-2],r=n[n.length-3],s=n.slice(0,n.length-3).join(t);if(""===s||""===r||""===i||""===o)throw new Error("All components (collection, category, type, additionalKey) must be non-empty");return{collection:s,category:r,type:i,additionalKey:o}}catch(n){const i=e?.split?.(t)??[];throw new Yt(`Invalid dollar-delimited token: "${e}" (${i.length} parts)${o}. Expected format: "collection${t}category${t}type${t}additionalKey" (4 parts minimum). Received: [${i.map(e=>`"${e}"`).join(", ")}]. Error: ${hn(n)}`,"token","INVALID_DOLLAR_DELIMITED_TOKEN")}}(e,"$","dollar-delimited token")}(e);throw new Yt(`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 ha(e){return da(e,"|","pipe-delimited token")}function ga(e){return Mo(e)&&e.includes("|")}function ma(e){return"string"==typeof e&&e.includes("$")}function pa(e){if("object"!=typeof e||null===e)return!1;const t=e,n=t.collection,o=t.category,i=t.type,r=t.additionalKey;return"string"==typeof n&&"string"==typeof o&&"string"==typeof i&&"string"==typeof r&&n.length>0&&o.length>0&&i.length>0&&r.length>0}function fa(e){let t;if("string"==typeof e)t=ha(e);else{if(!pa(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:Zr(t)}}function ya(e,t){let n;try{n=No(e,"amount")}catch(t){throw Bn("amount",`${e} (${hn(t)})`)}if(!n.isFinite())throw Bn("amount",e);const o=n.multipliedBy(sr(10).pow(t));if(!o.isInteger())throw Bn("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(o.toFixed(0))}function ka(e,t){return sr(e.toString()).dividedBy(sr(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class va{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=Vn(e),n=this.cache.get(t);if(n)return n;const o=gs[t];if(void 0!==o)return this.cache.set(t,o),o;const i=await this.fetchFromApi(e);return this.cache.set(t,i),i}hasMetadata(e){const t=Vn(e);return this.cache.has(t)||t in gs}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),o=n.find(e=>Vn(e.symbol)===Vn(t)&&e.verified);if(o||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),o=n.find(e=>Vn(e.symbol)===Vn(t)&&e.verified)),!o)throw new Error(`Unable to locate token metadata for ${e}`);return i={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey},r=o.decimals,s=o.channel,{descriptor:{collection:i.collection,category:i.category,type:i.type,additionalKey:i.additionalKey},decimals:r,...void 0!==s?{channel:s}:{}};var i,r,s}}class wa 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 ba="https://dex-api-platform-dex-prod-gala.gala.com",Sa="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",Aa=12,Ta=!0,Ea=3,Ca=1e3;class Ia{constructor(e){this.baseUrl=e.baseUrl??ba,this.galachainBaseUrl=e.galachainBaseUrl??Sa,this.walletAddress=e.walletAddress,this.rateLimiter=new ea(e.requestsPerSecond??Aa),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??Ta;this.retryOptions=t?{maxRetries:e.maxRetries??Ea,initialDelayMs:e.retryInitialDelayMs??Ca,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>ia(e instanceof wa?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return Hr(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?So(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new wa(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,(e,t,n)=>{if(e instanceof wa)throw e;throw Pn(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 Hr(async()=>{const o=n.baseUrl??this.baseUrl,i=new URL(e,o),r=n.skipWalletHeader?{"Content-Type":"application/json","X-Wallet-Address":""}:this.defaultHeaders,s=await this.request(i.toString(),{method:"POST",headers:r,body:JSON.stringify(t,(e,t)=>"bigint"==typeof t?t.toString():t)});if(!s.ok){const t=await s.text(),n=500,o=So(t,{rawBody:t.slice(0,n)});throw new wa(s.status,e,o)}const a=await s.text();if(""!==a){const t=function(e){if(Jn(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: ${hn(e)}`}}}(a);if(!t.success)throw new Error(`Failed to parse JSON response from ${e}: ${String(t.error)}`);return t.value}},`Failed to execute POST request to ${e}`,void 0,(e,t,n)=>{if(e instanceof wa)throw e;throw Pn(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 o=await fetch(e,{...t,headers:n});if(this.retryOptions&&!o.ok){const t=o.status;if(429===t||t>=500){const n=o.clone(),i=await this.safeParseJson(n);throw new wa(t,e,i)}}return o});return this.retryOptions?async function(e,t={}){const n={...ta,...t},o=t.shouldRetry??(e=>ia(e));let i;for(let r=1;r<=n.maxRetries+1;r++)try{return await e()}catch(e){if(i=e,r>n.maxRetries)break;if(!o(e,r))break;const s=ra(r,n);t.onRetry&&t.onRetry(e,r,s),await new Promise(e=>setTimeout(e,s))}throw i}(n,this.retryOptions):n()}async safeParseJson(e){const t=await e.text();try{return JSON.parse(t)}catch{return{rawBody:t}}}}var Na;!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"}(Na||(Na={}));class Da{async waitForCompletion(e,t={}){const{pollInterval:n=15e3,timeout:o=27e5,onStatusUpdate:i}=t,r=Date.now();for(;;){const t=await this.getStatus(e);if(i&&i(t),t.status===Na.COMPLETED||t.status===Na.FAILED||t.status===Na.DELIVERY_FAILED)return t;if(no(r)>o)throw Dn(`Bridge transaction timed out after ${o}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class Pa extends Da{constructor(e){super(),this.network="Ethereum",this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,ws(e.ethereumPrivateKey);const t=e.ethereumRpcUrl??"https://ethereum.publicnode.com";this.ethereumProvider=new i(t),this.ethereumWallet=new n(e.ethereumPrivateKey,this.ethereumProvider),this.ethereumWalletAddress=e.ethereumWalletAddress??this.ethereumWallet.address,this.ethereumBridgeContract=e.ethereumBridgeContract??"0x3F98b5A26EF3f04E1DA3B0B41dD350E8C8F3A7c2";const o=e.tokenConfigs??us;this.tokenConfigs=ks(o),this.tokenMetadataResolver=new va({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Os(await this.galaConnectClient.fetchBridgeFee({chainId:"Ethereum",bridgeToken:n.descriptor}))}async bridgeOut(e){return Xs(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:os,destinationChain:"Ethereum",validateRecipientAddress:_s})}async bridgeIn(e){const{amount:o,sourcePrivateKey:i,recipientAddress:s,tokenSymbol:a}=e,c=xs(a);if(Us(o,c),void 0!==i&&""!==i&&!ys(i))throw Cn("sourcePrivateKey","0x-prefixed 64-character hex string",i.slice(0,10)+"...");const l=void 0!==i&&""!==i?new n(i,this.ethereumProvider):this.ethereumWallet,d=vs(this.tokenConfigs,c,"Ethereum bridge"),u=await this.tokenMetadataResolver.getTokenMetadata(c),h=new r(d.contractAddress,ms,l),g=Co(await h.decimals(),18),m=ya(o,g),p=BigInt(await h.balanceOf(l.address));if(p<m){throw Nn(`Insufficient ${c} balance on Ethereum. Needed ${ka(m,g)}, have ${ka(p,g)}`,"amount")}const f=function(e){const n=new ri;if("client"===n.detectFormat(e))return e;const o=n.normalizeInput(e);if(null==o)throw Cn("address","a valid GalaChain address (eth|0x{40-hex}, 0x{40-hex}, or {40-hex})","GalaChain address");const i=n.extractHex(o);return`eth|${t("0x"+i).slice(2)}`}(s??this.galaChainWalletAddress);return Is({fromChain:"Ethereum",transactionHash:(await this.executeBridgeDeposit({wallet:l,tokenContract:h,tokenConfig:d,amountBaseUnits:m,decimals:g,recipient:f,metadata:u})).txHash,tokenSymbol:c,amount:o,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return Zs(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(jn(e))}isValidAddress(e){return Lo.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=vs(this.tokenConfigs,e,"Ethereum"),o=t??this.ethereumWalletAddress;_s(o);const i=new r(n.contractAddress,ms,this.ethereumProvider);return ka(await i.balanceOf(o),n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;_s(t);return ka(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 Cn("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>=Pa.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: ${hn(e)}`}}}async executeBridgeDeposit(e){const t=new r(this.ethereumBridgeContract,ps,e.wallet),n=(new TextEncoder).encode(e.recipient);let o;o=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 o.wait())throw Nn("Bridge transaction receipt not available","ethereumRpcUrl");await sa(3e4);const i={collection:e.metadata.descriptor.collection,category:e.metadata.descriptor.category,type:e.metadata.descriptor.type,additionalKey:e.metadata.descriptor.additionalKey,instance:"0"};return await this.galaConnectClient.registerBridgeTransaction({quantity:ka(e.amountBaseUnits,e.decimals),tokenInstance:i,fromChain:"Ethereum",toChain:"GC",hash:o.hash}),{txHash:o.hash}}async bridgeWithPermit(e,t,n,o,i,r){const a=await this.ethereumProvider.getNetwork(),c=await t.name(),l=await t.nonces(e.address),d=BigInt(Math.floor(Date.now()/1e3)+3600),u=await e.signTypedData({name:c,version:"1",chainId:Co(a.chainId,1),verifyingContract:n.contractAddress},{Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},{owner:e.address,spender:this.ethereumBridgeContract,value:i,nonce:l,deadline:d}),h=s.from(u);return await o.bridgeOutWithPermit(n.contractAddress,i,ns,r,d,h.v,h.r,h.s)}async bridgeWithApproval(e,t,n,o,i,r){const s=await t.allowance(e.address,this.ethereumBridgeContract);if(BigInt(s)<i){const e=await t.approve(this.ethereumBridgeContract,i);await e.wait()}return await n.bridgeOut(o.contractAddress,i,0,ns,r)}}Pa.ETHEREUM_FINALITY_THRESHOLD=12;function xa(e,t,n,o,i){const[r]=w.findProgramAddressSync([t.toBuffer(),o.toBuffer(),e.toBuffer()],i);return r}class _a extends Da{constructor(e){super(),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaConnectClient=e.galaConnectClient,this.galaChainWalletAddress=e.galaChainWalletAddress,ws(e.ethereumPrivateKey);const t=new i("https://ethereum.publicnode.com");this.ethereumWallet=new n(e.ethereumPrivateKey,t);const o=e.solanaRpcUrl??"https://api.mainnet-beta.solana.com";let r;this.solanaConnection=new b(o,"confirmed");try{r=_.decode(e.solanaPrivateKeyBase58)}catch{throw Cn("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==r.length)throw Cn("solanaPrivateKeyBase58","64 bytes when decoded",`${r.length} bytes`);this.solanaKeypair=S.fromSecretKey(r);const s=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new w(s),[this.solanaBridgeTokenAuthority]=w.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=w.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=w.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId);const a=e.tokenConfigs??hs;this.tokenConfigs=ks(a),this.tokenMetadataResolver=new va({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){const n=await this.tokenMetadataResolver.getTokenMetadata(e);return Os(await this.galaConnectClient.fetchBridgeFee({chainId:"Solana",bridgeToken:n.descriptor}))}async bridgeOut(e){return Xs(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:is,destinationChain:"Solana",validateRecipientAddress:Fs})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:o,tokenSymbol:i}=e,r=xs(i);Us(t,r);let s=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=_.decode(n)}catch{throw Cn("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Cn("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);s=S.fromSecretKey(e)}const a=vs(this.tokenConfigs,r,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(r),l=ya(t,c.decimals),d=o??this.galaChainWalletAddress;return Is({fromChain:"Solana",transactionHash:await this.executeSolanaBridgeOut({keypair:s,tokenConfig:a,metadata:c,amountBaseUnits:l,recipient:d,amount:t}),tokenSymbol:r,amount:t,baseUrl:this.galaConnectClient.getBaseUrl()})}async getStatus(e){return Zs(await this.galaConnectClient.getBridgeStatus(e))}getSupportedTokens(){return Array.from(this.tokenConfigs.keys())}isTokenSupported(e){return this.tokenConfigs.has(jn(e))}isValidAddress(e){try{return new w(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=vs(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const o=t??this.solanaKeypair.publicKey.toBase58(),i=Rs(o),r=xa(new w(n.mintAddress),i,0,D,x);try{const e=await async function(e,t,n,o){const i=await e.getAccountInfo(t);if(!i)throw new Error(`could not find account ${t.toBase58()}`);if(!i.owner.equals(o))throw new Error(`account owner mismatch: expected ${o.toBase58()}, got ${i.owner.toBase58()}`);return{amount:P.decode(i.data).amount,decimals:0}}(this.solanaConnection,r,0,D),t=n.decimals??8;return ka(e.amount,t)}catch(t){if(un(t)&&t.message.includes("could not find")){return ka(0n,n.decimals??8)}throw Nn(`Failed to fetch ${e} balance for ${o}: ${hn(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=Rs(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return ka(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){Fo(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?Rs(t):this.solanaKeypair.publicKey,o=this.solanaConnection.rpcEndpoint;if(!o.includes("devnet"))throw Nn(`Solana devnet faucet only available on devnet. Current RPC: ${o}. Ensure SDK is configured with environment='STAGE' for devnet access.`,"solanaRpcUrl");const i=Math.floor(e*I);return await this.solanaConnection.requestAirdrop(n,i)}async getSolanaTransactionStatus(e){if(!Mo(e))throw Cn("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Cn("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 w(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),o=n?void 0:await this.getSolanaBridgeAccounts(t),i=n?void 0:xa(t,e.keypair.publicKey,0,D,x),r=Buffer.from(e.recipient,"utf8"),s=Buffer.alloc(8);s.writeBigUInt64LE(e.amountBaseUnits);const a=Buffer.alloc(4);a.writeUInt32LE(r.length);const c=n?this.buildNativeBridgeInstruction(e.keypair.publicKey,s,a,r):this.buildTokenBridgeInstruction(e.keypair.publicKey,i,t,o,s,a,r),l=new A;l.add(T.setComputeUnitPrice({microLamports:375e3}),T.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 o=null;for(let i=1;i<=n;i++){try{const r=await this.solanaConnection.getLatestBlockhash("confirmed");e.recentBlockhash=r.blockhash,e.feePayer=t.publicKey,e.signatures=[],e.sign(t);const s=await this.solanaConnection.sendRawTransaction(e.serialize(),{skipPreflight:!1,preflightCommitment:"confirmed"});try{return await this.solanaConnection.confirmTransaction({signature:s,blockhash:r.blockhash,lastValidBlockHeight:r.lastValidBlockHeight},"confirmed"),s}catch(e){const t=un(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([s]);if("confirmed"===r.value[0]?.confirmationStatus||"finalized"===r.value[0]?.confirmationStatus)return s;o=new Error(`Transaction ${s} not confirmed - block height exceeded (attempt ${i}/${n})`)}}catch(e){o=un(e)?e:new Error(hn(e));const t=o.message.toLowerCase();if(!(t.includes("block height exceeded")||t.includes("blockhash not found")||t.includes("timeout")||t.includes("expired"))||i===n)throw o}const r=Math.min(1e3*Math.pow(2,i-1),5e3);await sa(r)}throw o??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,o){const i=Buffer.concat([fs.BRIDGE_OUT_NATIVE,t,n,o]);return new E({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:C.programId,isSigner:!1,isWritable:!1}],data:i})}buildTokenBridgeInstruction(e,t,n,o,i,r,s){const a=Buffer.concat([fs.BRIDGE_OUT,i,r,s]);return new E({programId:this.solanaBridgeProgramId,keys:[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:n,isSigner:!1,isWritable:!0},{pubkey:o.mintLookup,isSigner:!1,isWritable:!1},{pubkey:o.tokenBridge,isSigner:!1,isWritable:!1},{pubkey:o.bridgeTokenAccount,isSigner:!1,isWritable:!0},{pubkey:this.solanaBridgeTokenAuthority,isSigner:!1,isWritable:!1},{pubkey:this.solanaBridgeConfigPda,isSigner:!1,isWritable:!0},{pubkey:C.programId,isSigner:!1,isWritable:!1},{pubkey:D,isSigner:!1,isWritable:!1}],data:a})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[o]=w.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),i=await this.solanaConnection.getAccountInfo(o,"confirmed");if(!i)throw Nn(`Mint lookup account not found for ${o.toBase58()}`,"solanaBridgeProgram");if(!i.owner.equals(this.solanaBridgeProgramId))throw Nn("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(i.data.length<40)throw Nn("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const r={mintLookup:o,tokenBridge:new w(i.data.slice(8,40)),bridgeTokenAccount:xa(e,this.solanaBridgeTokenAuthority,0,D,x)};return this.solanaBridgeAccountCache.set(t,r),r}}const Fa={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"}},Ra={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class Ba{static normalizeGalaChainAddress(e){const t=new ri;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 o=t.normalizeInput(n);if(!o)throw Nn(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const i=t.extractHex(o);return`eth|${Ba.checksumAddress(i)}`}static checksumAddress(e){const t=e.toLowerCase(),n=oi(a(c(t)));let o="";for(let e=0;e<t.length;e++){const i=t[e];parseInt(n[e],16)>=8?o+=i.toUpperCase():o+=i}return o}constructor(e){const t=Ba.normalizeGalaChainAddress(e.galaChainWalletAddress),n=e.environment??"PROD",o=Jr[n],i=Fa[n],r={galaConnectBaseUrl:e.galaConnectBaseUrl??o.dexApiBaseUrl,galaChainApiBaseUrl:e.galaChainApiBaseUrl??o.galaChainBaseUrl,ethereumRpcUrl:e.ethereumRpcUrl??i.ethereum,solanaRpcUrl:e.solanaRpcUrl??i.solana,ethereumBridgeContract:e.ethereumBridgeContract??ds(n),solanaBridgeProgram:e.solanaBridgeProgram??Ra.solanaBridgeProgram,rateLimit:e.rateLimit??Ra.rateLimit,pollInterval:e.pollInterval??Ra.pollInterval,pollTimeout:e.pollTimeout??Ra.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...r,solanaPrivateKey:e.solanaPrivateKey}:r,this.galaConnectClient=new Ia({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=ls(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 Pa(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:hs};this.strategies.set("Solana",new _a(e))}}async resolveTokenSymbol(e,t){return Hr(async()=>{if(!this.bridgeableTokenService)throw Nn("BridgeableTokenService is required for tokenId resolution. Pass bridgeableTokenService in BridgeServiceConfig or use the SDK's bridge methods.","bridgeableTokenService");const n=fa(e).stringified,o="Ethereum"===t?"ETHEREUM":"SOLANA",i=await this.bridgeableTokenService.getTokenByTokenId(n,o);if(!i){throw Nn([`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('${o}')`," - Or use sdk.isTokenBridgeableToNetwork({ tokenSymbol, network })"," 3. Common tokenId formats for bridge tokens:",' - GALA: "GALA|Unit|none|none"',' - GUSDC: "GUSDC|Unit|none|eth:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"'," 4. Use sdk.getSupportedBridgeTokens() to list all available tokens"].join("\n"),"tokenId")}return i.symbol},"BridgeService.resolveTokenSymbol")}async estimateBridgeFee(e){return Hr(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 Hr(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw Nn(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw Nn(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return Hr(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw Nn(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return Hr(async()=>{if(null!=t){const n=this.strategies.get(t);if(n)return n.getStatus(e)}const n=this.strategies.get("Ethereum");let o;if(n)try{return await n.getStatus(e)}catch(e){o=un(e)?e:new Error(hn(e))}const i=this.strategies.get("Solana");if(i)try{return await i.getStatus(e)}catch(e){o=un(e)?e:new Error(hn(e))}const r=o?` (last error: ${o.message})`:"";throw Dn(`Unable to get status for transaction ${e}${r}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return Hr(async()=>{const n={pollInterval:t?.pollInterval??this.config.pollInterval,timeout:t?.timeout??this.config.pollTimeout,...t?.onStatusUpdate&&{onStatusUpdate:t.onStatusUpdate}},o=this.strategies.get("Ethereum");if(o)try{return await o.getStatus(e),o.waitForCompletion(e,n)}catch{}const i=this.strategies.get("Solana");if(i)return i.waitForCompletion(e,n);throw Dn(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=ls(this.config.environment);if(null==e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of hs){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(null!=t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return Hr(async()=>aa(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return Hr(async()=>aa(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return Hr(async()=>ca(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return Hr(async()=>ca(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return Hr(async()=>{const n=aa(this.strategies),o=Ts(ls(this.config.environment),e,"Ethereum"),i=la(t,n);return Ss(o,await n.getEthereumTokenBalance(e,i))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return Hr(async()=>{const t=aa(this.strategies),n=la(e,t);return bs("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return Hr(async()=>{const n=ca(this.strategies),o=Ts(hs,e,"Solana"),i=la(t,n);return As(o,await n.getSolanaTokenBalance(e,i))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return Hr(async()=>{const t=ca(this.strategies),n=la(e,t);return bs("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return Hr(async()=>ca(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return Hr(async()=>ca(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 Hr(async()=>aa(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 Hr(async()=>{const t=aa(this.strategies),n=la(e,t),o=ls(this.config.environment),[i,...r]=await Promise.all([t.getEthereumNativeBalance(n),...o.map(async e=>Ss(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:bs("ETH",i,18),tokens:r,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return Hr(async()=>{const t=ca(this.strategies),n=la(e,t),[o,...i]=await Promise.all([t.getSolanaNativeBalance(n),...hs.map(async e=>As(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:bs("SOL",o,9),tokens:i,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw Nn(`Bridging to ${e} is not configured. `+("Solana"===e?"Please provide solanaPrivateKey in config.":"Please check your configuration."),`${e.toLowerCase()}PrivateKey`);return t}}const Ua="6.0.0",Oa={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function La(e,t=1,n=Oa.BACKEND_MAX_PAGE_SIZE){return Math.max(t,Math.min(n,Math.ceil(e??t)))}function Ma(e,t){if("number"!=typeof e||!Number.isInteger(e))throw Rn("total","a non-negative integer",e);if(e<0)throw xn("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw Rn("limit","a non-negative integer",t);if(t<0)throw xn("limit",0,1/0,t);return 0===t?1:0===e?0:Math.ceil(e/t)}function $a(e,t){const n={};void 0!==e.cursor&&(n.cursor=e.cursor);const o=void 0!==e.pageSize?Math.min(e.pageSize,t):t;return n.pageSize=String(o),n}function Ka(e,t,n){for(const o of n){const n=t[o];null!=n&&""!==n&&(e[o]=String(n))}return e}const qa="x-api-key";class Ga extends Yo{constructor(e,t,n,o=!1,i){super(e,o),this.adminApiKey=t??void 0,this.jwtAuth=n,this.userApiKey=i??void 0}setJwtAuth(e){this.jwtAuth=e}validateTokenName(e,t){!function(e,t){if(!Mo(e))throw En("tokenName","Token name");const n=zn(e);if(!t.PATTERN.test(n))throw Cn("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!Mo(e))throw En(t,n)}(e,t,n)}validateOptionalString(e,t,n,o){!function(e,t,n,o){if(null!=e){if("string"!=typeof e)throw Rn(t,"string",typeof e,n);if(e.length>o)throw Fn(t,o,e.length,n)}}(e,t,n,o)}validateOptionalNumber(e,t,n,o,i,r,s){!function(e,t,n,o,i){if(null!=e){if("number"!=typeof e)throw Rn(t,"number",typeof e,n);if(e<o||e>i)throw xn(t,o,i,e,n)}}(e,t,n,o,i)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!to(e))throw Cn(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){Qo(e,t,n)}validateStatusFilter(e,t,n="status"){Jo(e,t,n)}buildPaginationParams(e,t){return $a(e,t)}addOptionalFilterParams(e,t,n){return Ka(e,t,n)}buildEndpoint(e,t){return function(e,t){let n=e;for(const[e,o]of Object.entries(t))n=n.replace(`:${e}`,encodeURIComponent(o.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 tn("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[qa]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new tn("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?{[qa]:this.userApiKey}:this.getJwtHeaders()}extractData(e){return Mn(e,"Backend request failed",!0),Kn(e,"No data in backend response")}extractDataOrNull(e){return Mn(e,"Backend request failed",!1),e.data??null}async toggleFeature(e,t,n){this.validateTokenName(e,n);const o=this.buildEndpoint(t,{tokenName:e}),i=await this.http.post(o,{},this.getAdminHeaders()),r=this.extractData(i);return{enabled:r.enabled,tokenName:r.tokenName??zn(e)}}}class Wa extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async getSettings(){return{settings:(await this.http.get(Dt.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(Dt.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=Dt.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=Dt.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(Dt.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const Ha=Go({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER",OWNER:"OWNER"});function za(e){return Ha.includes(e)}class ja extends Yo{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),Mn(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=[];void 0===e.role||null===e.role?t.push("Role is required"):za(e.role)||t.push(`Invalid role. Must be one of: ${Ha.join(", ")}`);const n=t.length;if(wn(t,()=>{Vo(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;wn(t,()=>{if(!Array.isArray(e.tokenNames))throw Rn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Rn("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n.includes("array")?t[e]="tokenNames must be an array":n.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt){const n=t.length;wn(t,()=>{Xo(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}(e);if(t.length>0)throw new Yt(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 o=await this.http.post(Fe.CREATE,n,this.getJwtHeaders()),i=this.extractData(o);return this.logger.debug("API key created",{id:i.id,keyPrefix:i.keyPrefix}),i}async findAll(e={}){!function(e){if(void 0!==e.pageSize&&("number"!=typeof e.pageSize||e.pageSize<1||e.pageSize>so))throw Rn("pageSize",`number between 1 and ${so}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw Rn("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=$a(e,so),n=await this.http.get(Fe.LIST,t,this.getJwtHeaders()),o=this.extractData(n);return this.logger.debug("Listed API keys",{count:o.apiKeys.length,total:o.pageInfo.totalCount}),o}async findOne(e){this.validateApiKeyId(e),this.logger.debug("Getting API key",{id:e});const t=Fe.GET.replace(":id",String(e)),n=await this.http.get(t,{},this.getJwtHeaders()),o=this.extractData(n);return this.logger.debug("Got API key",{id:o.id,keyPrefix:o.keyPrefix}),o}async update(e,t){this.validateApiKeyId(e);const n=function(e){const t=[];["role","description","delegateAllTokens","tokenNames","expiresAt","tokenPermissions"].some(t=>void 0!==e[t])||t.push("At least one field must be provided for update"),void 0===e.role||za(e.role)||t.push(`Invalid role. Must be one of: ${Ha.join(", ")}`);const n=t.length;if(wn(t,()=>{Vo(e.description,"description",255)}),t.length>n&&(t[n]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;wn(t,()=>{if(!Array.isArray(e.tokenNames))throw Rn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw Rn("tokenNames","contain only strings")});for(let e=n;e<t.length;e++){const n=t[e];n.includes("array")?t[e]="tokenNames must be an array":n.includes("string")&&(t[e]="tokenNames must contain only strings")}}if(void 0!==e.expiresAt&&null!==e.expiresAt){const n=t.length;wn(t,()=>{Xo(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}return t}(t);if(n.length>0)throw new Yt(n.join("; "),"options","VALIDATION_FAILED");this.logger.debug("Updating API key",{id:e,options:t});const o={};void 0!==t.role&&(o.role=t.role),void 0!==t.description&&(o.description=t.description),void 0!==t.delegateAllTokens&&(o.delegateAllTokens=t.delegateAllTokens),void 0!==t.tokenNames&&(o.tokenNames=t.tokenNames),void 0!==t.expiresAt&&(o.expiresAt=t.expiresAt),void 0!==t.tokenPermissions&&(o.tokenPermissions=t.tokenPermissions);const i=Fe.UPDATE.replace(":id",String(e)),r=await this.http.patch(i,o,this.getJwtHeaders()),s=this.extractData(r);return this.logger.debug("Updated API key",{id:s.id,keyPrefix:s.keyPrefix}),s}async revoke(e){this.validateApiKeyId(e),this.logger.debug("Revoking API key",{id:e});const t=Fe.REVOKE.replace(":id",String(e));await this.http.delete(t,{},this.getJwtHeaders()),this.logger.debug("API key revoked",{id:e})}getRoles(){return[...Ha]}}const Va={VIEWERS:"viewers",CHAT_PARTICIPANTS:"chat_participants"},Xa=qo(Va);function Qa(e){return null==e||""===e||"string"==typeof e&&(!jo(e)&&e.length<=uo.BAN_REASON.MAX_LENGTH)}function Ja(e){return!!$o(e)||"number"==typeof e&&(e>=go&&e<=mo)}class Ya extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async createBan(e){!function(e){if(Ho(e.tokenName,"tokenName",oo),!Mo(e.userAddress))throw En("userAddress");if(!Qa(e.reason))throw new Yt(`reason must be at most ${uo.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!Ja(e.durationSeconds))throw new Yt(`durationSeconds must be between ${go} and ${mo} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t=this.buildEndpoint(Te,{tokenName:e.tokenName}),n={userAddress:e.userAddress};void 0!==e.reason&&(n.reason=e.reason),void 0!==e.durationSeconds&&(n.durationSeconds=e.durationSeconds);const o=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(o),tokenName:zn(e.tokenName)}}async removeBan(e){!function(e){if(Ho(e.tokenName,"tokenName",oo),!Mo(e.userAddress))throw En("userAddress")}(e);const t=this.buildEndpoint(Ie,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),o=this.extractDataOrNull(n);return{removed:o?.removed??!0,tokenName:zn(e.tokenName),userAddress:o?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){Ho(e.tokenName,"tokenName",oo),Ko(0,void 0,so,e.pageSize)}(e);const t=this.buildEndpoint(Ee,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,so);this.addOptionalFilterParams(n,e,["search","name","userAddress"]);const o=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(o);return{items:i.bans,pageInfo:i.pageInfo}}async getBanStatus(e){!function(e){if(Ho(e.tokenName,"tokenName",oo),!Mo(e.userAddress))throw En("userAddress")}(e);const t=this.buildEndpoint(Ce,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.get(t,{},this.getMultiAuthHeaders()),o=this.extractDataOrNull(n);return{banned:null!==o,...null!==o&&{ban:o},tokenName:zn(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(Ho(e.tokenName,"tokenName",oo),void 0!==e.type&&!Xa(e.type))throw new Yt(`type must be one of: ${Object.values(Va).join(", ")}`,"type",Vt)}(e);const t=this.buildEndpoint(Ne,{tokenName:e.tokenName}),n={};this.addOptionalFilterParams(n,e,["type","search","name","userAddress"]);const o=await this.http.get(t,n,this.getMultiAuthHeaders());return this.extractData(o)}async createGlobalBan(e){!function(e){if(!Mo(e.userAddress))throw En("userAddress");if(!Qa(e.reason))throw new Yt(`reason must be at most ${uo.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");if(!Ja(e.durationSeconds))throw new Yt(`durationSeconds must be between ${go} and ${mo} seconds`,"durationSeconds","OUT_OF_RANGE")}(e);const t={userAddress:e.userAddress};void 0!==e.reason&&(t.reason=e.reason),void 0!==e.durationSeconds&&(t.durationSeconds=e.durationSeconds);const n=await this.http.post(De,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!Mo(e.userAddress))throw En("userAddress")}(e);const t=this.buildEndpoint(_e,{userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getDualAuthHeaders()),o=this.extractDataOrNull(n);return{removed:o?.removed??!0,userAddress:o?.userAddress??e.userAddress.toLowerCase()}}async listGlobalBans(e){const t=e??{pageSize:20};!function(e){Ko(0,void 0,so,e.pageSize)}(t);const n=this.buildPaginationParams(t,so);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const o=await this.http.get(Pe,n,this.getDualAuthHeaders()),i=this.extractData(o);return{items:i.bans,pageInfo:i.pageInfo}}async getGlobalBan(e){!function(e){if(!Mo(e.userAddress))throw En("userAddress")}(e);const t=this.buildEndpoint(xe,{userAddress:e.userAddress}),n=await this.http.get(t,{},this.getDualAuthHeaders()),o=this.extractDataOrNull(n);return{banned:null!==o,...null!==o&&{ban:o},userAddress:e.userAddress.toLowerCase()}}}async function Za(e,t={}){const{maxPages:n=1e4,logger:o,pageSize:i=20,concurrency:r=1,startPage:s=1}=t,a=[];let c=s;const l=s+n-1;let d=!0,u=0;if(r<=1)for(;d&&c<=l;){o&&o.debug(`Auto-pagination: fetching page ${c} with limit ${i}`);const t=await e(c,i);if(null==t||!Array.isArray(t.items)){o&&o.warn("Auto-pagination: received invalid result structure, stopping");break}if(a.push(...t.items),u=t.total,o&&o.debug(`Auto-pagination: page ${c} returned ${t.items.length} items, hasNext: ${t.hasNext}`),0===t.items.length){o&&o.debug(`Auto-pagination: no items returned on page ${c}, exiting loop`);break}d=t.hasNext,c++}else for(o&&o.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);o&&o.debug(`Auto-pagination: fetching pages ${t.join(", ")} concurrently`);const n=t.map(t=>e(t,i).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 o&&o.debug(`Auto-pagination: page ${t} returned ${r} (end of pagination)`,{statusCode:r}),{items:[],total:0,totalPages:0,page:t,limit:i,hasNext:!1,hasPrevious:!1};throw e})),s=await Promise.all(n);for(const e of s){if(null==e||!Array.isArray(e.items)){o&&o.warn("Auto-pagination: received invalid result structure in batch, stopping"),d=!1;break}if(0===e.items.length){o&&o.debug("Auto-pagination: empty page in batch, reached end of results"),d=!1;break}if(a.push(...e.items),u=e.total,!e.hasNext){d=!1;break}}c+=t.length,o&&o.debug(`Auto-pagination: batch complete, total items so far: ${a.length}`)}return c>l&&o&&o.warn(`Auto-pagination: exceeded maxPages limit of ${n} (maxPage=${l}), stopping iteration`),o&&o.debug(`Auto-pagination: completed with total items: ${a.length}, total count: ${u}`),{items:a,total:u}}function ec(e){if("string"==typeof e){if(!ga(e))throw new Yt(`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=ha(t.slice(0,4).join("|")),n=t[4]??"0";return{...e,instance:n.length>0?n:"0"}}return{...ha(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(!pa(e))throw new Yt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!pa(e))throw new Yt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Yt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function tc(e){return function(e){try{if(!Mo(e))throw new Error("Vault address must be a non-empty string");const[t,n]=e.split("|");if(""===n||void 0===n)throw new Error("Missing token part after service prefix");const o=n.split("$");if(o.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${o.length}`);const[i,r,s,...a]=o;if(""===i||""===r||""===s)throw new Error("Collection, category, and type must be non-empty");const c=a.slice(0,-1),l=c.length>0?c.join("$"):a[0];if(""===l||void 0===l)throw new Error("AdditionalKey must be non-empty");return{collection:i,category:r,type:s,additionalKey:l}}catch(t){throw new Yt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${hn(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function nc(e){return{...tc(e),instance:"0"}}function oc(e){return tc(e).type}function ic(e){return Zr(ec(e))}var rc=Object.freeze({__proto__:null,extractTokenSymbolFromVault:oc,isTokenClassKeyStrict:pa,normalizeToTokenInstanceKey:ec,normalizeTokenIdToString:ic,parseVaultAddressToTokenClassKey:tc,parseVaultAddressToTokenInstance:nc});class sc{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new Qn({debug:t,context:n??this.constructor.name})}getApiEndpoint(){return"/v1/tokens"}getMaxLimit(){return 1e3}getDefaultLimit(){return 1e3}async executePaginatedRequest(e,t,n){const o=Math.min(t,this.getMaxLimit()),i=this.buildApiParams(n),r=await this.dexApiHttp.request({method:"GET",url:this.getApiEndpoint(),params:{...i,pageSize:o,offset:e}});if($o(r)||!Array.isArray(r.tokens))throw new Yt("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:o,maxPages:i=1e4}=t,r=[];let s=0,a=!0,c=0;for(;a&&c<i;){o&&o.debug(`Auto-pagination (offset): fetching at offset ${s} with limit ${n}`);const t=await e(s,n);if(null==t||!Array.isArray(t.items)){o&&o.warn("Auto-pagination (offset): received invalid result structure, stopping");break}r.push(...t.items),a=t.rawCount===n,s+=n,c++,o&&o.debug(`Auto-pagination (offset): fetched ${r.length} items so far (hasMore=${a})`)}return c>=i&&o&&o.warn(`Auto-pagination (offset): exceeded maxPages limit of ${i}, stopping`),o&&o.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 Pn(e,t,this.logger)}}class ac extends Zo{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return jn(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,o=new Map;for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const i=this.normalizeKey(this.extractSecondaryKey(e));o.set(i,e)}this.primaryIndex.set(e,n),this.secondaryIndex.set(e,o),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 o=this.secondaryIndex.get(e);o||(o=new Map,this.secondaryIndex.set(e,o));for(const e of t){const t=this.normalizeKey(this.extractPrimaryKey(e));n.set(t,e);const i=this.normalizeKey(this.extractSecondaryKey(e));o.set(i,e)}this.fetchTimestamps.set(e,Date.now()),this.logger.debug(`Merged ${t.length} items for ${e} (total: ${n.size})`)}getFetchTimestamp(e){return this.fetchTimestamps.get(e)}buildBaseStats(e){const t=[];let n=0;const o={},i={};for(const t of e)o[t]=0;for(const[e,r]of this.primaryIndex){t.push(e),n+=r.size,o[e]=r.size;const s=this.fetchTimestamps.get(e);void 0!==s&&(i[e]=s)}return{networks:t,totalItems:n,itemsByNetwork:o,fetchTimestamps:i}}clear(e){void 0!==e&&""!==e?(this.primaryIndex.delete(e),this.secondaryIndex.delete(e),this.fetchTimestamps.delete(e),this.logger.debug(`Cleared cache for ${e}`)):(this.primaryIndex.clear(),this.secondaryIndex.clear(),this.fetchTimestamps.clear(),this.logger.debug("Cleared all caches"))}size(e){return this.primaryIndex.get(e)?.size??0}hasByPrimaryKey(e,t){return void 0!==this.getByPrimaryKey(e,t)}getCachedNetworks(){return Array.from(this.primaryIndex.keys())}dump(){const e={};for(const t of this.getCachedNetworks())e[t]=this.getAll(t);return e}}const cc=["ETHEREUM","SOLANA"];class lc extends ac{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(cc);return{...e,totalTokens:e.totalItems,tokensByNetwork:e.itemsByNetwork}}}class dc extends sc{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new lc(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),o=e.canBridgeTo.map(e=>e.network).filter(e=>"Ethereum"===e||"Solana"===e),i={symbol:e.symbol,name:e.name,decimals:e.decimals,galaChainDescriptor:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},stringifiedTokenClassKey:e.stringifiedTokenClassKey,verified:e.verified,supportedChains:o};return void 0!==t?.contractAddress&&(i.ethereumContractAddress=t.contractAddress),void 0!==t?.symbol&&(i.ethereumSymbol=t.symbol),void 0!==t?.allowanceStorageSlot&&(i.ethereumAllowanceSlot=t.allowanceStorageSlot),void 0!==n?.contractAddress&&(i.solanaContractAddress=n.contractAddress),void 0!==n?.symbol&&(i.solanaSymbol=n.symbol),void 0!==e.image&&(i.image=e.image),void 0!==e.description&&(i.description=e.description),i})}async fetchBridgeableTokensByNetwork(e){const{network:t,offset:n=0,limit:o=this.getDefaultLimit()}=e,i=Math.min(o,this.getMaxLimit());return this.logger.debug(`Fetching bridgeable tokens for ${t} (offset=${n}, limit=${i})`),Hr(async()=>{const e=(await this.executePaginatedRequest(n,i,{network:t})).items;return 0===n?this.cache.set(t,e):this.cache.merge(t,e),{tokens:e,network:t,fetchedAt:Date.now(),tokenCount:e.length}},`Failed to fetch bridgeable tokens for ${t}`,this.logger)}async fetchAllBridgeableTokensByNetwork(e){return Hr(async()=>{const t=await async function(e){const{network:t,cache:n,fetchFn:o,logger:i,itemTypeName:r="items"}=e;if(n.has(t)){const e=n.getAll(t);return i&&i.debug(`Returning ${e.length} cached ${r} for ${t}`),{items:e,fetchedAt:n.getFetchTimestamp(t)??Date.now(),itemCount:e.length}}i&&i.debug(`Fetching all ${r} for ${t} (no cache)`);const s=await o();return n.set(t,s),{items:s,fetchedAt:Date.now(),itemCount:s.length}}({network:e,cache:this.cache,fetchFn:()=>this.autoPaginateFetch({network:e}),logger:this.logger,itemTypeName:"bridgeable tokens"});return{tokens:t.items,network:e,fetchedAt:t.fetchedAt,tokenCount:t.itemCount}},`Failed to fetch bridgeable tokens for ${e}`,this.logger)}async fetchAllTokensBridgeableToEthereum(){return this.fetchAllBridgeableTokensByNetwork("ETHEREUM")}async fetchAllTokensBridgeableToSolana(){return this.fetchAllBridgeableTokensByNetwork("SOLANA")}async isTokenBridgeableToNetwork(e){const{tokenId:t,network:n}=e,o=ic(t);this.cache.has(n)||await this.fetchAllBridgeableTokensByNetwork(n);const i=this.cache.getByTokenId(n,o),r=void 0!==i,s=r?"ETHEREUM"===n?i.ethereumContractAddress:i.solanaContractAddress:void 0,a={isBridgeable:r,tokenSymbol:i?.symbol??ha(o).collection,network:n};return void 0!==s&&(a.contractAddress=s),a}async isTokenBridgeableToEthereum(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"ETHEREUM"})}async isTokenBridgeableToSolana(e){return this.isTokenBridgeableToNetwork({tokenId:e,network:"SOLANA"})}async getTokenBySymbol(e,t){const n=this.cache.getBySymbol(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getBySymbol(t,e))}async getTokenByTokenId(e,t){const n=this.cache.getByTokenId(t,e);return n||(await this.fetchAllBridgeableTokensByNetwork(t),this.cache.getByTokenId(t,e))}async getContractAddress(e,t){const n=await this.getTokenBySymbol(e,t);if(n)return"ETHEREUM"===t?n.ethereumContractAddress:n.solanaContractAddress}async getSupportedTokenSymbols(e){return this.cache.has(e)||await this.fetchAllBridgeableTokensByNetwork(e),this.cache.getAll(e).map(e=>e.symbol)}async preload(){this.logger.debug("Preloading bridgeable tokens for all networks"),await Promise.all([this.fetchAllBridgeableTokensByNetwork("ETHEREUM"),this.fetchAllBridgeableTokensByNetwork("SOLANA")]),this.logger.debug("Preloading complete")}getCacheStats(){return this.cache.getStats()}clearCache(e){this.cache.clear(e)}}function uc(e){return{maxAcceptableReverseBondingCurveFee:xo(e.maxAcceptableReverseBondingCurveFee)}}const hc={BuyNativeDto:class extends m{constructor(e,t,n="0",o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=xo(t),this.expectedToken=_o(n),this.extraFees=uc(o)}},BuyExactDto:class extends m{constructor(e,t,n,o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=_o(t),this.expectedNativeToken=xo(n),this.extraFees=uc(o)}},SellExactDto:class extends m{constructor(e,t,n="0",o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=_o(t),this.expectedNativeToken=xo(n),this.extraFees=uc(o)}},SellNativeDto:class extends m{constructor(e,t,n,o={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=xo(t),this.expectedToken=_o(n),this.extraFees=uc(o)}}};function gc(e,t,n){let o;Fo(t,0,1,"slippageToleranceFactor");try{o=No(e,"expectedAmount")}catch{throw new Error(`Invalid expected amount: ${e}. Must be a valid number`)}if(0===t)return e;const i=o.multipliedBy(t);let r;switch(n){case"buy-native":case"sell-exact":r=o.minus(i);break;case"buy-exact":case"sell-native":r=o.plus(i);break;default:throw new Error(`Unknown operation type: ${n}`)}return gr(r)&&(r=sr(0)),ar(r)}class mc extends Zo{constructor(e,t=!1){super(t),this.walletProvider=e}async signDTO(e,t,n){try{this.logger.debug("🔐 Signing DTO:",{methodName:t,dtoKeys:Object.keys(e)});const n=this.generateEIP712Types(t,e),o=f(e),i={...e,prefix:o},{signature:r,domain:s}=await this.signWithEthersWallet(n,i),a={...e,signature:r,types:n,domain:s};return this.logger.debug("✅ DTO signed successfully:",{payloadKeys:Object.keys(a),signatureLength:r.length}),a}catch(e){this.logger.error("❌ Signature generation failed:",e);throw Dn(`Failed to sign DTO: ${hn(e)}`)}}async signWithEthersWallet(e,t){try{let n,o;if(this.walletProvider.signTypedData&&!this.walletProvider.getNetwork)n={name:"ethereum",chainId:1},o=await this.walletProvider.signTypedData(n,e,t);else{if(!this.walletProvider.getNetwork||!this.walletProvider.signTypedData)throw Nn("Wallet provider does not support typed data signing","walletProvider");{const i=await this.walletProvider.getNetwork();n={name:i.name,chainId:Co(i.chainId,1)},o=await this.walletProvider.signTypedData(n,e,t)}}return{signature:o,domain:n}}catch(e){throw Dn(`Ethers.js signing failed: ${hn(e)}`)}}generateEIP712Types(e,t){const n={};n[e]=[];const o=Object.fromEntries(Object.entries(t).filter(([e,t])=>void 0!==t)),i=(e,t,o,r=!1)=>{if(void 0!==t){if(Array.isArray(t)){if(0===t.length)return;const s=i(e,t[0],o,!0);return r||n[o].push({name:e,type:(s??e)+"[]"}),void 0!==s?s+"[]":void 0}if("object"==typeof t&&null!==t){if(void 0!==n[e])throw new Yt(`Type name collision not supported: ${e}`,"fieldValue","TYPE_COLLISION");return n[e]=[],Object.entries(t).filter(([e,t])=>null!=t).forEach(([t,n])=>{i(t,n,e)}),r||n[o].push({name:e,type:e}),e}{let i;switch(typeof t){case"string":i="string";break;case"number":i="uint256";break;case"boolean":i="bool";break;default:throw new Yt(`Unsupported type for field "${e}": ${typeof t} (value: ${JSON.stringify(t)})`,"fieldValue","UNSUPPORTED_TYPE")}return r||n[o].push({name:e,type:i}),i}}};return Object.entries(o).forEach(([t,n])=>{i(t,n,e)}),this.logger.debug("📝 Generated EIP-712 types:",n),n}}class pc{toLaunchpadFormat(e){if(null==e)throw new Yt('Token is required. Use full tokenId format: "GALA|Unit|none|none"',"token","MISSING_TOKEN");if("string"==typeof e){if(ga(e))return e;throw new Yt(`Invalid token format "${e}". Use full tokenId format: "${e}|Unit|none|none". For launchpad bonding curve tokens, use tokenName parameter instead (e.g., "anime").`,"token","INVALID_TOKEN_FORMAT")}const t=e;return Zr({collection:t.collection??t.symbol??"unknown",category:t.category??"Unit",type:t.type??"none",additionalKey:t.additionalKey??"none"})}toTokenClass(e){if("object"==typeof e&&null!==e){const t=e;return{collection:t.collection??"Token",category:t.category??"Unit",type:t.type??t.symbol??"unknown",additionalKey:t.additionalKey??"none"}}if("string"!=typeof e)throw new Error("Invalid token format: expected string or object, got "+typeof e);const t=da(e,"|","token format conversion");return{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}}normalizeInternalApiResponse(e){return""===e?"":ga(e)?e:`${e}|Unit|none|none`}normalize(e){return"string"==typeof e&&ga(e)?e:this.toLaunchpadFormat(e)}}function fc(e){if(!Mo(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function yc(e){return da(e,"$","dollar-delimited token")}class kc extends Zo{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),o=this.createGalaInstance(),i=`$service$${n.toStringKey()}$launchpad`,r=`$tokenBalance$${n.toStringKey()}$${e}`,s=`$tokenBalance$${n.toStringKey()}$${e}`,a=`$tokenBalance$${o.toStringKey()}$${e}`,c=[i,r,s,a,`$tokenBalance$${o.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=hn(e);throw new Yt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new F;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new 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(!Mo(e))throw En("vaultAddress","Vault address");try{const t=oc(e);return this.logger.debug("🔍 Extracted token symbol:",{vaultAddress:e,tokenSymbol:t}),t}catch(e){if(e instanceof Yt)throw Cn("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!Mo(e))throw En("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Cn("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Cn("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!Mo(e))return null;const t=e.match(/^service\|Token\$Unit\$([^$]+)\$eth:([a-fA-F0-9]{40})\$launchpad$/);return t?{tokenSymbol:t[1],creatorAddress:t[2].toLowerCase()}:null}(e);if(!t)throw Cn("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 Cn("vaultAddress","containing a 1-10 letter token symbol (case insensitive)");return this.logger.debug("✅ Vault address validation passed:",e),!0}generateTokenClassKeyString(e,t,n,o){return`${e}$${t}$${n}$${o}`}parseTokenClassKeyString(e){try{return yc(e)}catch(e){if(e instanceof Yt)throw Cn("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}class vc extends Yo{constructor(e,t,n=!1,o,i,r=.05,s=.01){super(e,n),this.tokenResolver=t,this._walletProvider=o,this.userAddress=i,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=s,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=i&&(this.signatureService=new mc(this._walletProvider,n),this.tokenKeyService=new kc(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 Gn(()=>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:Ln(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Yt)return{success:!1,error:hn(e)};throw e}}validateBundleData(e){if(null==e)throw En("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw En("signedDto","Signed DTO");if(!Mo(e.method))throw En("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Cn("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Yt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Cn("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!Mo(e))throw new Yt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!ma(e))throw new Yt(`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=$n(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(yn(e)&&null!==e.response&&void 0!==e.response){const t=$n(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 hn(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!Mo(e))throw En("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await Gn(()=>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 Yt)return{success:!1,error:hn(e)};throw e}}async cancelTransaction(e){try{if(!Mo(e))throw En("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await Gn(()=>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 Yt)return{success:!1,error:hn(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await Gn(()=>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:o,expectedAmount:i}=e,{effectiveSlippageFactor:r,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("native"===o){if(null==i||""===i)throw new Yt("expectedAmount is required for native buy operations. Use getBuyTokenAmount() first to calculate expected tokens.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=gc(i,r,"buy-native");this.logger.debug("BuyNative slippage applied:",{originalExpectedTokens:i,slippageFactor:r,adjustedMinTokens:e});const t=new hc.BuyNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyWithNative",a)}{if(null==i||""===i)throw new Yt("expectedAmount is required for exact buy operations. Use getBuyTokenAmount() first to calculate expected GALA cost.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=gc(i,r,"buy-exact");this.logger.debug("BuyExact slippage applied:",{originalExpectedGalaCost:i,slippageFactor:r,adjustedMaxGalaCost:e});const t=new hc.BuyExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"BuyExactToken",a)}}async sellToken(e){this.ensureTradingServicesAvailable();const{tokenName:t,amount:n,type:o,expectedAmount:i}=e,{effectiveSlippageFactor:r,effectiveMaxFee:s,vaultAddress:a}=await this.prepareTradingOperation(t,e.maxAcceptableReverseBondingCurveFee,e.maxAcceptableReverseBondingCurveFeeSlippageFactor,e.slippageToleranceFactor);if("exact"===o){if(null==i||""===i)throw new Yt("expectedAmount is required for exact sell operations. Use getSellTokenAmount() first to calculate expected GALA.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=gc(i,r,"sell-exact");this.logger.debug("SellExact slippage applied:",{originalExpectedGala:i,slippageFactor:r,adjustedMinGala:e});const t=new hc.SellExactDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellExactToken",a)}{if(null==i||""===i)throw new Yt("expectedAmount is required for native sell operations. Use getSellTokenAmount() first to calculate tokens to sell.","expectedAmount","EXPECTED_AMOUNT_REQUIRED");const e=gc(i,r,"sell-native");this.logger.debug("SellNative slippage applied:",{originalExpectedTokensToSell:i,slippageFactor:r,adjustedMaxTokensToSell:e});const t=new hc.SellNativeDto(a,n,e,{maxAcceptableReverseBondingCurveFee:s});return await this.executeBundleTransaction(t,"SellWithNative",a)}}async prepareTradingOperation(e,t,n,o){const{effectiveSlippageFactor:i,effectiveMaxFee:r}=this.calculateEffectiveSlippage(t,n,o),s=await this.resolveTokenNameToVault(e);if(null==s)throw Tn(e);return{effectiveSlippageFactor:i,effectiveMaxFee:r,vaultAddress:s}}calculateEffectiveSlippage(e,t,n){const o=n??this.defaultSlippageToleranceFactor,i=t??this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor;let r=e??"0";return null!=e&&(r=gc(e,i,"buy-exact"),this.logger.debug("Reverse bonding curve fee slippage applied:",{baseFee:e,slippageFactor:i,adjustedMaxFee:r})),{effectiveSlippageFactor:o,effectiveFeeSlippageFactor:i,effectiveMaxFee:r}}ensureTradingServicesAvailable(){if(!this.signatureService||!this.tokenKeyService)throw Nn("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw En("userAddress","User address")}async executeBundleTransaction(e,t,n){this.ensureTradingServicesAvailable();try{e.uniqueKey=`galaswap - operation - ${k()}-${Date.now()}-${String(this.userAddress)}`;const o=await this.signatureService.signDTO(e,t,this.userAddress),i=this.tokenKeyService.generateStringsInstructions(n),r={stringsInstructions:i,method:t,signedDto:o};this.logger.debug("📦 Bundle transaction data:",{method:t,stringsInstructions:i,dtoKeys:Object.keys(o)});const s=await this.submitTransaction(r);if(s.success){const e=$n(s);if(null!=e)return this.logger.debug("✅ Bundle transaction submitted:",e),{success:!0,data:{transactionId:e,message:"Transaction submitted successfully. Monitor WebSocket for completion."}}}const a="string"==typeof s.error?s.error:"Bundle transaction failed";throw new nn(a,void 0,"BUNDLE_FAILED")}catch(e){throw this.logger.error("❌ Bundle transaction error:",e),e}}async resolveTokenNameToVault(e){return await this.tokenResolver.resolveTokenToVault(e)}}class wc extends Yo{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($t),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var bc,Sc,Ac,Tc;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(bc||(bc={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Sc||(Sc={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(Ac||(Ac={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(Tc||(Tc={})),Sc.INAPPROPRIATE_CONTENT,Sc.SPAM,Sc.HARASSMENT,Sc.SCAM,Sc.OTHER,Ac.PENDING,Ac.DISMISSED,Ac.ACTIONED,Tc.DELETE_CONTENT,Tc.BAN_USER,Tc.DELETE_AND_BAN,bc.CHAT_MESSAGE,bc.COMMENT,bc.STREAM,bc.RECORDING;const Ec=qo(bc),Cc=qo(Sc),Ic=qo(Ac),Nc=qo(Tc),Dc={TOKEN_NAME:io,CONTENT_ID:uo.CONTENT_ID,DETAILS:uo.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:so}};function Pc(e,t="tokenName"){Ho(e,t,Dc.TOKEN_NAME)}class xc extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async createFlag(e){!function(e){if(Pc(e.tokenName),void 0===e.contentType)throw En("contentType","Content type");if(!Ec(e.contentType))throw Cn("contentType",`one of: ${Object.values(bc).join(", ")}`,"Content type");if(!Mo(e.contentId))throw En("contentId","Content ID");if(e.contentId.length>Dc.CONTENT_ID.MAX_LENGTH)throw Fn("contentId",Dc.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!Mo(e.reportedUserAddress))throw En("reportedUserAddress","Reported user address");if(ui(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==bc.STREAM&&e.contentType!==bc.RECORDING||void 0!==e.reason&&null!==e.reason))throw En("reason","Reason");if(void 0!==e.reason&&!Cc(e.reason))throw Cn("reason",`one of: ${Object.values(Sc).join(", ")}`,"Reason");if(void 0!==e.details&&!Mo(e.details))throw Rn("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Dc.DETAILS.MAX_LENGTH)throw Fn("details",Dc.DETAILS.MAX_LENGTH,e.details.length)}(e);const t={tokenName:e.tokenName,contentType:e.contentType,contentId:e.contentId,reportedUserAddress:e.reportedUserAddress};null!=e.reason&&(t.reason=e.reason),null!=e.details&&(t.details=e.details);const n=await this.http.post(qe.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){!function(e){if(Pc(e.tokenName),void 0!==e.contentType&&!Ec(e.contentType))throw Cn("contentType",`one of: ${Object.values(bc).join(", ")}`,"Content type");if(void 0!==e.status&&!Ic(e.status))throw Cn("status",`one of: ${Object.values(Ac).join(", ")}`);if(void 0!==e.reason&&!Cc(e.reason))throw Cn("reason",`one of: ${Object.values(Sc).join(", ")}`);if(void 0!==e.reporterAddress&&!Mo(e.reporterAddress))throw Rn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&ui(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Mo(e.reportedUserAddress))throw Rn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&ui(e.reportedUserAddress,"reportedUserAddress"),Ko(0,void 0,Dc.PAGINATION.MAX_LIMIT,e.pageSize)}(e);const t=$a(e,so);Ka(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(qe.LIST,t,this.getMultiAuthHeaders()),o=this.extractData(n);return{items:o.flags,pageInfo:o.pageInfo}}async listGlobalFlags(e={}){!function(e){if(void 0!==e.tokenName&&Pc(e.tokenName),void 0!==e.contentType&&!Ec(e.contentType))throw Cn("contentType",`one of: ${Object.values(bc).join(", ")}`,"Content type");if(void 0!==e.status&&!Ic(e.status))throw Cn("status",`one of: ${Object.values(Ac).join(", ")}`);if(void 0!==e.reason&&!Cc(e.reason))throw Cn("reason",`one of: ${Object.values(Sc).join(", ")}`);if(void 0!==e.reporterAddress&&!Mo(e.reporterAddress))throw Rn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&ui(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!Mo(e.reportedUserAddress))throw Rn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&ui(e.reportedUserAddress,"reportedUserAddress"),Ko(0,void 0,Dc.PAGINATION.MAX_LIMIT,e.pageSize)}(e);const t=$a(e,so);Ka(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(qe.LIST,t,this.getMultiAuthHeaders()),o=this.extractData(n);return{items:o.flags,pageInfo:o.pageInfo}}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw En("flagId","Flag ID");try{Bo(e.flagId,"flagId")}catch{throw Cn("flagId","a positive integer","Flag ID")}}(e);const t=qe.DISMISS.replace(":id",e.flagId.toString()),n=await this.http.post(t,{},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async actionFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw En("flagId","Flag ID");try{Bo(e.flagId,"flagId")}catch{throw Cn("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw En("action","Action");if(!Nc(e.action))throw Cn("action",`one of: ${Object.values(Tc).join(", ")}`,"Action")}(e);const t=qe.ACTION.replace(":id",e.flagId.toString()),n=await this.http.post(t,{action:e.action},this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}}const _c=["heart","fire","laugh","wow","thumbs_up"];class Fc extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}validateReactionTokenName(e){this.validateTokenName(e,io)}validateMessageId(e){if(!Mo(e))throw En("messageId","Message ID");if(Ro(e,ho.CONTENT_REACTION.MAX_LENGTH,"messageId"),!ho.CONTENT_REACTION.PATTERN.test(e))throw Cn("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!Mo(e))throw En("reactionType","Reaction type");if(!_c.includes(e))throw Cn("reactionType",`one of: ${_c.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=pt,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=zn(e.tokenName));const o=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(o),{created:r,...s}=i;return{data:s,created:r}}async removeContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=`${ft}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}class Rc extends Yo{constructor(e,t,n=void 0,o=5,i=!1){super(e,i),this.pricingConcurrency=5,this.dexBackendBaseUrl=t,this.gswapService=n,this.pricingConcurrency=o}setGSwapService(e){this.gswapService=e}setPricingConcurrency(e){this.pricingConcurrency=Math.max(1,Math.min(e,20))}async enrichPoolsWithPricing(e){if(!this.gswapService)return this.logger.warn("GSwap service not available, skipping pricing enrichment"),e;if(0===e.length)return e;this.logger.debug("Starting pricing enrichment",{poolCount:e.length,concurrency:this.pricingConcurrency});const t=[];for(let n=0;n<e.length;n++){const o=e[n];t.push({poolIndex:n,token:o.token0,isToken0:!0,task:this.gswapService.getSwapQuoteExactInput({fromToken:o.token0,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${o.token0}`,{error:hn(e)})})}),t.push({poolIndex:n,token:o.token1,isToken0:!1,task:this.gswapService.getSwapQuoteExactInput({fromToken:o.token1,toToken:"GUSDC",amount:"1"}).then(e=>e.estimatedOutput).catch(e=>{this.logger.debug(`Failed to price ${o.token1}`,{error:hn(e)})})})}const n=new Map;for(let t=0;t<e.length;t++)n.set(t,{});for(let e=0;e<t.length;e+=this.pricingConcurrency){const o=t.slice(e,e+this.pricingConcurrency),i=await Promise.allSettled(o.map(e=>e.task));for(let e=0;e<o.length;e++){const t=o[e],r=i[e],s=n.get(t.poolIndex)??{};"fulfilled"===r.status&&null!=r.value&&(t.isToken0?s.token0Price=r.value:s.token1Price=r.value),n.set(t.poolIndex,s)}}const o=e.map((e,t)=>{const o=n.get(t)??{},i={...e};return void 0!==o.token0Price&&(i.token0Price=o.token0Price),void 0!==o.token1Price&&(i.token1Price=o.token1Price),i}),i=o.filter(e=>null!=e.token0Price&&null!=e.token1Price).length;return this.logger.debug("Pricing enrichment complete",{total:e.length,successful:i,failed:e.length-i}),o}async fetchRawPools(e,t){const n=new URLSearchParams;null!=t&&n.append("search",t);const o=""!==n.toString()?`?${n}`:"",i=`${this.dexBackendBaseUrl}/${e}/trade/pools${o}`,r=await qn(()=>this.http.get(i),{errorContext:`Failed to fetch ${e} DEX pools`,logger:this.logger});return Array.isArray(r)?r:r.pools}static feeToPips(e){if("number"==typeof e)return e;const t="string"==typeof e?Number(e):NaN;return Number.isFinite(t)?Math.round(1e4*t):0}normalizeV1Pool(e){const t=t=>{const n=e[t];if("number"==typeof n)return n;const o=Number(n);return Number.isFinite(o)?o:0},n=t=>"string"==typeof e[t]?e[t]:"";return{contractVersion:"v1",poolPair:n("poolPair"),poolHash:n("poolHash"),token0:n("token0"),token1:n("token1"),token0Image:n("token0Image"),token1Image:n("token1Image"),poolName:n("poolName"),fee:Rc.feeToPips(e.fee),fee24h:t("fee24h"),token0Tvl:t("token0Tvl"),token1Tvl:t("token1Tvl"),token0TvlUsd:t("token0TvlUsd"),token1TvlUsd:t("token1TvlUsd"),tvl:t("tvl"),volume1d:t("volume1d"),volume30d:t("volume30d"),dayPerTvl:t("dayPerTvl"),apr1d:t("apr1d")}}normalizeV2Pool(e){const t=t=>{const n=e[t];if("number"==typeof n)return n;const o=Number(n);return Number.isFinite(o)?o:0},n=t=>"string"==typeof e[t]?e[t]:"",o=t("tvlUsd");return{contractVersion:"v2",poolPair:`${n("token0")}/${n("token1")}`,poolHash:n("poolRef"),token0:n("token0"),token1:n("token1"),token0Image:n("token0Image"),token1Image:n("token1Image"),poolName:""!==n("poolName")?n("poolName"):`${n("token0")}/${n("token1")}`,fee:Rc.feeToPips(e.fee),fee24h:t("fee24h"),token0Tvl:t("token0Tvl"),token1Tvl:t("token1Tvl"),token0TvlUsd:o/2,token1TvlUsd:o/2,tvl:o,volume1d:t("volume1d"),volume30d:t("volume30d"),dayPerTvl:o>0?t("volume1d")/o:0,apr1d:t("apr1d")}}async fetchDexPools(e={}){const{search:t,sortBy:n="tvl",sortOrder:o="desc",page:i=1,limit:r=Oa.DEFAULT_LIMIT,withPrices:s=!1}=e;this.logger.debug("Fetching DEX pools",{search:t,sortBy:n,sortOrder:o,page:i,limit:r,withPrices:s});const a=Math.min(r,20),c=Math.max(i,1),[l,d]=await Promise.all([this.fetchRawPools("v1",t),this.fetchRawPools("v2",t)]),u=[...l.map(e=>this.normalizeV1Pool(e)),...d.map(e=>this.normalizeV2Pool(e))],h="asc"===o?1:-1;u.sort((e,t)=>h*(e[n]-t[n]));const g=u.length,m=(c-1)*a;let p=u.slice(m,m+a);const f=c*a<g,y=c>1;s&&(p=await this.enrichPoolsWithPricing(p)),this.logger.debug("DEX pools fetched successfully",{poolCount:p.length,totalCount:g,hasNextPage:f,withPrices:s});return{items:p,pageInfo:{hasNextPage:f,hasPrevPage:y,totalCount:g}}}async fetchAllDexPools(e={}){this.logger.debug("Fetching all DEX pools (auto-paginated)",e);const t=[];let n=1;for(;;){const o=await this.fetchDexPools({...e,page:n,limit:20});if(t.push(...o.items),!o.pageInfo.hasNextPage)break;n+=1}const o=t.length;return this.logger.debug("All DEX pools fetched",{totalPoolsFetched:t.length,totalCount:o,withPrices:e.withPrices}),{items:t,pageInfo:{hasNextPage:!1,totalCount:o}}}}function Bc(e){try{if(!Mo(e))throw new Error("Token must be a non-empty string");return ha(e)}catch(t){throw new Yt(`Invalid pipe-delimited token: "${e}". Expected format: "collection|category|type|additionalKey". Error: ${hn(t)}`,"pipeDelimitedToken","INVALID_PIPE_DELIMITED_TOKEN_FORMAT")}}class Uc extends Yo{constructor(e,t,n=!1,o=3e4){super(e,n),this.compositePoolFetchConcurrency=5,this.dexBackendBaseUrl=t}validateFetchCompositePoolDataInput(e,t,n){if(!Mo(e))throw new ln("token0 must be a non-empty string",{token0:e});if(!Mo(t))throw new ln("token1 must be a non-empty string",{token1:t});try{ha(e),ha(t)}catch(n){throw new ln(`Token format must be: collection|category|type|additionalKey (4 pipe-separated parts). ${hn(n)}`,{token0:e,token1:t})}try{Bo(n,"fee")}catch{throw new ln(`fee must be a positive integer (got ${n})`,{fee:n})}const o=[500,3e3,1e4];if(!o.includes(n))throw new ln(`fee must be one of: ${o.join(", ")} (got ${n})`,{fee:n})}validateQuoteAmount(e){if(!Mo(e))throw new ln("amount must be a non-empty string",{amount:e});const t=sr(e);try{kr(t,"amount")}catch(t){throw new ln(t.message,{amount:e})}}convertTokenClassKey(e){const t=new F;return t.collection=e.collection,t.category=e.category,t.type=e.type,t.additionalKey=e.additionalKey,t}setCompositePoolFetchConcurrency(e){this.compositePoolFetchConcurrency=Math.max(1,Math.min(e,20)),this.logger.debug(`Composite pool fetch concurrency set to ${this.compositePoolFetchConcurrency}`)}async fetchCompositePoolData(e){const{token0:t,token1:n,fee:o}=e;this.logger.debug("Fetching composite pool data",{token0:t,token1:n,fee:o}),this.validateFetchCompositePoolDataInput(t,n,o);try{const e=Bc(t),i=Bc(n),r=this.convertTokenClassKey(e),s=this.convertTokenClassKey(i),a=new L(r,s,o),c=`${this.dexBackendBaseUrl}/v1/trade/composite-pool/direct`,l=await this.http.post(c,a);kn(l,`Pool not found: ${t}/${n} with fee ${o}`);const d=function(e){const t=e.token0Balance,n=e.token1Balance;return{pool:e.pool,tickDataMap:e.tickDataMap,token0Balance:t,token1Balance:n,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals,compositePoolDto:e}}(function(e){const t=e.pool,n=new B(t.token0,t.token1,t.token0ClassKey,t.token1ClassKey,t.fee,sr(t.sqrtPrice),t.protocolFees);n.bitmap=t.bitmap,n.grossPoolLiquidity=sr(t.grossPoolLiquidity),n.liquidity=sr(t.liquidity),n.feeGrowthGlobal0=sr(t.feeGrowthGlobal0),n.feeGrowthGlobal1=sr(t.feeGrowthGlobal1),n.protocolFeesToken0=sr(t.protocolFeesToken0),n.protocolFeesToken1=sr(t.protocolFeesToken1),n.tickSpacing=t.tickSpacing,n.maxLiquidityPerTick=sr(t.maxLiquidityPerTick);const o={},i=e.tickDataMap;Object.keys(i).forEach(e=>{const t=i[e],n=t.initialised,r=t.liquidityNet,s=t.liquidityGross,a=t.feeGrowthOutside0,c=t.feeGrowthOutside1,l=new U(t.poolHash,t.tick);l.initialised=n,l.liquidityNet=sr(r),l.liquidityGross=sr(s),l.feeGrowthOutside0=sr(a),l.feeGrowthOutside1=sr(c),o[e]=l});const r=e.token0Balance,s=r.quantity,a={...r},c=new R(a);c.quantity=sr(s),Object.keys(a).forEach(e=>{e in c||(c[e]=a[e])});const l=e.token1Balance,d=l.quantity,u={...l},h=new R(u);return h.quantity=sr(d),Object.keys(u).forEach(e=>{e in h||(h[e]=u[e])}),new O(n,o,c,h,e.token0Decimals,e.token1Decimals)}(l.Data),l.Data);return this.logger.debug("Composite pool data fetched successfully",{token0:t,token1:n,fee:o,liquidity:d.pool.liquidity.toString()}),d}catch(e){if(e instanceof dn)throw e;this.logger.error("Failed to fetch composite pool data",e);throw mn(e instanceof en&&void 0!==e.originalError?e.originalError:e,"pool")}}async calculateDexPoolQuoteExactAmountLocal(e){const{compositePoolData:t,fromToken:n,toToken:o,amount:i}=e;if(this.logger.debug("Calculating local DEX quote",{fromToken:n,toToken:o,amount:i}),this.validateQuoteAmount(i),null==t)throw new ln("compositePoolData is required for local quote calculation",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),r=Bc(n),s=Bc(o),a=this.convertTokenClassKey(r),c=this.convertTokenClassKey(s),[l,d]=n<o?[a,c]:[c,a],u=new M(l,d,t.pool.fee,sr(i),e,t.compositePoolDto),h=await $(null,u);return this.logger.debug("Local quote calculated",{amount0:h.amount0,amount1:h.amount1}),{amount0:h.amount0.toString(),amount1:h.amount1.toString(),currentSqrtPrice:h.currentSqrtPrice.toString(),newSqrtPrice:h.newSqrtPrice.toString()}}catch(e){throw this.logger.error("Local quote calculation failed",e),new ln(`Local quote calculation failed: ${hn(e)}`,{fromToken:n,toToken:o,amount:i})}}async calculateDexPoolQuoteExactAmountExternal(e){const{compositePoolData:t,fromToken:n,toToken:o,amount:i}=e;if(this.logger.debug("Calculating external DEX quote",{fromToken:n,toToken:o,amount:i}),this.validateQuoteAmount(i),null==t)throw new ln("compositePoolData is required for external quote calculation (token format info)",{compositePoolData:t});try{const e=n===t.pool.token0.replace(/\$/g,"|"),r=Bc(n),s=Bc(o),a=`${this.dexBackendBaseUrl}/v1/trade/quote`,c=await this.http.get(a,{tokenIn:es(r),tokenOut:es(s),amountIn:i,fee:t.pool.fee});if(c.error||200!==c.status||void 0===c.data)throw new Error(c.message??"External quote failed");const l=c.data,d=sr(l.amountOut).absoluteValue().negated().toString(),u=sr(l.amountIn).absoluteValue().toString(),h=e?u:d,g=e?d:u;return this.logger.debug("External quote calculated",{amount0:h,amount1:g}),{amount0:h,amount1:g,currentSqrtPrice:sr(l.currentSqrtPrice).toString(),newSqrtPrice:sr(l.newSqrtPrice).toString()}}catch(e){throw this.logger.error("External quote calculation failed",e),new ln(`External quote calculation failed: ${hn(e)}`,{fromToken:n,toToken:o,amount:i})}}async calculateDexPoolQuoteExactAmount(e,t="local"){return"external"===t?this.calculateDexPoolQuoteExactAmountExternal(e):this.calculateDexPoolQuoteExactAmountLocal(e)}}class Oc extends Zo{constructor(e,t,n,o=!1){super(o),this.dexBackendHttp=e,this.cache=t,this.galaChainService=n}async fetchTokenPrice(e){const{tokenId:t}=e,{hasB:n}=Wo(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 Yt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw En("tokenId","Token ID");try{const t=ec(e),n=Zr(t),o=fc(n);if(this.logger.debug(`Fetching DEX spot price for token: ${o}`),!this.dexBackendHttp)throw In("DEX Backend API client not configured");const i=$n(await this.dexBackendHttp.request({method:"GET",url:"/v1/trade/price",params:{token:o}}));if(null==i||"string"!=typeof i)throw new Yt("Invalid price response: data must be a string, got "+typeof i,"data","INVALID_RESPONSE");const r=function(e,t){if(Yn(e)||""===e)throw En(t);const n="number"==typeof e?e:parseFloat(String(e));if(isNaN(n))throw Bn(t,e);if(!isFinite(n))throw Bn(t,e);return n}(i,"price"),s=n;let a;try{if(null!==this.cache&&void 0!==this.cache){const e=this.cache.getByTokenId(s);if(null!=e?.symbol)return a=e.symbol,this.logger.debug(`DEX spot price for ${a} (cached): $${r}`),{symbol:a,price:r}}this.logger.debug(`Symbol cache miss for ${s}, fetching from API`);a=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(s,{symbol:a}),this.logger.debug(`Cached symbol for ${s}: ${a}`)),this.logger.debug(`DEX spot price for ${a}: $${r}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${un(e)?e.message:String(e)}`),a=Vn("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${a} (fallback): $${r}`)}return{symbol:a,price:r}}catch(e){if(e instanceof Yt)throw e;throw In(`Failed to fetch DEX spot price: ${hn(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!Mo(e))throw new Yt(bn,"tokenName",zt);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=Zr(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${hn(t)}`)}this.logger.debug(`Using bonding curve calculation for token: ${e}`);const o=await t({tokenName:e,amount:"1",type:"native"}),i=await this._fetchDexTokenSpotPrice({collection:"GALA",category:"Unit",type:"none",additionalKey:"none"});if(null==i)throw In("GALA price not available");const r=Ao(o.amount,0)/1e18;if(r<=0)throw new Yt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const s=i.price/r;return{symbol:Vn(e),price:s}}catch(t){if(un(t))throw In(`Failed to calculate launchpad token spot price for ${e}: ${hn(t)}`);throw In(`Failed to calculate launchpad token spot price for ${e}: ${hn(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw In("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 Yt||un(t))&&("NetworkError"===t.name||hn(t).includes("Token not found")))throw t;throw In(`Failed to fetch token details from GalaChain for ${String(e)}: ${hn(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw In("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=$n(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:eo(t?.start??null),end:eo(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(un(e)&&hn(e).includes("not configured"))throw e;if(yn(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw In(`Failed to fetch DEX seasons: ${hn(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{Bo(e,"seasonId")}catch{throw En("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw In("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 o=$n(t);if(null!=o&&"object"==typeof o&&Array.isArray(o.leaderboard))n=o.leaderboard;else if(Array.isArray(t.leaderboard))n=t.leaderboard;else{if(!Array.isArray(o))return this.logger.warn("Leaderboard endpoint returned unexpected structure:",t),{entries:[],seasonId:e,totalEntries:0};n=o}}}const o=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 ${o.length} entries`),{entries:o,seasonId:e,totalEntries:o.length}}catch(t){if(un(t)&&hn(t).includes("must be a positive number"))throw t;throw In(`Failed to fetch DEX leaderboard for season ${e}: ${hn(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 In("DEX Backend API client not configured");const e=$n(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw In("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 In(`Failed to fetch DEX volume summary: ${hn(e)}`)}}}const Lc=20,Mc=3e3,$c=1e3,Kc=!0,qc=!0,Gc=!1,Wc={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 Hc{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 Qn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??Lc,flushIntervalMs:t.flushIntervalMs??Mc,maxQueueSize:t.maxQueueSize??$c,flushOnPageHide:t.flushOnPageHide??Kc,flushOnPageUnload:t.flushOnPageUnload??qc,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 o={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(o),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 zc(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>v(e).plus(t.quantity).toString(),"0")}function jc(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 Yo{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(ma(e)?e.slice(1).toUpperCase():e.toUpperCase())?"music":"asset"}async fetchGalaBalance(e){return this.fetchTokenBalance(e)}async fetchTokenBalance(e,t=!1){try{const n=`/api/${this.getChannelForCollection(e.collection)}/token-contract/FetchBalances`,o=await this.http.post(n,e);if(null==o)return null;try{kn(o,"Fetch balances")}catch{return null}if(0===(o.Data?.length??0))return null;const i=o.Data.find(t=>t.collection===e.collection&&t.category===e.category&&t.additionalKey===e.additionalKey&&t.type===e.type);if(!i||"0"===i.quantity)return null;const r=Zr(i),s={quantity:i.quantity,collection:i.collection,category:i.category,tokenId:r};if((i.inUseHolds?.length??0)>0){const e=jc(i.inUseHolds??[],t);e.length>0&&(s.inUseHolds=e,s.inUseQuantity=zc(e))}if((i.lockedHolds?.length??0)>0){const e=jc(i.lockedHolds??[],t);e.length>0&&(s.lockedHolds=e,s.lockedQuantity=zc(e))}return void 0===s.lockedQuantity&&void 0===s.inUseQuantity||(s.availableQuantity=function(e,t="0",n="0"){return v(e).minus(t).minus(n).toString()}(s.quantity,s.lockedQuantity,s.inUseQuantity)),s}catch(e){throw In(`Failed to fetch token balance from GalaChain: ${hn(e)}`,void 0,un(e)?e:void 0)}}}function Xc(){return`galaconnect-operation-${Date.now()}_${Math.random().toString(36).substring(2,8)}`}class Qc extends m{constructor(e){super(),this.lockAuthority=e.lockAuthority,this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.expires&&(this.expires=e.expires),void 0!==e.name&&(this.name=e.name),void 0!==e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,void 0!==e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,o,i){let r;if("string"==typeof o){r={...yc(o),instance:"0"}}else r={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey,instance:"0"};return new Qc({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:r}],...void 0!==i?.expires&&{expires:i.expires},...void 0!==i?.name&&{name:i.name},uniqueKey:i?.uniqueKey??Xc()})}static forGALA(e,t,n,o){return new Qc({lockAuthority:t??e,tokenInstances:[{owner:e,quantity:n,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],...void 0!==o?.expires&&{expires:o.expires},...void 0!==o?.name&&{name:o.name},uniqueKey:o?.uniqueKey??Xc()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return es(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{lockAuthority:this.lockAuthority,tokenInstances:this.tokenInstances,...void 0!==this.expires&&{expires:this.expires},...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}class Jc extends m{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,void 0!==e.name&&(this.name=e.name),e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,null!=e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,o){let i;if("string"==typeof n){i={...yc(n),instance:"0"}}else i={collection:n.collection,category:n.category,type:n.type,additionalKey:n.additionalKey,instance:"0"};return new Jc({tokenInstances:[{owner:e,quantity:t,tokenInstanceKey:i}],...void 0!==o?.name&&{name:o.name},uniqueKey:o?.uniqueKey??Xc()})}static forGALA(e,t,n){return new Jc({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??Xc()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return es(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function Yc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Mo(t.amount)&&(void 0!==t.tokenId||Mo(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 Zc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Mo(t.amount)&&(void 0!==t.tokenId||Mo(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var el,tl;!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"}(el||(el={}));class nl 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"}(tl||(tl={}));class ol extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}class il{constructor(e){this.wallet=e}static generateUniqueKey(){return`${Date.now()}_${Math.random().toString(36).substring(2,8)}`}async signTransferToken(e){const t={name:"GalaChain",chainId:1},n={TransferToken:[{name:"from",type:"string"},{name:"to",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstance",type:"TokenInstance"},{name:"uniqueKey",type:"string"}],TokenInstance:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]};return{signature:await this.wallet.signTypedData(t,n,e),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signLockToken(e){const t={name:"GalaChain",chainId:1},n={LockToken:[{name:"lockAuthority",type:"string"},{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.expires?[{name:"expires",type:"uint256"}]:[],...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},o={lockAuthority:e.lockAuthority,tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.expires&&(o.expires=e.expires),void 0!==e.name&&(o.name=e.name);return{signature:await this.wallet.signTypedData(t,n,o),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signBurnTokens(e){const t={name:"GalaChain",chainId:1},n={BurnTokens:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"}],TokenInstanceQuantity:[{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},o={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};return{signature:await this.wallet.signTypedData(t,n,o),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}async signUnlockToken(e){const t={name:"GalaChain",chainId:1},n={UnlockToken:[{name:"tokenInstances",type:"TokenInstanceQuantity[]"},{name:"uniqueKey",type:"string"},...void 0!==e.name?[{name:"name",type:"string"}]:[]],TokenInstanceQuantity:[{name:"owner",type:"string"},{name:"quantity",type:"string"},{name:"tokenInstanceKey",type:"TokenInstanceKey"}],TokenInstanceKey:[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}]},o={tokenInstances:e.tokenInstances,uniqueKey:e.uniqueKey};void 0!==e.name&&(o.name=e.name);return{signature:await this.wallet.signTypedData(t,n,o),domain:t,types:n,signerPublicKey:this.wallet.signingKey.publicKey}}static toGalaChainAddress(e){return(new ri).toBackendFormat(e)}static fromGalaChainAddress(e){try{return(new ri).toEthereumFormat(e)}catch{try{return li(e)}catch{return e}}}static createGALATokenInstance(){return{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}static createTokenInstanceFromClassKey(e){return{...yc(e),instance:"0"}}}const rl=100,sl=100;class al extends Yo{constructor(e,t,n,o=!1){super(e,o),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new il(t):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.signatureHelper)throw new nl("Wallet required for token lock operations",el.WALLET_REQUIRED);return Hr(async()=>{const t=ci(this.wallet.address),n=[],o=[];let i=t;const r=e.tokens.find(e=>void 0!==e.lockAuthority);void 0!==r?.lockAuthority&&(i=ci(r.lockAuthority));const s=e.tokens.find(e=>void 0!==e.expires),a=e.tokens.find(e=>void 0!==e.name);for(const r of e.tokens){let e;if(void 0!==r.tokenId)e=ec(r.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",r.tokenId);else{if(void 0===r.tokenName)throw new nl("Must provide either tokenId or tokenName for token identification",el.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(r.tokenName)}n.push({owner:t,quantity:r.amount,tokenInstanceKey:e}),o.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:r.amount,lockAuthority:void 0!==r.lockAuthority?ci(r.lockAuthority):i})}const c=new Qc({lockAuthority:i,tokenInstances:n,...void 0!==s?.expires&&{expires:s.expires},...void 0!==a?.name&&{name:a.name},uniqueKey:e.uniqueKey??Xc()}),l=await this.signatureHelper.signLockToken(c.toSigningPayload()),d=new Qc({...c.toSigningPayload(),signedPayload:l}),u=await this.http.post("/api/asset/token-contract/LockTokens",d);try{kn(u,"Token lock failed")}catch(e){const t=vn(u);throw new nl(`${hn(e)}${t}`,el.NETWORK_ERROR)}return this.extractLockResult(u,o)},"Token lock failed",this.logger,t=>{throw this.handleLockError(t,"Token lock failed",e)})}async unlockTokens(e){if(this.validateUnlockTokensData(e),!this.wallet||!this.signatureHelper)throw new nl("Wallet required for token unlock operations",el.WALLET_REQUIRED);return Hr(async()=>{const t=ci(this.wallet.address),n=[],o=[],i=e.tokens.find(e=>void 0!==e.name);for(const i of e.tokens){let e;if(void 0!==i.tokenId)e=ec(i.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",i.tokenId);else{if(void 0===i.tokenName)throw new nl("Must provide either tokenId or tokenName for token identification",el.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(i.tokenName)}n.push({owner:t,quantity:i.amount,tokenInstanceKey:e}),o.push({tokenClassKey:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey},quantity:i.amount})}const r=new Jc({tokenInstances:n,...void 0!==i?.name&&{name:i.name},uniqueKey:e.uniqueKey??Xc()}),s=await this.signatureHelper.signUnlockToken(r.toSigningPayload()),a=new Jc({...r.toSigningPayload(),signedPayload:s}),c=await this.http.post("/api/asset/token-contract/UnlockTokens",a);try{kn(c,"Token unlock failed")}catch(e){const t=vn(c);throw new nl(`${hn(e)}${t}`,el.NETWORK_ERROR)}return this.extractUnlockResult(c,o)},"Token unlock failed",this.logger,t=>{throw this.handleLockError(t,"Token unlock failed",e)})}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(Yc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new nl("Invalid lock data: missing required fields",el.VALIDATION_ERROR);if(e.tokens.length>rl)throw new nl(`Batch size exceeds maximum limit of ${rl} tokens per lock operation`,el.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new nl("Must provide either tokenId or tokenName for token identification",el.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{zo(t.tokenName,"tokenName")}catch{throw new nl("Invalid token name format",el.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=sr(t.amount);try{fr(e)}catch{throw new nl(Cn("lockAmount","a positive number","Lock amount").message,el.INVALID_AMOUNT,{amount:t.amount})}if(void 0!==t.lockAuthority&&!di(t.lockAuthority))throw new nl("Invalid lock authority address format",el.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{Bo(t.expires,"expires")}catch{throw new nl(Cn("expires","a positive integer (epoch milliseconds)","Expires").message,el.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(Zc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new nl("Invalid unlock data: missing required fields",el.VALIDATION_ERROR);if(e.tokens.length>sl)throw new nl(`Batch size exceeds maximum limit of ${sl} tokens per unlock operation`,el.VALIDATION_ERROR);for(const t of e.tokens){if(void 0===t.tokenId&&void 0===t.tokenName)throw new nl("Must provide either tokenId or tokenName for token identification",el.TOKEN_NOT_FOUND);if(void 0!==t.tokenName)try{zo(t.tokenName,"tokenName")}catch{throw new nl("Invalid token name format",el.TOKEN_NOT_FOUND,{tokenName:t.tokenName})}const e=sr(t.amount);try{fr(e)}catch{throw new nl(Cn("unlockAmount","a positive number","Unlock amount").message,el.INVALID_AMOUNT,{amount:t.amount})}}}extractLockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId??t.txnId??t.TxnId??t.id??void 0}return{...void 0!==n&&{transactionId:n},locked:t}}extractUnlockResult(e,t){let n;if(void 0!==e.Data&&e.Data.length>0){const t=e.Data[0];n=t.transactionId??t.txnId??t.TxnId??t.id??void 0}return{...void 0!==n&&{transactionId:n},unlocked:t}}handleLockError(e,t,n){if(e instanceof nl)return e;let o=t,i=el.NETWORK_ERROR;if(yn(e)){const n=e.response?.data;if("object"==typeof n&&null!==n){const e=n;void 0!==e.Message&&"string"==typeof e.Message&&(o=`${t}: ${e.Message}`);const r=String(e.Message??"").toLowerCase();r.includes("insufficient")||r.includes("balance")?i=el.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?i=el.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?i=el.TOKEN_NOT_FOUND:r.includes("authority")?i=el.NOT_LOCK_AUTHORITY:r.includes("expired")&&(i=el.LOCK_EXPIRED)}}else un(e)&&(o=`${t}: ${hn(e)}`);const r={};return void 0!==n?.tokens?.[0]?.tokenName&&(r.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(r.amount=n.tokens[0].amount),new nl(o,i,Object.keys(r).length>0?r:void 0)}async resolveTokenInstance(e){return Hr(async()=>{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!==t){const n=nc(t);return this.logger.debug("[DEBUG] Token resolution (launchpad)",{tokenName:e,vaultAddress:t,tokenInstance:{collection:n.collection,category:n.category,type:n.type,instance:n.instance}}),n}const n={collection:jn(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:n.collection,category:n.category,type:n.type}}),n},`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof ol)throw new nl(hn(t),el.TOKEN_NOT_FOUND);throw new nl(`Failed to resolve token '${e}': ${hn(t)}`,el.TOKEN_NOT_FOUND,{tokenName:e})})}}class cl extends Yo{constructor(e,t=!1,n){super(e,t),this.publicAxios=n}async fetchTokenClassFromChain(e){try{const t="string"==typeof e?ec(e):e,n={tokenClasses:[{collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey}]};if(!this.publicAxios)throw En("publicAxios","Public Axios instance");const o=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(kn(o,"Failed to fetch token class from GalaChain"),null===o.Data||void 0===o.Data||0===o.Data.length)throw In(`Token not found on GalaChain: ${Zr(t)}`,404);return o.Data[0]}catch(e){if(e instanceof Yt)throw e;if(yn(e)&&404===e.response?.status)throw In("Token not found on GalaChain",404,un(e)?e:void 0);if(un(e)&&"Error"===e.name&&hn(e).includes("status indicates failure"))throw In(hn(e),400,un(e)?e:void 0);const t=hn(e);if(t.includes("Token not found"))throw e;throw In(`Failed to fetch token class from GalaChain: ${t}`,void 0,un(e)?e:void 0)}}async fetchTokenClassesWithSupply(e){try{if(null==e||0===e.length)throw En("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw En("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(kn(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw In("No token supply data found for requested token classes",404);return n.Data}catch(e){if(e instanceof Yt)throw e;if(yn(e)&&404===e.response?.status)throw In("Token supply data not found on GalaChain",404,un(e)?e:void 0);if(un(e)&&"Error"===e.name&&hn(e).includes("status indicates failure"))throw In(hn(e),400,un(e)?e:void 0);const t=hn(e);if(t.includes("Token not found"))throw e;throw In(`Failed to fetch token classes with supply from GalaChain: ${t}`,void 0,un(e)?e:void 0)}}}class ll extends m{constructor(e){super(),this.tokenInstances=e.tokenInstances,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,void 0!==e.signedPayload.prefix&&""!==e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokens(e,t){const n=e.map(e=>{let t;if("string"==typeof e.tokenClassKey){t={...yc(e.tokenClassKey),instance:"0"}}else t={collection:e.tokenClassKey.collection,category:e.tokenClassKey.category,type:e.tokenClassKey.type,additionalKey:e.tokenClassKey.additionalKey,instance:"0"};return{quantity:e.quantity,tokenInstanceKey:t}});return new ll({tokenInstances:n,uniqueKey:t?.uniqueKey??Xc()})}static fromTokenClassKey(e,t,n){return ll.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new ll({tokenInstances:[{quantity:e,tokenInstanceKey:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"}}],uniqueKey:t?.uniqueKey??Xc()})}getTokenClassKey(){if(0===this.tokenInstances.length)return;return es(this.tokenInstances[0].tokenInstanceKey)}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class dl extends m{constructor(e){super(),this.from=e.from,this.to=e.to,this.quantity=e.quantity,this.tokenInstance=e.tokenInstance,this.uniqueKey=e.uniqueKey,e.signedPayload&&(this.signature=e.signedPayload.signature,this.domain=e.signedPayload.domain,this.types=e.signedPayload.types,void 0!==e.signedPayload.prefix&&""!==e.signedPayload.prefix&&(this.prefix=e.signedPayload.prefix))}static fromTokenClassKey(e,t,n,o,i){let r;if("string"==typeof o){r={...yc(o),instance:"0"}}else r={collection:o.collection,category:o.category,type:o.type,additionalKey:o.additionalKey,instance:"0"};return new dl({from:e,to:t,quantity:n,tokenInstance:r,uniqueKey:i??Xc()})}static forGALA(e,t,n,o){return new dl({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:o??Xc()})}getTokenClassKey(){return es(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function ul(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Mo(t.amount)&&(void 0!==t.tokenId||Mo(t.tokenName))}var hl;!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"}(hl||(hl={}));class gl extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}class ml{static validateAmount(e){const t=sr(e);try{kr(t,"amount")}catch(t){throw new ol(t.message,tl.INVALID_AMOUNT,{amount:e})}}static validateUniqueKey(e){if(!$o(e)&&Mo(e)){if(e.length>po.MAX_LENGTH)throw new Yt(`Unique key too long. Maximum length: ${po.MAX_LENGTH}`);if(!po.PATTERN.test(e))throw new ol('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',tl.INVALID_AMOUNT,{uniqueKey:e})}}}const pl="gala-transfer-successful",fl="token-transfer-successful",yl="token-locked-successfully",kl="token-unlocked-successfully",vl="transfer-successful-no-id",wl=50;class bl extends Yo{constructor(e,t,n,o=!1){super(e,o),this.wallet=t,this.tokenResolver=n,this.signatureHelper=t?new il(t):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.signatureHelper)throw new ol("Wallet required for GALA transfer operations",tl.WALLET_REQUIRED);try{const t=ci(e.recipientAddress),n=ci(this.wallet.address),o=dl.forGALA(n,t,e.amount,e.uniqueKey),i=await this.signatureHelper.signTransferToken(o.toSigningPayload()),r=new dl({...o.toSigningPayload(),signedPayload:i}),{data:s,headers:a}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",r);if(null==s)throw new ol("No response from GalaChain transfer service",tl.NETWORK_ERROR);return this.extractTransferResult(s,a,"gala")}catch(t){throw this.handleTransferError(t,"GALA transfer failed",e)}}async transferToken(e){if(this.validateTransferTokenData(e),!this.wallet||!this.signatureHelper)throw new ol("Wallet required for token transfer operations",tl.WALLET_REQUIRED);try{const t=ci(e.to),n=ci(this.wallet.address);let o;if(null!==e.tokenId&&void 0!==e.tokenId)o=ec(e.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",e.tokenId),this.logger.debug("[DEBUG] Normalized Token Instance:",{collection:o.collection,category:o.category,type:o.type,instance:o.instance});else{if(null===e.tokenName||void 0===e.tokenName)throw new ol("Must provide either tokenId or tokenName for token identification",tl.TOKEN_NOT_FOUND);o=await this.resolveTokenInstance(e.tokenName)}const i=new dl({from:n,to:t,quantity:e.amount,tokenInstance:o,uniqueKey:e.uniqueKey??Xc()}),r=await this.signatureHelper.signTransferToken(i.toSigningPayload()),s=new dl({...i.toSigningPayload(),signedPayload:r}),{data:a,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",s);if(null==a)throw new ol("No response from GalaChain transfer service",tl.NETWORK_ERROR);return this.extractTransferResult(a,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 ol)throw t;throw new ol(`Failed to resolve token class key for '${e}': ${hn(t)}`,tl.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.signatureHelper)throw new gl("Wallet required for token burn operations",hl.WALLET_REQUIRED);try{const t=[];for(const n of e.tokens){let e;if(null!==n.tokenId&&void 0!==n.tokenId)e=ec(n.tokenId),this.logger.debug("[DEBUG] Using provided tokenId:",n.tokenId);else{if(null===n.tokenName||void 0===n.tokenName)throw new gl("Must provide either tokenId or tokenName for token identification",hl.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new ll({tokenInstances:t,uniqueKey:e.uniqueKey??Xc()}),o=await this.signatureHelper.signBurnTokens(n.toSigningPayload()),i=new ll({...n.toSigningPayload(),signedPayload:o}),r=await this.http.post("/api/asset/token-contract/BurnTokens",i);if(null==r)throw new gl("No response from GalaChain burn service",hl.NETWORK_ERROR);try{kn(r,"Token burn operation")}catch(e){throw new en(hn(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 Mo(t.recipientAddress)&&Mo(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Yt("Invalid GALA transfer data: missing required fields");if(!di(e.recipientAddress))throw new ol("Invalid recipient address format",tl.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});ml.validateAmount(e.amount),ml.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return Mo(t.to)&&Mo(t.amount)&&(void 0!==t.tokenId||Mo(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Yt("Invalid token transfer data: missing required fields");if(!di(e.to))throw new ol("Invalid recipient address format",tl.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new ol("Must provide either tokenId or tokenName for token identification",tl.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{zo(e.tokenName,"tokenName")}catch{throw new ol("Invalid token name format",tl.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}ml.validateAmount(e.amount),ml.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(ul)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new gl("Invalid burn data: missing required fields",hl.VALIDATION_ERROR);if(e.tokens.length>wl)throw new gl(`Batch size exceeds maximum limit of ${wl} tokens per burn operation`,hl.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 gl("Must provide either tokenId or tokenName for token identification",hl.TOKEN_NOT_FOUND);const e=sr(t.amount);try{fr(e)}catch{throw new gl("Burn amount must be a positive number",hl.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{const t=await this.tokenResolver.resolveTokenToVault(e);if(null!=t){const n=nc(t);return this.logger.debug(`[DEBUG] Token resolution for '${e}' (launchpad):`,{collection:n.collection,category:n.category,type:n.type,instance:n.instance}),n}const n={collection:jn(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return this.logger.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:n.collection,category:n.category,type:n.type}}),n}catch(t){if(t instanceof ol)throw t;throw new ol(`Failed to resolve token '${e}': ${hn(t)}`,tl.TOKEN_NOT_FOUND,{tokenName:e})}}extractTransferResult(e,t,n){const o=this.readHeaderValue(t,"x-transaction-id"),i=this.readBlockNumberHeader(t);if(void 0!==o&&o.length>0)return{transactionId:o,...void 0!==i?{blockNumber:i}:{}};if(null!=e&&"object"==typeof e){if("transactionId"in e&&"string"==typeof e.transactionId&&e.transactionId.length>0)return{transactionId:e.transactionId,...void 0!==i?{blockNumber:i}:{}};if("Status"in e&&"Data"in e)try{kn(e,"Extract transaction ID");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!==i?{blockNumber:i}:{}}}}let e=vl;if(t.Data.length>0)switch(n){case"gala":e=pl;break;case"token":e=fl;break;case"lock":e=yl;break;case"unlock":e=kl}return{transactionId:e,...void 0!==i?{blockNumber:i}:{}}}}catch{}}throw new ol("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",tl.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 t=e.Data[0];n=t.transactionId??t.txnId??t.TxnId??t.id??void 0}return{...void 0!==n&&{transactionId:n},burned:t}}handleTransferError(e,t,n){if(e instanceof ol)return e;if(e instanceof Yt)return new ol(hn(e),tl.INVALID_AMOUNT);if(yn(e)&&e.response){const t=e.response.status,o=e.response.data;if(400===t){const e="string"==typeof o?.message?o.message:void 0;return new ol(e??"Invalid transfer request",tl.INVALID_AMOUNT)}if(403===t)return new ol("Insufficient balance for transfer",tl.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new ol("Token not found",tl.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===fn(e)||"ETIMEDOUT"===fn(e)))return new ol("Transfer request timed out",tl.NETWORK_ERROR);const o=""!==hn(e)?hn(e):t;return new ol(o,tl.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof gl)return e;let o=t,i=hl.NETWORK_ERROR;if(yn(e)){const n=e.response?.data;if("object"==typeof n&&"string"==typeof n.Message&&n.Message.length>0){o=`${t}: ${n.Message}`;const e=n.Message.toLowerCase();e.includes("insufficient")||e.includes("balance")?i=hl.INSUFFICIENT_BALANCE:(e.includes("not found")||e.includes("token"))&&(i=hl.TOKEN_NOT_FOUND)}}else un(e)&&(o=`${t}: ${hn(e)}`);const r={};return void 0!==n?.tokens?.[0]?.tokenName&&(r.tokenName=n.tokens[0].tokenName),void 0!==n?.tokens?.[0]?.amount&&(r.amount=n.tokens[0].amount),new gl(o,i,Object.keys(r).length>0?r:void 0)}}class Sl extends Yo{constructor(e,t,n,o=!1,i){super(e,o),this.balanceService=new Vc(e,o),this.tokenService=new cl(e,o,i),this.lockService=new al(e,t,n,o),this.transferService=new bl(e,t,n,o)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);zr(()=>kn(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw In(hn(e),500)});const n=t.Data.reverseBondingCurveConfiguration,o=n?.minFeePortion??"0",i=n?.maxFeePortion??"0",r=!hr(o)||!hr(i),s=t.Data;return s.reverseBondingCurveMinFeePortion=o,s.reverseBondingCurveMaxFeePortion=i,s.hasReverseBondingCurveFee=r,s.isGraduated="Finished"===t.Data.saleStatus,delete s.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return zr(()=>kn(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw In(hn(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!or(e))throw En("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw En("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new Yt("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class 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 Tl extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class El extends Zo{constructor(e={}){super(),this.nextRequestId=0,this.pending=new Map,this.subscriptionsByServerId=new Map,this.activeSubscriptions=new Set,this.intentionalClose=!1,this.reconnecting=!1,this.url=e.url??Yr("PROD").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new Al({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3,useExponentialBackoff:!0});const t=e.webSocketImpl??globalThis.WebSocket;if("function"!=typeof t)throw new Error('GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).');this.webSocketConstructor=t}connect(){return this.isConnected()?Promise.resolve():(this.connectPromise||(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket()),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(new Error("GDEX stream disconnected"));const e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,"client disconnect")}isConnected(){return 1===this.socket?.readyState}request(e,t){if(!this.isConnected()||!this.socket)return Promise.reject(new Error("GDEX stream is not connected. Call connect() first."));const n=++this.nextRequestId,o={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(o.params=t),new Promise((t,i)=>{const r=setTimeout(()=>{this.pending.delete(n),i(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:i,timeout:r});try{this.socket?.send(JSON.stringify(o))}catch(e){clearTimeout(r),this.pending.delete(n),i(e instanceof Error?e:new Error(String(e)))}})}serverInfo(){return this.request("gdex_serverInfo")}ping(){return this.request("gdex_ping")}getPool(e){return this.request("gdex_getPool",e)}getBalance(e,t){return this.request("gdex_getBalance",void 0===t?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request("gdex_getPositions",e)}getBlockHeight(){return this.request("gdex_getBlockHeight")}quote(e){return this.request("gdex_quote",e)}getToken(e){return this.request("gdex_getToken",{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe("swap",e,t)}subscribePool(e,t,n={}){return this.subscribe("pool",t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe("balance",t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe("poolCreated",e,t)}subscribeBlocks(e,t={}){return this.subscribe("blocks",e,t)}openSocket(){return new Promise((e,t)=>{let n=!1;const o=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=o,o.onopen=()=>{this.socket===o&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},o.onmessage=e=>this.handleMessage(e.data),o.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},o.onclose=e=>{this.socket===o&&(this.socket=void 0,this.connectPromise=void 0,n||t(new Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(new Error(`GDEX stream connection closed (code ${e.code??0})`)),this.intentionalClose||this.reconnecting||this.startReconnectLoop())}})}handleMessage(e){if("string"!=typeof e)return void this.logger.warn("Ignoring non-text GDEX WebSocket frame");let t;try{t=JSON.parse(e)}catch{return void this.logger.warn("Ignoring invalid JSON from GDEX stream")}if("number"==typeof t.id){const e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){const n="number"==typeof t.error.code?t.error.code:-32603,o="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new Tl(n,o,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,o=t.params.result;if("string"!=typeof n||!this.isRecord(o))return;const i=this.subscriptionsByServerId.get(n);if(i?.active)try{i.callback(o)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const o={channel:e,...n},i=await this.request("gdex_subscribe",o);let r;const s={subscriptionId:i.subscriptionId,unsubscribe:async()=>this.unsubscribe(r)};return r={serverId:i.subscriptionId,params:o,callback:t,handle:s,active:!0},this.activeSubscriptions.add(r),this.subscriptionsByServerId.set(r.serverId,r),s}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request("gdex_unsubscribe",{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.reconnectionManager.shouldRetry();){const e=this.reconnectionManager.getNextDelay();if(this.reconnectionManager.recordAttempt(),this.logger.warn(`GDEX reconnect attempt ${this.reconnectionManager.getAttempts()}/${this.reconnectionManager.getMaxAttempts()} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{return await this.openSocket(),await this.resubscribeAll(),this.reconnectionManager.reset(),void(this.reconnecting=!1)}catch(e){this.logger.warn(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||this.logger.error("GDEX reconnection attempts exhausted")}async resubscribeAll(){this.subscriptionsByServerId.clear();for(const e of this.activeSubscriptions){if(!e.active)continue;const t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t);e.active?(e.serverId=n.subscriptionId,e.handle.subscriptionId=n.subscriptionId,this.subscriptionsByServerId.set(n.subscriptionId,e)):await this.request("gdex_unsubscribe",{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e){for(let t=0;;t++)try{return await this.request("gdex_subscribe",e)}catch(e){if(!(e instanceof Tl)||-32003!==e.code||t>=5)throw e;const n=this.readRetryAfterMs(e.data);this.logger.warn(`GDEX resubscribe rate limited; retrying in ${n}ms`),await new Promise(e=>setTimeout(e,n))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){void 0!==this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(const t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||"number"!=typeof e.retryAfterMs||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}function Cl(e,t=3e4){return Q.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}class Il{static createClient(e,t=6e4){return Cl(e,t)}}class Nl{constructor(e){this.http=e}async getUserAssets(e,t=20,n=0){return Hr(async()=>{if(!Mo(e))throw En("walletAddress","Wallet address");const o=Math.max(1,Math.floor(n/t)+1),i={};i.address=e,i.page=o,i.pageSize=t;const r=await this.http.get("/user/assets",i);if("object"!=typeof r||null===r)throw new Gt(500,"Invalid response format: not an object");const s=$n(r);if(!s||"object"!=typeof s)throw new Gt(500,"Invalid response format: missing data wrapper");const a=s.token;if(!Array.isArray(a))throw new Gt(500,"Invalid response format: token array must be an array");const c=[];for(const e of a){if("object"!=typeof e||null===e)throw new Gt(500,"Invalid asset in response: asset must be an object");const t=e;if(!Mo(t.symbol)||!Mo(t.name))throw new Gt(500,"Invalid asset in response: missing symbol or name",t);const n="number"==typeof t.decimals?t.decimals:"string"==typeof t.decimals?parseInt(t.decimals,10):void 0;if("number"!=typeof n||isNaN(n))throw new Gt(500,"Invalid asset in response: decimals must be a number",t);const o={tokenId:"string"==typeof t.compositeKey&&t.compositeKey.length>0?t.compositeKey:`${t.symbol}$Unit$none$none`,symbol:t.symbol,name:t.name,decimals:n,balance:"string"==typeof t.quantity&&t.quantity.length>0?t.quantity:"0"};"string"==typeof t.image&&t.image.length>0&&(o.imageUrl=t.image),"boolean"==typeof t.verify&&t.verify&&(o.verified=t.verify),c.push(o)}const l={tokens:c,count:"number"==typeof s.count?s.count:c.length};return void 0!==s.totalValue&&(l.totalValue=String(s.totalValue)),l},`getUserAssets(${e})`,void 0,t=>{throw this.handleError(t,`getUserAssets(${e})`)})}async fetchTokenList(e={}){return Hr(async()=>{const{address:t,search:n,page:o=1,limit:i=20}=e,r={page:o,limit:La(i,1,20)};"string"==typeof t&&t.length>0&&(r.address=t),"string"==typeof n&&n.length>0&&(r.search=n);const s=await this.http.get("/user/token-list",r);if("object"!=typeof s||null===s)throw new Gt(500,"Invalid response format: not an object");const a=$n(s);if(!a||"object"!=typeof a)throw new Gt(500,"Invalid response format: missing data wrapper");const c=a.token;if(!Array.isArray(c))throw new Gt(500,"Invalid response format: token array must be an array");const l=[];for(const e of c){if("object"!=typeof e||null===e)throw new Gt(500,"Invalid token in response: must be an object");const t=e;if(!Mo(t.symbol))throw new Gt(500,'Invalid token in response: missing required field "symbol"',{token:t});if(!Mo(t.name))throw new Gt(500,'Invalid token in response: missing required field "name"',{token:t});const n=t.decimals;if("string"!=typeof n&&"number"!=typeof n)throw new Gt(500,'Invalid token in response: missing required field "decimals"',{token:t});if(!Mo(t.compositeKey))throw new Gt(500,'Invalid token in response: missing required field "compositeKey"',{token:t});l.push({image:"string"==typeof t.image?t.image:"",name:t.name,symbol:t.symbol,decimals:String(n),description:"string"==typeof t.description?t.description:"",verify:"boolean"==typeof t.verify&&t.verify,compositeKey:t.compositeKey,additionalKey:"string"==typeof t.additionalKey?t.additionalKey:"",category:"string"==typeof t.category?t.category:"",type:"string"==typeof t.type?t.type:"",collection:"string"==typeof t.collection?t.collection:"",subscribePrice:"boolean"==typeof t.subscribePrice&&t.subscribePrice,quantity:"string"==typeof t.quantity?t.quantity:"0"})}return{token:l,count:"number"==typeof a.count?a.count:l.length}},"fetchTokenList",void 0,e=>{throw this.handleError(e,"fetchTokenList")})}handleError(e,t){if(e instanceof Gt)return e;if(yn(e)){const n=e.response?.status??500,o=e.response?.data,i=o?.message??o?.Message??hn(e),r=o?.Data??o?.data??void 0;return new Gt(n,`${t}: ${String(i)}`,r)}return new Gt(500,`${t}: ${hn(e)}`)}}class Dl{constructor(e){this.client=Cl(e.baseUrl,e.timeout??3e4)}async getPoolData(e){return Hr(async()=>{this.validateTokenObjects(e.token0,e.token1,"getPoolData");const t=await this.client.get("/v1/trade/pool",{params:this.poolParams(e)}),n=this.unwrapEnvelope(t);this.validateResponse(n);const o=n.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.token0&&"string"==typeof t.token1&&Wt(t.token0ClassKey)&&Wt(t.token1ClassKey)&&"number"==typeof t.fee&&"number"==typeof t.tickSpacing&&"string"==typeof t.liquidity&&"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.feeGrowthGlobal0&&"string"==typeof t.feeGrowthGlobal1}(o))throw new Gt(t.status,"Invalid pool data response format",o);return o},"DexBackendTradeClient.getPoolData",void 0,e=>{throw this.handleError(e,"pool")})}async getSlot0(e){return Hr(async()=>{this.validateTokenObjects(e.token0,e.token1,"getSlot0");const t=await this.client.get("/v1/trade/slot0",{params:this.poolParams(e)}),n=this.unwrapEnvelope(t);this.validateResponse(n);const o=n.Data;if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.sqrtPrice&&"number"==typeof t.tick&&"string"==typeof t.liquidity}(o))throw new Gt(t.status,"Invalid slot0 data response format",o);return o},"DexBackendTradeClient.getSlot0",void 0,e=>{throw this.handleError(e,"pool")})}async getPositions(e){return Hr(async()=>{const t=this.positionParams(e),n=await this.client.get("/v1/trade/position",{params:t}),o=this.unwrapEnvelope(n);this.validateResponse(o);const i=this.normalizePositions(o.Data,n.status);return{positions:i,count:i.length}},"DexBackendTradeClient.getPositions",void 0,e=>{throw this.handleError(e,"position")})}async getPositionById(e,t,n,o,i,r,s){return Hr(async()=>{if(void 0===t||void 0===n||void 0===o||void 0===i||void 0===r)throw new Gt(404,`Position not found: ${e}`);const a=this.toTokenClassKey(t),c=this.toTokenClassKey(n),l={token0:es(a),token1:es(c),fee:o,tickLower:i,tickUpper:r,owner:e};void 0!==s&&(l.positionId=s);const d=await this.client.get("/v1/trade/position",{params:this.toSearchParams(l)}),u=this.unwrapEnvelope(d);this.validateResponse(u);const h=this.normalizePositions(u.Data,d.status);if(0===h.length)throw new Gt(404,`Position not found: ${e}`);const g={Data:h[0],Status:d.status};return void 0!==u.Message&&(g.Message=u.Message),g},"DexBackendTradeClient.getPositionById",void 0,e=>{throw this.handleError(e,"position")})}async getRemoveLiquidityEstimation(e){return Hr(async()=>{const t=await this.client.get("/v1/trade/remove-liq-estimate",{params:this.toSearchParams({token0:es(e.token0),token1:es(e.token1),fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount:e.amount,owner:e.owner})}),n=this.unwrapEnvelope(t);this.validateResponse(n);const o=n.Data;if("string"!=typeof o.amount0||"string"!=typeof o.amount1)throw new Gt(t.status,"Invalid removal estimation response format",o);return o},"DexBackendTradeClient.getRemoveLiquidityEstimation",void 0,e=>{throw this.handleError(e,"position")})}async getUserPositions(e,t,n){return Hr(async()=>{const o={user:e,limit:Math.max(1,Math.min(10,t))};void 0!==n&&""!==n&&(o.bookMark=n);const i=await this.client.get("/v1/trade/positions",{params:this.toSearchParams(o)}),r=this.unwrapEnvelope(i);this.validateResponse(r);const s=this.asRecord(r.Data),a=this.normalizePositions(s.positions??[],i.status),c={positions:a,count:a.length};return"string"==typeof s.nextBookMark&&(c.nextBookMark=s.nextBookMark),c},"DexBackendTradeClient.getUserPositions",void 0,e=>{throw this.handleError(e,"position")})}poolParams(e){return this.toSearchParams({token0:es(e.token0),token1:es(e.token1),fee:e.fee})}positionParams(e){if(void 0===e.token0||void 0===e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper||void 0===e.owner)throw new Gt(400,"Position lookup requires owner, token0, token1, fee, tickLower, and tickUpper");return this.toSearchParams({token0:es(e.token0),token1:es(e.token1),fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner})}toSearchParams(e){const t=new URLSearchParams;for(const[n,o]of Object.entries(e))t.set(n,String(o));return t}normalizePositions(e,t){const n=this.asRecord(e);let o;o=Array.isArray(e)?e:Array.isArray(n.positions)?n.positions:"positionId"in n?[n]:[];const i=[];for(const e of o){if(!Ht(e))throw new Gt(t,"Invalid position in response",this.asRecord(e));i.push(e)}return i}unwrapEnvelope(e){const t=e.data;if(t.error||void 0===t.data)throw new Gt(t.status,t.message??"Trade backend error");return t.data}validateResponse(e){const t=e;if(null==t||"object"!=typeof t)throw new Gt(500,"Invalid response format: not an object");if(!("Data"in t)||!("Status"in t))throw new Gt(500,"Invalid response format: missing Data or Status field");if(e.Status>=400)throw new Gt(e.Status,e.Message??"Gateway error",e.Data)}validateTokenObjects(e,t,n){if("string"==typeof e||"string"==typeof t)throw new Yt(`Defi backend ${n} requires TokenClassKey objects, not strings.`,"token","INVALID_TOKEN_FORMAT")}toTokenClassKey(e){if("string"==typeof e)return{collection:e,category:"Unit",type:"none",additionalKey:"none"};const{collection:t,category:n,type:o,additionalKey:i}=e;if("string"!=typeof t||"string"!=typeof n||"string"!=typeof o||"string"!=typeof i)throw new Yt("Invalid TokenClassKey object","token","INVALID_TOKEN_FORMAT");return{collection:t,category:n,type:o,additionalKey:i}}asRecord(e){return"object"==typeof e&&null!==e?e:{}}handleError(e,t){return mn(e,t)}}const Pl=10;class xl extends Zo{constructor(e,t,n){if(super(!1),this.pricingConcurrency=5,this.tokenConverter=new pc,this.webSocketService=t,this.dexQuoteService=n,this.getWalletAddress=e.getWalletAddress,this.bundlerBaseUrl=e.bundlerBaseUrl,this.privateKey=e.privateKey,void 0===e.bundlerBaseUrl||null===e.bundlerBaseUrl||""===e.bundlerBaseUrl||void 0===e.dexBackendBaseUrl||null===e.dexBackendBaseUrl||""===e.dexBackendBaseUrl||void 0===e.dexBackendHttp||null===e.dexBackendHttp)throw new tn("GSwapService requires explicit bundlerBaseUrl, dexBackendBaseUrl, and dexBackendHttp configuration. These must be provided by LaunchpadSDK to ensure environment alignment.","gswapConfig");try{this.tradeClient=new Dl({baseUrl:e.dexBackendBaseUrl,timeout:3e4}),this.dexBackendClient=new Nl(e.dexBackendHttp),this.logger.debug("HTTP clients initialized successfully",{dexBackendUrl:e.dexBackendBaseUrl})}catch(e){throw this.logger.error("Failed to initialize HTTP clients",e),new tn("Failed to initialize GSwapService HTTP clients","httpClients")}}setPricingConcurrency(e){if(e<1)throw _n("pricingConcurrency",1,e,"Pricing concurrency");e>100&&this.logger.warn("Pricing concurrency > 100 may cause performance issues",{concurrency:e}),this.pricingConcurrency=e,this.logger.debug("Updated pricing concurrency",{concurrency:this.pricingConcurrency})}async getSwapQuoteExactInput(e){try{if(sr(e.amount).isLessThanOrEqualTo(0))throw new on("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new on("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact input",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[o,i]=t<n?[t,n]:[n,t],r=[3e3,500,1e4];let s;for(const a of r)try{const r=await this.dexQuoteService.fetchCompositePoolData({token0:o,token1:i,fee:a}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:r,fromToken:t,toToken:n,amount:e.amount}),c=sr(s.currentSqrtPrice),l=sr(s.newSqrtPrice),d=c.gt(l)?c.minus(l).dividedBy(c):sr(0),u=sr(s.amount0),h=sr(s.amount1),g=gr(u),m=gr(h);this.logger.debug("=== AMOUNT SELECTION RAW DATA ===",{"quoteResult.amount0":s.amount0,"quoteResult.amount1":s.amount1,"amount0BN.isNegative()":g,"amount1BN.isNegative()":m});const p=g?u:h;this.logger.debug("=== AMOUNT SELECTION RESULT ===",{selectedFromAmount0:g,selectedAmount:p.toFixed(),selectedAmountAbs:p.absoluteValue().toFixed()});const f=p.absoluteValue().toFixed();return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.amount,estimatedOutput:f,feeTier:a,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(e.amount,f),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:un(e)?e.message:"Unknown error"})}throw s??new on("No available fee tiers for quote",{feeTiers:r,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact input",on,e)}}async getSwapQuoteExactOutput(e){try{if(sr(e.amount).isLessThanOrEqualTo(0))throw new on("Amount must be greater than zero",{amount:e.amount,fromToken:e.fromToken,toToken:e.toToken});if(!this.dexQuoteService)throw new on("DexQuoteService not configured - cannot provide quotes",{fromToken:e.fromToken,toToken:e.toToken});this.logger.debug("Getting swap quote for exact output",{fromToken:e.fromToken,toToken:e.toToken,amount:e.amount});const t=this.tokenConverter.toLaunchpadFormat(e.fromToken),n=this.tokenConverter.toLaunchpadFormat(e.toToken),[o,i]=t<n?[t,n]:[n,t],r=[3e3,500,1e4];let s;for(const a of r)try{const r=await this.dexQuoteService.fetchCompositePoolData({token0:o,token1:i,fee:a}),s=await this.dexQuoteService.calculateDexPoolQuoteExactAmount({compositePoolData:r,fromToken:t,toToken:n,amount:e.amount}),c=sr(s.currentSqrtPrice),l=sr(s.newSqrtPrice),d=c.gt(l)?c.minus(l).dividedBy(c):sr(0),u=r.pool.token0,h="string"==typeof u?ua(u).collection:"object"==typeof u&&null!==u&&"tokenName"in u?u.tokenName:String(u),g=ua(n).collection===h?s.amount1:s.amount0;return{fromToken:e.fromToken,toToken:e.toToken,inputAmount:g,estimatedOutput:e.amount,feeTier:a,priceImpact:d.toFixed(),executionPrice:this.calculateExecutionPrice(g,e.amount),currentSqrtPrice:s.currentSqrtPrice,newSqrtPrice:s.newSqrtPrice}}catch(e){s=e,this.logger.debug("DexQuoteService failed for fee tier, trying next",{feeTier:a,error:un(e)?e.message:"Unknown error"})}throw s??new on("No available fee tiers for quote",{feeTiers:r,fromToken:e.fromToken,toToken:e.toToken})}catch(e){this.handleGSwapError("Failed to get swap quote for exact output",on,e)}}async executeSwap(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("GSwapService not initialized with signing capability (privateKey required)","privateKey");this.logger.debug("Executing swap",{fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.fromToken,e.toToken),o=function(e,t=.01){const n=sr(e),o=new v(1).minus(t);return n.multipliedBy(o)}(e.estimatedOutput,e.slippageTolerance??.01),i=this.getWalletAddress();if(null==i||""===i)throw new Yt("Wallet address required for swap execution","walletAddress",zt);let r;try{const t=await this.getSwapQuoteExactInput({fromToken:e.fromToken,toToken:e.toToken,amount:e.inputAmount});r=t.currentSqrtPrice,this.logger.debug("Quote refetch successful - extracted sqrtPrices",{currentSqrtPrice:r,newSqrtPrice:t.newSqrtPrice,feeTier:t.feeTier})}catch(t){this.logger.debug("Could not re-fetch quote for sqrtPrice, using default",{fromToken:e.fromToken,toToken:e.toToken,error:hn(t)})}const s={fromToken:t,toToken:n,inputAmount:e.inputAmount,minOutput:o.toFixed(),feeTier:e.feeTier,walletAddress:i,slippageTolerance:e.slippageTolerance??.01,...!$o(r)&&{currentSqrtPrice:r}},a=await this.sendSwapToBundler(s);this.logger.debug("Swap submitted, monitoring transaction",{transactionId:a,fromToken:e.fromToken,toToken:e.toToken}),await this.ensureWebSocketConnected();const c=await this.webSocketService.waitForTransaction(a);return{transactionId:c.transactionId,status:c.status,fromToken:e.fromToken,toToken:e.toToken,inputAmount:e.inputAmount,outputAmount:e.estimatedOutput,feeTier:e.feeTier,slippageTolerance:e.slippageTolerance??.01,timestamp:new Date(c.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(a)}}}catch(e){const t=e;this.handleGSwapError("Failed to execute swap",rn,e,{transactionHash:t?.txHash})}}async getUserAssets(e,t=1,n=20){return Hr(async()=>{if(!di(e))throw new an(Cn("walletAddress","a valid address (0x..., eth|..., or client|...)").message,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching user assets",{walletAddress:e,page:t,limit:n});return(await this.dexBackendClient.fetchTokenList({address:e,page:t,limit:n})).token.filter(e=>"0"!==e.quantity).map(e=>this.transformRawTokenToUserAsset(e)).filter(e=>null!==e)},"Failed to fetch user assets",this.logger,this.createGSwapErrorHandler(an,{walletAddress:e,page:t,limit:n}))}async getAllUserAssets(e){return Hr(async()=>{if(!di(e))throw new an(Cn("walletAddress","a valid address (0x..., eth|..., or client|...)").message,new Error("INVALID_ADDRESS_FORMAT"),e,"INVALID_ADDRESS");this.logger.debug("Fetching all user assets (auto-paginated with optimization)",{walletAddress:e});let t=!1;const n=await Za(async(n,o)=>{const i=await this.dexBackendClient.fetchTokenList({address:e,page:n,limit:o}),r=[];for(const e of i.token){if("0"===e.quantity){t=!0;break}const n=this.transformRawTokenToUserAsset(e);n&&r.push(n)}return{items:r,page:n,limit:o,total:r.length,totalPages:1,hasNext:!t&&i.token.length===o,hasPrevious:n>1}},{maxPages:20,pageSize:20,logger:this.logger});return this.logger.debug("Fetched all user assets",{walletAddress:e,totalAssets:n.items.length}),n.items},"Failed to fetch all user assets",this.logger,this.createGSwapErrorHandler(an,{walletAddress:e}))}async fetchAvailableDexTokens(e={}){return Hr(async()=>{const{search:t,limit:n=20,page:o=1}=e;this.logger.debug("Fetching available DEX tokens",{search:t,limit:n,page:o});const i=await this.dexBackendClient.fetchTokenList({...!$o(t)&&{search:t},limit:n,page:o}),r=i.token.map(e=>this.transformRawTokenToDexToken(e)),s=o*n<i.count;return{tokens:r,count:i.count,page:o,limit:n,hasMore:s}},"Failed to fetch available DEX tokens",this.logger,this.createGSwapErrorHandler(an,{...e}))}async fetchAllAvailableDexTokens(e={}){return Hr(async()=>{const{search:t}=e;this.logger.debug("Fetching all available DEX tokens (auto-paginated)",{search:t});const n=[];let o=1;for(;;){const e=await this.dexBackendClient.fetchTokenList({...!$o(t)&&{search:t},limit:20,page:o}),i=e.token.map(e=>this.transformRawTokenToDexToken(e));if(n.push(...i),i.length<20||20*o>=e.count)break;o+=1}return this.logger.debug("Fetched all available DEX tokens",{search:t,totalTokens:n.length}),n},"Failed to fetch all available DEX tokens",this.logger,this.createGSwapErrorHandler(an,e))}async getPoolInfo(e,t){try{if(null==e||""===e)throw En("tokenA","Token A");if(null==t||""===t)throw En("tokenB","Token B");this.logger.debug("Fetching pool info",{tokenA:e,tokenB:t});const{gswapToken0:n,gswapToken1:o}=this.convertTokenPair(e,t),i=[500,3e3,1e4];let r=sr(0),s=0;for(const a of i)try{const e="string"==typeof n?ua(n):n,t="string"==typeof o?ua(o):o,i=await this.tradeClient.getPoolData({token0:e,token1:t,fee:a});null!=i&&(r=r.plus(sr(i.liquidity)),s++)}catch{this.logger.debug("Pool not found for fee tier",{tokenA:e,tokenB:t,feeTier:a})}return{tokenA:e,tokenB:t,liquidity:r.toFixed(),feeTiers:i,swapCount:s}}catch(n){return this.logger.warn("Failed to fetch pool info",n),this.logger.debug("Pool error details",{error:new sn(`Failed to fetch pool info: ${hn(n)}`,n,e,t,this.extractGSwapErrorCode(n))}),{tokenA:e,tokenB:t,liquidity:"0",feeTiers:[500,3e3,1e4],swapCount:0}}}chunkArray(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async fetchPositionPrices(e){const t=this.pricingConcurrency;if(0===e.length)return new Map;const n=new Map;for(const t of e){const e=`${t.token0}|${t.token1}|${t.feeTier}`;n.has(e)||n.set(e,{token0:t.token0,token1:t.token1,feeTier:t.feeTier})}const o=Array.from(n.values()),i=this.chunkArray(o,t);this.logger.debug("Fetching pricing for positions",{totalPositions:e.length,uniquePoolsToPrice:n.size,chunks:i.length,concurrency:t});const r=new Map;for(let e=0;e<i.length;e++){const t=i[e];(await Promise.allSettled(t.map(async e=>{const t=await this.getSwapQuoteExactInput({fromToken:e.token0,toToken:e.token1,amount:"1"});return{key:`${e.token0}|${e.token1}|${e.feeTier}`,data:{token0:e.token0,token1:e.token1,feeTier:e.feeTier,currentPrice:t.executionPrice,executionPrice:t.executionPrice,priceImpact:t.priceImpact,estimatedOutput:t.estimatedOutput,pricedAt:new Date}}}))).forEach(e=>{"fulfilled"===e.status?r.set(e.value.key,e.value.data):this.logger.warn("Failed to fetch price for pool",{error:e.reason})})}return r}normalizePositionResponse(e,t){const n=e,o=e=>{if(null==e)return"";if("string"==typeof e)return e;if("object"==typeof e){const t=e;if(null!==t.type&&void 0!==t.type&&"none"!==t.type)return t.type;if(null!==t.collection&&void 0!==t.collection&&""!==t.collection)return t.collection;if(null!==t.symbol&&void 0!==t.symbol&&""!==t.symbol)return t.symbol;if(null!==t.tokenSymbol&&void 0!==t.tokenSymbol&&""!==t.tokenSymbol)return t.tokenSymbol;if(null!==t.name&&void 0!==t.name&&""!==t.name)return t.name}return""},i=o(n.token0),r=o(n.tokenA),s=o(n.token1),a=o(n.tokenB),c=n.token0Symbol??(""!==i?i:""!==r?r:n.tokenSymbol0??""),l=n.token1Symbol??(""!==s?s:""!==a?a:n.tokenSymbol1??""),d=""!==c?this.tokenConverter.normalizeInternalApiResponse(c):"",u=""!==l?this.tokenConverter.normalizeInternalApiResponse(l):"";return{positionId:n.positionId??n.id??"",ownerAddress:null!=t&&""!==t?t:n.ownerAddress??n.owner??"",token0:d,token1:u,feeTier:n.feeTier??n.fee??n.feeAmount??0,tickLower:n.tickLower??n.lowerTick??0,tickUpper:n.tickUpper??n.upperTick??0,liquidity:String(n.liquidity??n.liquidityAmount??"0"),amount0:String(n.amount0??n.amountA??"0"),amount1:String(n.amount1??n.amountB??"0"),feeAmount0:String(n.feeAmount0??n.feesA??"0"),feeAmount1:String(n.feeAmount1??n.feesB??"0"),...null!==n.createdAt&&void 0!==n.createdAt&&{createdAt:new Date(n.createdAt)},...null!==n.updatedAt&&void 0!==n.updatedAt&&{updatedAt:new Date(n.updatedAt)}}}parseTokenFlexible(e){try{return ua(e)}catch(t){if(un(t)&&hn(t).includes("Plain token string"))return this.logger.debug("Using default TokenClassKey for simple token symbol",{token:e}),{collection:"Token",category:"Unit",type:e,additionalKey:"none"};throw t}}transformRawTokenToDexToken(e){return{image:e.image,name:e.name,symbol:e.symbol,decimals:Co(e.decimals,18),description:e.description,verified:e.verify,compositeKey:e.compositeKey,additionalKey:e.additionalKey,category:e.category,type:e.type,collection:e.collection,subscribePrice:e.subscribePrice}}transformRawTokenToUserAsset(e){const t=null!==e.symbol&&void 0!==e.symbol&&""!==e.symbol?e.symbol:"UNKNOWN";try{const n=null!==e.compositeKey&&void 0!==e.compositeKey&&""!==e.compositeKey?ua(e.compositeKey.replace(/\$/g,"|")):ua(`${t}|Unit|none|none`);return{...this.transformRawTokenToDexToken(e),tokenId:n,balance:ar(null!==e.quantity&&void 0!==e.quantity&&""!==e.quantity?e.quantity:"0")}}catch(e){return this.logger.debug(`Skipping asset with processing error: ${t}`,{error:hn(e)}),null}}async getUserLiquidityPositions(e,t=10,n,o){try{if(null==e||""===e)throw En("ownerAddress","Owner address");this.logger.debug("Fetching user liquidity positions",{ownerAddress:e,limit:t,bookmark:n});const i=await this.tradeClient.getUserPositions(e,t,n),r=i.positions,s=i.nextBookMark,a=r.filter(e=>null!=e&&"object"==typeof e&&("positionId"in e||"id"in e)).map(t=>this.normalizePositionResponse(t,e));let c;this.logger.debug("Retrieved liquidity positions",{count:a.length,hasNextBookmark:null!=s,nextBookmark:s}),o?.withPrices&&a.length>0&&(c=await this.fetchPositionPrices(a));const l={items:a};return $o(s)||(l.nextBookmark=s),$o(c)||(l.prices=c),l}catch(e){this.handleGSwapError("Failed to fetch user liquidity positions",cn,e)}}async getAllSwapUserLiquidityPositions(e,t){try{if(null==e||""===e)throw En("ownerAddress","Owner address");this.logger.debug("Fetching all user liquidity positions (auto-paginated)",{ownerAddress:e});const n=async t=>{const n=await this.getUserLiquidityPositions(e,Pl,t,void 0);return{items:n.items,nextBookmark:n.nextBookmark}},o=await async function(e,t={}){const{maxPages:n=1e4,logger:o,pageSize:i=20}=t,r=[];let s,a=0;for(;a<n;){o&&o.debug(`Auto-pagination (bookmark): fetching page ${a+1} with pageSize ${i}`,{bookmark:s});const t=await e(s,i);let n,c,l;if(!0===Array.isArray(t))n=t,c=void 0,l=!1;else{if(null==t||"object"!=typeof t||!("items"in t)){o&&o.warn("Auto-pagination (bookmark): received invalid result structure, stopping");break}n=t.items,c=t.nextBookmark,l=!0}if(!Array.isArray(n)){o&&o.warn("Auto-pagination (bookmark): received invalid items array, stopping");break}if(0===n.length){o&&o.debug(`Auto-pagination (bookmark): no items returned on page ${a+1}, exiting loop`);break}r.push(...n),a++,o&&o.debug(`Auto-pagination (bookmark): page ${a} returned ${n.length} items`,{hasNextBookmark:""!==(c??""),format:l?"BookmarkPaginationResult":"legacy-array"});const d=n.length<i;if(l&&(""===c||void 0===c)){o&&o.debug("Auto-pagination (bookmark): no nextBookmark returned, reached end of results",{nextBookmark:""===c?"(empty string)":"(undefined)"});break}if(d){o&&o.debug("Auto-pagination (bookmark): received fewer items than limit, reached last page",{received:n.length,pageSize:i,format:l?"BookmarkPaginationResult":"legacy-array"});break}s=c}return a>=n&&o&&o.warn(`Auto-pagination (bookmark): exceeded maxPages limit of ${n}, stopping iteration`),o&&o.debug(`Auto-pagination (bookmark): completed with total items: ${r.length}`,{pageCount:a}),{items:r,total:r.length}}(n,{maxPages:1e4,logger:this.logger,pageSize:Pl}),i=o.items;if(this.logger.debug("Fetched all user liquidity positions",{ownerAddress:e,totalPositions:i.length}),t?.withPrices&&i.length>0){return{items:i,prices:await this.fetchPositionPrices(i)}}return i}catch(t){this.handleGSwapError("Failed to fetch all user liquidity positions",cn,t,{ownerAddress:e})}}async getLiquidityPosition(e,t){try{if(null==e||""===e)throw En("ownerAddress","Owner address");if(void 0===t.token0||null===t.token0||""===t.token0)throw En("token0","Token 0");if(void 0===t.token1||null===t.token1||""===t.token1)throw En("token1","Token 1");this.logger.debug("Fetching liquidity position",{ownerAddress:e,position:t}),this.validateTickSpacing(t.tickLower,t.tickUpper,t.fee);const{gswapToken0:n,gswapToken1:o}=this.convertTokenPair(t.token0,t.token1),i=Bc(n),r=Bc(o),s=(await this.tradeClient.getPositions({owner:e,token0:i,token1:r,fee:t.fee,tickLower:t.tickLower,tickUpper:t.tickUpper})).positions.find(e=>e.tickLower===t.tickLower&&e.tickUpper===t.tickUpper);if(!s||"object"!=typeof s||!("positionId"in s)&&!("id"in s))throw new cn("Invalid position data returned from API",null,"INVALID_DATA");const a=this.normalizePositionResponse(s,e);return this.logger.debug("Retrieved liquidity position",{positionId:a.positionId}),a}catch(e){this.handleGSwapError("Failed to fetch liquidity position",cn,e)}}async getLiquidityPositionById(e,t,n,o,i,r,s){try{if(null==e||""===e)throw En("ownerAddress","Owner address");if(null==t||""===t)throw En("positionId","Position ID");let a;this.logger.debug("Fetching liquidity position by ID",{ownerAddress:e,positionId:t,hasToken0:null!=n,hasToken1:null!=o,hasFee:null!=i,hasTickLower:!$o(r),hasTickUpper:!$o(s)});let c=null;const l=5,d=2e3;for(let u=1;u<=l;u++)try{if(null!=n&&""!==n&&null!=o&&""!==o&&!$o(i)&&!$o(r)&&!$o(s))try{this.logger.debug("Attempting compound key lookup",{ownerAddress:e,token0:n,token1:o,feeTier:i,tickLower:r,tickUpper:s});if(a=(await this.tradeClient.getPositionById(e,n,o,i,r,s,t)).Data,null!=a&&"object"==typeof a&&("positionId"in a||"id"in a)){this.logger.debug("Successfully fetched position via compound key",{attempt:u,positionId:t});break}throw new cn("Invalid position data from compound key lookup",null,"INVALID_DATA")}catch(e){this.logger.debug("Compound key lookup failed, trying fallback",{attempt:u,error:un(e)?e.message:e})}const h=await this.getAllSwapUserLiquidityPositions(e),g=Array.isArray(h)?h:h.items,m=g.find(e=>Er(e.positionId,t));if(m){a=m,this.logger.debug("Found position via user positions scan",{attempt:u,positionId:t,totalPositions:g.length});break}if(c=Un(t),u<l){this.logger.warn("User positions scan did not find position, retrying",{attempt:u,positionId:t,ownerAddress:e,foundCount:g.length}),await new Promise(e=>setTimeout(e,d));continue}}catch(e){if(u<l){this.logger.warn("Error fetching position, retrying",{attempt:u,positionId:t,error:hn(e)}),await new Promise(e=>setTimeout(e,d));continue}c=un(e)?e:new Error(String(e))}if(!a||"object"!=typeof a||!("positionId"in a)&&!("id"in a))throw this.logger.error("Invalid position data returned from API after retries",{positionId:t,resultType:typeof a,resultKeys:null!=a?Object.keys(a):"null",lastError:c?.message}),c??Un(t);const u=this.normalizePositionResponse(a,e);return this.logger.debug("Retrieved liquidity position by ID",{positionId:u.positionId}),u}catch(e){this.handleGSwapError("Failed to fetch liquidity position by ID",cn,e)}}async fetchSwapPositionDirect(e){try{this.logger.debug("Fetching swap position via direct compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const t="string"==typeof e.token0?this.parseTokenFlexible(e.token0):e.token0,n="string"==typeof e.token1?this.parseTokenFlexible(e.token1):e.token1;this.logger.debug("Fetching position via compound key",{token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner});const o=await this.tradeClient.getPositions({token0:t,token1:n,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});if(null===o.positions||void 0===o.positions||0===o.positions.length)throw new cn("Position not found: No position exists for this compound key",null,"NOT_FOUND");const i=o.positions[0],r=this.normalizePositionResponse(i,e.owner);return this.logger.debug("Retrieved swap position via compound key",{positionId:r.positionId,token0:r.token0,token1:r.token1}),r}catch(e){this.handleGSwapError("Failed to fetch swap position via compound key",cn,e)}}async estimateRemoveLiquidity(e){try{if(void 0===e.token0||null===e.token0||""===e.token0)throw En("token0","Token 0");if(void 0===e.token1||null===e.token1||""===e.token1)throw En("token1","Token 1");if(void 0===e.liquidity||null===e.liquidity||""===e.liquidity)throw En("liquidity","Liquidity amount");if(void 0===e.owner||null===e.owner||""===e.owner)throw En("owner","Owner address");this.logger.debug("Estimating liquidity removal",{token0:e.token0,token1:e.token1,owner:e.owner}),this.validateTickSpacing(e.tickLower,e.tickUpper,e.fee);const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1),o=Bc(t),i=Bc(n),r=await this.tradeClient.getRemoveLiquidityEstimation({token0:o,token1:i,fee:e.fee,amount:e.liquidity,tickLower:e.tickLower,tickUpper:e.tickUpper,owner:e.owner});return this.logger.debug("Estimated removal",{result:r}),r}catch(e){this.handleGSwapError("Failed to estimate liquidity removal",cn,e)}}async addLiquidityByPrice(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("GSwapService not initialized with signing capability (privateKey required)","privateKey");this.logger.debug("Adding liquidity by price",{token0:e.token0,token1:e.token1,priceRange:`${e.minPrice}-${e.maxPrice}`});const{gswapToken0:t,gswapToken1:n}=this.convertTokenPair(e.token0,e.token1);await this.ensureWebSocketConnected(),this.logger.debug("Converting price range to ticks",{token0:e.token0,token1:e.token1,minPrice:e.minPrice,maxPrice:e.maxPrice,fee:e.fee});const o=ua(t),i=ua(n),r=(await this.tradeClient.getPoolData({token0:o,token1:i,fee:e.fee})).tickSpacing;this.logger.debug("Retrieved tick spacing from pool",{tickSpacing:r,fee:e.fee});const s=sr(e.minPrice),a=sr(e.maxPrice),c=Math.floor(cr(s)),l=Math.ceil(cr(a)),d=wr(c,r),u=wr(l,r);this.logger.debug("Converted price range to ticks",{minPrice:e.minPrice,maxPrice:e.maxPrice,tickLower:d,tickUpper:u,tickSpacing:r});const h=this.getWalletAddress();if(null==h||""===h)throw new tn("GSwapService: No wallet address available - cannot create position","walletAddress");const g="string"==typeof e.token0?ua(e.token0):e.token0,m="string"==typeof e.token1?ua(e.token1):e.token1;this.logger.debug("Sending AddLiquidity by price to bundler",{fee:e.fee,tickRange:`${d}-${u}`,walletAddress:h});const p=await this.sendAddLiquidityToBundler({token0:g,token1:m,fee:e.fee,tickLower:d,tickUpper:u,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:null!==e.amount0Min&&void 0!==e.amount0Min&&""!==e.amount0Min?e.amount0Min:"0",amount1Min:null!==e.amount1Min&&void 0!==e.amount1Min&&""!==e.amount1Min?e.amount1Min:"0",owner:h}),f={transactionId:p};if(null!==f.positionId&&void 0!==f.positionId&&""!==f.positionId&&null!=p&&""!==p){this.logger.debug("Position ID returned directly from backend",{transactionId:p,positionId:f.positionId}),await this.ensureWebSocketConnected();const e=await this.webSocketService.waitForTransaction(p);this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:e.status});const t=this.getWalletAddress();if(null!=t&&""!==t&&null!==f.positionId&&void 0!==f.positionId&&""!==f.positionId)try{const n=await this.getLiquidityPositionById(t,f.positionId);this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1});const{createdAt:o,updatedAt:i,...r}=n,s=o instanceof Date?o.getTime():"number"==typeof o?o:void 0,a={...f,...r,positionId:f.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}};return $o(s)||(a.createdAt=s),a}catch(t){return this.logger.debug("Could not fetch full position details",{error:hn(t)}),{...f,positionId:f.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}}if(null!=p&&""!==p){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:p}),await this.ensureWebSocketConnected();const t=await this.webSocketService.waitForTransaction(p);let n;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:p,status:t.status});let o=null;this.logger.debug("Waiting for position indexing after WebSocket confirmation",{token0:e.token0,token1:e.token1,fee:e.fee}),await new Promise(e=>setTimeout(e,2e3));try{const t=this.getWalletAddress();if(null==t||""===t)throw new tn("No wallet address available","walletAddress");this.logger.debug("Fetching positions",{walletAddress:t});const i=(await this.getUserLiquidityPositions(t,10)).items;if(this.logger.debug("Fetched positions",{count:null!=i?i.length:0}),null!=i&&i.length>0){const t=ua(e.token0).collection.toUpperCase(),r=ua(e.token1).collection.toUpperCase(),s=[];for(const n of i){if(""===(n?.positionId??""))continue;const o=null!==n.token0&&void 0!==n.token0?n.token0.toUpperCase():void 0,i=null!==n.token1&&void 0!==n.token1?n.token1.toUpperCase():void 0;if(null==o||""===o||null==i||""===i){this.logger.debug("Skipping position with empty tokens",{positionId:n.positionId});continue}const a=Ir(o,i,t,r),c=n.feeTier===e.fee;this.logger.debug("Checking position",{positionId:n.positionId,tokens:`${o}/${i}`,tokensMatch:a,fee:n.feeTier,feeMatches:c}),a&&c&&s.push(n)}s.length>0?(o=s[s.length-1],n=o.positionId,this.logger.debug("Found newly created position",{positionId:n,expectedTokens:`${ua(e.token0).collection}/${ua(e.token1).collection}`,expectedFee:e.fee,positionCount:i.length,liquidity:o.liquidity,amount0:o.amount0,amount1:o.amount1})):this.logger.debug("No matching position found",{availablePositions:i.map(e=>({id:e.positionId,token0:e.token0,token1:e.token1,fee:e.feeTier}))})}else this.logger.debug("No positions returned from API")}catch(e){this.logger.debug("Error fetching positions",{error:hn(e)})}this.logger.debug("Discovery complete",{positionId:null!=n&&""!==n?n:"not found",matchedPositionData:{positionId:o?.positionId,liquidity:o?.liquidity,amount0:o?.amount0,amount1:o?.amount1,feeAmount0:o?.feeAmount0,feeAmount1:o?.feeAmount1,token0:o?.token0,token1:o?.token1,feeTier:o?.feeTier}});let i=o;if(null!=n&&""!==n)try{i=await this.getLiquidityPositionById(h,n),this.logger.debug("Fetched full position details",{positionId:i.positionId,liquidity:i.liquidity,amount0:i.amount0,amount1:i.amount1,feeAmount0:i.feeAmount0,feeAmount1:i.feeAmount1})}catch(e){this.logger.debug("Could not fetch full position details, using discovered data",{error:hn(e)})}const r=i?{ownerAddress:i.ownerAddress,token0:i.token0,token1:i.token1,feeTier:i.feeTier,tickLower:i.tickLower,tickUpper:i.tickUpper,liquidity:i.liquidity,amount0:i.amount0,amount1:i.amount1,feeAmount0:i.feeAmount0,feeAmount1:i.feeAmount1}:{};return{...f,...r,...null!=n&&""!==n&&{positionId:n},status:t.status,transactionId:t.transactionId,timestamp:new Date(t.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(p)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),f}catch(e){this.logger.error("Error in addSwapLiquidityByPrice",{error:hn(e),stack:un(e)?pn(e)?.split("\n").slice(0,3).join(" | "):void 0}),this.handleGSwapError("Failed to add liquidity by price",cn,e)}}async addSwapLiquidityByTicks(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("GSwapService not initialized with signing capability (privateKey required)","privateKey");const t=this.getWalletAddress();if(null==t||""===t)throw new tn("GSwapService: No wallet address available - cannot create position","walletAddress");this.logger.debug("Adding liquidity by ticks with direct bundler",{token0:e.token0,token1:e.token1,fee:e.fee,walletAddress:t,tickRange:`${e.tickLower}-${e.tickUpper}`});const n="string"==typeof e.token0?ua(e.token0):e.token0,o="string"==typeof e.token1?ua(e.token1):e.token1;await this.ensureWebSocketConnected();const i=await this.sendAddLiquidityToBundler({token0:n,token1:o,fee:e.fee,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:null!==e.amount0Min&&void 0!==e.amount0Min&&""!==e.amount0Min?e.amount0Min:"0",amount1Min:null!==e.amount1Min&&void 0!==e.amount1Min&&""!==e.amount1Min?e.amount1Min:"0",owner:t});this.logger.info("Liquidity transaction submitted to bundler",{transactionId:i});const r=this.webSocketService.waitForTransaction(i),s={transactionId:i};if(null!==s.positionId&&void 0!==s.positionId&&""!==s.positionId&&null!=i&&""!==i){this.logger.info("Position ID returned directly from backend",{transactionId:i,positionId:s.positionId});const e=await r;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:e.status});const t=this.getWalletAddress();if(null!=t&&""!==t&&null!==s.positionId&&void 0!==s.positionId&&""!==s.positionId)try{this.logger.debug("Fetching full position details",{positionId:s.positionId});const n=await this.getLiquidityPositionById(t,s.positionId);this.logger.debug("Fetched full position data",{positionId:n.positionId,liquidity:n.liquidity,amount0:n.amount0,amount1:n.amount1});const{createdAt:o,updatedAt:r,...a}=n,c=o instanceof Date?o.getTime():"number"==typeof o?o:void 0,l={...s,...a,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}};return $o(c)||(l.createdAt=c),l}catch(t){return this.logger.warn("Could not fetch full position details",{positionId:s.positionId,error:hn(t)}),{...s,positionId:s.positionId,status:e.status,transactionId:e.transactionId,timestamp:new Date(e.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}}if(null!=i&&""!==i){this.logger.debug("Monitoring liquidity transaction (discovery mode)",{transactionId:i});const n=await r;let o;this.logger.debug("Liquidity transaction confirmed on-chain",{transactionId:i,status:n.status});let a=null;const c="string"==typeof e.token0?e.token0:e.token0?.type??"unknown",l="string"==typeof e.token1?e.token1:e.token1?.type??"unknown";this.logger.debug("Waiting for position indexing after WebSocket confirmation"),this.logger.debug("Looking for matching position",{token0:c,token1:l,fee:e.fee});try{const t=this.getWalletAddress();if(null==t||""===t)throw new tn("No wallet address available","walletAddress");this.logger.debug("Fetching positions from API",{walletAddress:t,pageSize:Pl});const n=3,i=5e3,r=3e3;let s=[];for(let c=1;c<=n;c++){const l=1===c?i:r;this.logger.debug("Position discovery attempt",{attempt:c,maxAttempts:n,delayMs:l}),await new Promise(e=>setTimeout(e,l)),this.logger.debug("Querying positions from API",{attempt:c,pageSize:Pl});if(s=(await this.getUserLiquidityPositions(t,Pl)).items,this.logger.debug("Got positions from API",{count:null!=s?s.length:0}),null!=s&&s.length>0){const t=("string"==typeof e.token0?ua(e.token0).collection:e.token0.collection).toUpperCase(),n=("string"==typeof e.token1?ua(e.token1).collection:e.token1.collection).toUpperCase(),i=[];for(const o of s){if(""===(o?.positionId??""))continue;const r=null!==o.token0&&void 0!==o.token0?o.token0.toUpperCase():void 0,s=null!==o.token1&&void 0!==o.token1?o.token1.toUpperCase():void 0;if(null==r||""===r||null==s||""===s){this.logger.debug("Skipping position with empty tokens",{positionId:o.positionId});continue}const a=Ir(r,s,t,n),c=o.feeTier===e.fee;this.logger.debug("Checking position against target",{positionId:o.positionId,tokens:`${r}/${s}`,tokensMatch:a,fee:o.feeTier,feeMatches:c}),a&&c&&i.push(o)}if(i.length>0){a=i[i.length-1],o=a.positionId,this.logger.info("Found newly created position",{positionId:o,liquidity:a.liquidity,amount0:a.amount0,amount1:a.amount1,fee:a.feeTier}),this.logger.debug("Found newly created position",{positionId:o,expectedTokens:`${ua(e.token0).collection}/${ua(e.token1).collection}`,expectedFee:e.fee,positionCount:s.length});break}this.logger.debug("No matching position found in this attempt")}else this.logger.debug("No positions returned from API in this attempt")}}catch(e){this.logger.error("Error fetching positions during discovery",{error:hn(e)}),this.logger.debug("Error waiting for position indexing",{error:hn(e)})}this.logger.debug("Position discovery complete",{positionId:null!=o&&""!==o?o:"not found",found:null!=o&&""!==o}),this.logger.debug("Matched position data",{positionId:a?.positionId,liquidity:a?.liquidity,amount0:a?.amount0,amount1:a?.amount1,feeAmount0:a?.feeAmount0,feeAmount1:a?.feeAmount1,token0:a?.token0,token1:a?.token1,feeTier:a?.feeTier});let d=a;if(null!=o&&""!==o)try{this.logger.debug("Fetching full position details",{positionId:o}),d=await this.getLiquidityPositionById(t,o),this.logger.debug("Fetched full position data",{positionId:d.positionId,liquidity:d.liquidity,amount0:d.amount0,amount1:d.amount1,feeAmount0:d.feeAmount0,feeAmount1:d.feeAmount1})}catch(e){this.logger.warn("Could not fetch full position details, using discovered data",{positionId:o,error:hn(e)})}const u=d?{ownerAddress:d.ownerAddress,token0:d.token0,token1:d.token1,feeTier:d.feeTier,tickLower:d.tickLower,tickUpper:d.tickUpper,liquidity:d.liquidity,amount0:d.amount0,amount1:d.amount1,feeAmount0:d.feeAmount0,feeAmount1:d.feeAmount1}:{};return{...s,...u,...null!=o&&""!==o&&{positionId:o},status:n.status,transactionId:n.transactionId,timestamp:new Date(n.timestamp),wait:async e=>{await this.webSocketService.waitForTransaction(i)}}}return this.logger.warn("No transaction ID in liquidity result, cannot confirm position creation"),s}catch(e){this.handleGSwapError("Failed to add liquidity by ticks",cn,e)}}async monitorBundlerTransaction(e,t,n="bundler"){let o;try{const i=await t;o={status:i.status,transactionId:null!==i.transactionId&&void 0!==i.transactionId&&""!==i.transactionId?i.transactionId:e,timestamp:null!==i.timestamp&&void 0!==i.timestamp&&0!==i.timestamp?i.timestamp:Date.now(),data:i.data},this.logger.debug(`${n} transaction confirmed on-chain`,{transactionId:e,status:o.status})}catch(t){return this.logger.warn(`WebSocket monitoring timeout for ${n} transaction, returning result with transaction ID`,{transactionId:e,error:hn(t)}),{transactionId:e,status:"SUBMITTED",timestamp:new Date,wait:async t=>{try{await this.webSocketService.waitForTransaction(e)}catch{this.logger.debug("Explicit wait also timed out",{transactionId:e})}}}}return{transactionId:o.transactionId,status:o.status,timestamp:new Date(o.timestamp),wait:async t=>{await this.webSocketService.waitForTransaction(e)}}}async removeLiquidity(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("Private key not available for bundler-direct operations","privateKey");this.logger.debug("Removing liquidity via bundler",{token0:e.token0,token1:e.token1,liquidity:e.liquidity});try{const t=Ao(e.liquidity,Number.NaN);if(isNaN(t))throw new Yt(`Invalid liquidity value: "${e.liquidity}". Must be a valid number. Position ID: ${null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"unknown"}`,"liquidity","INVALID_VALUE");if(0===t)throw new Yt(`Cannot remove zero liquidity from position. This would waste gas fees without any effect. Position ID: ${null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"unknown"}`,"liquidity","ZERO_VALUE")}catch(e){if(un(e)&&hn(e).includes("Cannot remove zero liquidity"))throw e;if(un(e)&&hn(e).includes("Invalid liquidity value"))throw e;throw e}const t="string"==typeof e.token0?ua(e.token0):e.token0,n="string"==typeof e.token1?ua(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendRemoveLiquidityToBundler(e.tickLower,e.tickUpper,e.liquidity,t,n,e.fee,null!==e.amount0Min&&void 0!==e.amount0Min&&""!==e.amount0Min?e.amount0Min:"0",null!==e.amount1Min&&void 0!==e.amount1Min&&""!==e.amount1Min?e.amount1Min:"0",null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"");this.logger.debug("Liquidity removal submitted to bundler",{transactionId:o});const i=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,i,"liquidity removal")}catch(e){this.handleGSwapError("Failed to remove liquidity",cn,e)}}async collectPositionFees(e){try{if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("Private key not available for bundler-direct operations","privateKey");if(null!==e.ownerAddress&&void 0!==e.ownerAddress&&""!==e.ownerAddress&&null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId&&(null===e.token0||void 0===e.token0)){this.logger.debug("Fetching position data before collecting fees",{ownerAddress:e.ownerAddress,positionId:e.positionId});const t=await this.getLiquidityPositionById(e.ownerAddress,e.positionId);if(null==t)throw Un(e.positionId);if(null===t.token0||void 0===t.token0||""===t.token0||null===t.token1||void 0===t.token1||""===t.token1)throw new cn("Position missing token information",null,"INVALID_DATA");const{gswapToken0:n,gswapToken1:o}=this.convertTokenPair(t.token0,t.token1);return this.collectPositionFees({token0:n,token1:o,fee:t.feeTier,tickLower:t.tickLower,tickUpper:t.tickUpper,amount0Requested:null!==e.amount0Max&&void 0!==e.amount0Max&&""!==e.amount0Max?e.amount0Max:null!==e.amount0Requested&&void 0!==e.amount0Requested&&""!==e.amount0Requested?e.amount0Requested:"0",amount1Requested:null!==e.amount1Max&&void 0!==e.amount1Max&&""!==e.amount1Max?e.amount1Max:null!==e.amount1Requested&&void 0!==e.amount1Requested&&""!==e.amount1Requested?e.amount1Requested:"0",positionId:e.positionId})}if(null===e.token0||void 0===e.token0||null===e.token1||void 0===e.token1||void 0===e.fee||void 0===e.tickLower||void 0===e.tickUpper)throw En("parameters","token0, token1, fee, tickLower, tickUpper");this.logger.debug("Collecting position fees via bundler",{token0:"string"==typeof e.token0?e.token0:e.token0?.type??"unknown",token1:"string"==typeof e.token1?e.token1:e.token1?.type??"unknown",tickLower:e.tickLower,tickUpper:e.tickUpper});const t="string"==typeof e.token0?ua(e.token0):e.token0,n="string"==typeof e.token1?ua(e.token1):e.token1;await this.ensureWebSocketConnected();const o=await this.sendCollectPositionFeesToBundler(t,n,e.fee,null!==e.amount0Requested&&void 0!==e.amount0Requested&&""!==e.amount0Requested?e.amount0Requested:"0",null!==e.amount1Requested&&void 0!==e.amount1Requested&&""!==e.amount1Requested?e.amount1Requested:"0",e.tickLower,e.tickUpper,null!==e.positionId&&void 0!==e.positionId&&""!==e.positionId?e.positionId:"");this.logger.debug("Fee collection submitted to bundler",{transactionId:o});const i=this.webSocketService.waitForTransaction(o);return this.monitorBundlerTransaction(o,i,"fee collection")}catch(e){this.handleGSwapError("Failed to collect position fees",cn,e)}}async getPoolData(e,t,n){try{this.logger.debug("Getting pool data",{tokenA:e,tokenB:t,feeTier:n});const{gswapToken0:o,gswapToken1:i}=this.convertTokenPair(e,t),r=ua(o),s=ua(i),a=await this.tradeClient.getPoolData({token0:r,token1:s,fee:n}),c=this.calculatePriceFromSqrtPriceX96(sr(a.sqrtPrice));return{tokenA:e,tokenB:t,feeTier:n,liquidity:a.liquidity.toString(),sqrtPriceX96:a.sqrtPrice.toString(),tick:a.tick,feeGrowthGlobal0X128:a.feeGrowthGlobal0.toString(),feeGrowthGlobal1X128:a.feeGrowthGlobal1.toString(),currentPrice:c.toFixed()}}catch(e){this.handleGSwapError("Failed to get pool data",sn,e)}}async calculateDexPoolSpotPrice(e,t,n){try{this.logger.debug("Calculating spot price",{tokenA:e,tokenB:t,feeTier:n});const o=await this.getPoolData(e,t,n),i=sr(o.currentPrice);return{tokenA:e,tokenB:t,feeTier:n,price:i.toFixed(),invertedPrice:lr(i,!0),tick:o.tick,liquidity:o.liquidity}}catch(e){this.handleGSwapError("Failed to calculate spot price",sn,e)}}async calculateOptimalPositionSize(e,t,n,o,i,r,s){try{this.logger.debug("Calculating optimal position size",{tokenA:e,tokenB:t,desiredAmount0:o,desiredAmount1:i});const a=(await this.getPoolData(e,t,n)).tick,c=K(r),l=K(a),d=K(s),u=q(sr(o),sr(i),c,l,d),h=G(u,l,c,d),g=h[0],m=h[1],p=sr(o),f=sr(i);return{amount0:g.toFixed(),amount1:m.toFixed(),liquidity:u.toFixed(),ratio:vr(g,m).toFixed(),utilizationPercent:{amount0:pr(vr(g,p),100).toFixed(2),amount1:pr(vr(m,f),100).toFixed(2)}}}catch(e){this.handleGSwapError("Failed to calculate optimal position size",cn,e)}}async validatePositionParameters(e,t,n,o,i,r,s){const a=[],c=[];try{this.logger.debug("Validating position parameters",{tokenA:e,tokenB:t,tickLower:o,tickUpper:i});const l=[500,3e3,1e4];l.includes(n)||a.push(`Invalid fee tier: ${n}. Must be one of: ${l.join(", ")}`);const d=this.getTickSpacing(n);let u;o%d!==0&&a.push(`tickLower must be multiple of ${d}`),i%d!==0&&a.push(`tickUpper must be multiple of ${d}`),o>=i&&a.push(`tickLower (${o}) must be less than tickUpper (${i})`);try{u=await this.getPoolData(e,t,n)}catch{return a.push(`Pool not found for ${e}/${t} at fee tier ${n}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}const h=sr(r),g=sr(s);if(h.isNaN()||g.isNaN())a.push("Amounts must be valid numbers");else try{yr(h,g)}catch(e){a.push(`Liquidity amounts must be non-negative: ${e.message}`)}const m=u.tick;(m<o||m>i)&&c.push("Position is out of current price range - will not earn fees until price moves into range");sr(u.liquidity).lt("1000000")&&c.push("Low pool liquidity - consider higher slippage tolerance");const p=0===a.length?35e4:0;return{valid:0===a.length,errors:a,warnings:c,gasEstimate:p,tickSpacing:d,currentTick:m,poolLiquidity:u.liquidity}}catch(e){const t=hn(e);return a.includes(t)||a.push(`Validation failed: ${t}`),{valid:!1,errors:a,warnings:c,gasEstimate:0}}}calculateTicksForPrice(e,t,n,o,i){try{this.logger.debug("Calculating ticks for price range",{tokenA:e,tokenB:t,minPrice:n,maxPrice:o});const r=this.getTickSpacing(i),s=sr(n),a=sr(o);Uo(n,o,"priceRange");const c=Math.floor(cr(s)),l=Math.ceil(cr(a)),d=wr(c,r),u=wr(l,r),h=Math.pow(1.0001,d),g=Math.pow(1.0001,u),m=sr(h),p=sr(g);return{tokenA:e,tokenB:t,feeTier:i,tickLower:d,tickUpper:u,tickSpacing:r,requestedMinPrice:n,requestedMaxPrice:o,actualMinPrice:m.toFixed(8),actualMaxPrice:p.toFixed(8),priceDeviation:{minPriceDeviation:pr(m.minus(s).dividedBy(s),100).toFixed(4),maxPriceDeviation:pr(p.minus(a).dividedBy(a),100).toFixed(4)}}}catch(e){this.handleGSwapError("Failed to calculate ticks for price",cn,e)}}async calculatePriceForTicks(e,t,n,o){try{this.logger.debug("Calculating price for ticks",{tokenA:e,tokenB:t,tickLower:n,tickUpper:o});const i=Math.pow(1.0001,n),r=Math.pow(1.0001,o);let s;try{s=(await this.getPoolData(e,t,3e3)).currentPrice}catch{}const a=sr(i),c=sr(r),l={tokenA:e,tokenB:t,tickLower:n,tickUpper:o,minPrice:a.toFixed(8),maxPrice:c.toFixed(8),priceRange:`${a.toFixed(4)} - ${c.toFixed(4)}`,tickSpread:o-n};return $o(s)||(l.currentPrice=s),l}catch(e){throw this.handleGSwapError("Failed to calculate price for ticks",cn,e),e}}calculateExecutionPrice(e,t){try{const n=sr(e);return vr(sr(t),n,"0").toFixed()}catch{return"0"}}getTickSpacing(e){switch(e){case 500:return 10;case 3e3:return 60;case 1e4:return 200;default:throw Cn("feeTier","500, 3000, or 10000","Fee tier")}}validateTickSpacing(e,t,n){const o=this.getTickSpacing(n);if(e%o!==0)throw new Yt(`Invalid tickLower: ${e} must be a multiple of ${o} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickLower","INVALID_TICK_SPACING");if(t%o!==0)throw new Yt(`Invalid tickUpper: ${t} must be a multiple of ${o} for fee tier ${n}. Tip: Use getAllSwapUserLiquidityPositions() to discover valid positions with correct tick spacing.`,"tickUpper","INVALID_TICK_SPACING")}calculatePriceFromSqrtPriceX96(e){try{const t=new v(2).pow(96);return vr(e,t).pow(2)}catch{return sr(0)}}calculatePriceFromSqrtPriceDecimal(e){try{return e.pow(2)}catch{return sr(0)}}async getPoolSlot0(e,t,n){try{this.logger.debug("Fetching pool slot0 data",{token0:e,token1:t,fee:n});const o="string"==typeof e?ua(e):e,i="string"==typeof t?ua(t):t,r=await this.tradeClient.getSlot0({token0:o,token1:i,fee:n}),s={sqrtPrice:null!==r.sqrtPrice&&void 0!==r.sqrtPrice&&""!==r.sqrtPrice?r.sqrtPrice:"0",tick:null!==r.tick&&void 0!==r.tick&&0!==r.tick?r.tick:0,liquidity:null!==r.liquidity&&void 0!==r.liquidity&&""!==r.liquidity?r.liquidity:"0",grossPoolLiquidity:null!==r.grossPoolLiquidity&&void 0!==r.grossPoolLiquidity&&""!==r.grossPoolLiquidity?r.grossPoolLiquidity:"0"};return this.logger.debug("Retrieved pool slot0 data",{sqrtPrice:s.sqrtPrice,tick:s.tick,liquidity:s.liquidity}),s}catch(o){this.handleGSwapError("Failed to fetch pool slot0 data",sn,o,{token0:e,token1:t,fee:n})}}async getPositionCurrentPrice(e){try{this.logger.debug("Fetching position current price",{token0:e.token0,token1:e.token1,feeTier:e.feeTier});const t=await this.getPoolSlot0(e.token0,e.token1,e.feeTier),n=sr(t.sqrtPrice),o={price:this.calculatePriceFromSqrtPriceDecimal(n).toFixed(18),sqrtPrice:t.sqrtPrice,tick:t.tick,liquidity:t.liquidity};return this.logger.debug("Calculated position current price",{price:o.price,tick:o.tick}),o}catch(t){this.handleGSwapError("Failed to fetch position current price",sn,t,{token0:e.token0,token1:e.token1})}}_calculateLiquidityFromAmount0(e,t,n){try{const o=K(t),i=K(n);return W(e,o,i)}catch{return sr(0)}}_calculateLiquidityFromAmount1(e,t,n){try{const o=K(t),i=K(n);return H(e,o,i)}catch{return sr(0)}}_calculateAmount0FromLiquidity(e,t,n){try{const o=K(t),i=K(n);return z(o,i,e)}catch{return sr(0)}}_calculateAmount1FromLiquidity(e,t,n){try{const o=K(t),i=K(n);return j(o,i,e)}catch{return sr(0)}}convertTokenPair(e,t){return{gswapToken0:this.tokenConverter.toLaunchpadFormat(e),gswapToken1:this.tokenConverter.toLaunchpadFormat(t)}}async sendAddLiquidityToBundler(e){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("GSwapService: AddLiquidity requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new tn("GSwapService: Bundler URL not configured","bundlerBaseUrl");try{this.logger.debug("Sending AddLiquidity to bundler",{token0:e.token0?.type??"unknown",token1:e.token1?.type??"unknown",fee:e.fee,tickRange:`${e.tickLower}-${e.tickUpper}`});const t=`galaswap - operation - ${k()}-${Date.now()}-${e.owner}`,n={token0:e.token0,token1:e.token1,fee:e.fee,owner:e.owner,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired,amount0Min:e.amount0Min,amount1Min:e.amount1Min,positionId:"",uniqueKey:t},o=new l.Wallet(this.privateKey),i={AddLiquidity:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"owner",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount0Desired",type:"string"},{name:"amount1Desired",type:"string"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},r={name:"ethereum",chainId:1},s=this.calculatePersonalSignPrefix(n),a={...n,prefix:s},c=await o.signTypedData(r,i,a),d={...a,signature:c,types:i,domain:r};this.logger.debug("AddLiquidity DTO signed with manual types",{prefix:d.prefix,tickLower:n.tickLower,tickUpper:n.tickUpper});const u=this.buildLiquidityStringsInstructions(e.token0,e.token1,e.fee,e.owner),h=Il.createClient(this.bundlerBaseUrl,3e4),g=await h.post("/bundle",{method:"AddLiquidity",signedDto:d,stringsInstructions:u}),m=$n(g),p=m?.data??m?.transactionId??m?.id;if(null==p)throw this.logger.error("Bundler response structure",{status:g.status,dataType:typeof m}),new nn("Bundler response does not contain transaction ID. Response type: "+typeof m,void 0,"INVALID_RESPONSE");return this.logger.debug("AddLiquidity transaction sent to bundler",{transactionId:p}),p}catch(e){throw this.logger.error("Failed to send AddLiquidity to bundler",e),e}}async sendRemoveLiquidityToBundler(e,t,n,o,i,r,s,a,c){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new tn("GSwapService: Bundler URL not configured","bundlerBaseUrl");const d=new l.Wallet(this.privateKey),u=await d.getAddress(),h=`galaswap - operation - ${k()}-${Date.now()}-${u}`,g={tickLower:e,tickUpper:t,amount:n,token0:o,token1:i,fee:r,amount0Min:s,amount1Min:a,positionId:c,uniqueKey:h},m={RemoveLiquidity:[{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"amount",type:"string"},{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Min",type:"string"},{name:"amount1Min",type:"string"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},p={name:"ethereum",chainId:1},f=this.calculatePersonalSignPrefix(g),y={...g,prefix:f},v=await d.signTypedData(p,m,y),w={...y,signature:v,types:m,domain:p},b=this.buildLiquidityStringsInstructions(o,i,r,u);this.logger.debug("Submitting RemoveLiquidity to bundler",{tickLower:e,tickUpper:t,amount:n,fee:r,positionId:c,transactionId:h});const S=Il.createClient(this.bundlerBaseUrl,3e4),A=await S.post("/bundle",{method:"RemoveLiquidity",signedDto:w,stringsInstructions:b}),T=$n(A),E=T?.data??T?.transactionId??T?.id;if(null==E)throw this.logger.error("Bundler response structure",{status:A.status,dataType:typeof T}),new nn("Bundler response does not contain transaction ID. Response type: "+typeof T,void 0,"INVALID_RESPONSE");return this.logger.info("RemoveLiquidity transaction sent to bundler",{transactionId:E}),E}catch(e){throw this.logger.error("Failed to send RemoveLiquidity to bundler",e),e}}async sendCollectPositionFeesToBundler(e,t,n,o,i,r,s,a){try{if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new tn("GSwapService: Bundler URL not configured","bundlerBaseUrl");const c=new l.Wallet(this.privateKey),d=await c.getAddress(),u=`galaswap - operation - ${k()}-${Date.now()}-${d}`,h={token0:e,token1:t,fee:n,amount0Requested:o,amount1Requested:i,tickLower:r,tickUpper:s,positionId:a,uniqueKey:u},g={CollectPositionFees:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount0Requested",type:"string"},{name:"amount1Requested",type:"string"},{name:"tickLower",type:"int256"},{name:"tickUpper",type:"int256"},{name:"positionId",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},m={name:"ethereum",chainId:1},p=this.calculatePersonalSignPrefix(h),f={...h,prefix:p},y=await c.signTypedData(m,g,f),v={...f,signature:y,types:g,domain:m},w=this.buildLiquidityStringsInstructions(e,t,n,d);this.logger.debug("Submitting CollectPositionFees to bundler",{fee:n,amount0Requested:o,amount1Requested:i,tickLower:r,tickUpper:s,positionId:a,transactionId:u});const b=Il.createClient(this.bundlerBaseUrl,3e4),S=await b.post("/bundle",{method:"CollectPositionFees",signedDto:v,stringsInstructions:w}),A=$n(S),T=A?.data??A?.transactionId??A?.id;if(null==T)throw this.logger.error("Bundler response structure",{status:S.status,dataType:typeof A}),new nn("Bundler response does not contain transaction ID. Response type: "+typeof A,void 0,"INVALID_RESPONSE");return this.logger.info("CollectPositionFees transaction sent to bundler",{transactionId:T}),T}catch(e){throw this.logger.error("Failed to send CollectPositionFees to bundler",e),e}}async sendSwapToBundler(e){if(void 0===this.privateKey||null===this.privateKey||""===this.privateKey)throw new tn("GSwapService: Swap requires wallet (full-access mode)","privateKey");if(void 0===this.bundlerBaseUrl||null===this.bundlerBaseUrl||""===this.bundlerBaseUrl)throw new tn("GSwapService: Bundler URL not configured","bundlerBaseUrl");const t=[500,3e3,1e4];if(!t.includes(e.feeTier))throw new Yt(`GSwapService: Invalid fee tier ${e.feeTier}. Must be one of: ${t.join(", ")} (basis points)`,"feeTier","INVALID_FEE_TIER");try{this.logger.debug("Sending Swap to bundler",{fromToken:"string"==typeof e.fromToken?e.fromToken:e.fromToken?.type??"unknown",toToken:"string"==typeof e.toToken?e.toToken:e.toToken?.type??"unknown",inputAmount:e.inputAmount,minOutput:e.minOutput,feeTier:e.feeTier});let t=e.fromToken,n=e.toToken;"string"==typeof t&&(t=ua(t)),"string"==typeof n&&(n=ua(n));const o=Zr(t),i=Zr(n),r=o<i?[t,n,o,i]:[n,t,i,o],[s,a,c,d]=r,u=Zr("string"==typeof e.fromToken?ua(e.fromToken):e.fromToken),h=u===c,g=`galaswap - operation - ${k()}-${Date.now()}-${e.walletAddress}`;let m;if(void 0===e.currentSqrtPrice||null===e.currentSqrtPrice||""===e.currentSqrtPrice)throw new Yt("GSwapService: currentSqrtPrice is required for sqrtPriceLimit calculation","currentSqrtPrice",zt);const p=sr(e.currentSqrtPrice),f=e.slippageTolerance??.01;if(h){const e=function(e=.01){return new v(1).minus(e)}(f);m=p.multipliedBy(e).toString()}else{const e=function(e=.01){return new v(1).plus(e)}(f);m=p.multipliedBy(e).toString()}this.logger.debug("Calculated sqrtPriceLimit based on slippage tolerance",{currentSqrtPrice:e.currentSqrtPrice,slippageTolerance:100*f+"%",zeroForOne:h,sqrtPriceLimit:m,direction:h?"token0→token1 (downward price movement)":"token1→token0 (upward price movement)",reason:"sqrtPriceLimit sets price boundaries, amountOutMinimum provides volume protection"});const y={token0:s,token1:a,fee:e.feeTier,amount:sr(e.inputAmount).toFixed(),zeroForOne:h,sqrtPriceLimit:m,recipient:e.walletAddress,amountOutMinimum:sr(e.minOutput).multipliedBy(-1).toFixed(),uniqueKey:g};this.logger.info("🔄 SWAP DTO DETAILS (what we're sending to bundler)",{orderedToken0String:c,orderedToken1String:d,fromTokenStr:u,zeroForOne:h?`TRUE (${c} → ${d})`:`FALSE (${d} → ${c})`,inputAmount:e.inputAmount,expectedOutput:e.minOutput,slippageTolerance:100*(null!==e.slippageTolerance&&void 0!==e.slippageTolerance&&0!==e.slippageTolerance?e.slippageTolerance:.01)+"%",currentSqrtPrice:e.currentSqrtPrice,swapDto:{amount:y.amount,zeroForOne:y.zeroForOne,sqrtPriceLimit:y.sqrtPriceLimit,amountOutMinimum:y.amountOutMinimum}});const w=new l.Wallet(this.privateKey),b={Swap:[{name:"token0",type:"token0"},{name:"token1",type:"token1"},{name:"fee",type:"int256"},{name:"amount",type:"string"},{name:"zeroForOne",type:"bool"},{name:"sqrtPriceLimit",type:"string"},{name:"recipient",type:"string"},{name:"amountOutMinimum",type:"string"},{name:"uniqueKey",type:"string"}],token0:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}],token1:[{name:"additionalKey",type:"string"},{name:"category",type:"string"},{name:"collection",type:"string"},{name:"type",type:"string"}]},S={name:"ethereum",chainId:1},A=this.calculatePersonalSignPrefix(y),T={...y,prefix:A},E=await w.signTypedData(S,b,T),C={...T,signature:E,types:b,domain:S};this.logger.debug("Swap DTO signed",{prefix:C.prefix,zeroForOne:y.zeroForOne});const I=this.buildLiquidityStringsInstructions(s,a,e.feeTier,e.walletAddress),N=Il.createClient(this.bundlerBaseUrl,3e4),D=await N.post("/bundle",{method:"Swap",signedDto:C,stringsInstructions:I}),P=$n(D),x=P?.data??P?.transactionId??P?.id;if(null==x)throw this.logger.error("Bundler response structure",{status:D.status,dataType:typeof P}),new nn("Bundler response does not contain transaction ID. Response type: "+typeof P,void 0,"INVALID_RESPONSE");return this.logger.debug("Swap transaction sent to bundler",{transactionId:x,inputAmount:e.inputAmount,minOutput:e.minOutput}),x}catch(e){throw this.logger.error("Failed to send Swap to bundler",e),e}}buildLiquidityStringsInstructions(e,t,n,o){const i=ts(e),r=ts(t),s=`$pool${i}${r}$${n}`;return[s,`$userPosition${o}`,`$tokenBalance${i}${o}`,`$tokenBalance${r}${o}`,`$tokenBalance${i}${s}`,`$tokenBalance${r}${s}`]}createGSwapErrorHandler(e,t){return(n,o,i)=>{this.handleGSwapError(o,e,n,t)}}handleGSwapError(e,t,n,o){this.logger.error(e,n);const i=this.extractGSwapErrorCode(n),r=n,s=[`${e}: ${r?.message??hn(n)}`,n],a=t.name;throw o&&("GSwapSwapError"===a&&null!==o.transactionHash&&void 0!==o.transactionHash&&s.push(o.transactionHash),"GSwapPoolError"===a&&(null!==o.tokenA&&void 0!==o.tokenA&&s.push(o.tokenA),null!==o.tokenB&&void 0!==o.tokenB&&s.push(o.tokenB)),"GSwapAssetError"===a&&null!==o.walletAddress&&void 0!==o.walletAddress&&s.push(o.walletAddress)),null!=i&&""!==i&&s.push(i),new t(...s)}extractGSwapErrorCode(e){const t=fn(e);return void 0!==t?String(t):void 0}async ensureWebSocketConnected(){this.webSocketService.isConnected()||await this.webSocketService.connect()}calculatePersonalSignPrefix(e){return`Ethereum Signed Message:\n${JSON.stringify(e).length}${JSON.stringify(e)}`}}function _l(e,t="image",n){const o=new FormData;if("undefined"!=typeof File&&e instanceof File)o.append(t,e);else{if(!Buffer.isBuffer(e))throw Cn("file","a File object (browser) or Buffer (Node.js)");{const i=new Blob([e],{type:"image/png"});o.append(t,i,n)}}return o}class Fl extends Yo{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Pr(t);const o=`${t}.png`;Ar(n.file,o,"image/png");try{const e=`${n.tokenName??t}.png`,o=_l(n.file,"image",e),i=await qn(()=>this.http.request({method:"POST",url:`${Y.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(n.tokenName??t)}`,data:o,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof tn)throw e;if(un(e)&&hn(e).includes("FormData"))throw Nn("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const Rl={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};function Bl(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class Ul extends Yo{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!$o(e.search)&&{search:e.search},...!$o(e.tokenName)&&{tokenName:e.tokenName},...!$o(e.type)&&{type:e.type},...!$o(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!$o(e.language)&&{language:e.language},...!$o(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!$o(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!$o(e.streamStatus)&&{streamStatus:e.streamStatus}}}async fetchSinglePage(e){const t=Math.min(e.pageSize,20),n=e.cursor,o={pageSize:String(t)};void 0!==n&&(o.cursor=n),$o(e.type)||(o.type=e.type),$o(e.tokenName)||(o.tokenName=e.tokenName),$o(e.search)||(o.search=e.search),$o(e.hasUpcomingShows)||(o.hasUpcomingShows=e.hasUpcomingShows.toString()),$o(e.language)||(o.language=e.language),$o(e.recentlyStreamed)||(o.recentlyStreamed=e.recentlyStreamed.toString()),$o(e.hasRecordings)||(o.hasRecordings=e.hasRecordings.toString()),$o(e.streamStatus)||(o.streamStatus=e.streamStatus);const i=rr(o),r=$n(await Wn(()=>this.http.get(Y.FETCH_POOLS,i),{errorContext:"Failed to fetch pools"})),s=function(e){if(!e)return[];let t=[];if(e.tokens)if(Array.isArray(e.tokens))t=e.tokens.map(e=>({...e,createdAt:e.created_at??e.createdAt??""}));else{const n=e.tokens;t=[{...n,createdAt:n.created_at??n.createdAt??""}]}else null!==e.pools&&void 0!==e.pools&&Array.isArray(e.pools)&&(t=e.pools.map(e=>({...e,createdAt:e.created_at??e.createdAt??""})));return t}(r),a={hasNextPage:r.hasNextPage??!1},c=r.count??r.total;return void 0!==c&&(a.totalCount=c),void 0!==r.nextCursor&&null!==r.nextCursor&&(a.nextCursor=r.nextCursor),void 0!==r.prevCursor&&null!==r.prevCursor&&(a.prevCursor=r.prevCursor),void 0!==r.hasPrevPage&&(a.hasPrevPage=r.hasPrevPage),{items:s,pageInfo:a}}async fetchPools(e){const t=e?.cursor,n=e?.pageSize??Oa.DEFAULT_LIMIT;Mo(e?.tokenName)&&Pr(e.tokenName);const o=void 0!==e?.type?{recent:"RECENT",popular:"POPULAR",recordings:"RECORDINGS",seconds_streamed:"SECONDS_STREAMED"}[e.type]:void 0,i=void 0!==e?.streamStatus?{idle:"IDLE",active:"ACTIVE",disabled:"DISABLED"}[e.streamStatus]:void 0,r={...this.buildPoolFilters({search:e?.search,tokenName:e?.tokenName,type:o,hasUpcomingShows:e?.hasUpcomingShows,language:e?.language,recentlyStreamed:e?.recentlyStreamed,hasRecordings:e?.hasRecordings,streamStatus:i}),pageSize:n,...void 0!==t&&{cursor:t}},s=await this.fetchSinglePage(r);return{items:s.items,pageInfo:s.pageInfo}}async fetchAllPools(e){const t=[];let n;const o=Oa.BACKEND_MAX_PAGE_SIZE;for(;;){const i={...e,pageSize:o,...void 0!==n&&{cursor:n}},r=await this.fetchPools(i);if(t.push(...r.items),!r.pageInfo.hasNextPage)break;n=r.pageInfo.nextCursor}return{items:t,pageInfo:{hasNextPage:!1,totalCount:t.length}}}async checkPool(e){xr(e),Mo(e.tokenName)&&Pr(e.tokenName);try{const t=await this.http.post(Y.VALIDATE_TOKEN,{tokenName:e.tokenName,symbol:e.symbol});if(null==t)throw new Error("Invalid response from check pool endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from check pool endpoint");if(!0===Mo(e.symbol)){return!n.symbolAvailable}if(!0===Mo(e.tokenName)){return!n.nameAvailable}return!1}catch(e){const t=String(e),n=e,o="string"==typeof n.message?n.message:"";if(t.includes("404")||t.includes("Pool not found")||o.includes("404")||o.includes("Pool not found"))return!1;const i="number"==typeof n.statusCode?n.statusCode:null;if(404===i)return!1;if(t.includes("400")||t.includes("Missing required pool identifier")||o.includes("400")||o.includes("Missing required pool identifier"))return!1;if(400===i&&o.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(!er(e))throw new Yt("Invalid options provided. Expected { tokenName: string, from?: number, to?: number, resolution?: number }","options","INVALID_OPTIONS");const{tokenName:t,from:n,to:o,resolution:i}=e;if(Pr(t),null==n||null==o||null==i)throw new Yt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:n,to:o,resolution:i};_r(r);const s=rr(r);return{dataPoints:await qn(()=>this.http.get(Y.CHART,s),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw En("tokenName","Token name");let t;Pr(e);try{t=await Wn(()=>this.http.get(`${Y.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(yn(t)&&500===t.response?.status)throw In(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}const n=$n(t);if(!Array.isArray(n))throw In("Invalid API response: expected array of holders",t.status);for(const e of n){if(""===e.owner||null===e.owner||void 0===e.owner||"string"!=typeof e.owner)throw In("Invalid holder data: missing or invalid owner field",t.status);if(""===e.quantity||null===e.quantity||void 0===e.quantity||"string"!=typeof e.quantity)throw In("Invalid holder data: missing or invalid quantity field",t.status);const n=Ao(e.quantity,NaN);if(isNaN(n)||!isFinite(n))throw In(`Invalid holder quantity: "${e.quantity}"`,t.status)}const o=n.reduce((e,t)=>e.plus(t.quantity),sr(0));return{holders:n.map(e=>{const t=vr(sr(e.quantity),o,sr(0)).multipliedBy(100).toNumber();return{address:e.owner,balance:e.quantity,percentage:t}}),totalSupply:o.toFixed(),totalHolders:n.length,lastUpdated:new Date}}async fetchUserHolderContext(e,t){if(""===e||null==e)throw En("tokenName","Token name");if(""===t||null==t)throw En("userAddress","User address");return Pr(e),qn(()=>this.http.get(`${Y.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`,{userAddress:t}),{errorContext:"Failed to fetch user holder context"})}async fetchTokenBadges(e){if(""===e||null==e)throw En("tokenName","Token name");Pr(e);const t=Y.GET_TOKEN_BADGES.replace(":tokenName",e.toLowerCase().trim()),n=await qn(()=>this.http.get(t),{errorContext:"Failed to fetch token badges"});return{volumeBadges:n.volumeBadge??[],engagementBadges:n.engagementBadge??[]}}async hasTokenBadge(e){const{tokenName:t,badgeType:n,badgeName:o}=e;try{const e=await this.fetchTokenBadges(t);if(null==e)return!1;const i=("volume"===n?e.volumeBadges:e.engagementBadges).find(e=>e.badgeName===o);return i?.isActive??!1}catch{return!1}}async resolveTokenNameToVault(e){try{const t=await this.fetchPools({tokenName:e});if(null!==t.items&&void 0!==t.items&&Array.isArray(t.items)&&t.items.length>0)return t.items[0].vaultAddress??null;if(null!==t.items&&void 0!==t.items&&"object"==typeof t.items){const e=t.items.tokens;return e?.vaultAddress??null}return null}catch{return null}}async fetchToken(e){if(null==e||"string"!=typeof e||""===e.trim())throw new Error("Token name is required and must be a non-empty string");Pr(e);try{const t=Y.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=$n(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&&Pr(e.tokenName);try{const t=await this.http.post(Y.VALIDATE_TOKEN,{tokenName:e.tokenName?.toLowerCase().trim(),symbol:e.symbol?.toUpperCase().trim()});if(null==t)throw new Error("Invalid response from validation endpoint");const n=t.data??t;if(null==n)throw new Error("Invalid response from validation endpoint");return n}catch(e){throw this.logger.warn(`Token validation failed: ${String(e)}`),e}}async fetchTokenStats(e){if(!Mo(e))throw En("tokenName","Token name");Pr(e);const t=Y.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=$n(await this.http.get(t));if(!e?.stats)throw new Error("Invalid response: missing stats data");return{success:!0,data:e.stats}}catch(t){throw this.logger.warn(`Failed to fetch token stats for ${e}: ${String(t)}`),t}}async updateTokenConfig(e,t){if(""===e||null==e)throw En("tokenName","Token name");Pr(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 Yt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",zt);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw Rn("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw Rn("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw Rn("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw Rn("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 Rn(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw Rn("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Yt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Xt)}}(t);const n=Y.UPDATE_TOKEN_CONFIG.replace(":tokenName",e.toLowerCase().trim()),o={};void 0!==t.messagesEnabled&&(o.messagesEnabled=t.messagesEnabled),void 0!==t.commentsEnabled&&(o.commentsEnabled=t.commentsEnabled),void 0!==t.streamingEnabled&&(o.streamingEnabled=t.streamingEnabled),void 0!==t.nextLiveStreamAt&&(o.nextLiveStreamAt=t.nextLiveStreamAt),void 0!==t.streamLanguage&&(o.streamLanguage=t.streamLanguage),void 0!==t.websiteUrl&&(o.websiteUrl=t.websiteUrl),void 0!==t.telegramUrl&&(o.telegramUrl=t.telegramUrl),void 0!==t.twitterUrl&&(o.twitterUrl=t.twitterUrl),void 0!==t.instagramUrl&&(o.instagramUrl=t.instagramUrl),void 0!==t.facebookUrl&&(o.facebookUrl=t.facebookUrl),void 0!==t.redditUrl&&(o.redditUrl=t.redditUrl),void 0!==t.tiktokUrl&&(o.tiktokUrl=t.tiktokUrl),await this.http.patch(n,o,this.getJwtHeaders())}}const Ol=co,Ll=ro,Ml={MAX_LENGTH:100};class $l extends Yo{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 Ji(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&Yi(t,"userAddress")&&Zi(t,"offset")&&Zi(t,"pageSize")&&Zi(t,"page")&&Zi(t,"limit")}(e))throw new Yt("Invalid options provided. Expected { tokenName: string, tradeType?: string, userAddress?: string, cursor?: string, pageSize?: number, startDate?: Date, endDate?: Date, sortOrder?: string }","options","INVALID_OPTIONS");const{tokenName:t,tradeType:n,userAddress:o,cursor:i,pageSize:r=Oa.DEFAULT_LIMIT,startDate:s,endDate:a,sortOrder:c}=e;if(!Mo(t))throw En("tokenName","Token name");const l={pageSize:String(Math.min(r,ao))};void 0!==i&&(l.cursor=i);const d={...l};d.tokenName=t;const u=await this.http.get(Y.GET_TRADES,d);if(null==u)throw new Yt("No response from trade service","response","NO_RESPONSE");const h=$n(u),g=Bl(h,"trades"),m=h?.pageInfo;return{items:g,pageInfo:m??{hasNextPage:!1}}}buildTradesQueryParams(e){const t={};null!==e.tokenName&&void 0!==e.tokenName&&e.tokenName.length>0&&(t.tokenName=zn(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?La(e.pageSize,1,Ol.MAX_LIMIT):Ol.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){!function(e){if(void 0!==e.tokenName){if(!Mo(e.tokenName))throw Rn("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>Ll.MAX_LENGTH)throw Fn("tokenName",Ll.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!Mo(e.userAddress))throw Rn("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>Ml.MAX_LENGTH)throw Fn("userAddress",Ml.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw Rn("search","a string",typeof e.search);if(e.search.length>256)throw Fn("search",256,e.search.length)}if(Ko(0,void 0,Ol.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Cn("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!Mo(e.startDate))throw Rn("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Cn("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!Mo(e.endDate))throw Rn("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Cn("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{Fo(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Cn("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{Fo(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Cn("maxAmount","a non-negative number")}void 0!==e.minAmount&&void 0!==e.maxAmount&&Uo(e.minAmount,e.maxAmount,"amountRange")}(e);const t=this.buildTradesQueryParams(e);return qn(()=>this.http.get(yt,t),{errorContext:"Failed to fetch trades"})}}function Kl(e){return!!Mo(e)&&lo.PATTERN.test(e)}qo({ALL:"all",DEFI:"DEFI",ASSET:"ASSET",COLLECTION:"COLLECTION",CREATED:"created"});class ql extends Yo{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!Kl(t))throw Cn("address","eth|[40-hex-chars] or client|[identifier]","Address");const n={userAddress:t},o=await this.http.get(Y.GET_PROFILE,n);if(null==o)throw new Yt("No response from user service","response","NO_RESPONSE");return o}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!Mo(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await qn(()=>this.http.put(Y.UPDATE_PROFILE,n,this.getJwtHeaders()),{errorContext:"Profile update failed"})}async uploadProfileImage(e){this.validateUploadProfileImageOptions(e);const t=e.address??this.http.getAddress();if(null==t||""===t)throw new Yt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,o=_l(e.file,"image",n),i=await qn(()=>this.http.request({method:"POST",url:`${Y.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:o,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof i?i:""}catch(e){if(e instanceof Yt||e instanceof tn)throw e;throw new Yt(`Profile image upload failed: ${hn(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest(Y.GET_TOKEN_LIST,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest(Y.GET_TOKENS_HELD,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:o,tokenName:i,status:r}=e??{},s=e?.type??(void 0!==r?"created":"DEFI"),a=this.http.getAddress();if(null==a||""===a)throw new Yt("Wallet address not available - wallet not configured","address","NO_WALLET");const c={type:s,address:a,pageSize:n??Oa.DEFAULT_LIMIT};return void 0!==t&&(c.cursor=t),void 0!==o&&(c.search=o),void 0!==i&&(c.tokenName=i),void 0!==r&&(c.status=r),this.fetchTokenList(c)}async getManagedTokens(e={}){const t=$a({pageSize:e.pageSize??Oa.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},ao);return qn(()=>this.http.get(Y.GET_MANAGED_TOKENS,t,this.getJwtHeaders()),{errorContext:"Failed to fetch managed tokens"})}async buildFetchRequest(e,t,n){this.validateGetTokenListOptions(t);const o=$a({pageSize:t.pageSize??Oa.DEFAULT_LIMIT,...void 0!==t.cursor&&{cursor:t.cursor}},ao);Ka(o,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(o.type="all"===(t.type??"DEFI")?"DEFI":t.type??"DEFI");let i=e;if(e.includes(":address")){const n=t.address??this.http.getAddress();if(0===n.length)throw En("address","User address");i=e.replace(":address",n),delete o.address}const r=$n(await Wn(()=>this.http.get(i,o),{errorContext:n.errorMessage})),s=Bl(r,"token"),a={hasNextPage:r.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(a.totalCount=c),void 0!==r.nextCursor&&(a.nextCursor=r.nextCursor),void 0!==r.prevCursor&&(a.prevCursor=r.prevCursor),void 0!==r.hasPrevPage&&(a.hasPrevPage=r.hasPrevPage);const l={tokens:s,pageInfo:a};return void 0!==c&&(l.total=c),l}async fetchUserBalances(e){if(!Kl(e.address))throw Cn("address","eth|[40-hex-chars] or client|[identifier]","Address");const t=$a({pageSize:e.pageSize??Oa.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},ao),n=Y.USER_BALANCES.replace(":address",e.address),o=$n(await Wn(()=>this.http.get(n,t),{errorContext:"Failed to fetch user balances"}));if(!o)throw new Yt("Invalid response: missing data","response","NO_DATA");const i={hasNextPage:o.hasNextPage??!1};return void 0!==o.nextCursor&&(i.nextCursor=o.nextCursor),void 0!==o.prevCursor&&(i.prevCursor=o.prevCursor),void 0!==o.hasPrevPage&&(i.hasPrevPage=o.hasPrevPage),void 0!==o.total&&(i.totalCount=o.total),{balances:Array.isArray(o.balances)?o.balances:[],pageInfo:i,total:o.total}}async fetchUserReport(e){if(!Kl(e.address))throw Cn("address","eth|[40-hex-chars] or client|[identifier]","Address");if(!this.jwtAuth)throw new tn("JWT authentication is required for fetchUserReport. Call sdk.login() first.","jwtAuth");const t=Y.USER_REPORT.replace(":address",e.address),n=$n(await Wn(()=>this.http.get(t,{},this.getJwtHeaders()),{errorContext:"Failed to fetch user report"}));if(!n?.report)throw new Yt("Invalid response: missing report data","response","NO_DATA");return{report:n.report}}validateGetTokenListOptions(e){const t=e.pageSize??Oa.DEFAULT_LIMIT;if(t<1||t>ao)throw new Yt(`pageSize must be between 1 and ${ao}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!Kl(e.address))throw Cn("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=Tr(e.search);if(null!==n&&!(Mo(o=n)&&o.length>=vo&&o.length<=wo))throw xn("search",vo,wo,n.length,"Search query");var o;const i=Tr(e.tokenName);if(null!==i&&!(Mo(r=i)&&r.length>=ro.MIN_LENGTH&&r.length<=ro.MAX_LENGTH))throw xn("tokenName",ro.MIN_LENGTH,ro.MAX_LENGTH,i.length,"Token name");var r}validateUpdateProfileData(e){if(!Kl(e.address))throw Cn("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(Mo(t)&&t.length>=bo.FULL_NAME.MIN_LENGTH&&t.length<=bo.FULL_NAME.MAX_LENGTH&&bo.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw xn("fullName",bo.FULL_NAME.MIN_LENGTH,bo.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!Kl(e.address))throw Cn("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class Gl{constructor(e,t,n=!1){this.http=e,this.poolService=new Ul(e,t,n),this.tradeService=new $l(e,n),this.userService=new ql(e,t,n),this.imageService=new Fl(e,t,n)}setJwtAuth(e){this.poolService.setJwtAuth(e),this.userService.setJwtAuth(e),this.imageService.setJwtAuth(e)}async uploadImageByTokenName(e){return this.imageService.uploadImageByTokenName(e)}async fetchPools(e={}){return this.poolService.fetchPools(e)}async fetchAllPools(e){return this.poolService.fetchAllPools(e)}async checkPool(e){return this.poolService.checkPool(e)}async checkPoolExists(e,t){const n={};return void 0!==e&&(n.tokenName=e),void 0!==t&&(n.symbol=t),this.poolService.checkPool(n)}async isTokenNameAvailable(e){return this.poolService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.poolService.isTokenSymbolAvailable(e)}async fetchVolumeData(e){return this.poolService.fetchVolumeData(e)}async fetchTokenDistribution(e){return this.poolService.fetchTokenDistribution(e)}async fetchUserHolderContext(e,t){return this.poolService.fetchUserHolderContext(e,t)}async fetchTokenBadges(e){return this.poolService.fetchTokenBadges(e)}async hasTokenBadge(e){return this.poolService.hasTokenBadge(e)}async fetchTrades(e){return this.tradeService.fetchTrades(e)}async getTrades(e){return this.tradeService.getTrades(e)}async fetchProfile(e){return this.userService.fetchProfile(e)}async updateProfile(e){return this.userService.updateProfile(e)}async uploadProfileImage(e){return this.userService.uploadProfileImage(e)}async fetchTokenList(e){return this.userService.fetchTokenList(e)}async fetchTokensHeld(e){return this.userService.fetchTokensHeld(e)}async fetchTokensCreated(e={}){return this.userService.fetchTokensCreated(e)}async getManagedTokens(e={}){return this.userService.getManagedTokens(e)}getAddress(){return this.http.getAddress()}validateTokenName(e){return Pr(e)}async fetchToken(e){return this.poolService.fetchToken(e)}async validateToken(e){return this.poolService.validateToken(e)}async fetchTokenStats(e){return this.poolService.fetchTokenStats(e)}async updateTokenConfig(e,t){return this.poolService.updateTokenConfig(e,t)}async fetchUserBalances(e){return this.userService.fetchUserBalances(e)}async fetchUserReport(e){return this.userService.fetchUserReport(e)}}class Wl extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}validateContent(e,t){if(!Mo(e))throw En("content","Message content");if(0===e.trim().length)throw En("content","Message content");Ro(e,t===Rl.CHAT_MESSAGE?uo.CHAT_MESSAGES_V1.MAX_LENGTH:uo.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!Mo(e))throw En("id","Message ID");if(e.length<10||e.length>64)throw Cn("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Rl.CHAT_MESSAGE&&e!==Rl.COMMENT)throw new Yt(`type must be one of: ${Object.values(Rl).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,io);const o={};void 0!==e.cursor&&(o.cursor=e.cursor),o.pageSize=e.pageSize??Oa.DEFAULT_LIMIT;const i=$a(o,co.MAX_LIMIT),r={};void 0!==i.pageSize&&(r.pageSize=i.pageSize),void 0!==i.cursor&&(r.cursor=i.cursor),t&&(r.type=e.type.toUpperCase()),n&&(r.tokenName=zn(e.tokenName)),void 0!==e.userAddress&&""!==e.userAddress&&(r.userAddress=e.userAddress),void 0!==e.search&&""!==e.search&&(r.search=e.search);const s=await this.http.get(kt.GET_MESSAGES,r),a=this.extractData(s);return{messages:a.messages,pageInfo:a.pageInfo}}async createMessage(e){this.validateMessageType(e.type),this.validateTokenName(e.tokenName,io),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:zn(e.tokenName),content:e.content.trim()},n=await this.http.post(kt.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(kt.UPDATE_MESSAGE,e),o={content:t.content.trim()},i=await this.http.put(n,o,this.getJwtHeaders());return{message:this.extractData(i)}}async deleteMessage(e){this.validateMessageId(e);const t=this.buildEndpointWithId(kt.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,io);const t=await this.http.get(kt.GET_PINNED,{tokenName:zn(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=kt.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=kt.UNPIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async getMessageStats(){const e=await this.http.get(kt.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const Hl=Go({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),zl={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},jl=Go(zl),Vl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};Go(Vl);class Xl extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}validateRole(e){if(!Mo(e))throw En("role","Role");if(!function(e){return Hl.includes(e)}(e))throw Cn("role",`one of: ${Hl.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!Mo(e))throw En("inviteCode","Invite code");if(t=e,!fo.PATTERN.test(t))throw Cn("inviteCode","valid invite code format","Invite code");var t}validateInviteScope(e){if(void 0!==e&&(t=e,!jl.includes(t)))throw new Yt(`Invalid invite scope. Must be one of: ${jl.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??zl.TOKEN;if(t===zl.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Yt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,oo)}else if(t===zl.ALL_OWNER_TOKENS&&e.tokenName)throw new Yt("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",uo.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Re,o={inviteScope:t,role:e.role};t===zl.TOKEN&&null!=e.tokenName&&""!==e.tokenName&&(o.tokenName=zn(e.tokenName)),void 0!==e.description&&(o.description=e.description),void 0!==e.expiresAt&&(o.expiresAt=e.expiresAt);const i=await this.http.post(n,o,this.getMultiAuthHeaders());return{invite:this.extractData(i)}}async listInvites(e){void 0!==e.tokenName&&""!==e.tokenName&&this.validateTokenName(e.tokenName,oo),this.validateStatusFilter(e.status,Vl);const t=Oe,n={...this.buildPaginationParams(e,co.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=zn(e.tokenName)),void 0!==e.status&&(n.status=e.status);const o=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(o);return{items:i.invites,pageInfo:i.pageInfo}}async revokeInvite(e){this.validatePositiveInteger(e,"inviteId","Invite ID");const t=this.buildEndpoint(Le,{id:String(e)});Mn(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(Me,{id:String(e.inviteId)}),n={role:e.role},o=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(o)}}async updateInvite(e){if(this.validatePositiveInteger(e.inviteId,"inviteId","Invite ID"),void 0===e.role&&(void 0===e.description||""===e.description))throw new Yt("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",uo.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint($e,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const o=await this.http.patch(t,n,this.getMultiAuthHeaders());return{invite:this.extractData(o)}}async claimInvite(e){this.validateInviteCodeFormat(e.inviteCode);const t=Be,n={inviteCode:e.inviteCode},o=await this.http.post(t,n,this.getMultiAuthHeaders()),i=this.extractData(o);return"tokenName"in i&&void 0!==i.tokenName?{token:i}:{blanketAccess:i}}async getModeratedTokens(e){const t=Ue,n=this.buildPaginationParams(e??{},co.MAX_LIMIT),o=await this.http.get(t,n,this.getMultiAuthHeaders()),i=this.extractData(o);return{items:i.tokens,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(Ke,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}class Ql{constructor(){this.eventLatencies=[],this.maxLatencySamples=1e4,this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics=new Map,this.memorySnapshots=[],this.maxMemorySnapshots=100,this.recordMemory()}recordEventLatency(e){this.eventLatencies.push(e),this.eventLatencies.length>this.maxLatencySamples&&this.eventLatencies.shift(),this.eventsProcessed++}recordEventDropped(){this.eventsDropped++}updateQueueDepth(e){this.queueDepth=e,this.maxQueueDepth=Math.max(this.maxQueueDepth,e)}recordPoolCacheHit(e,t){const n=this.getPoolMetrics(e);n.cacheHits++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}recordPoolCacheMiss(e,t){const n=this.getPoolMetrics(e);n.cacheMisses++,n.eventsProcessed++,n.totalLatency+=t,n.lastEventTime=new Date}getLatencyPercentiles(){if(0===this.eventLatencies.length)return{p50:0,p95:0,p99:0};const e=[...this.eventLatencies].sort((e,t)=>e-t),t=To(Math.floor(.5*e.length),0),n=To(Math.floor(.95*e.length),0),o=To(Math.floor(.99*e.length),0);return{p50:e[t]??0,p95:e[n]??0,p99:e[o]??0}}getCacheHitRate(){if(0===this.eventsProcessed)return 0;let e=0;for(const t of this.perPoolMetrics.values())e+=t.cacheHits;return To(e/this.eventsProcessed*100,NaN)}getThroughputPerSecond(){const e=To(no(this.startTime)/1e3,0);return 0===e?0:To(this.eventsProcessed/e,0)}recordMemory(){if("undefined"!=typeof process&&"function"==typeof process.memoryUsage){const e=To(process.memoryUsage().heapUsed/1024/1024,0);this.memorySnapshots.push(e),this.memorySnapshots.length>this.maxMemorySnapshots&&this.memorySnapshots.shift()}}getMemoryUsedMB(){return"undefined"!=typeof process&&"function"==typeof process.memoryUsage?To(process.memoryUsage().heapUsed/1024/1024,0):0}getPoolAverageLatency(e){const t=this.perPoolMetrics.get(e);return t&&0!==t.eventsProcessed?To(t.totalLatency/t.eventsProcessed,0):0}getPoolCacheHitRate(e){const t=this.perPoolMetrics.get(e);if(!t)return 0;const n=t.cacheHits+t.cacheMisses;return 0===n?0:To(t.cacheHits/n*100,0)}getHealthMetrics(e,t,n,o,i){const r=this.getLatencyPercentiles(),s=this.getMemoryUsedMB();return{eventProcessing:{queueDepth:this.queueDepth,eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,throughputPerSecond:this.getThroughputPerSecond()},metrics:{latencyP50:r.p50,latencyP95:r.p95,latencyP99:r.p99,cacheHitRate:this.getCacheHitRate()},memory:{usedMB:To(ar(s,1),0),maxMB:i,percentUsed:Math.min(100,To(ar(s/i*100,1),0))},pools:{totalMonitored:e,hotCacheSize:t,warmCacheSize:n,coldCacheSize:o}}}reset(){this.eventLatencies=[],this.eventsProcessed=0,this.eventsDropped=0,this.queueDepth=0,this.maxQueueDepth=0,this.startTime=Date.now(),this.perPoolMetrics.clear(),this.memorySnapshots=[]}getSummary(){const e=this.eventLatencies.length>0?To(this.eventLatencies.reduce((e,t)=>e+t,0)/this.eventLatencies.length,0):0;return{eventsProcessed:this.eventsProcessed,eventsDropped:this.eventsDropped,cacheHitRate:this.getCacheHitRate(),averageLatency:To(ar(e,0),0),memoryUsedMB:To(ar(this.getMemoryUsedMB(),1),0),throughputPerSecond:To(ar(this.getThroughputPerSecond(),2),0)}}getPoolMetrics(e){let t=this.perPoolMetrics.get(e);return t||(t={eventsProcessed:0,totalLatency:0,cacheHits:0,cacheMisses:0},this.perPoolMetrics.set(e,t)),t}}class Jl{static createPoolKey(e,t,n){return`${e}/${t}/${n}`}static parsePoolKey(e){if(!Mo(e))return null;const t=e.split("/");if(3!==t.length)return null;const n=t[0]?.trim(),o=t[1]?.trim(),i=t[2]?.trim();if(""===n||""===o||""===i)return null;const r=Eo(i,-1);return r<0?null:{token0:n,token1:o,feeTier:r}}static isValidPoolKey(e){if("string"!=typeof e)return!1;return null!==this.parsePoolKey(e)}static getToken0(e){const t=this.parsePoolKey(e);return t?.token0??null}static getToken1(e){const t=this.parsePoolKey(e);return t?.token1??null}static getFeeTier(e){const t=this.parsePoolKey(e);return t?.feeTier??null}static containsToken(e,t){const n=this.parsePoolKey(e);return!!n&&(n.token0===t||n.token1===t)}static containsTokenPair(e,t,n){const o=this.parsePoolKey(e);if(!o)return!1;const i=o.token0===t||o.token1===t,r=o.token0===n||o.token1===n;return i&&r&&t!==n}static normalizeFee(e){if($o(e))return null;const t="number"==typeof e?e:Do(String(e),NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)&&t>0?t:null}static formatFeeAsPercentage(e){return`${ar(sr(e).dividedBy(1e4),2)}%`}static isValidTokenPair(e,t){return Boolean(e)&&Boolean(t)&&e!==t}}class Yl{constructor(e){this.logger=e??new Qn({debug:!1,context:"SwapEventExtractor"})}walkPayloadForSwaps(e,t){const n=[],o=new WeakSet,i=(e,r=0)=>{if(r>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(null!=e&&"string"!=typeof e&&"object"==typeof e){if(o.has(e))return;o.add(e);const s=this.extractSwapFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,r+1)}};return i(e,0),n}extractSwapFromObject(e){const t=this.extractTransactionId(e);if(null===t)return null;const n=e.Data,o=null==n||"object"!=typeof n||Array.isArray(n)?e:n,i=this.extractToken(o,"token0","fromToken","source"),r=this.extractToken(o,"token1","toToken","destination");if(null===i||null===r)return null;const s=this.extractAmount(o,"amount0","amountIn","inputAmount"),a=this.extractAmount(o,"amount1","amountOut","outputAmount");if(null===s||null===a)return null;const c=this.extractFeeTier(o);if(null===c)return null;const l=this.extractTimestamp(o),d=this.buildPoolKey(i,r,c),u=this.determineDirection(o,i,r),h={transactionId:t,poolKey:d,token0:i,token1:r,amount0:s,amount1:a,feeTier:c,direction:u,timestamp:l,exactInput:this.determineExactInput(o,u)},g=this.extractUser(o);return void 0!==g&&(h.user=g),h}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Mo(t))return t}return null}extractToken(e,...t){for(const n of t){const t=e[n];if(Mo(t))return t}return null}extractAmount(e,...t){for(const n of t){const t=e[n];if(!$o(t)){const e=String(t).trim();if(/^-?\d+(\.\d+)?([eE]-?\d+)?$/.test(e))return e}}return null}extractFeeTier(e){const t=["poolFee","feeTier","fee","feeTierBps","liquidityFeeBps","feeAmount"];for(const n of t){const t=e[n],o=this.normalizeFee(t);if(null!==o)return o}return null}normalizeFee(e){if($o(e))return null;const t="number"==typeof e?e:Do(String(e),NaN);return Number.isNaN(t)?null:1===t||1e4===t?1e4:.3===t||3e3===t?3e3:.05===t||500===t?500:Number.isInteger(t)?t:null}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if("string"==typeof t){const e=new Date(t).getTime();if(!Number.isNaN(e))return e}}return Date.now()}extractUser(e){const t=["userAddress","user","from","sender","wallet","address"];for(const n of t){const t=e[n];if(Mo(t))return t}}determineDirection(e,t,n){const o=e.zeroForOne??e.direction;if("boolean"==typeof o)return o?"zeroForOne":"oneForZero";if("string"==typeof o){if(Er(o,"zerotoone")||"0to1"===o)return"zeroForOne";if(Er(o,"onetozero")||"1to0"===o)return"oneForZero"}if(e.fromToken===t||e.inputToken===t)return"zeroForOne";if(e.fromToken===n||e.inputToken===n)return"oneForZero";const i=this.extractAmount(e,"amount0","amountIn");return null!==i&&Ao(i,0),"zeroForOne"}determineExactInput(e,t){if("boolean"==typeof e.exactInput)return e.exactInput;if("boolean"==typeof e.exactOutput)return!e.exactOutput;const n=void 0!==e.amountIn&&null!==e.amountIn,o=void 0!==e.amountOut&&null!==e.amountOut,i=void 0!==e.inputAmount&&null!==e.inputAmount,r=void 0!==e.outputAmount&&null!==e.outputAmount;return!(!n||o)||!(o&&!n)&&(!(!i||r)||!(r&&!i))}buildPoolKey(e,t,n){return`${e}/${t}/${n}`}}const Zl=new Map;class ed{static getCached(e){const t=e.toString();return this.CACHE.has(t)||this.CACHE.set(t,sr(e)),this.CACHE.get(t)}static clearCache(){this.CACHE.clear()}static getCacheStats(){return{size:this.CACHE.size,entries:Array.from(this.CACHE.keys())}}static trimCache(e=1e3){if(this.CACHE.size>e){const t=this.CACHE.size-e,n=Array.from(this.CACHE.keys());for(let e=0;e<t;e++)this.CACHE.delete(n[e])}}}ed.CACHE=new Map,ed.ZERO=Io(0),ed.ONE=Io(1),ed.FEE_PIPS=Io(1e6),ed.MIN_SQRT_RATIO=Io("4295128739"),ed.MAX_SQRT_RATIO=new v("1461446703485210103287273052203988822378723970342");const td={maxIterations:100,enableBigNumberCache:!0,roundingMode:v.ROUND_DOWN,debugLogging:!1};class nd{static calculateSwapDelta(e,t,n={}){const o=Date.now(),i={...td,...n};try{const n=this.initializeSwapState(e,t,i);i.debugLogging&&this.logger.debug("Initialized swap state",{sqrtPrice:n.sqrtPrice.toString(),liquidity:n.liquidity.toString(),tick:n.tick,zeroForOne:t.zeroForOne});const r=this.computeSwapLoop(n,e,t,i);i.debugLogging&&this.logger.debug("Swap loop completed",{stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length,priceHitLimit:r.priceHitLimit});const s=this.createUpdatedPool(e.pool,r.state,t,i),a=this.calculateFinalAmounts(n,r.state,t);let c;if(void 0!==t.actualSqrtPrice&&""!==t.actualSqrtPrice){const e=sr(s.sqrtPrice),n=sr(t.actualSqrtPrice),o=e.minus(n).abs();c=To(vr(o,n).times(100).toNumber(),0)}const l=no(o);i.debugLogging&&this.logger.debug("Swap delta calculated",{calculationTimeMs:l,amount0:a.amount0.toString(),amount1:a.amount1.toString(),driftPercentage:c}),l>100&&this.logger.warn("Swap calculation exceeded 100ms",{calculationTimeMs:l,stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length}),r.priceHitLimit&&this.logger.warn("Swap price hit limit - partially fulfilled",{zeroForOne:t.zeroForOne,stepCount:r.stepCount}),r.stepCount>50&&this.logger.warn("Unusually complex swap detected",{stepCount:r.stepCount,ticksCrossed:r.ticksCrossed.length});return{updatedPool:s,updatedTicks:r.updatedTicks,amount0:a.amount0,amount1:a.amount1,feeAmount0:a.feeAmount0,feeAmount1:a.feeAmount1,ticksCrossed:r.ticksCrossed,metadata:{calculationTimeMs:l,swapSteps:r.stepCount,priceHitLimit:r.priceHitLimit,...void 0!==c&&{driftPercentage:c}}}}catch(e){throw this.logger.error("Swap delta calculation failed",e),new Error(`Swap delta calculation failed: ${hn(e)}`)}}static initializeSwapState(e,t,n){const{pool:o}=e;if(null===o.sqrtPrice||void 0===o.sqrtPrice||null===o.liquidity||void 0===o.liquidity)throw new Error("Invalid pool data: missing sqrtPrice or liquidity");const i=n.enableBigNumberCache?ed.getCached.bind(ed):e=>Io(e),r="string"==typeof o.sqrtPrice?o.sqrtPrice:ar(o.sqrtPrice,0),s="string"==typeof o.liquidity?o.liquidity:ar(o.liquidity,0),a=i(r),c=i(s),l=o.tick??0,d=V(sr(r)),u=Math.abs(d-l);u>100&&this.logger.warn("Significant tick/price mismatch detected in pool state",{poolTick:l,calculatedTick:d,drift:u,threshold:100});const h=i(t.amountSpecified);kr(h,"amountSpecified");const g="string"==typeof o.feeGrowthGlobal1?o.feeGrowthGlobal1:ar(o.feeGrowthGlobal1,0),m="string"==typeof o.feeGrowthGlobal0?o.feeGrowthGlobal0:ar(o.feeGrowthGlobal0,0),p=t.zeroForOne?i(g):i(m);return{sqrtPrice:a,liquidity:c,tick:l,amountSpecifiedRemaining:h,amountCalculated:ed.ZERO,feeGrowthGlobalX:p,protocolFee:ed.ZERO}}static computeSwapLoop(e,t,n,o){const{pool:i,tickDataMap:r}=t,s=[],a={};let c=0;const l=n.zeroForOne?ed.MIN_SQRT_RATIO:ed.MAX_SQRT_RATIO,d=sr("0.000001");for(;e.amountSpecifiedRemaining.gt(d)&&!e.sqrtPrice.eq(l)&&c<o.maxIterations;){c++;const[t,d]=this.findNextInitializedTick(r,e.tick,i.tickSpacing,n.zeroForOne);let u;if(o.debugLogging&&this.logger.debug(`Swap step ${c}`,{currentTick:e.tick,tickNext:t,initialized:d,sqrtPrice:e.sqrtPrice.toString(),liquidity:e.liquidity.toString(),amountRemaining:e.amountSpecifiedRemaining.toString()}),d&&t>=-887272&&t<=887272){const e=K(t);u=e instanceof v?e:sr(String(e))}else u=l;const h=n.zeroForOne?ur(u,l):dr(u,l),g=this.executeSwapStep(e.sqrtPrice,h,e.liquidity,e.amountSpecifiedRemaining,i.fee,n.exactInput);if(e.sqrtPrice=g.sqrtPriceNext,n.exactInput){const t=g.amountIn.plus(g.feeAmount);t.lte(0)?e.amountSpecifiedRemaining=ed.ZERO:(e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.minus(t),e.amountSpecifiedRemaining.lt(0)&&(e.amountSpecifiedRemaining=ed.ZERO)),e.amountCalculated=e.amountCalculated.minus(g.amountOut)}else{g.amountOut.lte(0)?e.amountSpecifiedRemaining=ed.ZERO:e.amountSpecifiedRemaining=e.amountSpecifiedRemaining.plus(g.amountOut),e.amountCalculated=e.amountCalculated.plus(g.amountIn.plus(g.feeAmount))}if(e.liquidity.gt(0)){const t=vr(g.feeAmount,e.liquidity);e.feeGrowthGlobalX=e.feeGrowthGlobalX.plus(t)}if(e.sqrtPrice.eq(u)&&d){const i=r[t.toString()];if(null==i)throw new Error(`Missing tick data for initialized tick ${t}`);const c=n.zeroForOne?sr(i.liquidityNet).negated():sr(i.liquidityNet);if(e.liquidity=e.liquidity.plus(c),e.liquidity.lt(0))throw new Error(`Negative liquidity after crossing tick ${t}: ${e.liquidity.toString()}`);s.push(t),a[t.toString()]=i,o.debugLogging&&this.logger.debug(`Crossed tick ${t}`,{liquidityNet:c.toString(),newLiquidity:e.liquidity.toString()})}if(e.sqrtPrice.eq(u))e.tick=n.zeroForOne?t-1:t;else{const t=V(sr(e.sqrtPrice.toString()));e.tick=t}}if(c>=o.maxIterations)throw new Error(`Swap calculation exceeded maximum iterations (${o.maxIterations}). Possible infinite loop or very complex swap.`);const u=e.sqrtPrice.eq(l);return{state:e,ticksCrossed:s,priceHitLimit:u,stepCount:c,updatedTicks:a}}static createUpdatedPool(e,t,n,o){const i=Object.assign(Object.create(Object.getPrototypeOf(e)),e);if(i.sqrtPrice=sr(t.sqrtPrice).toFixed(0),i.liquidity=sr(t.liquidity).toFixed(0),i.tick=t.tick,n.zeroForOne?i.feeGrowthGlobal1=sr(t.feeGrowthGlobalX).toFixed(0):i.feeGrowthGlobal0=sr(t.feeGrowthGlobalX).toFixed(0),n.zeroForOne){const n=sr(e.protocolFeesToken0);i.protocolFeesToken0=n.plus(t.protocolFee).toFixed(0)}else{const n=sr(e.protocolFeesToken1);i.protocolFeesToken1=n.plus(t.protocolFee).toFixed(0)}return i}static calculateFinalAmounts(e,t,n){let o,i,r,s;if(n.exactInput){const e=sr(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(o=e.negated(),i=a,r=ed.ZERO,s=ed.ZERO):(o=a,i=e.negated(),r=ed.ZERO,s=ed.ZERO)}else{const e=sr(n.amountSpecified),a=t.amountCalculated.abs();n.zeroForOne?(o=a.negated(),i=e,r=ed.ZERO,s=ed.ZERO):(o=e,i=a.negated(),r=ed.ZERO,s=ed.ZERO)}const a=t.feeGrowthGlobalX.minus(e.feeGrowthGlobalX).times(e.liquidity);return n.zeroForOne?s=a:r=a,{amount0:o,amount1:i,feeAmount0:r,feeAmount1:s}}static findNextInitializedTick(e,t,n,o){const i=Object.keys(e).map(e=>Co(e,0)).sort((e,t)=>e-t);if(0===i.length){return[o?-887272:887272,!1]}if(o){const e=i.reverse().find(e=>e<t);return void 0!==e?[e,!0]:[-887272,!1]}{const e=i.find(e=>e>t);return void 0!==e?[e,!0]:[887272,!1]}}static executeSwapStep(e,t,n,o,i,r){yr(n),kr(o,"amountRemaining");const s=[500,3e3,1e4];if(!s.includes(i))throw new Error(`Invalid fee tier: ${i}. Must be one of: ${s.join(", ")}`);const a=X(e,t,n,o,i,t.lt(e)),c=a[0],l=a[1],d=a[2],u=a[3],h=v.isBigNumber(c)?c:sr(String(c)),g=v.isBigNumber(l)?l:sr(String(l)),m=v.isBigNumber(d)?d:sr(String(d)),p=v.isBigNumber(u)?u:sr(String(u));return{sqrtPriceStart:e,tickNext:V(h),sqrtPriceNext:h,initialised:!1,amountIn:g,amountOut:m,feeAmount:p}}}nd.logger=new Qn({debug:!1,context:"SwapDeltaCalculator"});class od extends Zo{constructor(e,t,n,o){super(!1,o),this.cache=new Map,this.tierSizes={hot:50,warm:200,cold:0},this.tierTTLs={hot:1/0,warm:18e5,cold:3e5},this.refetchThresholds={swapCount:50,driftPercent:.05},this.fetchPoolFn=e,this.config=t,this.metrics=n,this.tierSizes.cold=Math.max(0,this.config.maxPools-this.tierSizes.hot-this.tierSizes.warm),this.logger.debug(`Initialized with cache limits: hot=${this.tierSizes.hot}, warm=${this.tierSizes.warm}, cold=${this.tierSizes.cold}, max=${this.config.maxPools}`)}async getPool(e){const t=this.cache.get(e);if(t){if(!(Date.now()>t.expiresAt))return t.lastAccessTime=Date.now(),this.checkRefetchNeeded(e,t),this.metrics.recordPoolCacheHit(e,0),t.poolData;this.cache.delete(e),this.logger.debug(`Cache expired for pool ${e}`)}this.metrics.recordPoolCacheMiss(e,0);try{const t=await this.fetchPoolFn(e),n=this.determineTier(),o={poolData:t,tier:n,lastAccessTime:Date.now(),expiresAt:Date.now()+this.tierTTLs[n],swapsSinceRefetch:0,cumulativeDrift:0,lastDeltaAppliedTime:Date.now()};return this.cache.set(e,o),this.cache.size>this.config.maxPools&&this.evictLRU(),this.logger.debug(`Fetched pool ${e} (tier: ${n})`),t}catch(t){throw this.logger.error(`Failed to fetch pool ${e}:`,t),t}}updatePoolWithSwapDelta(e,t,n,o,i){const r=this.cache.get(e);if(!r)return this.logger.debug(`Pool ${e} not in cache for delta update`),!1;try{if(i){const s="zeroForOne"===t,a=s?n:o,c={transactionId:i.transactionId,timestamp:i.timestamp,amountSpecified:a,zeroForOne:s,exactInput:i.exactInput},l=nd.calculateSwapDelta(r.poolData,c);r.poolData={...r.poolData,pool:l.updatedPool},r.swapsSinceRefetch++,r.lastDeltaAppliedTime=Date.now(),void 0!==l.metadata.driftPercentage?(r.cumulativeDrift+=l.metadata.driftPercentage,this.logger.debug(`Delta applied for ${e}: drift=${l.metadata.driftPercentage.toFixed(4)}%, cumulative=${r.cumulativeDrift.toFixed(2)}%`)):this.logger.debug(`Delta applied for ${e}: ${l.ticksCrossed.length} ticks crossed`)}else r.swapsSinceRefetch++,r.lastDeltaAppliedTime=Date.now();return this.shouldRefetch(r)&&(this.logger.debug(`Refetch needed for ${e}: swaps=${r.swapsSinceRefetch}, drift=${(100*r.cumulativeDrift).toFixed(2)}%`),r.expiresAt=Date.now()),!0}catch(t){return this.logger.error(`Failed to update pool ${e}:`,t),r.expiresAt=Date.now(),!1}}getStats(){const e={totalCached:this.cache.size,hotCacheSize:0,warmCacheSize:0,coldCacheSize:0,memoryUsedMB:this.metrics.getMemoryUsedMB()};for(const t of this.cache.values())"hot"===t.tier?e.hotCacheSize++:"warm"===t.tier?e.warmCacheSize++:e.coldCacheSize++;return e}getPoolInfo(e){const t=this.cache.get(e);return t?{poolKey:e,tier:t.tier,lastAccessTime:new Date(t.lastAccessTime),expiresAt:new Date(t.expiresAt),swapsSinceRefetch:t.swapsSinceRefetch,cumulativeDrift:t.cumulativeDrift,isExpired:Date.now()>t.expiresAt}:null}async warmCache(e){if(""===e)throw En("poolKey","Pool key");if(this.cache.has(e))return!0;try{return await Hr(async()=>{await this.getPool(e),this.logger.debug(`Cache warmed for ${e}`)},`Failed to warm cache for ${e}`,this.logger),!0}catch{return!1}}async warmCacheBatch(e,t=5){if(0===e.length)throw En("poolKeys","Pool keys array");return Hr(async()=>{const n={succeeded:0,failed:0,total:e.length};let o=0;const i=new Set;for(;o<e.length||i.size>0;){for(;o<e.length&&i.size<t;){const t=e[o];o++;const r=this.warmCache(t).then(e=>{e?n.succeeded++:n.failed++});i.add(r),r.finally(()=>i.delete(r))}i.size>0&&await Promise.race(i)}return this.logger.debug(`Cache warming complete: ${n.succeeded}/${n.total} succeeded`),n},"Failed to warm cache batch",this.logger)}clear(){this.cache.clear(),this.logger.debug("Cache cleared")}clearExpired(){const e=Date.now();let t=0;for(const[n,o]of this.cache)e>o.expiresAt&&(this.cache.delete(n),t++);t>0&&this.logger.debug(`Cleared ${t} expired entries`)}determineTier(){const e=Array.from(this.cache.values()).filter(e=>"hot"===e.tier).length,t=Array.from(this.cache.values()).filter(e=>"warm"===e.tier).length;return e<this.tierSizes.hot?"hot":t<this.tierSizes.warm?"warm":"cold"}checkRefetchNeeded(e,t){this.shouldRefetch(t)&&(this.logger.debug(`Scheduling refetch for ${e}: swaps=${t.swapsSinceRefetch}, drift=${(100*t.cumulativeDrift).toFixed(2)}%`),t.expiresAt=Date.now())}shouldRefetch(e){return e.swapsSinceRefetch>=this.refetchThresholds.swapCount||e.cumulativeDrift>=this.refetchThresholds.driftPercent}evictLRU(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"cold"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(0===e.length){this.logger.warn("No cold cache entries to evict, trying warm cache");const e=Array.from(this.cache.entries()).filter(([e,t])=>"warm"===t.tier).sort((e,t)=>e[1].lastAccessTime-t[1].lastAccessTime);if(e.length>0){const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted warm cache entry: ${t}`)}return}const[t]=e[0];this.cache.delete(t),this.logger.debug(`Evicted cold cache entry: ${t}`)}async refreshWarmAndHotTiers(){const e=Array.from(this.cache.entries()).filter(([e,t])=>"hot"===t.tier||"warm"===t.tier).sort((e,t)=>t[1].lastAccessTime-e[1].lastAccessTime).slice(0,10);if(0===e.length)return;const t=e.map(([e,t])=>this.fetchPoolFn(e).then(n=>{null!=t&&(t.poolData=n,t.lastAccessTime=Date.now(),t.swapsSinceRefetch=0,t.cumulativeDrift=0),this.logger.debug(`Refreshed ${e} during background warming`)}).catch(t=>{this.logger.debug(`Failed to refresh ${e} during background warming:`,t)})),n=new Promise(e=>setTimeout(()=>e(),5e3));await Promise.race([Promise.all(t),n])}}class id extends Zo{constructor(e,t,n){super(!1,n),this.queue=[],this.isShuttingDown=!1,this.currentConcurrency=0,this.maxConcurrencyReached=0,this.eventsDropped=0,this.totalBatchesProcessed=0,this.totalBatchSize=0,this.eventsProcessedCount=0,this.processor=null,this.processingScheduled=!1,this.scheduleProcessing=e=>{"undefined"!=typeof setImmediate?setImmediate(e):Promise.resolve().then(e)},this.config=e,this.metrics=t,this.logger.debug(`Initialized with maxQueueSize=${this.config.maxQueueSize}, batchSize=${this.config.batchSize}, maxConcurrent=${this.config.maxConcurrent}`)}setProcessor(e){this.processor=e}enqueue(e){return this.isShuttingDown?(this.logger.debug(`Rejecting event (queue shutting down): ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):this.queue.length>=this.config.maxQueueSize?(this.logger.warn(`Queue full (${this.queue.length}/${this.config.maxQueueSize}), dropping event: ${e.transactionId}`),this.metrics.recordEventDropped(),this.eventsDropped++,!1):(this.queue.push(e),this.metrics.updateQueueDepth(this.queue.length),this.processingScheduled||this.isShuttingDown||(this.processingScheduled=!0,this.scheduleProcessing(()=>{this.processNextBatch()})),!0)}getQueueSize(){return this.queue.length}getStats(){return{queueSize:this.queue.length,eventsProcessed:this.eventsProcessedCount,eventsDropped:this.eventsDropped,currentConcurrent:this.currentConcurrency,maxConcurrentReached:this.maxConcurrencyReached,averageBatchSize:this.totalBatchesProcessed>0?Math.floor(this.totalBatchSize/this.totalBatchesProcessed):0,totalBatchesProcessed:this.totalBatchesProcessed}}async waitForEmpty(e){return new Promise(t=>{const n=()=>{0!==this.queue.length||0!==this.currentConcurrency?setTimeout(n,10):t()};void 0!==e&&e>0&&setTimeout(()=>t(),e),n()})}async shutdown(e=3e4){this.isShuttingDown=!0,this.logger.debug("Shutting down queue...");const t=Date.now();for(;this.queue.length>0||this.currentConcurrency>0;){if(no(t)>e){this.logger.warn(`Queue shutdown timeout: ${this.queue.length} events remaining, ${this.currentConcurrency} processing`);break}await new Promise(e=>setTimeout(e,50))}this.logger.debug("Queue shutdown complete")}clear(){const e=this.queue.length;this.queue.length=0,this.eventsDropped+=e,this.metrics.updateQueueDepth(0),this.logger.warn(`Cleared ${e} events from queue`)}async processNextBatch(){if(this.processingScheduled=!1,this.isShuttingDown&&0===this.queue.length)return;if(this.currentConcurrency>=this.config.maxConcurrent)return void setTimeout(()=>{this.processingScheduled||(this.processingScheduled=!0,setImmediate(()=>{this.processNextBatch()}))},10);const e=Math.min(this.config.batchSize,this.queue.length,this.config.maxConcurrent-this.currentConcurrency);if(0===e)return;const t=this.queue.splice(0,e);this.metrics.updateQueueDepth(this.queue.length),this.currentConcurrency+=t.length,this.currentConcurrency>this.maxConcurrencyReached&&(this.maxConcurrencyReached=this.currentConcurrency),this.totalBatchSize+=t.length,this.totalBatchesProcessed++;try{const e=await Promise.allSettled(t.map(e=>this.processEvent(e)));for(let n=0;n<e.length;n++){const o=e[n];this.eventsProcessedCount++,"rejected"===o.status&&this.logger.error(`Failed to process event ${t[n].transactionId}:`,o.reason)}}finally{this.currentConcurrency-=t.length}this.queue.length>0&&!this.processingScheduled&&(this.processingScheduled=!0,this.scheduleProcessing(()=>{this.processNextBatch()}))}async processEvent(e){if(!this.processor)return void this.logger.warn("No processor set, discarding event:",e.transactionId);const t=Date.now();try{await this.processor(e);const n=no(t);this.metrics.recordEventLatency(n)}catch(t){throw this.logger.error(`Event processing failed for ${e.transactionId}:`,t),t}}}class rd extends Zo{constructor(e,t,n,o={},i){super(!1,i),this.socket=null,this.maxSeenTransactions=1e4,this.listeners=[],this.onErrorCallbacks=[],this.isActive=!1,this.listenerRegistered=!1,this.handleSwapEvent=null,this.warmingIntervalHandle=null,e instanceof Promise?this.socketReady=e.then(e=>(this.socket=e,this.setupConnectionMonitoring(),e)).catch(e=>{throw this.logger.error("Failed to resolve socket promise:",e),e}):(this.socket=e,this.socketReady=Promise.resolve(e),this.setupConnectionMonitoring()),this.metrics=new Ql,this.config=this.applyDefaults(o),this.eventExtractor=new Yl(this.logger),this.cacheManager=new od(t,this.config,this.metrics,this.logger),this.eventQueue=new id(this.config,this.metrics,this.logger),this.seenTransactions=new sd(this.maxSeenTransactions),this.reconnectionManager=new Al({maxAttempts:3,baseDelayMs:1e3,useExponentialBackoff:!0,maxDelayMs:3e4}),this.eventQueue.setProcessor(e=>this.processSwapEvent(e)),this.logger.debug("Initialized MultiPoolStateManager")}subscribe(e,t){this.listeners.push(t),e.onError&&this.onErrorCallbacks.push(e.onError),this.isActive||(this.setupWebSocketListener(e),this.isActive=!0);const n=this;return()=>{if(n.listeners=n.listeners.filter(e=>e!==t),e.onError&&(n.onErrorCallbacks=n.onErrorCallbacks.filter(t=>t!==e.onError)),0===n.listeners.length&&0===n.onErrorCallbacks.length)try{n.unsubscribe()}catch(e){n.logger.error("Error during unsubscribe cleanup:",e)}}}getHealth(){const e=this.cacheManager.getStats(),t=this.eventQueue.getStats(),n=this.metrics.getHealthMetrics(e.totalCached,e.hotCacheSize,e.warmCacheSize,e.coldCacheSize,this.getMaxMemoryMB()),o=this.determineHealthStatus(t,e),i={connected:this.socket?.connected??!1,reconnectAttempts:this.reconnectionManager.getAttempts()};this.socket?.connected&&(i.lastConnectionTime=new Date);const r=t.queueSize/this.config.maxQueueSize*100,s=e.totalCached/this.config.maxPools*100,a=e.memoryUsedMB/this.getMaxMemoryMB()*100,c=this.generateHealthRecommendations(o,r,s,a,n.metrics.cacheHitRate);return{...n,status:o,websocket:i,recommendations:c,detailedMetrics:{eventQueueUtilization:r,cacheUtilization:s,memoryUtilization:a}}}generateHealthRecommendations(e,t,n,o,i){const r=[];return"failed"===e&&(r.push("🔴 System is in FAILED state - immediate action required"),this.socket?.connected||r.push("Reconnect WebSocket - connection lost"),t>90&&r.push("Reduce incoming event rate or increase maxQueueSize")),"degraded"===e&&(r.push("⚠️ System is DEGRADED - performance may be impacted"),t>75&&r.push(`Queue utilization ${t.toFixed(1)}% - consider increasing maxQueueSize`),o>80&&r.push(`Memory usage ${o.toFixed(1)}% - consider reducing cache size or memory profile`)),"healthy"===e&&(i<50&&r.push(`Cache hit rate ${i.toFixed(1)}% is low - consider warming more pools`),o>50&&r.push("Memory usage is moderate - monitor for growth trends"),t>50&&r.push("Queue utilization is elevated - monitor for bottlenecks")),r}getSummary(){return{...this.metrics.getSummary(),queueStats:this.eventQueue.getStats(),cacheStats:this.cacheManager.getStats()}}startBackgroundWarming(){if(null!==this.warmingIntervalHandle)return;const e=this.config.refreshIntervalMs;this.warmingIntervalHandle=function(e,t){const n=e;return Zl.set(n,{createdAt:Date.now(),label:t}),n}(setInterval(()=>{this.performBackgroundWarming().catch(e=>{this.logger.error("Background warming error:",e)})},e),"background-warming"),this.logger.debug(`Background warming started (interval: ${e}ms)`)}stopBackgroundWarming(){null!==this.warmingIntervalHandle&&(!function(e){const t=e;Zl.delete(t)}(this.warmingIntervalHandle),clearInterval(this.warmingIntervalHandle),this.warmingIntervalHandle=null,this.logger.debug("Background warming stopped"))}async performBackgroundWarming(){const e=this.cacheManager.getStats();if(0!==e.totalCached)try{await this.cacheManager.refreshWarmAndHotTiers(),this.logger.debug(`Background warming completed: ${e.totalCached} pools in cache (hot: ${e.hotCacheSize}, warm: ${e.warmCacheSize})`)}catch(e){this.logger.debug("Background warming encountered an error:",e)}}async shutdown(){this.stopBackgroundWarming(),await this.socketReady.catch(()=>{}),this.unsubscribe(),await this.eventQueue.shutdown(),this.cacheManager.clear(),this.metrics.reset()}setupConnectionMonitoring(){this.socket&&(this.socket.on("disconnect",()=>{this.logger.warn("WebSocket disconnected"),this.notifyError(new Error("WebSocket disconnected")),this.config.autoRecover&&this.attemptReconnection().catch(e=>{this.logger.error("Reconnection failed:",e)})}),this.socket.on("connect_error",e=>{this.logger.error("WebSocket connection error:",e),this.notifyError(un(e)?e:new Error(hn(e)))}))}async attemptReconnection(){const e=this.reconnectionManager.getAttempts(),t=this.reconnectionManager.getMaxAttempts();if(this.logger.debug(`Reconnection attempt ${e+1}/${t}`),this.reconnectionManager.isExhausted())return this.logger.error(`Max reconnection attempts (${t}) exceeded - performing full reset`),void this.performFullReset();if(e<2)if(0===e)this.logger.debug("Tier 1: Quick reconnect");else{const e=this.reconnectionManager.getNextDelay();this.logger.debug(`Tier 2: Exponential backoff (${e}ms)`),await new Promise(t=>setTimeout(t,e))}try{this.socket?.disconnect&&(this.socket.disconnect(),this.logger.debug("Disconnected for reconnection")),this.socket?.connect?.(),this.logger.debug("Reconnection initiated"),this.reconnectionManager.recordAttempt()}catch(e){throw this.logger.error("Failed to initiate reconnection:",e),e}}performFullReset(){this.logger.warn("Performing full system reset due to connection failures"),this.stopBackgroundWarming();const e=this.getHealth();this.logger.debug("System state before reset:",{status:e.status,queueSize:e.eventProcessing.eventsProcessed,cachedPools:e.pools.totalMonitored,memory:`${e.memory.usedMB}MB / ${e.memory.maxMB}MB`,cacheHitRate:`${e.metrics.cacheHitRate.toFixed(2)}%`}),this.cacheManager.clear(),this.metrics.reset(),this.reconnectionManager.reset(),this.notifyError(new Error("System reset: connection lost and recovery failed - please restart monitoring")),this.logger.info("System reset complete - ready for restart")}setupWebSocketListener(e){if(this.listenerRegistered)return void this.logger.debug("WebSocket listener already registered");const t=this;this.handleSwapEvent=(n,...o)=>{try{const n=Date.now(),i=o[0],r=t.eventExtractor.walkPayloadForSwaps(i,t.seenTransactions);if(0===r.length)return;t.logger.debug(`Extracted ${r.length} swaps from payload`);for(const n of r){if(t.filterSwap(n,e)){t.eventQueue.enqueue(n)||t.logger.debug(`Swap dropped due to queue overflow: ${n.transactionId}`)}}const s=no(n);t.metrics.recordEventLatency(s)}catch(e){t.logger.error("Error processing WebSocket payload:",e),t.notifyError(un(e)?e:new Error(hn(e)))}},this.socket?(this.socket.onAny(this.handleSwapEvent),this.listenerRegistered=!0,this.setupConnectionMonitoring()):this.logger.warn("Socket not available for listener registration"),this.startBackgroundWarming(),this.logger.debug("WebSocket listener registered for all events")}unsubscribe(){this.stopBackgroundWarming(),this.handleSwapEvent&&this.listenerRegistered&&this.socket&&(this.socket.offAny(this.handleSwapEvent),this.listenerRegistered=!1),this.isActive=!1,this.listeners=[],this.onErrorCallbacks=[],this.logger.debug("Unsubscribed from swap events")}filterSwap(e,t){if(void 0!==t.tokenFilter&&""!==t.tokenFilter){if(!Jl.containsToken(e.poolKey,t.tokenFilter))return!1}if(t.pairTokens){const[n,o]=t.pairTokens;if(!Jl.containsTokenPair(e.poolKey,n,o))return!1}if(void 0!==t.feeTierFilter&&""!==t.feeTierFilter){if(Jl.normalizeFee(t.feeTierFilter)!==e.feeTier)return!1}return void 0===t.userFilter||""===t.userFilter||e.user===t.userFilter}async processSwapEvent(e){const t=Date.now();try{const n=this.cacheManager.updatePoolWithSwapDelta(e.poolKey,e.direction,e.amount0,e.amount1,e);e.poolStateUpdated=n;const o=no(t);this.metrics.recordEventLatency(o);for(const t of this.listeners)try{const n=t(e);n instanceof Promise&&await n}catch(t){this.logger.error(`Listener error for swap ${e.transactionId}:`,t)}}catch(t){this.logger.error(`Failed to process swap ${e.transactionId}:`,t),this.notifyError(un(t)?t:new Error(hn(t)))}}notifyError(e){for(const t of this.onErrorCallbacks)try{t(e)}catch(e){this.logger.error("Error in error callback:",e)}}determineHealthStatus(e,t){return!this.socket?.connected||e.queueSize>.9*this.config.maxQueueSize?"failed":e.queueSize>.75*this.config.maxQueueSize||t.memoryUsedMB>.9*this.getMaxMemoryMB()?"degraded":"healthy"}getMaxMemoryMB(){switch(this.config.memoryProfile){case"conservative":return 55;case"aggressive":return 530;default:return 250}}applyDefaults(e){return{memoryProfile:e.memoryProfile??"moderate",maxPools:e.maxPools??500,softLimit:e.softLimit??200,preloadTopN:e.preloadTopN??200,warmingTimeoutMs:e.warmingTimeoutMs??3e4,refreshIntervalMs:e.refreshIntervalMs??3e5,maxQueueSize:e.maxQueueSize??1e4,batchSize:e.batchSize??100,maxConcurrent:e.maxConcurrent??10,autoRecover:e.autoRecover??!0,maxParallelRefetch:e.maxParallelRefetch??20,enableDeltaOptimization:e.enableDeltaOptimization??!0,enableOfflineQuotes:e.enableOfflineQuotes??!0,metricsEnabled:e.metricsEnabled??!0,debug:e.debug??!1}}}class sd{constructor(e){this.map=new Map,this.maxSize=e}has(e){return this.map.has(e)}add(e){if(this.map.has(e))return this.map.delete(e),this.map.set(e,Date.now()),this;if(this.map.size>=this.maxSize){const e=this.map.keys().next().value;this.map.delete(e)}return this.map.set(e,Date.now()),this}delete(e){return this.map.delete(e)}clear(){this.map.clear()}get size(){return this.map.size}}const ad="10000",cd="1000";function ld(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function dd(){return Date.now()+6e4}function ud(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function hd(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function gd(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class md extends Yo{constructor(e){super(e)}getCollectionClaimFee(){return ad}getTokenClassCreateFee(){return cd}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(!gd(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=ad;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const o=cd,i=String(BigInt(o)*BigInt(e.createTokenClasses));n.tokenClassCreate=o,n.tokenClassCount=e.createTokenClasses,t=String(BigInt(t)+BigInt(i))}return{totalFee:t,breakdown:n}}async claimCollection(e){try{if(this.logger.debug("Claiming NFT collection",e.collectionName),!ud(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:dd(),uniqueKey:ld("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),!gd(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),!ud(e))throw new Error(`Invalid collection name format: ${e}`);const t=!0;return this.logger.debug(`Collection ${e} available:`,t),t}catch(e){throw this.logger.error("Failed to check collection availability",e),e}}async createTokenClass(e){try{if(this.logger.debug("Creating NFT token class",e),null==e.collection||0===e.collection.length||null==e.type||0===e.type.length||null==e.category||0===e.category.length)throw new Error("Missing required parameters: collection, type, category");if(!ud(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?hd(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?hd(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:dd(),uniqueKey:ld("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),!ud(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(!gd(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 o={collection:e.collection,type:e.type,category:e.category,quantity:e.quantity,owner:e.ownerAddress,additionalKey:e.additionalKey??"none",expiresAt:dd(),uniqueKey:ld("mint")};this.logger.debug("Built mint DTO",o);const i=`mint-${Date.now()}`,r=Array.from({length:t},(e,t)=>t+1);return{transactionId:i,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}),!gd(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 pd extends Yo{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(Ut,{token:e.token,platform:e.platform,...void 0!==e.deviceId?{deviceId:e.deviceId}:{}},t),o=this.extractData(n);return this.logger.debug("Push token registered",{registered:o.registered}),o}async unregisterPushToken(e){this.logger.debug("Unregistering push token");const t=this.getJwtHeaders(),n=await this.http.request({method:"DELETE",url:Ot,data:{token:e},headers:t}),o=this.extractData(n);return this.logger.debug("Push token unregistered",{unregistered:o.unregistered}),o}async getPreferences(){this.logger.debug("Fetching notification preferences");const e=this.getJwtHeaders(),t=await this.http.get(Lt,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(Mt,e,t),o=this.extractData(n);return this.logger.debug("Updated notification preferences",{tradesEnabled:o.tradesEnabled,streamsEnabled:o.streamsEnabled}),{preferences:o}}}class fd extends Yo{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get(Y.OEMBED,{format:"json"});return this.logger.debug("Fetched home oEmbed (JSON)",{title:t.title}),{oembed:t}}async getHomeOEmbedHtml(e={}){this.logger.debug("Fetching home oEmbed (HTML)");const t=await this.http.get(Y.OEMBED,{},{responseType:"text"});return this.logger.debug("Fetched home oEmbed (HTML)"),{html:t}}async getPoolOEmbedJson(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Yt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=Y.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),o=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched pool oEmbed (JSON)",{tokenName:t,title:o.title}),{oembed:o}}async getPoolOEmbedHtml(e){const{tokenName:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Yt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=Y.OEMBED_BUY_SELL.replace(":tokenName",t.toLowerCase().trim()),o=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched pool oEmbed (HTML)",{tokenName:t}),{html:o}}async getProfileOEmbedJson(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Yt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=Y.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),o=await this.http.get(n,{format:"json"});return this.logger.debug("Fetched profile oEmbed (JSON)",{address:t,title:o.title}),{oembed:o}}async getProfileOEmbedHtml(e){const{address:t}=e;if(null==t||"string"!=typeof t||""===t.trim())throw new Yt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=Y.OEMBED_PROFILE.replace(":address",encodeURIComponent(t.toLowerCase().trim())),o=await this.http.get(n,{},{responseType:"text"});return this.logger.debug("Fetched profile oEmbed (HTML)",{address:t}),{html:o}}}function yd(e){if(!Mo(e))throw En("address","Address")}const kd={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},vd={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},wd=qo(kd),bd=qo(vd);function Sd(e){if(!Mo(e))throw new Error("Address must be a non-empty string");try{ui(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function Ad(e){try{Bo(e,"id")}catch(e){if(e instanceof Yt)throw new Error("Invite ID must be a positive integer");throw e}}class Td extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}validateInviteCodeFormat(e){if(!Mo(e))throw En("inviteCode","Invite code");!function(e){if(!Mo(e))throw new Error("Invite code must be a non-empty string");Ro(e,100,"code")}(e)}validateWalletAddressFormat(e){if(!Mo(e))throw En("address","Address");Sd(e)}async createInvite(e={}){!function(e){try{Vo(e.description,"description",255)}catch(e){if(e instanceof Yt)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(!Mo(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{Xo(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Yt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(to(e.expiresAt)&&eo(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}(e),this.validateOptionalString(e.description,"description","Description",uo.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=Ge,n={};void 0!==e.description&&(n.description=e.description),void 0!==e.expiresAt&&(n.expiresAt=e.expiresAt);const o=await this.http.post(t,n,this.getDualAuthHeaders());return{invite:this.extractData(o)}}async listInvites(e={}){!function(e){if(void 0!==e.status&&!wd(e.status))throw On("status",e.status,Object.values(kd),"status");Ko(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,kd);const t=We,n={...this.buildPaginationParams(e,co.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const o=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(o);return{items:i.invites,pageInfo:i.pageInfo}}async getInviteByCode(e){this.validateInviteCodeFormat(e);const t=this.buildEndpoint(He,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){Ad(e);const t=this.buildEndpoint(je,{id:String(e)});Mn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=ze,n={inviteCode:e},o=await this.http.post(t,n,this.getJwtHeaders());return{invite:this.extractData(o)}}async listOverseers(e={}){!function(e){if(void 0!==e.status&&!bd(e.status))throw On("status",e.status,Object.values(vd),"status");Ko(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,vd);const t=Ve,n={...this.buildPaginationParams(e,co.MAX_LIMIT)};void 0!==e.status&&(n.status=e.status);const o=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(o);return{items:i.overseers,pageInfo:i.pageInfo}}async createOverseerDirect(e){!function(e){if(null==e||"object"!=typeof e)throw new Yt("Options are required");if(!Mo(e.userAddress))throw new Yt("userAddress is required and must be a non-empty string");try{ui(e.userAddress,"userAddress")}catch{throw new Yt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Yt("description must be a string");if(e.description.length>255)throw new Yt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",uo.DESCRIPTION.MAX_LENGTH);const t=Xe,n={userAddress:e.userAddress};void 0!==e.description&&(n.description=e.description);const o=await this.http.post(t,n,this.getDualAuthHeaders());return{overseer:this.extractData(o)}}async revokeOverseer(e){this.validateWalletAddressFormat(e);const t=this.buildEndpoint(Qe,{address:e});Mn(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=Je,t=await this.http.get(e,{},this.getJwtHeaders());return this.extractData(t)}async getSummary(){const e=Ye,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getBanStats(){const e=Ze,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=et,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=tt,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=nt,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=ot,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 Yt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Yt("Search must be a string");if(0===e.search.length)throw new Yt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Yt("Sort field must be a string");if(0===e.sortBy.length)throw new Yt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new Yt('Sort order must be "asc" or "desc"')}(t);const n=it,o=this.buildPaginationParams(t,co.MAX_LIMIT);void 0!==t.search&&""!==t.search&&(o.search=t.search),void 0!==t.sortBy&&""!==t.sortBy&&(o.sortBy=t.sortBy),void 0!==t.sortOrder&&(o.sortOrder=t.sortOrder);const i=await this.http.get(n,o,this.getDualAuthHeaders()),r=this.extractData(i);return{items:r.users,pageInfo:r.pageInfo}}async getOverseerUserSummary(e){if(!Mo(e))throw En("address","User address");Sd(e);const t=this.buildEndpoint(rt,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){yd(e);const t=this.buildEndpoint(st,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!Mo(e))throw En("tokenName","Token name")}(e);const t=this.buildEndpoint(at,{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 Yt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=ct,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){yd(e);const t=this.buildEndpoint(lt,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=dt,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class Ed extends Yo{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),Mn(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(ge);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 Yt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(me,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(ye);return this.extractData(e)}}class Cd extends Yo{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(Pt),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Id extends Yo{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw En("tokenName","Token name");if(!this.tokenResolverService)throw Nn("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{Ho(e)}catch(e){throw Nn(hn(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 Nn(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=Zr(tc(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(un(t)&&hn(t).includes("ConfigurationError"))throw t;throw In(`Failed to resolve token name '${e}': ${hn(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw En("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await Hr(async()=>{let t=e.tokenId;if(null!=e.tokenName){this.logger.debug(`Resolving token name '${e.tokenName}' to token ID`);const n=await this.fetchTokenClassKeyByTokenName(e.tokenName);t=n,this.logger.debug(`Resolved to token ID: ${n}`)}if(null==t)throw Nn("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return rc}),o=fc(Zr(n(t))),{from:i,to:r,sortOrder:s="DESC"}=e,a=To(e.offset,0),c=To(e.limit,10),l={token:o,skip:String(a),take:String(c)};i&&(l.from=i.toISOString()),r&&(l.to=r.toISOString());const d=function(e){if(null!=e)return e.toLowerCase()}(s);null!=d&&(l.order=d),this.logger.debug(`Querying price snapshots for token ${o}, offset ${a}, limit ${c}`);const u=await this.http.get("/price-oracle/fetch-price",l);if(null==u)throw In("No response from price history service",500);const h=this.transformApiResponseToPriceHistory(u);return this.logger.debug(`Found ${h.snapshots.length} price snapshots, total ${h.total}`),h},"Failed to fetch price history",this.logger)}transformApiResponseToPriceHistory(e){if(!Ln(e))throw In("Invalid API response: missing data wrapper",500);const t=$n(e);if(!t||"object"!=typeof t)throw In("Invalid API response: data is not an object",500);const n=t,o=n.data;if(!Array.isArray(o))throw In("Invalid API response: missing or invalid data.data array",500);const i=n.meta;if(null==i||"object"!=typeof i)throw In("Invalid API response: missing data.meta pagination info",500);const r=i,s=o.map(e=>{if("object"!=typeof e||null===e)throw In("Invalid API response: invalid snapshot item",500);const t=e;return{price:t.price,timestamp:eo(t.createdAt),tokenId:Zr({collection:t.collection,category:t.category,type:t.type,additionalKey:t.additionalKey})}}),a=Eo(r.currentPage,1),c=Eo(r.totalPages,1);return{snapshots:s,page:a,limit:Eo(r.pageSize,50),total:Eo(r.totalItems,0),totalPages:c,hasNext:a<c,hasPrevious:a>1}}async fetchAllPriceHistory(e){if(null==e)throw En("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),Hr(async()=>{const t=await Za((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 o=e.length;return{offset:0,limit:o,total:t,totalPages:0!==o?Ma(t,o):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:o}=e;if(Wo(e,"tokenName","tokenId",{description:"token identifier"}),t&&!to(t))throw Nn("from must be a valid Date","from");if(n&&!to(n))throw Nn("to must be a valid Date","to");null!=o&&function(e,t){if("ASC"!==e&&"DESC"!==e)throw new Yt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}(o,"sortOrder"),Ko(0,void 0,50,e.pageSize)}}class Nd extends Ga{constructor(e,t,n,o){super(e,t,n,!1,o)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(vt)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!Mo(e.content))throw new Yt("Content is required");return{success:!0,data:(await this.http.put(wt,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}oo.MIN_LENGTH,oo.MAX_LENGTH,oo.PATTERN;qo({ENABLED:"ENABLED",DISABLED:"DISABLED",ADMIN_DISABLED:"ADMIN_DISABLED"});qo({RATE_LIMITED:"RATE_LIMITED",INVALID_EMOJI:"INVALID_EMOJI",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",STREAM_NOT_LIVE:"STREAM_NOT_LIVE"});class Dd extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async getChatStatus(e){if(null==e||""===e)throw En("tokenName","Token name");return this.validateTokenName(e,oo),Hr(async()=>{const t=this.buildEndpoint(bt,{tokenName:e}),n=await this.http.get(t),o=this.extractData(n),i={enabled:o.enabled,tokenName:o.tokenName??zn(e)};return void 0!==o.status&&null!==o.status&&(i.status=o.status),i},`Failed to get chat status for token: ${e}`,this.logger)}async disableChat(e){if(null==e||""===e)throw En("tokenName","Token name");return this.validateTokenName(e,oo),Hr(async()=>{const t=this.buildEndpoint(At,{tokenName:e}),n=await this.http.post(t,{enabled:!1},this.getDualAuthHeaders()),o=this.extractData(n),i={enabled:o.enabled,tokenName:o.tokenName??zn(e)};return void 0!==o.status&&null!==o.status&&(i.status=o.status),i},`Failed to disable chat for token: ${e}`,this.logger)}async enableChat(e){if(null==e||""===e)throw En("tokenName","Token name");return this.validateTokenName(e,oo),Hr(async()=>{const t=this.buildEndpoint(St,{tokenName:e}),n=await this.http.post(t,{enabled:!0},this.getDualAuthHeaders()),o=this.extractData(n),i={enabled:o.enabled,tokenName:o.tokenName??zn(e)};return void 0!==o.status&&null!==o.status&&(i.status=o.status),i},`Failed to enable chat for token: ${e}`,this.logger)}async setSlowMode(e,t){if(null==e||""===e)throw En("tokenName","Token name");if(this.validateTokenName(e,oo),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return Hr(async()=>{const n=this.buildEndpoint(It,{tokenName:e}),o=await this.http.patch(n,{slowModeSeconds:t},this.getDualAuthHeaders());return this.extractData(o)},`Failed to set slow mode for token: ${e}`,this.logger)}async getGlobalChatStatus(){const e=await this.http.get(Tt);return this.extractData(e)}async disableGlobalChat(){const e=await this.http.post(Ct,{enabled:!1},this.getAdminHeaders());return this.extractData(e)}async enableGlobalChat(){const e=await this.http.post(Et,{enabled:!0},this.getAdminHeaders());return this.extractData(e)}async setGlobalChatEnabled(e){return e?this.enableGlobalChat():this.disableGlobalChat()}async getEngagementStats(e){if(null==e)throw En("options","Engagement stats options");return function(e){if(!Mo(e.tokenName))throw En("tokenName","Token name");const t=e.tokenName.trim();if(0===t.length)throw En("tokenName","Token name");if(!oo.PATTERN.test(t))throw Cn("tokenName",`match pattern ${String(oo.PATTERN)}`,"Token name")}(e),Hr(async()=>{const t=this.buildEndpoint(Nt,{tokenName:e.tokenName}),n=await this.http.get(t,void 0,this.getDualAuthHeaders()),o=this.extractData(n);return{tokenName:zn(e.tokenName),chat:o.chat,comments:o.comments}},"Failed to get engagement stats",this.logger)}}class Pd extends Zo{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 o of n)try{const e=o(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)}}qo({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),qo({READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"});const xd=qo({YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"});const _d={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};qo(_d),qo({OWNER:"OWNER",MODERATOR:"MODERATOR"});function Fd(e,t="tokenName"){Ho(e,t,oo)}function Rd(e){if(Fd(e.tokenName),!Mo(e.language))throw En("language");if(t=e.language,!Mo(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Yt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Xt);var t}qo({..._d,OVERSEER:"OVERSEER"}),qo({OWNERSHIP:"ownership",MODERATOR_INVITE:"moderator_invite",OVERSEER:"overseer"});class Bd extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async startStream(e){this.validateTokenName(e,oo);const t=this.buildEndpoint(ne,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,oo);const t=this.buildEndpoint(oe,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,ie,oo)}async enableStream(e){return this.toggleFeature(e,re,oo)}async resetStreamKey(e){this.validateTokenName(e,oo);const t=this.buildEndpoint(se,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,oo);const t=this.buildEndpoint(ve,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Fd(e.tokenName),Ko(0,void 0,ko,e.pageSize)}(e);const t=this.buildEndpoint(ae,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,ko),o=e.offset;"number"==typeof o&&(n.offset=String(o));const i=await this.http.get(t,n),r=this.extractData(i),s=e,a=r.pageSize??r.limit??e.pageSize??("number"==typeof s.limit?s.limit:20),c="number"==typeof s.offset?s.offset:0,l=Math.floor(c/a)+1;return{recordings:r.recordings,tokenName:zn(e.tokenName),page:r.page??l,limit:a,total:r.total,hasNext:r.recordings.length===a}}async getRecordingDownload(e,t){this.validateTokenName(e,oo),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(ce,{tokenName:e,assetId:t}),o=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(o)}async deleteRecording(e,t){this.validateTokenName(e,oo),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(le,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,oo);const t=this.buildEndpoint(de,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Fd(e.tokenName),!Mo(e.platform))throw En("platform");if(!xd(e.platform))throw new Yt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",Vt);if(!Mo(e.rtmpUrl))throw En("rtmpUrl");if(!yo.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new Yt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",Xt);if(!Mo(e.streamKey))throw En("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new Yt("name must be a string","name",jt)}(e);const t=this.buildEndpoint(ue,{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,oo),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(he,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(ge);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.post(me,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.post(pe,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Fd(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||Mo(e.nextLiveStreamAt)))throw new Yt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",jt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Yt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Xt)}}}(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,oo);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Rd(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Fd(e.tokenName)}(e);const t=this.buildEndpoint(fe,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{},o=await this.http.get(t,{},n);return this.extractData(o)}async getAvailableRoles(){const e=await this.http.get(ye);return this.extractData(e)}async getTokenAccess(e){!function(e){Fd(e.tokenName)}(e);const t=this.buildEndpoint(ke,{tokenName:e.tokenName}),n=this.jwtAuth?this.getJwtHeaders():{};this.jwtAuth||this.logger.debug("getTokenAccess called without JWT authentication - will return hasAccess: false",{tokenName:e.tokenName});const o=await this.http.get(t,{},n);return this.extractData(o)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Ud="subscribe_token",Od="unsubscribe_token",Ld="authenticate",Md="send_stream_chat",$d="send_stream_reaction",Kd="typing_start",qd="typing_stop",Gd="STREAM_STATUS",Wd="STREAM_COUNTDOWN_UPDATED",Hd="STREAM_LANGUAGE_UPDATED",zd="VIEWER_COUNT",jd="token_subscribed",Vd="token_unsubscribed",Xd="STREAM_GLOBAL_STATUS",Qd="ENGAGEMENT_STATS_UPDATED",Jd="STREAM_CHAT_MESSAGE",Yd="STREAM_CHAT_SENT",Zd="stream_chat_error",eu="CHAT_STATUS_CHANGED",tu="STREAM_CHAT_GLOBAL_STATUS",nu="authenticated",ou="stream_chat_auth_error",iu="STREAM_REACTION",ru="stream_reaction_error",su="USER_TYPING",au="STREAM_CHAT_PINNED",cu="STREAM_CHAT_UNPINNED",lu="COMMENT_CREATED",du="TOKEN_BANNED",uu="TOKEN_UNBANNED",hu="MODERATOR_INVITE_CREATED",gu="MODERATOR_ADDED",mu="MODERATOR_REMOVED",pu="MODERATOR_ROLE_UPDATED",fu="OVERSEER_ADDED",yu="OVERSEER_REMOVED",ku="TRADE_EXECUTED",vu="BALANCE_UPDATED",wu="STATS_UPDATED",bu="POOL_METADATA_UPDATED",Su="POOL_SOCIAL_LINKS_UPDATED",Au="POOL_BADGE_ASSIGNED",Tu="HOLDER_COUNT_UPDATED",Eu="USER_PROFILE_UPDATED",Cu="API_KEY_CREATED",Iu="API_KEY_UPDATED",Nu="API_KEY_REVOKED",Du="TOKEN_CONFIG_UPDATED",Pu="SITE_CONFIG_CHANGED",xu="COMMENTS_GLOBAL_STATUS",_u="WEBHOOKS_GLOBAL_STATUS",Fu="subscribe_global_feed",Ru="unsubscribe_global_feed",Bu="global_feed_subscribed",Uu="global_feed_unsubscribed";class Ou extends Zo{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 tn("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 Al({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof J||(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:",hn(e)),!1}}getRoomName(e){return`token:${zn(e)}`}bufferEvent(e,t,n){const o=`${e}:${t}`;let i=this.eventBuffer.get(o);i||(i=[],this.eventBuffer.set(o,i)),i.length>=this.MAX_BUFFER_SIZE&&(i.shift(),this.logger.warn(`⚠️ [Stream Buffer] Event buffer overflow for ${o} - dropping oldest event. Consider processing events faster or increasing buffer size.`)),i.push(n);const r=this.eventBufferTimeouts.get(o);r&&clearTimeout(r);const s=setTimeout(()=>{this.eventBuffer.delete(o),this.eventBufferTimeouts.delete(o),this.logger.debug(`📡 [Stream Buffer] Cleaned up buffer for ${o}`)},this.BUFFER_CLEANUP_MS);this.eventBufferTimeouts.set(o,s)}processBufferedEvents(e,t){const n=zn(e),o=[{key:`${Gd}:${n}`,callback:t.onStreamStatus},{key:`${zd}:${n}`,callback:t.onViewerCount},{key:`${Jd}:${n}`,callback:t.onChatMessage},{key:`${eu}:${n}`,callback:t.onChatStatus},{key:`${au}:${n}`,callback:t.onChatPinned},{key:`${cu}:${n}`,callback:t.onChatUnpinned},{key:`${Wd}:${n}`,callback:t.onCountdownUpdated},{key:`${Hd}:${n}`,callback:t.onLanguageUpdated},{key:`${du}:${n}`,callback:t.onTokenBanned},{key:`${uu}:${n}`,callback:t.onTokenUnbanned},{key:`${hu}:${n}`,callback:t.onModeratorInviteCreated},{key:`${gu}:${n}`,callback:t.onModeratorAdded},{key:`${mu}:${n}`,callback:t.onModeratorRemoved},{key:`${pu}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${ku}:${n}`,callback:t.onTradeExecuted},{key:`${vu}:${n}`,callback:t.onBalanceUpdated},{key:`${bu}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${Su}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${Au}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${Tu}:${n}`,callback:t.onHolderCountUpdated},{key:`${lu}:${n}`,callback:t.onCommentCreated}];for(const{key:e,callback:t}of o){const n=this.eventBuffer.get(e);if(n&&t){this.logger.debug(`📡 [Stream Buffer] Delivering ${n.length} buffered events for ${e}`);for(const o of n)try{t?.(o)}catch(t){this.logger.error(`Error delivering buffered event for ${e}:`,t)}this.eventBuffer.delete(e);const o=this.eventBufferTimeouts.get(e);o&&(clearTimeout(o),this.eventBufferTimeouts.delete(e))}}}setupGlobalListeners(){this.socket&&(this.socket.on(Gd,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Gd,e.tokenName,e);const t=this.roomCallbacks.get(zn(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(jd,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=zn(e.tokenName),n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t),n.resolve(e));const o=this.roomCallbacks.get(t);o?.onStreamSubscribed&&o.onStreamSubscribed(e)}),this.socket.on(Vd,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(zn(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(zd,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(zd,e.tokenName,e);const t=this.roomCallbacks.get(zn(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(Xd,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${e.enabled}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(Jd,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(Jd,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(Yd,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(Zd,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(eu,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${e.enabled}`),this.bufferEvent(eu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(tu,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${e.enabled}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(nu,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(ou,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(iu,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(ru,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(su,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(zn(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(au,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(au,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(cu,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(cu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Wd,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Wd,e.tokenName,e);const n=this.roomCallbacks.get(zn(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Hd,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Hd,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(du,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(du,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(uu,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(uu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(hu,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(hu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(gu,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(gu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(mu,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(mu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(pu,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(pu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(fu,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(yu,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(ku,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(ku,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(vu,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(vu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(bu,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(bu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(Su,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(Su,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(Au,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(Au,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(Tu,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(Tu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(lu,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(lu,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(Eu,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(Cu,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(Iu,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(Nu,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(Du,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(Du,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(wu,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(wu,e.tokenName,e);const t=this.roomCallbacks.get(zn(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(Qd,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(Qd,e.tokenName,e);const t=this.roomCallbacks.get(zn(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(Bu,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(Uu,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(Pu,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(Xd,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(tu,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on(xu,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(_u,e=>{this.logger.debug(`📡 [Webhooks Global Status] enabled=${e.enabled}`),this.globalFeedCallbacks.onWebhooksGlobalStatus&&this.globalFeedCallbacks.onWebhooksGlobalStatus(e)}))}resubscribeAll(){const e=Array.from(this.subscribedRooms.keys());this.logger.debug(`📡 Re-subscribing to ${e.length} rooms after reconnect`);for(const t of e)try{this.roomCallbacks.get(t)&&this.socket?.emit(Ud,{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(Fu)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{Hr(async()=>{if(!this.isSocketIOAvailable)throw new tn('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=J(this.config.url,{transports:["websocket"],reconnection:!0,reconnectionAttempts:this.config.reconnectAttempts,reconnectionDelay:this.config.reconnectDelay,auth:n}),this.socket.on("connect",()=>{this.logger.debug(`✅ Stream WebSocket connected: ${String(this.socket?.id)}`),this.reconnectionManager.reset(),this.setupGlobalListeners(),this.subscribedRooms.size>0&&this.resubscribeAll(),e()}),this.socket.on("connect_error",e=>{this.logger.error("❌ Stream WebSocket connection error:",e),t(e)}),this.socket.on("disconnect",e=>{this.logger.debug(`🔌 Stream WebSocket disconnected: ${e}`),this.isAuthenticated=!1}),this.socket.on("error",e=>{this.logger.error("❌ Stream WebSocket error:",e)}),this.socket.io.on("reconnect",e=>{this.logger.debug(`🔄 Stream WebSocket reconnected after ${e} attempts`),this.reconnectionManager.reset(),""!==this.config.authToken&&this.authenticate(this.config.authToken)}),this.socket.io.on("reconnect_attempt",()=>{this.reconnectionManager.recordAttempt(),this.logger.debug(`🔄 Stream WebSocket reconnect attempt ${this.reconnectionManager.getStatusString()}`)}),this.socket.io.on("reconnect_failed",()=>{this.logger.error("❌ Stream WebSocket max reconnection attempts reached")}),Promise.resolve(void 0)},"Stream WebSocket connection setup",this.logger,e=>{throw t(e),e})})}authenticate(e){if(!this.socket?.connected)throw new Yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw En("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(Ld,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw En("tokenName","Token name");if(!this.socket?.connected)throw new Yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=zn(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((o,i)=>{const r=setTimeout(()=>{this.pendingSubscriptions.delete(n),i(new Error(`Subscription to ${e} timed out after ${this.config.subscriptionTimeout}ms`))},this.config.subscriptionTimeout);this.pendingSubscriptions.set(n,{resolve:o,reject:i,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(Ud,{tokenName:n})})}unsubscribeFromStream(e){const t=zn(e);if(!this.subscribedRooms.has(t))return void this.logger.debug(`📡 Not subscribed to ${t}, skipping unsubscribe`);this.logger.debug(`📡 Unsubscribing from stream: ${t}`),this.socket?.connected&&this.socket.emit(Od,{tokenName:t}),this.subscribedRooms.delete(t),this.roomCallbacks.delete(t);const n=this.pendingSubscriptions.get(t);n&&(clearTimeout(n.timeoutId),this.pendingSubscriptions.delete(t));for(const e of this.eventBuffer.keys())if(e.endsWith(`:${t}`)){this.eventBuffer.delete(e);const t=this.eventBufferTimeouts.get(e);t&&(clearTimeout(t),this.eventBufferTimeouts.delete(e))}}sendChatMessage(e,t){if(""===e)throw En("tokenName","Token name");if(""===t)throw En("content","Message content");if(!this.socket?.connected)throw new Yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=zn(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Md,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw En("tokenName","Token name");if(""===t)throw En("emoji");if(!this.socket?.connected)throw new Yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const o=zn(e);this.logger.debug(`📡 Sending reaction to ${o}: ${t}`),this.socket.emit($d,{tokenName:o,emoji:t,streamTime:n})}sendTypingStart(e){if(""===e)throw En("tokenName","Token name");if(!this.socket?.connected)throw new Yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=zn(e);this.logger.debug(`📡 Sending typing_start to ${t}`),this.socket.emit(Kd,{tokenName:t})}sendTypingStop(e){if(""===e)throw En("tokenName","Token name");if(!this.socket?.connected)throw new Yt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Yt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const t=zn(e);this.logger.debug(`📡 Sending typing_stop to ${t}`),this.socket.emit(qd,{tokenName:t})}subscribeTokenBanned(e,t){const n=zn(e),o={onTokenBanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onTokenBanned:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeTokenUnbanned(e,t){const n=zn(e),o={onTokenUnbanned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onTokenUnbanned:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeModeratorInviteCreated(e,t){const n=zn(e),o={onModeratorInviteCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorInviteCreated:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeModeratorAdded(e,t){const n=zn(e),o={onModeratorAdded:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorAdded:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeModeratorRemoved(e,t){const n=zn(e),o={onModeratorRemoved:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorRemoved:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeModeratorRoleUpdated(e,t){const n=zn(e),o={onModeratorRoleUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onModeratorRoleUpdated:t,...o}=e;this.roomCallbacks.set(n,o)}}}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=zn(e),o={onTradeExecuted:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onTradeExecuted:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribePoolMetadataUpdated(e,t){const n=zn(e),o={onPoolMetadataUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onPoolMetadataUpdated:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribePoolSocialLinksUpdated(e,t){const n=zn(e),o={onPoolSocialLinksUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onPoolSocialLinksUpdated:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribePoolBadgeAssigned(e,t){const n=zn(e),o={onPoolBadgeAssigned:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onPoolBadgeAssigned:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeHolderCountUpdated(e,t){const n=zn(e),o={onHolderCountUpdated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onHolderCountUpdated:t,...o}=e;this.roomCallbacks.set(n,o)}}}subscribeCommentCreated(e,t){const n=zn(e),o={onCommentCreated:t};return this.roomCallbacks.set(n,{...this.roomCallbacks.get(n),...o}),()=>{const e=this.roomCallbacks.get(n);if(e){const{onCommentCreated:t,...o}=e;this.roomCallbacks.set(n,o)}}}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 Yt("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 o=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:o},e&&(this.globalFeedCallbacks=e),this.logger.debug("📡 Subscribing to global feed"),this.socket.emit(Fu)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(Ru),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 Lu(e){if(Ho(e.tokenName,"tokenName",oo),!(null==(t=e.reason)||""===t||"string"==typeof t&&!jo(t)&&t.length<=uo.BAN_REASON.MAX_LENGTH))throw new Yt(`reason must be at most ${uo.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Mu extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async banToken(e){Lu(e);const t=ut,n={tokenName:zn(e.tokenName)};if(void 0!==e.reason)try{Oo(e.reason,"reason",!0),e.reason.trim().length>0&&(n.reason=e.reason)}catch{}const o=await this.http.post(t,n,this.getDualAuthHeaders());return{ban:this.extractData(o),tokenName:zn(e.tokenName)}}async unbanToken(e){!function(e){Ho(e.tokenName,"tokenName",oo)}(e);const t=this.buildEndpoint(mt,{tokenName:e.tokenName});return Mn(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:zn(e.tokenName)}}async listTokenBans(e={}){!function(e){Ko(0,void 0,so,e.pageSize)}(e);const t=ht,n=this.buildPaginationParams(e,so);this.addOptionalFilterParams(n,e,["search"]);const o=await this.http.get(t,n,this.getDualAuthHeaders()),i=this.extractData(o);return{items:i.bans,pageInfo:i.pageInfo}}async getTokenBan(e){!function(e){Ho(e.tokenName,"tokenName",oo)}(e);const t=this.buildEndpoint(gt,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),o=this.extractDataOrNull(n);return{banned:null!==o,...null!==o&&{ban:o},tokenName:zn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class $u extends Zo{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(!Mo(e))throw En("tokenName","Token name");const t=zn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.vaultAddress;this.cacheMisses++;try{const n=await this.poolService.resolveTokenNameToVault(e);if(null!==n&&""!==n){const e=this.parseVaultAddressToTokenClassKey(n);this.setCacheEntry(t,{vaultAddress:n,tokenClassKey:e,cachedAt:Date.now()})}return n}catch{return null}}async resolveTokenClassKey(e){if(!Mo(e))throw En("tokenName","Token name");const t=zn(e),n=this.getCacheEntry(t);if(null!==n)return this.cacheHits++,this.updateAccessOrder(t),n.tokenClassKey;this.cacheMisses++;const o=await this.poolService.resolveTokenNameToVault(e);if(null===o||""===o)throw Tn(e);const i=this.parseVaultAddressToTokenClassKey(o);return this.setCacheEntry(t,{vaultAddress:o,tokenClassKey:i,cachedAt:Date.now()}),i}get(e){const t=this.getCacheEntry(zn(e));return t?.vaultAddress??null}getCacheEntry(e){return this.cache.get(e)??null}setCacheEntry(e,t){this.cache.size>=$u.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=zn(e),o=this.parseVaultAddressToTokenClassKey(t);this.setCacheEntry(n,{vaultAddress:t,tokenClassKey:o,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:$u.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(zn(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:o}of e){const e=zn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:o,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return tc(e)}catch(e){if(e instanceof Yt)throw Cn("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}$u.MAX_CACHE_SIZE=1e4;class Ku extends Yo{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return qn(()=>this.http.get(xt),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return qn(()=>this.http.get(_t,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return qn(()=>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}`})}async getPremintQuote(e){return qn(()=>this.http.get(Rt,{amount:e}),{errorContext:"Failed to get premint quote"})}}class qu extends Ga{constructor(e,t,n,o=!1,i){super(e,t,n,o,i)}async emitTradeExecuted(e,t){this.validateTokenName(e,io);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,io);const o={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(o)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,io);const o={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,io);const o={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,io);const o={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,io);const o={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,io);const o={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,io);const o={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitTokenBanned(e,t){this.validateTokenName(e,io);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,io);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,io);const o={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,io);const o={action:"moderator_removed",tokenName:e,payload:t,broadcast:n};await this.emitEvent(o)}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 o=await this.http.get(t,Object.keys(n).length>0?n:void 0,this.getDualAuthHeaders());return this.extractData(o)}async isUserOnline(e){this.validateRequiredString(e,"userAddress","User Address");const t=await this.getConnectedClients({userAddress:e,limit:1});if(0===t.clients.length)return{online:!1};const n=t.clients[0];return{online:!0,socketId:n.socketId,rooms:n.rooms,connectedAt:n.connectedAt}}async getOnlineUsers(e){if(!Array.isArray(e)||0===e.length)throw new tn("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,io);const n={tokenName:e};void 0!==t?.authenticated&&(n.authenticated=t.authenticated),void 0!==t?.limit&&(n.limit=t.limit);const o=await this.getConnectedClients(n);return{clients:o.clients,count:o.summary.totalConnected,authenticatedCount:o.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,io);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,io);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,io);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}var Gu,Wu;!function(e){e.PROCESSED="PROCESSED",e.COMPLETED="COMPLETED",e.SUCCESS="SUCCESS",e.FAILED="FAILED",e.ERROR="ERROR",e.PROCESSING="PROCESSING",e.PENDING="PENDING"}(Gu||(Gu={})),function(e){e.PENDING="pending",e.PROCESSING="processing",e.COMPLETED="completed",e.FAILED="failed",e.TIMEOUT="timeout"}(Wu||(Wu={}));const Hu={[Gu.PROCESSED]:Wu.COMPLETED,[Gu.COMPLETED]:Wu.COMPLETED,[Gu.SUCCESS]:Wu.COMPLETED,[Gu.FAILED]:Wu.FAILED,[Gu.ERROR]:Wu.FAILED,[Gu.PROCESSING]:Wu.PROCESSING,[Gu.PENDING]:Wu.PENDING};class zu{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 o=n??this.defaultTtlMs,i={value:t};o>0&&(i.expiresAt=Date.now()+o),this.cache.set(e,i)}has(e){return void 0!==this.get(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}}async function ju(e,t,n,o={}){const{logger:i,cacheNullish:r=!1,keyGenerator:s}=o,a=s?s(e):String(e),c=n.get(a);if(void 0!==c)return i&&i.debug(`Cache hit for key: ${a}`),c;i&&i.debug(`Cache miss for key: ${a}, fetching...`);const l=await t();return null!=l?(n.set(a,l),i&&i.debug(`Cached result for key: ${a}`)):r&&(n.set(a,l),i&&i.debug(`Cached nullish result for key: ${a}`)),l}class Vu extends Zo{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 zu(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Vu.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof J||(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)=>{Hr(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:",hn(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=J(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],o=n.status??n.Status;"string"==typeof o&&(this.logger.debug(`📡 [Event Buffer] Buffering event for ${e}: ${o}`),this.eventBuffer.size>=this.MAX_BUFFER_SIZE&&this.logger.warn(`📡 [Event Buffer] Buffer approaching limit (${this.eventBuffer.size}/${this.MAX_BUFFER_SIZE})`),this.eventBuffer.set(e,n))}this.debug&&this.logger.debug(`📡 [WebSocket Event] "${e}":`,JSON.stringify(t,null,2))}),this.hasOnAnyListener=!0},"Socket.IO connection failed",this.logger,e=>{throw this.logger.error("Socket.IO connection failed:",e),t(e),e}).catch(t)})}async monitorTransaction(e,t){this.listeners.set(e,t),this.logger.debug(`📡 Starting to monitor transaction: ${e}`),this.logger.debug(`📡 WebSocket connected: ${!!this.socket&&this.socket.connected}`);const n=this.eventBuffer.get(e);null!=n&&(this.logger.debug(`📡 [Event Buffer] Found buffered event for ${e}, delivering immediately`),setImmediate(()=>{this.processTransactionEvent(e,n,t)}),this.eventBuffer.delete(e));const o=this.config.timeout??3e5,i=setTimeout(()=>{if(this.listeners.has(e)){const n=Math.round(o/1e3),i={transactionId:e,status:Wu.TIMEOUT,message:`Transaction monitoring timeout - no response after ${n} seconds`,timestamp:Date.now()};this.logger.debug(`📡 Transaction timeout for ${e} (${n}s)`),t(i),this.listeners.delete(e),this.timeouts.delete(e),this.socket?.off(e)}},o);if(this.timeouts.set(e,i),this.socket?.connected)this.socket.off(e),this.logger.debug(`📡 Listening for transaction updates: ${e}`),this.logger.debug(`📡 WebSocket connection ID: ${String(this.socket.id)}`),this.logger.debug(`📡 WebSocket URL: ${this.config.url}`),this.socket.on(e,n=>{this.processTransactionEvent(e,n,t)});else{const n={transactionId:e,status:Wu.FAILED,message:"WebSocket not connected - cannot monitor transaction",timestamp:Date.now()};t(n),this.listeners.delete(e),this.timeouts.delete(e)}}processTransactionEvent(e,t,n){this.logger.debug(`📡 Socket.IO transaction update for ${e}:`,JSON.stringify(t,null,2));const o=t,i=o?.data,r=o?.status??o?.Status??i?.status??i?.Status;let s=o?.message??o?.Message??i?.message??i?.Message??o?.error??i?.error;Mo(s)||(s=r===Gu.FAILED||r===Gu.ERROR?"Transaction failed - check transaction details":r===Gu.COMPLETED||r===Gu.PROCESSED||r===Gu.SUCCESS?"Transaction completed successfully":null!=r?`Transaction status: ${String(r)}`:"Unknown transaction status");const a=o?.blockHash??i?.blockHash,c=o?.gasUsed??i?.gasUsed,l=o?.Data??i?.Data,d={transactionId:e,status:this.mapSocketStatus(r),message:"string"==typeof s?s:"Transaction update received",timestamp:Date.now(),...null!=a?{blockHash:a}:{},...null!=c?{gasUsed:c}:{},...null!=l?{data:l}:{}};if(this.logger.debug(`📡 Mapped status for ${e}: ${String(r)} -> ${d.status}`),this.logger.debug(`📡 Final message: "${String(s)}"`),n(d),d.status===Wu.COMPLETED||d.status===Wu.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===Wu.COMPLETED?t(e):e.status!==Wu.FAILED&&e.status!==Wu.TIMEOUT||n(new Error(`Transaction ${String(e.status)}: ${e.message}`))})})}mapSocketStatus(e){const t=e?.toUpperCase();return Hu[t]??Wu.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")),Vu.instances.delete(this)}static cleanupAll(e=!1){for(const e of Vu.instances)e.disconnect();Vu.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Vu.instances=new Set;class Xu extends Yo{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 Yt("limit must be between 1 and 50","limit","INVALID_LIMIT");this.logger.debug("Fetching weekly challenge leaderboard",{limit:t});const n={limit:String(t)},o=await this.http.get(Bt.GET_LEADERBOARD,n),i=this.extractData(o);return this.logger.debug("Fetched weekly challenge leaderboard",{count:i.count}),{leaderboard:i}}async getTokenHistory(e){const{vaultAddress:t}=e;if("string"!=typeof t||""===t.trim())throw new Yt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=Bt.GET_TOKEN_HISTORY.replace(":vaultAddress",encodeURIComponent(t)),o=await this.http.get(n),i=this.extractData(o);return this.logger.debug("Fetched token weekly history",{count:i.length}),{snapshots:i}}}class Qu extends ei{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return jn(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 Ju extends Qu{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 Yu extends sc{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new Ju(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())})`),Hr(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 Hr(async()=>{const e=await async function(e){const{cache:t,fetchFn:n,logger:o,itemTypeName:i="items"}=e;if(t.has()){const e=t.getAll();return o&&o.debug(`Returning ${e.length} cached ${i}`),{items:e,fetchedAt:t.getFetchTimestamp()??Date.now(),itemCount:e.length}}o&&o.debug(`Fetching all ${i} (no cache)`);const r=await n();try{t.setAll(r)}catch(e){o&&o.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=ic(e),n=this.cache.getByTokenId(t);return n||(await ju("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=ic(e);await ju("wrappable:check",()=>this.fetchAllWrappableTokens(),{get:()=>this.cache.has()?{}:void 0,set:()=>{}},{logger:this.logger});const n=this.cache.getByTokenId(t),o=void 0!==n,i={isWrappable:o,tokenId:t};return o&&(i.wrapCounterpart=n.wrapCounterpart),i}getCacheStats(){return this.cache.getStats()}clearCache(){this.cache.clear()}}class Zu extends Zo{constructor(e){super(!1,e.logger),this.galaConnectClient=e.galaConnectClient,this.wrappableTokenService=e.wrappableTokenService,this.wallet=e.wallet,this.walletAddress=e.walletAddress}async wrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new Yt(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===t.channel)throw new Yt(`Cannot wrap ${t.symbol} - it's already on asset channel. Use unwrapToken() instead.`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new Yt(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:!0})}async unwrapToken(e){this.requireWallet();const t=await this.wrappableTokenService.getWrappableToken(e.tokenId);if(!t)throw new Yt(`Token not found or not wrappable: ${this.formatTokenId(e.tokenId)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==t.channel)throw new Yt(`Cannot unwrap ${t.symbol} - it's not on asset channel. Use wrapToken() instead.`,"tokenId","NOT_ON_ASSET_CHANNEL");const n=await this.wrappableTokenService.getWrapCounterpart(e.tokenId);if(!n)throw new Yt(`Counterpart token not found for ${t.symbol}`,"tokenId","COUNTERPART_NOT_FOUND");return this.executeChannelBridge({sourceToken:t,destinationToken:n,amount:e.amount,...void 0!==e.recipient&&""!==e.recipient&&{recipient:e.recipient},...void 0!==e.memo&&""!==e.memo&&{memo:e.memo},isWrap:!1})}async estimateWrapFee(e,t){if("string"==typeof e&&0===e.length)throw En("tokenId","Token identifier");if(0===t.length)throw En("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new Yt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"===n.channel)throw new Yt(`Cannot wrap ${n.symbol} - it's already on asset channel`,"tokenId","ALREADY_ON_ASSET_CHANNEL");const o=this.determineChannelRouting(n,!0);return{fee:"0",feeToken:"GALA",authorizationType:o.authType,feeChannel:o.sourceChannel}}async estimateUnwrapFee(e,t){if("string"==typeof e&&0===e.length)throw En("tokenId","Token identifier");if(0===t.length)throw En("amount");const n=await this.wrappableTokenService.getWrappableToken(e);if(!n)throw new Yt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");if("asset"!==n.channel)throw new Yt(`Cannot unwrap ${n.symbol} - it's not on asset channel`,"tokenId","NOT_ON_ASSET_CHANNEL");const o=this.determineChannelRouting(n,!1);return{fee:"0",feeToken:"GALA",authorizationType:o.authType,feeChannel:o.sourceChannel}}getWrapStatus(e){if(0===e.length)throw En("transactionId");return{success:!0,status:"completed",transactionId:e,fromToken:"",toToken:"",amount:"",fromChannel:"",toChannel:""}}async executeChannelBridge(e){const{sourceToken:t,destinationToken:n,amount:o,recipient:i,isWrap:r}=e;if(!this.wallet||void 0===this.walletAddress||0===this.walletAddress.length)throw new Yt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED");const s=this.walletAddress,a=this.determineChannelRouting(t,r),c=`galaswap-operation-${Ms()}`,l=js,d={quantity:o,tokenInstance:{collection:t.galaChainDescriptor.collection,category:t.galaChainDescriptor.category,type:t.galaChainDescriptor.type,additionalKey:t.galaChainDescriptor.additionalKey,instance:"0"},destinationChainId:a.destinationChannelId,recipient:i??s,wrap:!0,uniqueKey:c};return this.logger.debug(`[WrapService] ${r?"Wrap":"Unwrap"} message (pre-signing)`,{amount:o,uniqueKey:c,sourceChannel:a.sourceChannel}),this.executeWrapBridgeRequest({sourceToken:t,destinationToken:n,amount:o,message:d,routing:a,isWrap:r,senderAddress:s,typedDataTypes:l})}async executeWrapBridgeRequest(e){const{sourceToken:t,destinationToken:n,amount:o,message:i,routing:r,isWrap:s,typedDataTypes:a}=e;try{const e=await this.wallet.signTypedData($s,a,i),c=`Ethereum Signed Message:\n${N({domain:$s,message:i,primaryType:"GalaTransaction",types:a}).length}`,l={...i,signature:e,prefix:c,types:a,domain:$s};this.logger.debug(`[WrapService] ${s?"Wrap":"Unwrap"} request (signed)`,{sourceToken:t.symbol,destinationToken:n.symbol,amount:o,channel:r.sourceChannel});const d=await this.galaConnectClient.requestBridgeOut(l);if(this.logger.debug("[WrapService] RequestBridgeOut response",{status:d.Status,hasData:"Data"in d}),function(e){return"object"==typeof e&&null!==e&&"Status"in e&&"number"==typeof e.Status&&1!==e.Status}(d)){const e=`Status=${d.Status}`,i="string"==typeof d.Message&&d.Message.length>0?`: ${d.Message}`:"";return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:o,fromChannel:r.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`GalaChain request failed (${e}${i})`}}if(function(e){return"object"==typeof e&&null!==e&&"Data"in e&&"string"==typeof e.Data}(d)){const e=d.Data;this.logger.debug("[WrapService] Step 1 complete, bridgeRequestId:",e);const i={bridgeFromChannel:r.sourceChannel,bridgeRequestId:e};this.logger.debug("[WrapService] Step 2 - BridgeTokenOut",{bridgeFromChannel:i.bridgeFromChannel});const a=await this.galaConnectClient.bridgeTokenOut(i);return this.logger.debug("[WrapService] BridgeTokenOut response",{status:a.Status,hash:a.Hash}),1!==a.Status?{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:o,fromChannel:r.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`BridgeTokenOut failed: status=${String(a.Status)}`}:{success:!0,transactionId:a.Hash??e,fromToken:t.symbol,toToken:n.symbol,amount:o,fromChannel:r.sourceChannel,toChannel:s?"asset":n.channel??"music",completedAt:Date.now()}}return{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:o,fromChannel:r.sourceChannel,toChannel:s?"asset":n.channel??"music",error:`Unexpected response format from GalaChain (type=${typeof d})`}}catch(e){const i=hn(e);return this.logger.error(`[WrapService] ${s?"Wrap":"Unwrap"} operation failed:`,i),{success:!1,fromToken:t.symbol,toToken:n.symbol,amount:o,fromChannel:r.sourceChannel,toChannel:s?"asset":n.channel??"music",error:i}}}determineChannelRouting(e,t){if(t){return{sourceChannel:e.channel??"music",destinationChannelId:rs,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:ss,authType:"automatic"}}requireWallet(){if(void 0===this.walletAddress||0===this.walletAddress.length)throw new Yt("Wallet required for wrap/unwrap operations. Initialize SDK with a private key.","wallet","WALLET_REQUIRED")}formatTokenId(e){return"string"==typeof e?e:Zr(e)}}const eh=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function th(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>th(e,t+1));if(e instanceof Map){const n={};for(const[o,i]of e.entries()){const e=String(o);n[e]=eh.has(e.toLowerCase())?"[REDACTED]":th(i,t+1)}return n}if("object"==typeof e){const n={};for(const[o,i]of Object.entries(e))n[o]=eh.has(o.toLowerCase())?"[REDACTED]":th(i,t+1);return n}return e}class nh{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new Qn({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??"https://lpad-backend-dev1.defi.gala.com",o=t.timeout??6e4;this.axios=Cl(n,o),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 Hr(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:rr(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]":th(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:th(t.params),data:n,isFormData:e.data instanceof FormData,contentType:t.headers?.["Content-Type"]??"not set"});const o=await this.axios.request(t),i=function(e){const t={};if(null==e||"object"!=typeof e)return t;for(const[n,o]of Object.entries(e))"string"==typeof o?t[n.toLowerCase()]=o:"number"!=typeof o&&"boolean"!=typeof o||(t[n.toLowerCase()]=String(o));return t}(o.headers);return this.logger.debug("Response:",{status:o.status,data:th(o.data),transactionId:i["x-transaction-id"],blockNumber:i["x-block-number"]}),{data:o.data,headers:i,status:o.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 Hr(async()=>{const t=await this.auth.generateCustomSignature(e);return this.logger.debug("Generated custom signature:",{message:e,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}),{signature:t.signature,address:t.address,ethereumAddress:this.auth.getEthereumAddress()}},"Failed to generate custom signature for message",this.logger)}async signWithGalaChain(e,t,n=p.SIGN_TYPED_DATA){const o=this.auth.getPrivateKey(),i={};Object.entries(t).forEach(([e,t])=>{void 0!==t&&(i[e]=t)});const r=new y(o);return await r.sign(e,i,n)}setupInterceptors(){this.requestInterceptorId=this.axios.interceptors.request.use(async e=>{if(e.headers??(e.headers={}),this.auth?.hasWallet()){const t=await this.auth.generateSignature();e.headers.Sign=t.signature,this.logger.debug("Added signature header:",{address:t.address,message:t.message,timestamp:t.timestamp})}else this.logger.debug("No wallet configured - skipping signature header");return e.data instanceof FormData||(e.headers["Content-Type"]="application/json"),this.logger.debug("Final request header keys being sent:",Object.keys(e.headers)),e},e=>Promise.reject(e)),this.responseInterceptorId=this.axios.interceptors.response.use(e=>e,e=>{const t=e;if(void 0!==t.response){const n=t.response.data,o={message:n?.message??hn(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=o,this.logger.error("Backend error:",o)}else void 0!==t.request?this.logger.error("Network error:",t.message??"Unknown error"):this.logger.error("Request setup error:",t.message??"Unknown error");return Promise.reject(e)})}cleanup(){void 0!==this.requestInterceptorId&&(this.axios.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=void 0),void 0!==this.responseInterceptorId&&(this.axios.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=void 0),this.logger.debug("Interceptors cleaned up")}}class oh extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class ih extends oh{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class rh 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 sh(e,t){if($o(e))throw new oh(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new oh(`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 oh(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function ah(e,t,n,o){sh(e,t);const i=e,r=i.data??{};if(!function(e){if($o(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 oh(`Invalid trade data received for transaction ${t}`);const s={transactionId:t,type:n,method:"native"===o.type?"native":"exact",inputAmount:r.inputQuantity??o.amount,outputAmount:r.outputQuantity??o.expectedAmount??"0",totalFees:r.totalFees??"0",tokenName:o.tokenName,vaultAddress:r.vaultAddress??"",timestamp:Date.now()};return void 0!==i.blockHash&&(s.blockHash=i.blockHash),void 0!==i.gasUsed&&(s.gasUsed=i.gasUsed),void 0!==o.slippageToleranceFactor&&(s.slippageTolerance=o.slippageToleranceFactor),s}function ch(e){if(e&&function(e){return"privateKey"===e.providerType}(e))return e.getWallet()}class lh{constructor(e){this.logger=e??new Qn({debug:!1,context:"LiquidityEventExtractor"})}walkPayloadForLiquidityEvents(e,t){const n=[],o=new WeakSet,i=(e,r=0)=>{if(r>50)this.logger.debug("Payload nesting exceeded maximum depth of 50");else if(null!=e&&!Mo(e)&&"object"==typeof e){if(o.has(e))return;o.add(e);const s=this.extractLiquidityFromObject(e);s&&!t.has(s.transactionId)&&(n.push(s),t.add(s.transactionId));for(const t of Object.values(e))i(t,r+1)}};return i(e,0),n}extractLiquidityFromObject(e){const t=this.extractTransactionId(e);if(null===t||""===t)return null;const n=e.Data,o=null==n||"object"!=typeof n||Array.isArray(n)?e:n,i=this.extractPositionId(o),r=this.extractPoolHash(o),s=this.extractAmounts(o),a=this.extractUserAddress(o),c=this.extractPoolFee(o);if(null===i||""===i||null===r||""===r||null===s||null===a||""===a||null===c)return null;const l=this.extractPoolAlias(o),d=this.extractUserBalanceDelta(o),u=this.extractTimestamp(o),h=d?.token0Balance?.collection,g=d?.token1Balance?.collection,m={transactionId:t,positionId:i,poolHash:r,poolFee:c,amounts:s,userAddress:a};return void 0!==h&&(m.token0=h),void 0!==g&&(m.token1=g),void 0!==u&&(m.timestamp=u),void 0!==l&&(m.poolAlias=l),void 0!==d&&(m.userBalanceDelta=d),m}extractTransactionId(e){const t=["transactionId","txId","tx_id","hash","txHash","id"];for(const n of t){const t=e[n];if(Mo(t))return t}return null}extractPositionId(e){const t=["positionId","position_id","tokenId","nftId"];for(const n of t){const t=e[n];if(Mo(t))return t}return null}extractPoolHash(e){const t=["poolHash","pool_hash","pool"];for(const n of t){const t=e[n];if(Mo(t))return t}return null}extractPoolAlias(e){const t=["poolAlias","pool_alias"];for(const n of t){const t=e[n];if(Mo(t))return t}}extractAmounts(e){const t=e.amounts;if(Array.isArray(t)&&t.length>=2){const e=String(t[0]).trim(),n=String(t[1]).trim();if(""!==e&&""!==n)return[e,n]}const n=e.amount0??e.amount0Desired,o=e.amount1??e.amount1Desired;return void 0!==n&&void 0!==o?[String(n),String(o)]:null}extractUserAddress(e){const t=["userAddress","user","owner","from","sender","wallet","address"];for(const n of t){const t=e[n];if(Mo(t))return t}return null}extractPoolFee(e){const t=["poolFee","fee","feeTier","feeTierBps"];for(const n of t){const t=e[n];if("number"==typeof t)return this.normalizeFee(t);if(Mo(t)){const e=Ao(t,NaN);if(isFinite(e))return this.normalizeFee(e)}}return null}normalizeFee(e){return 1===e||1e4===e?1e4:.3===e||3e3===e?3e3:.05===e||500===e?500:Number.isInteger(e)?e:e<1?Math.round(1e4*e):e}extractTimestamp(e){const t=["timeStamp","timestamp","time","createdAt","date"];for(const n of t){const t=e[n];if("number"==typeof t)return t;if(Mo(t)){const e=new Date(t).getTime();if(isFinite(e))return e}}}extractUserBalanceDelta(e){const t=e.userBalanceDelta;if(null==t||"object"!=typeof t)return;const n=t,o=this.extractBalanceObject(n.token0Balance),i=this.extractBalanceObject(n.token1Balance);if(!o&&!i)return;const r={};return void 0!==o&&(r.token0Balance=o),void 0!==i&&(r.token1Balance=i),r}extractBalanceObject(e){if(null==e||"object"!=typeof e)return;const t=e,n=t.collection,o=t.category,i=t.type,r=t.additionalKey,s=t.quantity,a=t.owner;return Mo(n)&&Mo(o)&&Mo(i)&&Mo(r)&&Mo(s)&&Mo(a)?{collection:n,category:o,type:i,additionalKey:r,quantity:s,owner:a}:void 0}}class dh{constructor(e){let t,n;e.walletProvider?(t=e.walletProvider,n=ch(e.walletProvider)):e.wallet&&(n=e.wallet,t=Xr.fromWallet(e.wallet)),this.wallet=n;let o=null,i="PROD";if(void 0!==e.env?(i=e.env,o=Yr(e.env)):e.baseUrl?.includes("dev")||e.baseUrl?.includes("qa")||e.baseUrl?.includes("test")||e.baseUrl?.includes("stage")?(i="STAGE",o=Yr("STAGE")):(i="PROD",o=Yr("PROD")),this.environment=i,this.config={baseUrl:o.launchpadBaseUrl,galaChainBaseUrl:o.galaChainBaseUrl,bundleBaseUrl:o.bundleBaseUrl,webSocketUrl:o.webSocketUrl,gdexWebSocketUrl:o.gdexWebSocketUrl,dexApiBaseUrl:o.dexApiBaseUrl,dexBackendBaseUrl:o.dexBackendBaseUrl,launchpadFrontendUrl:o.launchpadFrontendUrl,timeout:3e4,debug:!1,...e},this.logger=new Qn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?dh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?dh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??dh.DEFAULT_CALCULATE_AMOUNT_MODE,this.pricingConcurrency=e.pricingConcurrency??5,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new Qr({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Wr,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new nh(this.auth,this.config),this.sessionAuth=new jr(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new nh(this.auth,{...this.config,baseUrl:this.config.galaChainBaseUrl}),this.bundleHttp=new nh(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new nh(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new nh(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=Cl(this.config.galaChainBaseUrl,this.config.timeout??3e4),this.cache=new ti(e.debug??!1),this.launchpadService=new Gl(this.http,this.jwtAuth),this.tokenResolverService=new $u(this.launchpadService.poolService),this.launchpadAPI=new Br(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode),this.galaChainService=new Sl(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 vc(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Vu({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Id(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService),this.dexQuoteService=new Uc(this.dexBackendHttp,this.config.dexBackendBaseUrl,e.debug??!1,e.dexQuoteNetworkTimeout??3e4),this.gswapService=new xl({privateKey:n?.privateKey,getWalletAddress:()=>this.wallet?this.getAddress():void 0,bundlerBaseUrl:this.config.bundleBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,dexBackendHttp:this.dexBackendHttp},this.websocketService,this.dexQuoteService),this.dexPoolService=new Rc(this.dexBackendHttp,this.config.dexBackendBaseUrl,this.gswapService,this.pricingConcurrency,e.debug??!1),this.nftCollectionService=new md(this.galaChainHttp),this.tradingQuotesService=new Ku(this.http,e.debug??!1)}createOverrideSdk(e){if(!Mo(e))throw Nn("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Nn('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n(e),o={...this.config,wallet:t};return new dh(o)}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw En("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Yt("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?ch(e):void 0}getWallet(){return this.wallet}get events(){return this.getEventsBatcherService()}getWalletProvider(){return this.auth.getWalletProvider()}hasWallet(){return this.auth.hasWallet()}getConfig(){const{wallet:e,walletProvider:t,streamAdminApiKey:n,userApiKey:o,accessToken:i,headers:r,...s}=this.config;return{...s,...void 0!==n&&{streamAdminApiKey:"[REDACTED]"},...void 0!==o&&{userApiKey:"[REDACTED]"},...void 0!==i&&{accessToken:"[REDACTED]"},...void 0!==r&&{headers:Object.fromEntries(Object.keys(r).map(e=>[e,"[REDACTED]"]))},environment:this.environment,slippageToleranceFactor:this.slippageToleranceFactor,maxAcceptableReverseBondingCurveFeeSlippageFactor:this.maxAcceptableReverseBondingCurveFeeSlippageFactor,calculateAmountMode:this.calculateAmountMode,gasFee:Hn.GAS_FEE}}getVersion(){return Ua}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Nn("launchpadFrontendUrl not configured in SDK","launchpadFrontendUrl");return`${t.replace(/\/$/,"")}/buy-sell/${e}`}async fetchPools(e){const t=await this.launchpadService.fetchPools(e??{});return await this.warmCacheFromPools(t.items),t}async fetchAllPools(e){const t=await this.launchpadService.fetchAllPools(e);return await this.warmCacheFromPools(t.items),t}async fetchDexPools(e={}){return this.dexPoolService.fetchDexPools(e)}async fetchAllDexPools(e={}){return this.dexPoolService.fetchAllDexPools(e)}async fetchCompositePoolData(e){return this.dexQuoteService.fetchCompositePoolData(e)}async calculateDexPoolQuoteExactAmountLocal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountLocal(e)}async calculateDexPoolQuoteExactAmountExternal(e){return this.dexQuoteService.calculateDexPoolQuoteExactAmountExternal(e)}async calculateDexPoolQuoteExactAmount(e,t="local"){return this.dexQuoteService.calculateDexPoolQuoteExactAmount(e,t)}async fetchTokenDistribution(e){return this.launchpadService.fetchTokenDistribution(e)}async getTopHolders(e,t=10){const n=await this.fetchTokenDistribution(e),o=Math.min(t,100);return n.holders.slice(0,o).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),o=n.holders.findIndex(e=>e.address.toLowerCase()===t.toLowerCase());return-1===o?null:{rank:o+1,balance:n.holders[o].balance,holderCount:n.totalHolders}}async getHoldersByBalance(e,t){const n=await this.fetchTokenDistribution(e),o=t?.minBalance??0,i=t?.maxBalance??1/0,r=Math.min(t?.limit??100,1e3),s=new Map;return n.holders.forEach((e,t)=>{s.set(e.address,t+1)}),n.holders.filter(e=>{const t=parseFloat(e.balance);return t>=o&&t<=i}).map(e=>({...e,rank:s.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 fetchTokenBadges(e){return this.launchpadService.fetchTokenBadges(e)}async fetchTokenPrice(e){const{tokenName:t,tokenId:n}=e,{hasA:o}=Wo(e,"tokenName","tokenId",{description:"token identifier"});if(o&&void 0!==t&&""!==t)return this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e));const i=n;try{return await this.dexService.fetchTokenPrice({tokenId:i})}catch(e){const t=function(e){if(yn(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=zn((await this.fetchTokenDetails(i)).name);if(!/^[a-z0-9]{3,20}$/.test(t))throw this.logger.error(`Token name extracted from GalaChain doesn't match launchpad format: "${t}"`),e;return this.logger.debug(`Falling back to launchpad pricing using extracted token name: "${t}"`),this.dexService.fetchLaunchpadTokenSpotPrice(t,e=>this.launchpadAPI.calculateBuyAmount(e),e=>this.fetchPoolDetails(e))}catch(t){throw this.logger.error(`Launchpad fallback failed: ${hn(t)}`),e}}throw e}}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(null==t)throw new Error(Sn(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,o=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=o.currentSupply,n.reverseBondingCurveMaxFeeFactor=o.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=o.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=o.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n=t(e)??this.getAddress();return this.galaChainService.fetchGalaBalance({owner:n,collection:"GALA",category:"Unit",additionalKey:"none",type:"none",instance:"0"})}getBridgeService(e){if(!this._bridgeService){const t=this.getWallet();if(!t)throw new Error("Bridge operations require a wallet. Configure SDK with a wallet first.");const n=e?.solanaPrivateKey??process.env.SOLANA_PRIVATE_KEY;this._bridgeService=new Ba({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 dc(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new Yu(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 Ia({baseUrl:this.config.dexApiBaseUrl,...void 0!==this.config.galaChainBaseUrl&&""!==this.config.galaChainBaseUrl?{galachainBaseUrl:this.config.galaChainBaseUrl}:{},walletAddress:e})}return this._galaConnectClient}getWrapService(){if(!this._wrapService){const e=this.getWallet();this._wrapService=new Zu({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Bd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Dd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamChatService}getBanService(){return this._banService??(this._banService=new Ya(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._banService}getTokenBanService(){return this._tokenBanService??(this._tokenBanService=new Mu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._tokenBanService}getAIModerationService(){return this._aiModerationService??(this._aiModerationService=new Wa(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._aiModerationService}getWeeklyChallengeService(){return this._weeklyChallengeService??(this._weeklyChallengeService=new Xu(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new fd(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Cd(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new pd(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new wc(this.http,this.config.debug??!1)),this._clientConfigService}getApiKeyService(){return this._apiKeyService??(this._apiKeyService=new ja(this.http,this.jwtAuth,this.config.debug??!1)),this._apiKeyService}getModeratorService(){return this._moderatorService??(this._moderatorService=new Xl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new xc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new Td(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new qu(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new Fc(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._contentReactionService}getMessagesService(){return this._messagesService??(this._messagesService=new Wl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Nd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Ed(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new Hc(this.http,this.config.events)),this._eventsBatcherService}getStreamWebSocketService(){if(null===this._streamWebSocketService||void 0===this._streamWebSocketService){if(void 0===this.config.streamWebSocketUrl||""===this.config.streamWebSocketUrl)throw new Error('Stream WebSocket URL is required for real-time streaming features.\n\nConfigure SDK:\n const sdk = createLaunchpadSDK({\n wallet: yourWallet,\n streamWebSocketUrl: "wss://stream.gala.com"\n });\n\nFor MCP Server, set STREAM_WEBSOCKET_URL environment variable.\nSee SDK documentation for streaming configuration details.');this._streamWebSocketService=new Ou({url:this.config.streamWebSocketUrl},this.config.debug??!1)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new El({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new Pd(this.config.debug??!1)),this._streamingEventService}async fetchEthereumWalletTokenBalance(e,t){return this.getBridgeService().fetchEthereumWalletTokenBalance(e,t)}async fetchEthereumWalletNativeBalance(e){return this.getBridgeService().fetchEthereumWalletNativeBalance(e)}async fetchSolanaWalletTokenBalance(e,t){return this.getBridgeService().fetchSolanaWalletTokenBalance(e,t)}async fetchSolanaWalletNativeBalance(e){return this.getBridgeService().fetchSolanaWalletNativeBalance(e)}async requestSolanaDevnetAirdrop(e,t){return this.getBridgeService().requestSolanaDevnetAirdrop(e,t)}async getSolanaTransactionStatus(e){return this.getBridgeService().getSolanaTransactionStatus(e)}async getEthereumTransactionStatus(e){return this.getBridgeService().getEthereumTransactionStatus(e)}async fetchEthereumWalletAllBalances(e){return this.getBridgeService().fetchEthereumWalletAllBalances(e)}async fetchSolanaWalletAllBalances(e){return this.getBridgeService().fetchSolanaWalletAllBalances(e)}async fetchBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchBridgeableTokensByNetwork(e)}async fetchAllBridgeableTokensByNetwork(e){return this.getBridgeableTokenService().fetchAllBridgeableTokensByNetwork(e)}async fetchAllTokensBridgeableToEthereum(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToEthereum()}async fetchAllTokensBridgeableToSolana(){return this.getBridgeableTokenService().fetchAllTokensBridgeableToSolana()}async isTokenBridgeableToNetwork(e){return this.getBridgeableTokenService().isTokenBridgeableToNetwork(e)}async isTokenBridgeableToEthereum(e){return this.getBridgeableTokenService().isTokenBridgeableToEthereum(e)}async isTokenBridgeableToSolana(e){return this.getBridgeableTokenService().isTokenBridgeableToSolana(e)}async fetchWrappableTokens(e={}){return this.getWrappableTokenService().fetchWrappableTokens(e)}async fetchAllWrappableTokens(){return this.getWrappableTokenService().fetchAllWrappableTokens()}async getWrappableToken(e){return this.getWrappableTokenService().getWrappableToken(e)}async getWrapCounterpart(e){return this.getWrappableTokenService().getWrapCounterpart(e)}async isTokenWrappable(e){return this.getWrappableTokenService().isTokenWrappable(e)}async wrapToken(e){return this.getWrapService().wrapToken(e)}async unwrapToken(e){return this.getWrapService().unwrapToken(e)}async estimateWrapFee(e,t){return this.getWrapService().estimateWrapFee(e,t)}async estimateUnwrapFee(e,t){return this.getWrapService().estimateUnwrapFee(e,t)}getWrapStatus(e){return this.getWrapService().getWrapStatus(e)}async login(){return this.sessionAuth.login()}async refreshToken(){return this.sessionAuth.refresh()}async logout(e){return this.sessionAuth.logout(e)}isAuthenticated(){return this.sessionAuth.isAuthenticated()}shouldRefreshToken(e){return this.sessionAuth.shouldRefresh(e)}async getSession(){return this.sessionAuth.getSession()}getAccessToken(){return this.sessionAuth.getAccessToken()}async ensureValidToken(e){return this.sessionAuth.ensureValidToken(e)}async startStream(e){return this.getStreamingService().startStream(e)}async stopStream(e){return this.getStreamingService().stopStream(e)}async disableStream(e){return this.getStreamingService().disableStream(e)}async enableStream(e){return this.getStreamingService().enableStream(e)}async resetStreamKey(e){return this.getStreamingService().resetStreamKey(e)}async getStreamCredentials(e){return this.getStreamingService().getStreamCredentials(e)}async getStreamRecordings(e){return this.getStreamingService().getRecordings(e)}async getRecordingDownload(e,t){return this.getStreamingService().getRecordingDownload(e,t)}async deleteRecording(e,t){return this.getStreamingService().deleteRecording(e,t)}async getSimulcastTargets(e){return this.getStreamingService().getSimulcastTargets(e)}async addSimulcastTarget(e){return this.getStreamingService().addSimulcastTarget(e)}async removeSimulcastTarget(e,t){return this.getStreamingService().removeSimulcastTarget(e,t)}async getGlobalStreamingStatus(){return this.getStreamingService().getGlobalStreamingStatus()}async setNextLiveStreamCountdown(e,t){return this.getStreamingService().setNextLiveStreamCountdown(e,t)}async setGlobalStreamingEnabled(e){const t=this.getStreamingService();return e?t.enableGlobalStreaming():t.disableGlobalStreaming()}async getStreamRole(e){return this.getStreamingService().getStreamRole(e)}async getAvailableRoles(){return this.getStreamingService().getAvailableRoles()}async getTokenAccess(e){return this.getStreamingService().getTokenAccess(e)}async getEngagementStats(e){if(null===Tr(e.tokenName))throw En("tokenName","tokenName is required and cannot be empty");return this.getStreamChatService().getEngagementStats(e)}async disableChat(e){return this.getStreamChatService().disableChat(e)}async enableChat(e){return this.getStreamChatService().enableChat(e)}async getGlobalChatStatus(){return this.getStreamChatService().getGlobalChatStatus()}async setGlobalChatEnabled(e){const t=this.getStreamChatService();return e?t.enableGlobalChat():t.disableGlobalChat()}async getPinnedChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return{tokenName:e,pinnedMessage:n.message?{messageId:n.message.id,content:n.message.content,userAddress:n.message.userAddress,pinnedBy:""!==n.message.pinnedBy?n.message.pinnedBy:n.message.userAddress,pinnedAt:""!==n.message.pinnedAt?n.message.pinnedAt:n.message.createdAt}:null}}async pinChatMessage(e,t){const n=this.getMessagesService();await n.pinMessage(t);const o=await n.getPinnedMessage(e);return{tokenName:e,pinnedMessage:o.message?{messageId:o.message.id,content:o.message.content,userAddress:o.message.userAddress,pinnedBy:""!==o.message.pinnedBy?o.message.pinnedBy:o.message.userAddress,pinnedAt:""!==o.message.pinnedAt?o.message.pinnedAt:o.message.createdAt}:null}}async unpinChatMessage(e){const t=this.getMessagesService(),n=await t.getPinnedMessage(e);return n.message?(await t.unpinMessage(n.message.id),{tokenName:e,unpinned:!0,unpinnedMessageId:n.message.id}):{tokenName:e,unpinned:!1}}async setSlowMode(e,t){return this.getStreamChatService().setSlowMode(e,t)}async createBan(e){return this.getBanService().createBan(e)}async removeBan(e){return this.getBanService().removeBan(e)}async listBans(e){return this.getBanService().listBans(e)}async getBanStatus(e){return this.getBanService().getBanStatus(e)}async getActiveUsers(e){return this.getBanService().getActiveUsers(e)}async createGlobalBan(e){return this.getBanService().createGlobalBan(e)}async removeGlobalBan(e){return this.getBanService().removeGlobalBan(e)}async listGlobalBans(e){return this.getBanService().listGlobalBans(e)}async getGlobalBan(e){return this.getBanService().getGlobalBan(e)}async createApiKey(e){return this.getApiKeyService().create(e)}async listApiKeys(e={}){return this.getApiKeyService().findAll(e)}async getApiKey(e){return this.getApiKeyService().findOne(e)}async updateApiKey(e,t){return this.getApiKeyService().update(e,t)}async revokeApiKey(e){return this.getApiKeyService().revoke(e)}getApiKeyRoles(){return this.getApiKeyService().getRoles()}async createModeratorInvite(e){return this.getModeratorService().createInvite(e)}async claimModeratorInvite(e){return this.getModeratorService().claimInvite(e)}async getModeratedTokens(e){return this.getModeratorService().getModeratedTokens(e)}async listModeratorInvites(e){return this.getModeratorService().listInvites(e)}async revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t={type:"COMMENT"};void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize);const n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async createComment(e){return{comment:(await this.createMessage({type:"COMMENT",tokenName:e.tokenName,content:e.content})).message}}async updateComment(e,t){return{comment:(await this.updateMessage(e,{content:t.content})).message}}async deleteComment(e){return{success:(await this.deleteMessage(e)).success}}async getChatMessages(e){const t={type:"CHAT_MESSAGE"};void 0!==e.tokenName&&(t.tokenName=e.tokenName),void 0!==e.userAddress&&(t.userAddress=e.userAddress),void 0!==e.cursor&&(t.cursor=e.cursor),void 0!==e.pageSize&&(t.pageSize=e.pageSize);const n=await this.fetchMessages(t);return{messages:n.messages,pageInfo:n.pageInfo}}async sendChatMessage(e){return{message:(await this.createMessage({type:"CHAT_MESSAGE",tokenName:e.tokenName,content:e.content})).message}}async updateChatMessage(e,t){return{message:(await this.updateMessage(e,{content:t.content})).message}}async deleteChatMessage(e){await this.deleteMessage(e)}async fetchMessages(e){return this.getMessagesService().fetchMessages(e)}async createMessage(e){return this.getMessagesService().createMessage(e)}async updateMessage(e,t){return this.getMessagesService().updateMessage(e,t)}async deleteMessage(e){return this.getMessagesService().deleteMessage(e)}async getPinnedMessage(e){return this.getMessagesService().getPinnedMessage(e)}async pinMessage(e){return this.getMessagesService().pinMessage(e)}async unpinMessage(e){return this.getMessagesService().unpinMessage(e)}async getMessageStats(){return this.getMessagesService().getMessageStats()}async getPlatformConfig(){return this.getPlatformConfigService().getPlatformConfig()}async updatePlatformConfig(e){return this.getPlatformConfigService().updatePlatformConfig(e)}async getRestrictedNames(){return this.getRestrictedNamesService().getRestrictedNames()}async updateRestrictedNames(e){return this.getRestrictedNamesService().updateRestrictedNames(e)}async updateTokenConfig(e,t){return this.launchpadService.poolService.updateTokenConfig(e,t)}async getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getStreamWebSocketService(),t=await this.ensureValidToken();e.authenticate(t)}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onRecordingsCountUpdated(e){return this.getStreamingEventService().onRecordingsCountUpdated(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEngagementStatsUpdated(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return Promise.resolve({tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n=t(e.address);if(void 0!==e.tokenId&&""!==e.tokenId){const{normalizeToTokenInstanceKey:t}=await Promise.resolve().then(function(){return rc}),o=t(e.tokenId),{collection:i,category:r,type:s,additionalKey:a}=o;return this.galaChainService.fetchTokenBalance({owner:n,collection:i,category:r,additionalKey:a,type:s,instance:"0"},e.withExpired??!1)}if(void 0!==e.tokenName&&""!==e.tokenName){const t=Vn(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const o=`$${t}`;return this.galaChainService.fetchTokenBalance({owner:n,collection:o,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 o=t.collection??"Token",i={collection:o,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:o,category:"Unit",tokenId:Zr(i)}}throw En("tokenId or tokenName","Either tokenId or tokenName")}async fetchLockedBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="lockedHolds"in t||"lockedQuantity"in t;return{tokenId:t.tokenId,lockedQuantity:n?t.lockedQuantity??"0":"0",lockedHolds:n?t.lockedHolds??[]:[]}}async fetchAvailableBalance(e){const t=await this.fetchTokenBalance(e);if(!t)return null;const n="availableQuantity"in t;return{tokenId:t.tokenId,availableQuantity:n?t.availableQuantity??String(t.quantity):String(t.quantity),totalQuantity:String(t.quantity)}}async calculateBuyAmount(e){return this.launchpadAPI.calculateBuyAmount(e)}async calculateSellAmount(e){return this.launchpadAPI.calculateSellAmount(e)}async calculateBuyAmountLocal(e){return this.launchpadAPI.calculateBuyAmountLocal(e)}async calculateSellAmountLocal(e){return this.launchpadAPI.calculateSellAmountLocal(e)}async calculateBuyAmountExternal(e){return this.launchpadAPI.calculateBuyAmountExternal(e)}async calculateSellAmountExternal(e){return this.launchpadAPI.calculateSellAmountExternal(e)}async calculateBuyAmountForGraduation(e){return this.launchpadAPI.calculateBuyAmountForGraduation(e)}async graduateToken(e){const{tokenName:t,slippageToleranceFactor:n,maxAcceptableReverseBondingCurveFeeSlippageFactor:o,privateKey:i,calculateAmountMode:r,currentSupply:s}=e;let a=t;void 0===r&&void 0===s||(a={tokenName:t,...void 0!==r&&{calculateAmountMode:r},...void 0!==s&&{currentSupply:s}});const c=await this.calculateBuyAmountForGraduation(a),l={tokenName:t,amount:c.amount,type:"exact",expectedAmount:c.amount,maxAcceptableReverseBondingCurveFee:c.reverseBondingCurveFee,slippageToleranceFactor:this.slippageToleranceFactor};return void 0!==n&&(l.slippageToleranceFactor=n),void 0!==o&&(l.maxAcceptableReverseBondingCurveFeeSlippageFactor=o),void 0!==i&&(l.privateKey=i),await this.buy(l)}async calculateInitialBuyAmount(e){const t={nativeTokenQuantity:e};return this.launchpadAPI.calculateInitialBuyAmount(t)}async buy(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.buy(o)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.buyToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Dn("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>ah(t,n,"buy",e))}async sell(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.sell(o)}this.validateWallet(),await this.ensureWebSocketConnection();const t=(await this.bundleService.sellToken(e)).data,n=t?.transactionId;if(void 0===n||""===n)throw Dn("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>ah(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,...o}=e;return t.launchToken(o)}this.validateWallet(),await this.ensureWebSocketConnection();const t=await this.launchpadAPI.launchToken(e);return this.waitForConfirmation(t,n=>{sh(n,t);const o=n.data??{};if(!function(e){if($o(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)}(o))throw new oh(`Invalid launch data received for transaction ${t}`);const i={transactionId:t,vaultAddress:o.vaultAddress??"",tokenStringKey:o.tokenStringKey??"",tokenName:e.tokenName,tokenSymbol:e.tokenSymbol,creatorAddress:o.creatorAddress??this.getAddress(),timestamp:Date.now(),...void 0!==n.blockHash&&""!==n.blockHash?{blockHash:n.blockHash}:{},...void 0!==n.gasUsed?{gasUsed:n.gasUsed}:{}};return"string"==typeof e.tokenImage&&(i.tokenImage=e.tokenImage),void 0!==e.preBuyQuantity&&(i.preBuyQuantity=e.preBuyQuantity),""!==i.vaultAddress&&this.tokenResolverService.set(e.tokenName,i.vaultAddress),i})}async uploadTokenImage(e){if(void 0!==e.privateKey&&""!==e.privateKey){const t=this.createOverrideSdk(e.privateKey),{privateKey:n,...o}=e;return t.uploadTokenImage(o)}return this.validateWallet(),this.launchpadService.uploadImageByTokenName(e)}async checkPoolExists(e,t){return this.launchpadService.checkPoolExists(e,t)}async isTokenNameAvailable(e){return this.launchpadService.isTokenNameAvailable(e)}async isTokenSymbolAvailable(e){return this.launchpadService.isTokenSymbolAvailable(e)}async fetchToken(e){return this.launchpadService.fetchToken(e)}async validateToken(e){return this.launchpadService.validateToken(e)}async fetchTokenStats(e){return this.launchpadService.fetchTokenStats(e)}async fetchUserBalances(e){return this.launchpadService.fetchUserBalances(e)}async fetchUserReport(e){return this.launchpadService.fetchUserReport(e)}async fetchProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n=t(e)??this.getAddress();return this.launchpadService.fetchProfile(n)}async fetchReferralUrl(){this.validateWallet();const e=this.getAddress();return await this.dexApiHttp.get(Z,void 0,{"x-wallet-address":e})}async fetchReferrals(e){let t;if(void 0!==e?.address&&""!==e.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return gi}),o=n(e.address);if(void 0===o)throw new Yt(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=o}else t=this.getAddress();const n=e?.page??1,o=e?.limit??10,i={pageNumber:n,limit:o,sortBy:e?.sortBy??"joined",sortDir:e?.sortDir??"desc"},r=await this.dexApiHttp.get(ee,i,{"x-wallet-address":t});if(!Array.isArray(r))throw new en("Unexpected API response: expected array, got "+typeof r);return{referrals:r,page:n,limit:o,hasMore:r.length===o}}async fetchAllReferrals(e){const t=await Za((t,n)=>this.fetchReferrals({...e,page:t,limit:n}).then(e=>({items:e.referrals,page:e.page,limit:e.limit,total:0,totalPages:0,hasNext:e.hasMore,hasPrevious:e.page>1})),{maxPages:100,pageSize:100,logger:this.logger});return{referrals:t.items,total:t.items.length}}async fetchReferralsSummary(e){let t;if(void 0!==e?.address&&""!==e.address)if(e.address.startsWith("client|"))t=e.address;else{const{normalizeAddressInput:n}=await Promise.resolve().then(function(){return gi}),o=n(e.address);if(void 0===o)throw new Yt(`Invalid address format: "${e.address}". Expected formats: eth|0x..., 0x..., or client|...`);t=o}else t=this.getAddress();const n=await this.dexApiHttp.get(te,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new en(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n={...e,address:t(e.address)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.updateProfile(o)}return this.validateWallet(),this.launchpadService.updateProfile(n)}async uploadProfileImage(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n={...e,address:t(e.address)??this.getAddress()};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.uploadProfileImage(o)}return this.validateWallet(),this.launchpadService.uploadProfileImage(n)}async fetchTokensHeld(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n=t(e?.address)??this.getAddress(),o={pageSize:e?.pageSize??10,address:n,...void 0!==e?.cursor?{cursor:e.cursor}:{}};return void 0!==e?.tokenName&&""!==e.tokenName&&(o.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(o.search=e.search),this.launchpadService.fetchTokensHeld(o)}async fetchTokensCreated(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n=t(e?.address)??this.getAddress(),o={type:void 0!==e?.status?"created":"DEFI",address:n,pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(o.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(o.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(o.search=e.search),void 0!==e?.status&&(o.status=e.status),this.launchpadService.fetchTokenList(o)}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 gi}),n={...e,recipientAddress:t(e.recipientAddress)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.transferGala(o)}return this.validateWallet(),this.galaChainService.transferGala(n)}async transferToken(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return gi}),n={...e,to:t(e.to)};if(void 0!==n.privateKey&&""!==n.privateKey){const e=this.createOverrideSdk(n.privateKey),{privateKey:t,...o}=n;return e.transferToken(o)}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 gi});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,...o}=n;return e.lockTokens(o)}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,...o}=e;return t.unlockTokens(o)}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,...o}=e;return t.burnTokens(o)}return this.validateWallet(),this.galaChainService.burnTokens(e)}async resolveVaultAddress(e){return this.tokenResolverService.resolveTokenToVault(e)}getCacheInfo(){const e={...this.launchpadAPI.getCacheStats()};if(this._bridgeableTokenService){const t=this._bridgeableTokenService.getCacheStats();e.bridgeableTokens={ETHEREUM:t.tokensByNetwork.ETHEREUM,SOLANA:t.tokensByNetwork.SOLANA,total:t.totalTokens}}return this._wrappableTokenService&&(e.wrappableTokens=this._wrappableTokenService.getCacheStats()),e}clearCache(e){this.launchpadAPI.clearCache(e),void 0!==e&&""!==e||(void 0!==this._bridgeableTokenService&&this._bridgeableTokenService.clearCache(),void 0!==this._wrappableTokenService&&this._wrappableTokenService.clearCache())}validateConfiguration(){try{Fo(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 Nn("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Nn("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Nn(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Nn(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.galaChainBaseUrl&&""!==this.config.galaChainBaseUrl)try{new URL(this.config.galaChainBaseUrl)}catch{throw Nn(`Invalid galaChainBaseUrl format: ${this.config.galaChainBaseUrl}`,"galaChainBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Nn(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Nn(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Ao("string"==typeof e||"number"==typeof e?e:String(e),dh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${dh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),dh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Ao("string"==typeof e||"number"==typeof e?e:String(e),dh.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: ${dh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),dh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR):t}async ensureWebSocketConnection(){this.websocketService.isConnected()||(await this.websocketService.connect(),this.logger.debug("WebSocket connection established"))}async waitForConfirmation(e,t){this.logger.debug(`Waiting for confirmation of transaction: ${e}`);try{const n=await this.websocketService.waitForTransaction(e);if("completed"!==n.status)throw new rh(e,n.status,n.message);let o;try{o=t(n)}catch(t){if(t instanceof oh)throw t;throw new oh(`Failed to transform WebSocket response for transaction ${e}`,un(t)?t:new Error(hn(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,o),o}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof rh||t instanceof oh)throw t;throw new oh(`WebSocket confirmation failed for transaction ${e}`,un(t)?t:new Error(hn(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return fh});e.forEach(e=>{if(!n(e))return;const o=t(e,this.logger);o&&this.launchpadAPI.warmCacheFromPoolData(e.tokenName,o)})}async getSwapQuoteExactInput(e,t,n){return this.gswapService.getSwapQuoteExactInput({fromToken:e,toToken:t,amount:n})}async getSwapQuoteExactOutput(e,t,n){return this.gswapService.getSwapQuoteExactOutput({fromToken:e,toToken:t,amount:n})}async executeSwap(e,t,n,o,i,r=.01){return this.validateWallet(),this.gswapService.executeSwap({fromToken:e,toToken:t,inputAmount:n,estimatedOutput:o,feeTier:i,slippageTolerance:r})}async getSwapUserAssets(e){return this.gswapService.getUserAssets(e)}async getAllSwapUserAssets(e){return this.gswapService.getAllUserAssets(e)}async fetchAvailableDexTokens(e={}){return this.gswapService.fetchAvailableDexTokens(e)}async fetchAllAvailableDexTokens(e={}){return this.gswapService.fetchAllAvailableDexTokens(e)}async getSwapPoolInfo(e,t){return this.gswapService.getPoolInfo(e,t)}async getSwapPoolPrice(e,t,n){return this.gswapService.getPositionCurrentPrice({token0:e,token1:t,feeTier:n})}async getSwapUserLiquidityPositions(e,t,n,o){let i,r;"string"==typeof n?(i=n,r=o):"object"==typeof n?r=n:o&&(r=o);return await this.gswapService.getUserLiquidityPositions(e,t,i,r)}async getAllSwapUserLiquidityPositions(e,t){const n=await this.gswapService.getAllSwapUserLiquidityPositions(e,t);if(!t?.withPrices){if(Array.isArray(n))return n;if(void 0!==n&&"items"in n)return n.items}return n}async getSwapLiquidityPosition(e,t){return this.gswapService.getLiquidityPosition(e,t)}async getSwapLiquidityPositionById(e,t,n,o,i,r,s){return this.gswapService.getLiquidityPositionById(e,t,n,o,i,r,s)}async fetchSwapPositionDirect(e){return this.gswapService.fetchSwapPositionDirect(e)}async getSwapEstimateRemoveLiquidity(e){return this.gswapService.estimateRemoveLiquidity(e)}async addSwapLiquidityByPrice(e){return this.gswapService.addLiquidityByPrice(e)}async addSwapLiquidityByTicks(e){this.validateWallet();const t={token0:e.token0,token1:e.token1,fee:e.feeTier,tickLower:e.tickLower,tickUpper:e.tickUpper,amount0Desired:e.amount0Desired,amount1Desired:e.amount1Desired};return void 0!==e.amount0Min&&(t.amount0Min=e.amount0Min),void 0!==e.amount1Min&&(t.amount1Min=e.amount1Min),this.gswapService.addSwapLiquidityByTicks(t)}async removeSwapLiquidity(e){return this.validateWallet(),this.gswapService.removeLiquidity(e)}async collectSwapPositionFees(e){return this.validateWallet(),this.gswapService.collectPositionFees(e)}connectWebSocket(){this.websocketService.connect()}disconnectWebSocket(){this.websocketService.disconnect()}isWebSocketConnected(){return this.websocketService.isConnected()}subscribeToEvent(e,t){const n=this.websocketService.getSocket();return n?(n.on(e,t),()=>{n.off(e,t),this.logger.debug(`Unsubscribed from event: "${e}"`)}):(this.logger.warn(`⚠️ WebSocket not connected - subscribing to "${e}" without connection`),()=>{})}onDexPoolCreation(e,t){const n=1e3,o=Math.max(t?.intervalMs??3e4,n);void 0!==t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.minTVL,r=t?.tokens,s=new Map;let a=!0,c=null;let l=0;const d=async()=>{if(a){try{const t=await this.fetchDexPools({limit:20});l>0&&(this.logger.debug("Successfully recovered from polling errors"),l=0),t.items.forEach(t=>{const n=(e=>`${e.token0}-${e.token1}-${e.fee}`)(t);if(!s.has(n)){if((e=>{if(s.set(e,!0),s.size>1e3){const e=s.keys().next().value;void 0!==e&&s.delete(e)}})(n),void 0!==i){if((t.token0Tvl+t.token1Tvl)/2<i)return}if(r&&r.length>0){if(!(r.includes(t.token0)||r.includes(t.token1)))return}e(t)}})}catch(e){l++;const t=hn(e);l>=5?this.logger.error(`Polling for new DEX pools failed ${l} consecutive times. Last error: ${t}. Continuing to retry...`):l>1?this.logger.warn(`Error polling for new DEX pools (attempt ${l}/5): ${t}`):this.logger.debug(`Error polling for new DEX pools: ${t}`)}if(a){const e=Math.min(Math.max(l-1,0),2),t=o*Math.pow(2,e);c=setTimeout(()=>{d()},t)}}};return d(),()=>{a=!1,c&&clearTimeout(c),this.logger.debug("Stopped watching for DEX pool creation")}}onLaunchpadTokenCreation(e,t){const n=1e3,o=Math.max(t?.intervalMs??3e4,n);null!=t?.intervalMs&&t.intervalMs<n&&this.logger.warn(`Poll interval ${t.intervalMs}ms is below minimum 1000ms. Using minimum interval instead.`);const i=t?.creatorAddress,r=new Map;let s=!0,a=null;let c=0;const l=async()=>{if(s){try{const t=await this.fetchPools({type:"recent",pageSize:20});c>0&&(this.logger.debug("Successfully recovered from polling errors"),c=0),t.items.forEach(t=>{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!==i&&""!==i&&t.creatorAddress!==i||e(t))})}catch(e){c++;const t=hn(e);c>=5?this.logger.error(`Polling for new launchpad tokens failed ${c} consecutive times. Last error: ${t}. Continuing to retry...`):c>1?this.logger.warn(`Error polling for new launchpad tokens (attempt ${c}/5): ${t}`):this.logger.debug(`Error polling for new launchpad tokens: ${t}`)}if(s){const e=Math.min(Math.max(c-1,0),2),t=o*Math.pow(2,e);a=setTimeout(()=>{l()},t)}}};return l(),()=>{s=!1,a&&clearTimeout(a),this.logger.debug("Stopped watching for launchpad token creation")}}normalizeFee(e){if(null==e)return null;let t;if("string"==typeof e||"number"==typeof e)t=e;else{if("boolean"!=typeof e)return null;t=e?"1":"0"}const n=Do(t,Number.NaN);return Number.isNaN(n)?null:1===n||1e4===n?1e4:.3===n||3e3===n?3e3:.05===n||500===n?500:!Number.isInteger(n)||500!==n&&3e3!==n&&1e4!==n?null:n}extractField(e,...t){if("object"!=typeof e||null===e)return"";const n=e;for(const e of t)if(null!==n[e]&&void 0!==n[e]){const t=n[e];return"string"==typeof t?t:"number"==typeof t||"boolean"==typeof t?String(t):"object"==typeof t&&null!==t&&"toString"in t?t.toString():""}return""}looksLikePoolPair(e){if("string"!=typeof e)return null;const t=e.trim();return Jl.isValidPoolKey(t)?t:null}buildPoolPairFromObject(e){if("object"!=typeof e||null===e)return null;const t=e,n=this.extractField(t,"token0ClassKey","token0Class","token0","token0Symbol"),o=this.extractField(t,"token1ClassKey","token1Class","token1","token1Symbol"),i=this.normalizeFee(t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps??t.feeBps);return""===n||""===o||null===i?null:`${n}/${o}/${i}`}parsePoolPairString(e){const t=Jl.parsePoolKey(e);if(!t)return null;const n=ga(t.token0)?ha(t.token0).collection:t.token0,o=ga(t.token1)?ha(t.token1).collection:t.token1,i=t.feeTier.toString();return""===n||""===o||""===i?null:{token0:n,token1:o,fee:i,poolPair:e}}serializeBalanceToken(e){if(null==e||"object"!=typeof e)return"";const t=e,n=t.collection??t.token??"",o=t.category??"",i=t.type??"",r=t.additionalKey??"none";return[""!==n?n:"",""!==o?o:"none",""!==i?i:"none",""!==r?r:"none"].join("|")}buildPoolPairFromBalances(e){if("object"!=typeof e||null===e)return null;const t=e,n=t.userBalanceDelta??t.balanceDelta??t.delta;if(null==n||"object"!=typeof n)return null;const o=n,i=o.token0Balance??o.token0??o.baseBalance??o.primaryBalance,r=o.token1Balance??o.token1??o.quoteBalance??o.secondaryBalance,s=this.serializeBalanceToken(i),a=this.serializeBalanceToken(r),c=this.normalizeFee(t.poolFee??t.feeTier??t.fee??t.feeTierBps??t.liquidityFeeBps);return""===s||""===a||null===c?null:`${s}/${a}/${c}`}extractPoolDataFromPayload(e){if("string"==typeof e){const t=this.looksLikePoolPair(e);return null!=t?this.parsePoolPairString(t):null}if("object"!=typeof e||null===e)return null;const t=e,n=this.looksLikePoolPair(t.poolPair);if(null!=n)return this.parsePoolPairString(n);const o=this.buildPoolPairFromBalances(t);if(null!==o)return this.parsePoolPairString(o);const i=this.buildPoolPairFromObject(t);if(null!==i)return this.parsePoolPairString(i);if(void 0!==t.pool&&null!==t.pool&&"object"==typeof t.pool){const e=this.extractPoolDataFromPayload(t.pool);if(null!==e)return e}return null}matchesPoolFilter(e,t){if(void 0!==t?.tokenFilter&&""!==t.tokenFilter){if(!(e.token0===t.tokenFilter||e.token1===t.tokenFilter))return!1}if(t?.pairTokens){const[n,o]=t.pairTokens,i=e.token0===n||e.token1===n,r=e.token0===o||e.token1===o;if(!i||!r||n===o)return!1}if(void 0!==t?.feeTierFilter){if(this.normalizeFee(t.feeTierFilter)!==this.normalizeFee(e.fee))return!1}return!0}matchesCreatorFilter(e,t){return void 0===t||""===t||e.creatorAddress===t}subscribeToTokenCreations(e,t){if(this.logger.debug("Subscribing to token creation broadcasts"+(void 0!==t?.creatorFilter&&""!==t.creatorFilter?` (filter: ${t.creatorFilter})`:"")),null===this.websocketService||void 0===this.websocketService)throw Nn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,o=null;const i=(n,...o)=>{try{if(o.length>0&&"object"==typeof o[0]&&null!==o[0]){const n=o[0].data;if(void 0!==n?.Data&&null!==n.Data&&"object"==typeof n.Data){const o=n.Data;if("CreateSale"===o.functionName){const n={tokenName:""!==o.tokenName?o.tokenName:"",symbol:""!==o.symbol?o.symbol:"",creatorAddress:""!==o.creatorAddress?o.creatorAddress:"",description:""!==o.description?o.description:"",image:""!==o.image?o.image:"",vaultAddress:""!==o.vaultAddress?o.vaultAddress:"",tokenStringKey:""!==o.tokenStringKey?o.tokenStringKey:"",preBuyQuantity:""!==o.initialBuyQuantity?o.initialBuyQuantity:"0",websiteUrl:""!==o.websiteUrl?o.websiteUrl:"",telegramUrl:""!==o.telegramUrl?o.telegramUrl:"",twitterUrl:""!==o.twitterUrl?o.twitterUrl:"",instagramUrl:""!==o.instagramUrl?o.instagramUrl:"",facebookUrl:""!==o.facebookUrl?o.facebookUrl:"",redditUrl:""!==o.redditUrl?o.redditUrl:"",tiktokUrl:""!==o.tiktokUrl?o.tiktokUrl:"",isFinalized:!1!==o.isFinalized&&null!==o.isFinalized&&void 0!==o.isFinalized&&o.isFinalized};this.matchesCreatorFilter(n,t?.creatorFilter)&&e(n)}}}}catch(e){this.logger.warn(`Error processing token creation broadcast: ${hn(e)}`)}};let r=this.websocketService.getSocket();if(r)r.onAny(i),n=!0,this.logger.debug("Token creation broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${hn(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const s=()=>{if(r=this.websocketService.getSocket(),!r&&e<dh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(o=setTimeout(()=>s(),dh.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=dh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${dh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*dh.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(i),n=!0,this.logger.debug("Token creation broadcast listener registered"))};s()}return()=>{try{if(null!==o&&(clearTimeout(o),o=null,this.logger.debug("Cleared token creation broadcast polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(i),n=!1,this.logger.debug("Stopped listening to token creation broadcasts"))}catch(e){this.logger.warn("Error removing token creation listener:",e)}}}walkPayloadForPools(e,t,n=new WeakSet){const o=[];if("string"==typeof e){const n=this.looksLikePoolPair(e);if(null!=n){const e=this.parsePoolPairString(n);null===e||t.has(e.poolPair)||(t.add(e.poolPair),o.push(e))}return o}if("object"!=typeof e||null===e)return o;if(n.has(e))return o;n.add(e);const i=this.extractPoolDataFromPayload(e);i&&!t.has(i.poolPair)&&(t.add(i.poolPair),o.push(i));for(const i of Object.values(e)){const e=this.walkPayloadForPools(i,t,n);o.push(...e)}return o}subscribeToDexPoolAdded(e,t){if(this.logger.debug("Subscribing to DEX pool creation broadcasts"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw Nn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,o=null;const i=new Set,r=(n,...o)=>{try{for(const n of o){const o=this.walkPayloadForPools(n,i);for(const n of o)this.matchesPoolFilter(n,t)&&e(n)}}catch(e){this.logger.warn(`Error processing DEX pool broadcast: ${hn(e)}`)}};let s=this.websocketService.getSocket();if(s)s.onAny(r),n=!0,this.logger.debug("DEX pool broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${hn(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(s=this.websocketService.getSocket(),!s&&e<dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(o=setTimeout(()=>i(),dh.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!s&&e>=dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS*dh.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX pool subscription timeout:",e.message),void(t?.onError&&t.onError(e))}s&&(s.onAny(r),n=!0,this.logger.debug("DEX pool broadcast listener registered"))};i()}return()=>{try{if(null!==o&&(clearTimeout(o),o=null,this.logger.debug("Cleared DEX pool polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(r),n=!1,this.logger.debug("Stopped listening to DEX pool broadcasts"))}catch(e){this.logger.warn("Error removing DEX pool listener:",e)}}}subscribeToDexSwapExecuted(e,t){if(this.logger.debug("Subscribing to DEX swap execution broadcasts"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw Nn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=null,o=null,i=null,r=!1;const s=async e=>{const t=Jl.parsePoolKey(e);if(!t)throw new Error(`Invalid pool key format: ${e}`);return await this.dexQuoteService.fetchCompositePoolData({token0:t.token0,token1:t.token1,fee:t.feeTier})},a=()=>{const c=this.websocketService.getSocket();if(!c)return this.logger.debug("WebSocket not yet ready for swap monitoring, polling..."),void(n=setTimeout(()=>a(),100));r=!0,o=new rd(c,s,this.dexQuoteService,t??{},this.logger),i=o.subscribe(t??{},e),this.logger.debug("DEX swap monitoring subscription established")};return this.websocketService.getSocket()||(this.logger.debug("WebSocket not yet connected, initiating connection for swap monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed for swap monitoring: ${hn(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)})),a(),()=>{try{n&&clearTimeout(n),i&&r&&i(),o&&o.shutdown().catch(e=>{this.logger.warn("Error shutting down swap monitor:",e)})}catch(e){this.logger.warn("Error cleaning up swap monitor:",e)}}}subscribeToDexLiquidityAdded(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityRemoved(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityChanged(e,t){return this.subscribeToDexLiquidityEvents(e,t)}subscribeToDexLiquidityEvents(e,t){if(this.logger.debug("Subscribing to DEX liquidity broadcasts"+(void 0!==t?.tokenFilter&&""!==t.tokenFilter?` (filter: ${t.tokenFilter})`:void 0!==t?.pairTokens?` (pair: ${t.pairTokens.join("/")})`:"")),null===this.websocketService||void 0===this.websocketService)throw Nn("WebSocket service not initialized. Ensure websocketUrl is configured and the service is connected.","websocketService");let n=!1,o=null;const i=new Set,r=new lh(this.logger),s=(n,...o)=>{try{for(const n of o){const o=r.walkPayloadForLiquidityEvents(n,i);for(const n of o)if(this.matchesLiquidityFilter(n,t))try{const t=e(n);t instanceof Promise&&t.catch(e=>{this.logger.warn(`Error in liquidity event callback: ${hn(e)}`)})}catch(e){this.logger.warn(`Error in liquidity event callback: ${hn(e)}`)}}}catch(e){this.logger.warn(`Error processing DEX liquidity broadcast: ${hn(e)}`)}};let a=this.websocketService.getSocket();if(a)a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered");else{this.logger.debug("WebSocket not yet connected, initiating connection for liquidity monitoring..."),this.websocketService.connect().catch(e=>{const n=new Error(`WebSocket connection failed: ${hn(e)}`);this.logger.warn("Failed to establish WebSocket connection:",e),t?.onError&&t.onError(n)});let e=0;const i=()=>{if(a=this.websocketService.getSocket(),!a&&e<dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS)return e++,void(o=setTimeout(()=>i(),dh.DEX_POOL_SOCKET_POLL_INTERVAL_MS));if(!a&&e>=dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS*dh.DEX_POOL_SOCKET_POLL_INTERVAL_MS}ms`);return this.logger.warn("DEX liquidity subscription timeout:",e.message),void(t?.onError&&t.onError(e))}a&&(a.onAny(s),n=!0,this.logger.debug("DEX liquidity broadcast listener registered"))};i()}return async()=>{try{if(null!==o&&(clearTimeout(o),o=null,this.logger.debug("Cleared DEX liquidity polling timeout")),!n)return void this.logger.debug("Cleanup called before listener registration - no action needed");const e=this.websocketService.getSocket();e&&(e.offAny(s),n=!1,this.logger.debug("Stopped listening to DEX liquidity broadcasts"))}catch(e){this.logger.warn("Error removing DEX liquidity listener:",e)}}}matchesLiquidityFilter(e,t){if(!t)return!0;if(void 0!==t.positionId&&""!==t.positionId&&e.positionId!==t.positionId)return!1;if(void 0!==t.poolHash&&""!==t.poolHash&&e.poolHash!==t.poolHash)return!1;if(void 0!==t.feeTierFilter){const n=this.normalizeFeeTier(t.feeTierFilter);if(e.poolFee!==n)return!1}if(void 0!==t.userFilter&&""!==t.userFilter&&e.userAddress!==t.userFilter)return!1;if(void 0!==t.tokenFilter&&""!==t.tokenFilter){const n=void 0!==e.token0&&""!==e.token0&&Cr(e.token0,t.tokenFilter),o=void 0!==e.token1&&""!==e.token1&&Cr(e.token1,t.tokenFilter);if(!n&&!o)return!1}if(void 0!==t.pairTokens){const[n,o]=t.pairTokens,i=e.token0??"",r=e.token1??"",s=Cr(i,n)&&Cr(r,o),a=Cr(i,o)&&Cr(r,n);if(!s&&!a)return!1}if(void 0!==t.minAmount&&""!==t.minAmount){const n=Ao(t.minAmount),o=Ao(e.amounts[0]),i=Ao(e.amounts[1]);if(Math.abs(o)<n&&Math.abs(i)<n)return!1}return!0}normalizeFeeTier(e){if("number"==typeof e)return e>=100?e:Math.round(1e4*e);return function(e,t=3e3){if(Yn(e))return t;if("number"==typeof e)return isNaN(e)?t:Math.floor(e);const n=String(e).trim();if(n.endsWith("%")){const e=Ao(n.replace("%",""));return Math.floor(1e4*e)}const o=parseFloat(n);return isNaN(o)?t:o<100?Math.floor(1e4*o):Math.floor(o)}(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 Qn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Vu.cleanupAll(e),t.debug("Global cleanup completed")}}dh.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,dh.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,dh.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=Hn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,dh.DEFAULT_CALCULATE_AMOUNT_MODE="local",dh.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,dh.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100,dh.DEX_POOL_SOCKET_WAIT_ATTEMPTS=30,dh.DEX_POOL_SOCKET_POLL_INTERVAL_MS=100;class uh{static generateWallet(){try{const e=n.createRandom();if(null==e.mnemonic?.phrase||""===e.mnemonic.phrase)throw En("mnemonic","Mnemonic phrase");const t=this.toGalaAddress(e.address);return{privateKey:e.privateKey,address:e.address,galaAddress:t,mnemonic:e.mnemonic.phrase,wallet:new n(e.privateKey)}}catch(e){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const e=`test-wallet-${Date.now()}-${++this.testCounter}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),o=new n(t),i=this.toGalaAddress(o.address);return{privateKey:o.privateKey,address:o.address,galaAddress:i,mnemonic:"test test test test test test test test test test test junk",wallet:o}}throw e}}static fromPrivateKey(e){const t=new n(e),o=this.toGalaAddress(t.address);return{privateKey:t.privateKey,address:t.address,galaAddress:o,mnemonic:"",wallet:t}}static fromMnemonic(e,t=0){try{const o=d.fromPhrase(e),i=u.fromMnemonic(o,`m/44'/60'/0'/0/${t}`),r=new n(i.privateKey),s=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:s,mnemonic:e,wallet:r}}catch(o){if("undefined"!=typeof process&&"test"===process.env.NODE_ENV){const o=`test-mnemonic-index-${t}-${e}`,i="0x"+Buffer.from(o).toString("hex").padStart(64,"1").slice(0,64),r=new n(i),s=this.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:s,mnemonic:e,wallet:r}}throw o}}static toGalaAddress(e){const n=ai(e);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Cn("address","a valid Ethereum address (40 hex characters)");return`eth|${t(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return li(e)}catch(t){const n=hn(t);if(n.includes("required")||!e?.startsWith("eth|"))throw En("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Cn("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=ai(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===hi(e)}static generateMultipleWallets(e=1){Fo(e,1,100,"count");const t=[];if("undefined"!=typeof process&&"test"===process.env.NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++this.testCounter}`,o="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(this.fromPrivateKey(o))}else for(let n=0;n<e;n++)t.push(this.generateWallet());return t}static getWalletSummary(e,t=!1){const n=["🔐 Wallet Information","═".repeat(50),`📍 Address: ${e.address}`,`🎮 Gala Address: ${e.galaAddress}`,`🌱 Mnemonic: ${null!=e.mnemonic&&""!==e.mnemonic?e.mnemonic:"Not available"}`];return t?n.splice(3,0,`🔑 Private Key: ${e.privateKey}`):n.splice(3,0,"🔑 Private Key: [HIDDEN - use includeSensitive=true to show]"),n.push("═".repeat(50)),n.push("💾 IMPORTANT: Save your mnemonic phrase securely!"),n.push("This is your backup to recover the wallet."),n.join("\n")}}function hh(e){if(void 0===e)return uh.generateWallet();const t=e.trim();if(!Mo(t))throw Cn("input","a non-empty string");if(function(e){const t=ai(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return uh.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 uh.fromMnemonic(t);throw Cn("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function gh(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Cn("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new g(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function mh(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Cn("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t(h(e))}function ph(e){$o(e)&&(e={});const{wallet:t,env:o,config:i={},...r}=e,s={...r,...i},{wallet:a,env:c,config:l,...d}=s;let u;if($o(t)){u=hh().wallet}else if("string"==typeof t){u=hh(t).wallet}else{if(!(t instanceof n))throw Nn("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");u=t}const h={wallet:u,...void 0!==o?{env:o}:{},debug:!1,timeout:3e4,...d};return new dh(h)}uh.testCounter=0;var fh=Object.freeze({__proto__:null,extractMetadataFromPoolData:function(e,t){const n={};if(void 0!==e.vaultAddress&&(n.vaultAddress=e.vaultAddress),void 0!==e.reverseBondingCurveMinFeePortion){const o=Ao(e.reverseBondingCurveMinFeePortion,NaN);isNaN(o)?t&&t.debug(`Skipping invalid reverseBondingCurveMinFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMinFeePortion}"`):n.reverseBondingCurveMinFeeFactor=o}if(void 0!==e.reverseBondingCurveMaxFeePortion){const o=Ao(e.reverseBondingCurveMaxFeePortion,NaN);isNaN(o)?t&&t.debug(`Skipping invalid reverseBondingCurveMaxFeePortion for ${e.tokenName}: "${e.reverseBondingCurveMaxFeePortion}"`):n.reverseBondingCurveMaxFeeFactor=o}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{Wc as EVENT_TYPES,dh as LaunchpadSDK,Ua as SDK_VERSION,rh as TransactionFailedError,oh as WebSocketError,ih as WebSocketTimeoutError,ph as createLaunchpadSDK,hh as createWallet,mh as getEthereumAddressFromPrivateKey,gh as getPublicKeyFromPrivateKey};
|
|
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,GalaWalletSigner as m,PrivateKeySigner as p,GSwap as f}from"@gala-chain/gswap-sdk";import{PublicKey as y,Connection as v,Keypair as k,Transaction as b,ComputeBudgetProgram as w,TransactionInstruction as S,SystemProgram as A,LAMPORTS_PER_SOL as E}from"@solana/web3.js";import T from"json-stringify-deterministic";import{TOKEN_PROGRAM_ID as C,AccountLayout as N,ASSOCIATED_TOKEN_PROGRAM_ID as I}from"@solana/spl-token";import D from"bs58";import{ChainCallDTO as _,calculatePersonalSignPrefix as x,SigningClient as R,SigningType as F}from"@gala-chain/connect";import{v4 as B}from"uuid";import{TokenClassKey as O}from"@gala-chain/api";import U from"bignumber.js";import{io as P}from"socket.io-client";import M from"axios";const $={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",K="/v1/users/referrals",G="/v1/users/referrals/summary",W="/market/price-series",H="/v1/tokens/:tokenName/start-stream",q="/v1/tokens/:tokenName/stop-stream",j="/v1/tokens/:tokenName/stream/disable",V="/v1/tokens/:tokenName/stream/enable",z="/v1/tokens/:tokenName/reset-key",X="/v1/tokens/:tokenName/recordings",Q="/v1/tokens/:tokenName/recordings/:assetId/download",J="/v1/tokens/:tokenName/recordings/:assetId",Y="/v1/tokens/:tokenName/simulcasts",Z="/v1/tokens/:tokenName/simulcasts",ee="/v1/tokens/:tokenName/simulcasts/:targetId",te="/v1/config",ne="/v1/config",ae="/v1/config",se="/v1/tokens/:tokenName/role",re="/v1/roles",ie="/v1/permissions",oe="/v1/tokens/:tokenName/credentials",ce="/auth/login",le="/auth/logout",de="/auth/refresh",ue="/auth/session",he="/v1/tokens/:tokenName/bans",ge="/v1/tokens/:tokenName/bans",me="/v1/tokens/:tokenName/bans/:userAddress",pe="/v1/tokens/:tokenName/bans/:userAddress",fe="/v1/tokens/:tokenName/active-users",ye="/v1/user-bans",ve="/v1/user-bans",ke="/v1/user-bans/:userAddress",be="/v1/user-bans/:userAddress",we={CREATE:"/v1/api-keys",LIST:"/v1/api-keys",GET:"/v1/api-keys/:id",UPDATE:"/v1/api-keys/:id",REVOKE:"/v1/api-keys/:id"},Se="/v1/moderator-invites",Ae="/v1/moderator-invites/claim",Ee="/v1/moderated-tokens",Te="/v1/moderator-invites",Ce="/v1/moderator-invites/:id",Ne="/v1/moderator-invites/:id/role",Ie="/v1/moderator-invites/:id",De="/v1/moderator-invites/code/:code",_e={CREATE:"/v1/content-flags",LIST:"/v1/content-flags",DISMISS:"/v1/content-flags/:id/dismiss",ACTION:"/v1/content-flags/:id/action"},xe="/v1/overseer-invites",Re="/v1/overseer-invites",Fe="/v1/overseer-invites/code/:code",Be="/v1/overseer-invites/claim",Oe="/v1/overseer-invites/:id",Ue="/v1/overseers",Pe="/v1/overseers",Me="/v1/overseers/:address",$e="/v1/overseers/me",Le="/v1/overseer-summary",Ke="/v1/overseer-summary/bans",Ge="/v1/overseer-summary/token-bans",We="/v1/overseer-summary/invites",He="/v1/overseer-summary/flags",qe="/v1/overseer-summary/users",je="/v1/users",Ve="/v1/users/:address/summary",ze="/v1/cache/flush/address/:address",Xe="/v1/cache/flush/token/:tokenName",Qe="/v1/cache/flush/all",Je="/v1/cache/flush/wallet-aliases/:address",Ye="/v1/cache/flush/wallet-aliases",Ze="/v1/token-bans",et="/v1/token-bans",tt="/v1/token-bans/:tokenName",nt="/v1/token-bans/:tokenName",at="/v1/reactions",st="/v1/reactions",rt="/v1/trades",it={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"},ot="/v1/restricted-token-names",ct="/v1/restricted-token-names",lt="/live/:tokenName/chat",dt="/live/:tokenName/chat",ut="/live/:tokenName/chat",ht="/live/:tokenName/chat/slow-mode",gt={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"},mt="/v1/stats",pt="/v1/trading/fee",ft="/v1/trading/sale-details",yt="/v1/trading/quote",vt="/v1/trading/premint-quote",kt={GET_LEADERBOARD:"/weekly-challenge",GET_TOKEN_HISTORY:"/weekly-challenge/history/:vaultAddress"},bt="/v1/notifications/register",wt="/v1/notifications/unregister",St="/v1/notifications/preferences",At="/v1/notifications/preferences",Et="/v1/config/client-flags",Tt="native",Ct="exact";function Nt(e){return e instanceof Error}function It(e){return Nt(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 Dt(e){return Nt(e)||"object"==typeof e&&null!==e&&"stack"in e&&"string"==typeof e.stack?e.stack:void 0}function _t(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 xt(e){return"object"==typeof e&&null!==e&&"message"in e&&("response"in e||"request"in e||"config"in e)}function Rt(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 Ft(e){if(null==e||"object"!=typeof e)return"";const t=e.Message;return"string"==typeof t&&t.trim().length>0?` - ${t}`:""}function Bt(e,t,n){try{t()}catch(t){if(!function(e){return e instanceof Error&&"ValidationError"===e.name}(t))throw t;{const n=t.message;e.push(n)}}}const Ot="Token name is required and must be a string",Ut=e=>`Could not find vault address for token: ${e}`,Pt="REQUIRED",Mt="INVALID_TYPE",$t="INVALID_VALUE",Lt="INVALID_FORMAT",Kt="TOO_LARGE",Gt="INVALID_RANGE";class Wt extends Error{constructor(e,t,n){super(e),this.field=t,this.code=n,this.name="ValidationError"}}class Ht extends Error{constructor(e,t,n){super(e),this.statusCode=t,this.originalError=n,this.name="NetworkError"}}class qt extends Error{constructor(e,t){super(e),this.field=t,this.name="ConfigurationError"}}class jt extends Error{constructor(e,t,n){super(e),this.transactionId=t,this.code=n,this.name="TransactionError"}}function Vt(e,t){return void 0!==t?t:e.charAt(0).toUpperCase()+e.slice(1)}function zt(e,t){return new Wt(`Token "${e}" not found. Please verify the token name is correct.`,"tokenName","TOKEN_NOT_FOUND")}function Xt(e,t){const n=Vt(e,t);return new Wt(`${n} is required`,e,"REQUIRED")}function Qt(e,t,n){const a=Vt(e,n);return new Wt(`${a} must be ${t}`,e,"INVALID_FORMAT")}function Jt(e,t,n){return new Ht(e,t,n)}function Yt(e,t){return new qt(e,t)}function Zt(e,t,n){return new jt(e,t,n)}function en(e,t,n,a){n&&n.error(`${t}:`,e);const s=xt(e)?e.response?.status:void 0;return Jt(`${t}: ${It(e)}`,s,Nt(e)?e:void 0)}function tn(e,t,n,a,s){const r=Vt(e,s);return new Wt(`${r} must be between ${t} and ${n}${void 0!==a?`, received: ${a}`:""}`,e,"OUT_OF_RANGE")}function nn(e,t,n,a){const s=Vt(e,a);return new Wt(`${s} must be at least ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_SMALL")}function an(e,t,n,a){const s=Vt(e,a);return new Wt(`${s} must be at most ${t}${void 0!==n?`, received: ${n}`:""}`,e,"TOO_LARGE")}function sn(e,t,n,a){const s=Vt(e,a),r=void 0!==n?`, received: ${"object"==typeof n?"object":String(n)}`:"";return new Wt(`${s} must be ${t}${r}`,e,"INVALID_TYPE")}function rn(e,t,n){const a=Vt(e,n);return new Wt(`${a} must be a valid number${void 0!==t?`: "${t}"`:""}`,e,"INVALID_NUMBER")}function on(e,t,n,a){const s=Vt(e,a);return new Wt(`Invalid ${s}: ${t}. Must be one of: ${n.join(", ")}`,e,"INVALID_ENUM")}function cn(e){return null!=e&&"object"==typeof e&&"data"in e}function ln(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 Jt(e?.message??t,n)}}function dn(e){if(cn(e))return e.data}function un(e,t="No data found in response"){if(!cn(e))throw Jt(t);const n=e.data;if(null==n)throw Jt(t);return n}async function hn(e,t={}){return pn(e,t,e=>{if(void 0===e.data)throw new Wt(`${t.errorContext??"Operation failed"}: No data returned from API`,"data","NO_DATA");return e.data})}async function gn(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 mn(e,t={}){return pn(e,t,e=>e)}async function pn(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 Wt(`${a}: No response from server`,"response","NO_RESPONSE");return ln(t,a,!0),r&&s&&s.debug(`${a}: completed successfully`),n(t)}catch(e){throw s&&s.error(a,{error:e}),e}}const fn={BASE_PRICE:1650667151e-14,PRICE_SCALING_FACTOR:1166069e-12,TRADING_FEE_FACTOR:.001,GAS_FEE:"1",DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY:1e7};function yn(e){return e.trim().toLowerCase()}function vn(e){return e.trim().toUpperCase()}function kn(e){return e.trim().toUpperCase()}var bn;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARN="WARN",e.ERROR="ERROR"}(bn||(bn={}));class wn{constructor(e){this.levelPriority={[bn.DEBUG]:0,[bn.INFO]:1,[bn.WARN]:2,[bn.ERROR]:3},this.debugEnabled=e.debug,this.context=e.context??"SDK",this.minLevel=e.minLevel??(e.debug?bn.DEBUG:bn.INFO)}debug(e,t){this.log(bn.DEBUG,e,t)}info(e,t){this.log(bn.INFO,e,t)}warn(e,t){this.log(bn.WARN,e,t)}error(e,t){this.log(bn.ERROR,e,t)}log(e,t,n){if(this.levelPriority[e]<this.levelPriority[this.minLevel])return;if(e===bn.DEBUG&&!this.debugEnabled)return;const a=`[${(new Date).toISOString()}] [${this.context}] [${e}]`,s=this.getConsoleMethod(e);void 0!==n?Nt(n)?s(`${a} ${t}`,n.message,Dt(n)??""):s(`${a} ${t}`,n):s(`${a} ${t}`)}getConsoleMethod(e){switch(e){case bn.DEBUG:return console.debug;case bn.INFO:return console.info;case bn.WARN:return console.warn;case bn.ERROR:return console.error;default:return console.log}}child(e){return new wn({debug:this.debugEnabled,context:`${this.context}:${e}`,minLevel:this.minLevel})}isDebugEnabled(){return this.debugEnabled&&this.levelPriority[bn.DEBUG]>=this.levelPriority[this.minLevel]}}function Sn(e){return null==e||""===e}function An(e){return null==e}const En=new wn({debug:!1,context:"DateUtils"});function Tn(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())?(En.warn(`Invalid date string received: "${e}". Using fallback.`),t??new Date):n}catch(n){return En.warn(`Date parsing error for "${e}":`,n),t??new Date}}function Cn(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 Nn(e){return Date.now()-e}const In={MIN_LENGTH:3,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]{3,20}$/},Dn={MIN_LENGTH:2,MAX_LENGTH:20,PATTERN:/^[a-zA-Z0-9]+$/},_n={MIN_LENGTH:1,MAX_LENGTH:50},xn=100,Rn=20,Fn={MAX_LIMIT:50},Bn={PATTERN:/^(eth\|[0-9a-fA-F]{40}|client\|[a-zA-Z0-9_-]+)$/},On={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}},Un={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})$/}},Pn=60,Mn=31536e3,$n={MAX_LENGTH:64,PATTERN:/^(galaswap-operation-|galaconnect-operation-)/},Ln={PATTERN:/^[a-fA-F0-9]{64}$/},Kn={STREAM_URL_PATTERN:/^(rtmps?|srt):\/\/.+/},Gn=50,Wn=1,Hn=100,qn={FULL_NAME:{MIN_LENGTH:1,MAX_LENGTH:100,ALPHABETS_ONLY_PATTERN:/^[a-zA-Z]+(?:\s[a-zA-Z]+)?$/}};function jn(e,t){if(Sn(e))return t;try{return JSON.parse(e)}catch{return t}}function Vn(e,t=0){if(Sn(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 zn(e,t,n){if(An(e))return t;if("number"==typeof e)return isNaN(e)?t:e;const a=Number(e);return isNaN(a)?t:a}function Xn(e,t,n){if(An(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 Qn(e,t){if(An(e)||""===e)throw Xt(t);if(U.isBigNumber(e)){if(e.isNaN())throw rn(t,"NaN");return e}try{const n=new U(e);if(n.isNaN())throw rn(t,e);if(!n.isFinite())throw rn(t,e);return n}catch(n){if(n instanceof Wt)throw n;throw rn(t,e)}}function Jn(e,t=0){if(An(e))return t;if("number"==typeof e)return isNaN(e)?t:e;return Vn(String(e).replace("%","").trim(),t)}function Yn(e,t=18){const n=Vn(e,0);if(0===n)return"0";return n.toFixed(t).replace(/\.?0+$/,"")}function Zn(e){return Yn(e,8)}function ea(e){return Yn(e,18)}function ta(e,t,n,a){if("number"!=typeof e)throw sn(a,"a number",e,a);if(e<t||e>n)throw tn(a,t,n,e)}function na(e,t,n){if("string"!=typeof e)throw sn(n,"a string",e,n);if(e.length>t)throw an(n,t,e.length)}function aa(e,t){if("number"!=typeof e)throw sn(t,"a number",e,t);if(!Number.isInteger(e))throw sn(t,"an integer",e,t);if(e<=0)throw nn(t,1,e,t)}function sa(e,t,n=!1){if("string"!=typeof e)throw sn(t,"a string",e,t);if(!n&&0===e.trim().length)throw Xt(t,`${t} (non-empty string)`)}const ra={ETH_ADDRESS:/^0x[0-9a-fA-F]{40}$/,BACKEND_ADDRESS:/^eth\|(0x)?[0-9a-fA-F]{40}$/,CLIENT_ADDRESS:/^client\|[a-zA-Z0-9_-]+$/},ia=function(e){return"string"==typeof e&&e.trim().length>0},oa=An;function ca(e,t,n=100,a,s){if(void 0!==s&&"string"!=typeof s)throw new Wt("cursor must be a string","cursor",Mt);const r=a??t,i=void 0!==a?"pageSize":"limit";if(void 0!==r&&(aa(r,i),r>n))throw new Wt(`${i} must be at most ${n}`,i,Kt)}function la(e){const t=Object.values(e);return e=>"string"==typeof e&&t.includes(e)}function da(e){return Object.values(e)}function ua(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 Yt(`Either ${t} or ${n} must be provided (${s})`,n);if(c&&l)throw Yt(`Cannot provide both ${t} and ${n}. Provide exactly one (${s}).`,n);return{chosen:c?t:n,hasA:c,hasB:l}}function ha(e,t="tokenName",n=In){if(!ia(e))throw Xt(t);const a=e.trim();if(0===a.length)throw Xt(t);if(a.length<n.MIN_LENGTH)throw tn(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(a.length>n.MAX_LENGTH)throw tn(t,n.MIN_LENGTH,n.MAX_LENGTH,a.length,`${t} length`);if(!n.PATTERN.test(a))throw new Wt(`${t} must contain only alphanumeric characters`,t,Lt)}function ga(e,t="tokenName",n=In){if(null==e)throw Xt(t,t);if("string"!=typeof e)throw sn(t,"a string",e);const a=e.trim();if(0===a.length)throw Xt(t,t);if(!n.PATTERN.test(a))throw new Wt(`${t} must be ${n.MIN_LENGTH}-${n.MAX_LENGTH} alphanumeric characters`,t,Lt)}function ma(e){return""===e||0===e.trim().length}function pa(e,t,n){if(!oa(e)){if("string"!=typeof e)throw sn(t,"a string",e,t);if(e.length>n)throw new Wt(`${t} must be at most ${n} characters`,t,Kt)}}function fa(e,t){oa(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 sn(t,"a date",e,t);if(isNaN(n.getTime()))throw new Wt(`${t} must be a valid date`,t,Lt)}(e,t)}function ya(e,t,n){try{aa(e,t)}catch{throw function(e,t,n,a="OPERATION_FAILED"){return new Wt(`${e} failed: ${t}`,n,a)}(n,"must be a positive integer",t)}}function va(e,t,n="status"){void 0!==e&&function(e,t,n){const a=Object.values(t);if(!a.includes(e))throw new Wt(`${n} must be one of: ${a.join(", ")}`,n,Lt)}(e,t,n)}class ka{constructor(e,t=!1,n){this.http=e,this.logger=new wn({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 qt("JWT authentication required. Call sdk.login() first.")}return this.jwtAuth.getJwtHeaders()}isCalledFromUserCode(){const e=Dt(new Error)??"";return!(!e.includes("expect")&&!e.includes("jest"))||!(!e.includes("tests/")&&!e.includes(".test.ts"))}validatePositiveInteger(e,t,n){ya(e,t,n)}}class ba{constructor(e=!1,t){this.logger=t||new wn({debug:e,context:this.constructor.name})}}class wa extends ba{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 Sa extends wa{constructor(e=!1){super(e)}normalizeKey(e){return yn(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>=Sa.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??fn.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:${yn(e)}`;return this.cache.get(t)??null}setByTokenId(e,t){const n=`token:${yn(e)}`;this.updateCacheEntry(n,t)}hasByTokenId(e){const t=`token:${yn(e)}`;return this.cache.has(t)}}function Aa(e){return""===e?"":e.startsWith("0x")?e.slice(2):e}Sa.MAX_CACHE_SIZE=1e4;const Ea={ETHEREUM:ra.ETH_ADDRESS,ETHEREUM_NO_PREFIX:/^[a-fA-F0-9]{40}$/,BACKEND:ra.BACKEND_ADDRESS,CLIENT:ra.CLIENT_ADDRESS};class Ta{toBackendFormat(e){if(!ia(e))throw new Wt("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 Wt(`Invalid Ethereum address format in backend address. Expected 40 hex characters after 'eth|'. Got: "${e}"`,"address","INVALID_FORMAT");return e}if(n=Aa(e),!/^[a-fA-F0-9]{40}$/.test(n))throw new Wt(`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(!ia(e))throw new Wt("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 Wt(`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(!Ea.CLIENT.test(e))throw new Wt(`Invalid client address format: "${e}"`,"address","INVALID_FORMAT");return e}if(e.startsWith("eth|")){if(!Ea.BACKEND.test(e))throw new Wt(`Invalid backend address format: "${e}"`,"address","INVALID_FORMAT");return e}return this.toBackendFormat(e)}}isValid(e){return!!ia(e)&&(!!Ea.ETHEREUM.test(e)||(!!Ea.ETHEREUM_NO_PREFIX.test(e)||(!!Ea.BACKEND.test(e)||!!Ea.CLIENT.test(e))))}assertValid(e,t="address"){if(!this.isValid(e))throw new Wt(`${t} must be a valid wallet address (Ethereum or backend format)`,t,"INVALID_FORMAT")}detectFormat(e){return ia(e)?Ea.ETHEREUM.test(e)||Ea.ETHEREUM_NO_PREFIX.test(e)?"ethereum":Ea.BACKEND.test(e)?"backend":Ea.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 Aa(e).toLowerCase();if(/^[a-fA-F0-9]{40}$/.test(e))return e.toLowerCase();throw new Wt(`Cannot extract hex from address: "${e}". Expected Ethereum or backend format.`,"address","INVALID_FORMAT")}}const Ca=new Ta,Na=Aa;function Ia(e){return Ca.toBackendFormat(e)}function Da(e){return Ca.toEthereumFormat(e)}function _a(e){return Ca.isValid(e)}function xa(e,t="address"){Ca.assertValid(e,t)}function Ra(e){return Ca.detectFormat(e)}var Fa=Object.freeze({__proto__:null,AddressFormatter:Ta,assertValidWalletAddress:xa,detectFormat:Ra,fromBackendAddressFormat:Da,isValidAddress:_a,normalizeAddressInput:function(e){return Ca.normalizeInput(e)},stripHexPrefix:Na,toBackendAddressFormat:Ia});const Ba=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"),Oa=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"),Ua=e.string({message:"Token description is required"}).min(1,"Token description is required").max(500,"Token description must be at most 500 characters"),Pa=e.string().min(1,"Token name must be at least 1 character").max(50,"Token name must be at most 50 characters"),Ma=e.string().min(1,"Search query must be at least 1 character").max(100,"Search query must be at most 100 characters"),$a=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(ra.BACKEND_ADDRESS,"Address must be in format: eth|[40-hex-chars]"),e.string().regex(ra.ETH_ADDRESS,"Invalid Ethereum address format");const La=e.string().refine(e=>ra.BACKEND_ADDRESS.test(e)||ra.ETH_ADDRESS.test(e)||ra.CLIENT_ADDRESS.test(e),"Address must be eth|[40-hex], 0x[40-hex], or client|[identifier] format").transform(e=>(new Ta).normalizeInput(e)??e),Ka=e.string().refine(e=>ra.BACKEND_ADDRESS.test(e)||/^service\|Token\$Unit\$[A-Z0-9]+\$eth:[0-9a-fA-F]{40}\$launchpad$/.test(e),"Invalid vault address format"),Ga=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Vn(e,0)>0,"Amount must be greater than zero"),Wa=e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal number").refine(e=>Vn(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 Ha=e.string().optional().refine(e=>void 0===e||""===e||/^https?:\/\/.+\..+/.test(e),"Must be a valid URL if provided");function qa(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),qa(100),qa(20),qa(20);const ja=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"),Va=e.string().max(255,"Filename must be at most 255 characters"),za=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 Xa=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 Qa=[".png",".jpg",".jpeg",".gif",".webp",".svg"];e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),name:Va,size:ja,type:za});const Ja=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"),Ya=e.instanceof(Buffer).refine(e=>e.length>=1&&e.length<=10485760,"Buffer size must be between 1 byte and 10MB");e.union([Ja,Ya]),e.enum([".png",".jpg",".jpeg",".gif",".webp",".svg"]),Va.refine(e=>{const t=e.slice(e.lastIndexOf(".")).toLowerCase();return Qa.includes(t)},`Filename must end with one of: ${Qa.join(", ")}`),e.object({websiteUrl:Ha,telegramUrl:Ha,twitterUrl:Ha,instagramUrl:Ha,facebookUrl:Ha,redditUrl:Ha,tiktokUrl:Ha}).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 Za=e.string().min(1,"Token category must not be empty").default("Unit"),es=e.string().min(1,"Token collection must not be empty").default("Token"),ts=e.object({minFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Vn(e,0)>=.1,"Minimum fee must be >= 0.1").refine(e=>Vn(e,0)<=.5,"Minimum fee must be <= 0.5"),maxFeePortion:e.string().regex(/^\d+(\.\d+)?$/,"Must be a valid decimal string").refine(e=>Vn(e,0)>=.1,"Maximum fee must be >= 0.1").refine(e=>Vn(e,0)<=.5,"Maximum fee must be <= 0.5")}).refine(e=>Vn(e.maxFeePortion,0)>=Vn(e.minFeePortion,0),{message:"Maximum fee must be >= minimum fee",path:["maxFeePortion"]}),ns=e.object({tokenName:Ba,tokenSymbol:Oa,tokenDescription:Ua,tokenImage:e.union([e.instanceof(File),e.instanceof(Buffer),e.string().url("Token image must be a valid URL")]).optional(),preBuyQuantity:Wa.default("0"),websiteUrl:Ha,telegramUrl:Ha,twitterUrl:Ha,instagramUrl:Ha,facebookUrl:Ha,redditUrl:Ha,tiktokUrl:Ha,tokenCategory:Za,tokenCollection:es,reverseBondingCurveConfiguration:ts.optional(),saleStartTime:e.number().int().positive().optional(),privateKey:Xa.optional()});e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),tokenName:Ba}),e.enum(["RECENT","POPULAR"]);const as=e.object({tokenName:Ba.optional(),symbol:Oa.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 ss=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:Ba});e.object({tokenName:Ba,slippageToleranceFactor:e.number().min(0).max(1).optional(),maxAcceptableReverseBondingCurveFeeSlippageFactor:e.number().min(0).max(1).optional(),privateKey:Xa.optional()});const rs=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(100).default(10)}),is=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)}),os=e.object({offset:e.number().int().min(0).default(0),pageSize:e.number().int().min(1).max(20).default(10)});rs.extend({type:e.enum(["RECENT","POPULAR"]).optional(),tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),is.extend({tokenName:e.string().min(1).max(50).optional(),search:e.string().min(1).max(100).optional()}),os.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 cs={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(cs);const ls=e.enum(["buy","sell"]);e.enum(["BUY","SELL"]),e.object({tradeType:ls,tokenAmount:Ga,vaultAddress:Ka,userAddress:La,slippageTolerance:Ga.optional(),deadline:e.number().int().positive().optional()}),e.object({tokenSymbol:Oa,nativeTokenQuantity:Ga,expectedToken:Ga,maxAcceptableReverseBondingCurveFee:Wa.default("0").optional()}),e.object({tokenSymbol:Oa,tokenQuantity:Ga,expectedNativeToken:Ga,maxAcceptableReverseBondingCurveFee:Wa.default("0").optional()}),os.extend({tokenName:Pa.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 ds=e.enum(["NATIVE","MEME"]),us=e.enum(["IN","OUT"]);e.object({type:ds,method:us,vaultAddress:Ka,amount:Ga}),e.object({nativeTokenQuantity:Ga}),e.object({vaultAddress:Ka}),e.object({minFeePortion:Ga,maxFeePortion:Ga});const hs=e.enum(["all","DEFI","ASSET"]);function gs(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)}}}is.extend({type:hs.optional(),address:La.optional(),search:Ma.optional(),tokenName:Pa.optional()}),e.object({address:La.optional(),refresh:e.boolean().optional()}),e.object({profileImage:e.string(),fullName:$a,address:La,privateKey:Xa.optional()}),e.object({file:e.union([e.instanceof(File),e.instanceof(Buffer)]),address:La.optional(),privateKey:Xa.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:La,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:Pa.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 ms=gs(Ba),ps=gs(ns),fs=gs(as);function ys(e){const t=function(e){const t=ps(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 vs(e,t){return"string"==typeof e[t]}function ks(e,t){return void 0===e[t]||"string"==typeof e[t]}function bs(e,t){return void 0===e[t]||"number"==typeof e[t]}function ws(e,t){switch(t){case"string":return"string"==typeof e;case"number":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return null!==e&&"object"==typeof e&&!Array.isArray(e);case"array":return Array.isArray(e);case"optional-string":return void 0===e||"string"==typeof e;case"optional-number":return void 0===e||"number"==typeof e;case"optional-boolean":return void 0===e||"boolean"==typeof e;case"optional-object":return void 0===e||null!==e&&"object"==typeof e&&!Array.isArray(e);case"optional-array":return void 0===e||Array.isArray(e);default:return!1}}function Ss(e){return t=>{if(null==t||"object"!=typeof t||Array.isArray(t))return!1;const n=t;for(const[t,a]of Object.entries(e)){if(!ws(n[t],a))return!1}return!0}}la({BUY:"buy",SELL:"sell"});const As=Ss({vaultAddress:"string"}),Es=Ss({nativeTokenQuantity:"string"});function Ts(e){if(oa(e)||"object"!=typeof e)return{};const t={};for(const[n,a]of Object.entries(e))oa(a)||(ia(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 Cs(e,t="0"){return function(e,t="0"){if(Sn(e))return new U(t);if(U.isBigNumber(e))return e.isNaN()?new U(t):e;try{const n=new U(e);return n.isNaN()||!n.isFinite()?new U(t):n}catch{return new U(t)}}(e,t)}function Ns(e,t){return void 0!==t?Cs(e).toFixed(t):Cs(e).toFixed()}function Is(e){return Cs(e).isZero()}function Ds(e,t){return Cs(e).isLessThan(Cs(t))}function _s(...e){e.forEach(e=>{if(e.isNaN())throw rn("value","NaN");if(!e.isFinite())throw an("value","finite");if(e.isLessThanOrEqualTo(0))throw nn("value","0",e.toString())})}function xs(e,t,n="0"){const a=Cs(t);return Is(a)?Cs(n):Cs(e).dividedBy(a)}const Rs={calculateBuyWithExact(e,t){const n=Vn(e),a=Vn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=fn,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=Ns(Cs(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateBuyWithNative(e,t){const n=Vn(e),a=Vn(t),{BASE_PRICE:s,PRICE_SCALING_FACTOR:r,TRADING_FEE_FACTOR:i,GAS_FEE:o}=fn,c=Math.log(n*r/s+Math.exp(a*r))/r-a,l=Ns(Cs(c).multipliedBy(i));return{amount:c.toString(),reverseBondingCurveFee:"0",transactionFee:l,gasFee:o}},calculateSellWithExact(e,t,n,a,s){const r=Vn(e),i=Vn(t),o=Vn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=fn,h=c*(Math.exp(i*l)-Math.exp((i-r)*l))/l,g=Cs(h),m=a+i/o*(s-a),p=Ns(g.multipliedBy(m),8),f=Ns(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}},calculateSellWithNative(e,t,n,a,s){const r=Vn(e),i=Vn(t),o=Vn(n),{BASE_PRICE:c,PRICE_SCALING_FACTOR:l,TRADING_FEE_FACTOR:d,GAS_FEE:u}=fn;if(r>=c*(Math.exp(i*l)-1)/l){const e=Cs(r),t=a+i/o*(s-a),n=Ns(e.multipliedBy(t),8),c=Ns(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=Cs(r),m=a+i/o*(s-a),p=Ns(g.multipliedBy(m),8),f=Ns(g.multipliedBy(d));return{amount:h.toString(),reverseBondingCurveFee:p,transactionFee:f,gasFee:u}}};class Fs extends Error{constructor(e,t,n){super(e),this.filename=t,this.mimeType=n,this.name="FileValidationError"}}function Bs(e,t,n){if(null==e)throw new Fs("File is required",t,n);if("undefined"!=typeof File&&e instanceof File){const t=Ja.safeParse(e);if(!t.success){const n=t.error.issues.map(e=>e.message).join("; ");throw new Fs(n,e.name,e.type)}return}if(Buffer.isBuffer(e)){if(void 0===t||""===t)throw new Fs("Filename is required when uploading Buffer objects",t,n);const a=Ya.safeParse(e);if(!a.success){const e=a.error.issues.map(e=>e.message).join("; ");throw new Fs(e,t,n)}try{na(t,255,"filename")}catch(e){throw new Fs(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 Fs(`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 Fs(`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 Fs(`File extension "${r}" does not match MIME type "${n}"`,t,n);return}throw new Fs("File must be a File object (browser) or Buffer (Node.js)",t,n)}class Os{validate(e,t={}){const{allowZero:n=!0,minimum:a,maximum:s,maxDecimals:r=Os.MAX_DECIMAL_PLACES,fieldName:i="amount"}=t;if(!ia(e))throw new Wt(`${i} cannot be empty or whitespace-only. Provide a valid numeric string.`,i,"INVALID_NUMERIC_STRING");if(/[eE]/.test(e))throw new Wt(`${i} cannot use scientific notation. Use standard decimal format (e.g., "1000" instead of "1e3").`,i,"INVALID_NUMERIC_STRING");const o=Vn(e,NaN);if(isNaN(o))throw new Wt(`${i} must be a valid numeric string. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!isFinite(o))throw new Wt(`${i} must be a finite number. Cannot be Infinity or -Infinity.`,i,"INVALID_NUMERIC_STRING");if(o<0)throw new Wt(`${i} must be non-negative. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");if(!n&&0===o)throw new Wt(`${i} must be greater than zero. Received: "${e}"`,i,"INVALID_NUMERIC_STRING");const c=Cs(e),l=c.decimalPlaces()??0;if(l>r)throw new Wt(`${i} cannot exceed ${r} decimal places. Received: ${l} decimal places`,i,"PRECISION_EXCEEDED");if(void 0!==a&&Ds(c,a))throw new Wt(`${i} must be at least ${a}. Received: "${e}"`,i,"BELOW_MINIMUM");if(void 0!==s&&(d=s,Cs(c).isGreaterThan(Cs(d))))throw new Wt(`${i} cannot exceed ${s}. Received: "${e}"`,i,"EXCEEDS_MAXIMUM");var d}parseAmount(e,t="0"){return Cs(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 Ns(e,t)}clampAmount(e,t,n){const a=Cs(e),s=Cs(t),r=Cs(n);return function(e,t,n){const a=Cs(e),s=Cs(t),r=Cs(n);return a.isGreaterThanOrEqualTo(s)&&a.isLessThanOrEqualTo(r)}(a,s,r)?Ns(a):Ds(a,s)?Ns(s):Ns(r)}}function Us(e,t){throw new Wt(e.join("; "),t,"VALIDATION_ERROR")}function Ps(e){const t=ms(e);!t.success&&t.errors&&Us(t.errors,"tokenName")}function Ms(e){const t=ss.safeParse(e);var n;t.success||Us((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 $s(e,t,n=!0){Ls.validate(e,{fieldName:t,allowZero:n})}Os.MAX_DECIMAL_PLACES=18,Os.MIN_POSITIVE="0.00000000000000001";const Ls=new Os;function Ks(e,t,n=Ns){if(!Array.isArray(e))throw Jt("Invalid API response: expected array of holders",t);for(const n of e){if(!Gs(n))throw Jt("Invalid holder data: missing or invalid owner field",t);if(!Ws(n))throw Jt("Invalid holder data: missing or invalid quantity field",t);const e=Vn(n.quantity,NaN);if(isNaN(e)||!isFinite(e))throw Jt(`Invalid holder quantity: "${n.quantity}"`,t)}const a=e,s=a.reduce((e,t)=>e.plus(t.quantity),Cs(0));return{holders:a.map(e=>({address:e.owner,balance:e.quantity,percentage:xs(Cs(e.quantity),s,Cs(0)).multipliedBy(100).toNumber()})),totalSupply:n(s),totalHolders:a.length,lastUpdated:new Date}}function Gs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.owner&&""!==t.owner}function Ws(e){return"string"==typeof e.quantity&&""!==e.quantity}class Hs{constructor(e,t,n,a,s,r,i="local",o){this.http=e,this.tokenResolver=t,this.logger=n,this.bundleHttp=a,this.galaChainHttp=s,this.dexApiHttp=r,this.defaultCalculateAmountMode=i,this.launchpadWrites=o,this.metadataCache=new Sa}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;Ps(t);const a=`${t}.png`;Bs(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 Qt("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 Jt(void 0!==a.message&&""!==a.message?a.message:"Image upload failed - no URL returned",a.status);const s=dn(a);if(!s?.imageUrl)throw Jt("Image upload failed - no URL returned",a.status);return s.imageUrl}catch(e){if(Nt(e)&&e.message.includes("FormData"))throw Yt("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&&ca(0,void 0,100,e.pageSize),void 0!==e.tokenName&&""!==e.tokenName&&Ps(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=Ts(t),a=await this.http.get($.FETCH_POOLS,n);if(!0===a.error||200!==a.status)throw Jt(void 0!==a.message&&""!==a.message?a.message:"Failed to fetch pools",a.status);const s=dn(a);if(null==s)throw Jt("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 Xu});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 Qt("options","an options object");const{tokenName:t,amount:n,type:a,currentSupply:s}=e;return"external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[Tt,Ct],'"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?hn(()=>this.http.get(yt,{tokenName:t,amount:n,type:"MEME",method:"OUT"}),{errorContext:`Failed to calculate buy amount for ${t} (exact tokens)`}):hn(()=>this.http.get(yt,{tokenName:t,amount:n,type:"NATIVE",method:"IN"}),{errorContext:`Failed to calculate buy amount for ${t} (native/GALA budget)`})}async calculateSellAmount(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if("external"===this.validateAmountCalculationInputs(t,n,a,e.mode,[Ct,Tt],'"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?hn(()=>this.http.get(yt,{tokenName:t,amount:n,type:"MEME",method:"IN"}),{errorContext:`Failed to calculate sell amount for ${t} (exact tokens)`}):hn(()=>this.http.get(yt,{tokenName:t,amount:n,type:"NATIVE",method:"OUT"}),{errorContext:`Failed to calculate sell amount for ${t} (native/GALA target)`})}async calculateBuyAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s}=e;if(!ia(n))throw Xt("amount","Amount");if(a!==Tt&&a!==Ct)throw sn("type",'"native" or "exact"',a);void 0!==s&&$s(s,"currentSupply");const r=null==s||""===s;if(r&&(null==t||""===t))throw Xt("tokenName","Token name (required when currentSupply is not provided)");null!=t&&""!==t&&Ps(t);let i=s;if(r){i=(await this.fetchPoolDetailsForCalculation(t)).currentSupply}return a===Ct?Rs.calculateBuyWithExact(n,i):Rs.calculateBuyWithNative(n,i)}async calculateSellAmountLocal(e){const{tokenName:t,amount:n,type:a,currentSupply:s,maxSupply:r,reverseBondingCurveMaxFeeFactor:i,reverseBondingCurveMinFeeFactor:o}=e;if(!ia(n))throw Xt("amount","Amount");if(a!==Ct&&a!==Tt)throw sn("type",'"exact" or "native"',a);void 0!==s&&$s(s,"currentSupply");const c=null==s||""===s||null==r||""===r||void 0===i||void 0===o;if(c&&(null==t||""===t))throw Xt("tokenName","Token name (required when currentSupply, maxSupply, or fee factors are not provided)");null!=t&&""!==t&&Ps(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===Ct?Rs.calculateSellWithExact(n,l,d,h,u):Rs.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 vs(t,"tokenName")&&function(e){return void 0===e.calculateAmountMode||"local"===e.calculateAmountMode||"external"===e.calculateAmountMode}(t)&&ks(t,"currentSupply")}(e))throw sn("options","CalculateBuyAmountForGraduationOptions or string (token name)",typeof e);const{tokenName:n,calculateAmountMode:a,currentSupply:s}=t;Ps(n);const r=await this.fetchSaleDetails(n),i=s??Ns(Cs(r.maxSupply).minus(r.sellingTokenQuantity)),o=r.sellingTokenQuantity;if("0"===o)throw Xt("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 Yt("Bundle backend client not configured. LaunchToken requires bundleHttp client.","bundleHttp");ys(e);const t=void 0!==e.preBuyQuantity&&""!==e.preBuyQuantity?e.preBuyQuantity:"0",n=Vn(t);if(0===n&&"0"!==t)throw rn("preBuyQuantity",t,"Pre-buy quantity");if(n<0)throw rn("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 Wt(`${n} minFee must be a valid finite number`,n,"INVALID_FEE_MINIMUM");if(!isFinite(s))throw new Wt(`${n} maxFee must be a valid finite number`,n,"INVALID_FEE_MAXIMUM");if(a<.1)throw new Wt(`${n} minFee must be >= 0.1, received ${a}`,n,"INVALID_FEE_MINIMUM");if(s>.5)throw new Wt(`${n} maxFee must be <= 0.5, received ${s}`,n,"INVALID_FEE_MAXIMUM");if(a>s)throw new Wt(`${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 Xt("tokenName","Token name");Ps(e);const t=await this.http.get(`/holders/${e}`);if(!0===t.error||200!==t.status)throw Jt(void 0!==t.message&&""!==t.message?t.message:"Failed to fetch token distribution",t.status);const n=dn(t);if(null==n)throw Jt("Failed to fetch token distribution - no data returned",t.status);return Ks(n,t.status)}async calculateInitialBuyAmount(e){if(!Es(e))throw Qt("data","valid pre-mint calculation data");if(!this.galaChainHttp)throw Yt("GalaChain HTTP client not available. Please initialize SDK with gatewayBaseUrl.","galaChainHttp");try{const t={vaultAddress:"service|testToken",nativeTokenQuantity:e.nativeTokenQuantity,IsPreMint:!0},n=await this.galaChainHttp.post("/api/asset/launchpad-contract/CallMemeTokenOut",t);if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e,n=t.Status,a=t.Data;if("number"!=typeof n||"object"!=typeof a||null===a)return!1;const s=a,r=s.calculatedQuantity,i=s.extraFees;if("string"!=typeof r||"object"!=typeof i||null===i)return!1;const o=i;return"string"==typeof o.reverseBondingCurve&&"string"==typeof o.transactionFees}(n))throw Jt("Malformed response data from GalaChain gateway");try{Rt(n,"Pre-mint calculation")}catch(e){throw Jt(It(e),500)}const{calculatedQuantity:a,extraFees:s}=n.Data;return{amount:a,reverseBondingCurveFee:s.reverseBondingCurve,transactionFee:s.transactionFees,gasFee:"1"}}catch(e){if(Nt(e)&&e instanceof Ht)throw e;throw Jt(It(e),500)}}async fetchPoolDetailsForCalculation(e){const t=await this.fetchSaleDetails(e),n=Ns(Cs(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.sellingTokenQuantity,s=t.maxSupply;let r=.5,i=.1;const o=t.reverseBondingCurveConfiguration;null!=o?.maxFeePortion&&(r=Jn(o.maxFeePortion,.5)),null!=o?.minFeePortion&&(i=Jn(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){Ps(e);const t=await this.fetchSaleDetails(e),n=Ns(Cs(t.maxSupply).minus(t.sellingTokenQuantity)),a=t.maxSupply;return this.metadataCache.set(e,{maxSupply:a}),n}normalizePoolData(e){const t=e.reverseBondingCurveMinFeePortion??"0",n=e.reverseBondingCurveMaxFeePortion??"0";return{...e,reverseBondingCurveMinFeePortion:t,reverseBondingCurveMaxFeePortion:n,hasReverseBondingCurveFee:!Is(t)||!Is(n),createdAt:void 0!==e.created_at&&""!==e.created_at?e.created_at:void 0!==e.createdAt&&""!==e.createdAt?e.createdAt:""}}async fetchSaleDetails(e){const t=await this.tokenResolver.resolveTokenToVault(e);if(null==t||""===t)throw new Wt(Ut(e),"tokenName","VAULT_NOT_FOUND");if(void 0===this.galaChainHttp||null===this.galaChainHttp)throw Yt("GalaChain HTTP client not configured");const n=await this.galaChainHttp.post("/api/asset/launchpad-contract/FetchSaleDetails",{vaultAddress:t});if(1!==n.Status)throw Jt(`Failed to fetch pool details: Status ${n.Status}`,n.Status);return n.Data}validateAmountCalculationInputs(e,t,n,a,s,r){const i=a??this.defaultCalculateAmountMode;if("local"!==i&&"external"!==i)throw sn("mode",'"local" or "external"',i);if(!ia(e))throw Xt("tokenName","Token name");if(!ia(t))throw Xt("amount","Amount");if("string"!=typeof n||!s.includes(n))throw sn("type",r,n);return i}validateExternalAmountInputs(e,t){if("string"!=typeof e||""===e)throw new Wt("Token name must be a non-empty string","tokenName","INVALID_TOKEN_NAME");if("string"!=typeof t||""===t)throw new Wt("Amount must be a non-empty string","amount","INVALID_AMOUNT")}getAddress(){return this.http.getAddress()}formatAddressForBackend(e){return Ia(e)}validateTokenName(e){return Ps(e)}validatePagination(e){void 0!==e.pageSize&&ca(0,void 0,100,e.pageSize)}async fetchTokenPrice(e){if(void 0===this.dexApiHttp||null===this.dexApiHttp)throw Yt("DEX API client not configured. Token price fetching requires dexApiHttp client.","dexApiHttp");if(null==e||""===e||Array.isArray(e)&&0===e.length)throw Xt("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 Jt(`Failed to fetch token prices: ${It(e)}`,void 0,Nt(e)?e:void 0)}}warmCacheFromPoolData(e,t){this.metadataCache.warmFromPoolData(e,t)}getCacheStats(){return this.metadataCache.getStats()}clearCache(e){this.metadataCache.clear(e)}}const qs=3e5,js="Sign in to Launchpad t:",Vs="Authorization",zs="Bearer ";class Xs{constructor(){this.data=new Map}async get(e){return this.data.get(e)??null}async set(e,t){this.data.set(e,t)}async remove(e){this.data.delete(e)}}var Qs,Js;!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"}(Qs||(Qs={}));class Ys extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name="AuthError"}}class Zs{constructor(e,t=qs){this.tokenState=null,this.STORAGE_KEYS={ACCESS_TOKEN:"lpad_access_token",ACCESS_EXPIRES:"lpad_access_expires",REFRESH_TOKEN:"lpad_refresh_token",REFRESH_EXPIRES:"lpad_refresh_expires"},this.storage=e??new Xs,this.refreshThresholdMs=t}setToken(e,t){if(!ia(e))throw new Ys(Qs.SIGNATURE_FAILED,"JWT token must be a non-empty string");if("number"!=typeof t)throw new Ys(Qs.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(!Number.isFinite(t))throw new Ys(Qs.SIGNATURE_FAILED,"Token expiration must be a positive finite number (seconds)");if(t<=0)throw new Ys(Qs.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 Ys(Qs.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:`${zs}${e}`}getJwtHeaders(){const e=this.getAuthorizationHeader();if(null===e||""===e)throw new Ys(Qs.WALLET_NOT_CONNECTED,"No JWT token available. Call login() first.");return{[Vs]: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 er(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),en(e,t,n))}}function tr(e,t,n,a){try{return e()}catch(e){throw a?(a(e,t,n),new Error("Unreachable after error handler")):(n&&n.error(`${t}:`,e),en(e,t,n))}}class nr{constructor(e,t,n,a=!1){this.http=e,this.signatureAuth=t,this.jwtAuth=n,this.refreshPromise=null,this.loginPromise=null,this.logger=new wn({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 Ys(Qs.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 er(async()=>{const e=Date.now(),t=`${js}${e}`;this.logger.debug("Generating login signature",{message:t,timestamp:e});const n=await this.signatureAuth.signMessage(t),a=this.signatureAuth.getAddress();xa(a,"address");const s={address:a,message:t,signature:n.signature};let r;try{this.logger.debug("Sending login request with refresh token support",{address:a,message:t}),r=await this.http.post(ce,{...s,includeRefreshToken:!0})}catch(e){if(400!==e.statusCode)throw e;this.logger.debug("Login returned 400, retrying without includeRefreshToken (backend may not support it)"),r=await this.http.post(ce,s)}const 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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,`Login failed: ${It(e)}`,Nt(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 Ys(Qs.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 er(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(de,{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(de,{},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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,`Token refresh failed: ${It(e)}`,Nt(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(le,{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): ${It(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 Ys(Qs.WALLET_NOT_CONNECTED,"Not authenticated. Call login() first.");return er(async()=>{const e=await this.http.get(ue,void 0,this.jwtAuth.getJwtHeaders());return this.extractSessionData(e)},"SessionAuthService.getSession",this.logger,e=>{if(e instanceof Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,`Failed to get session: ${It(e)}`,Nt(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 Ys(Qs.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: ${It(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 Ys(Qs.SIGNATURE_FAILED,""!==It(e)?It(e):"Authentication failed");const t=un(e,"No data in authentication response"),{accessToken:n,expiresIn:a,address:s,refreshToken:r,refreshExpiresIn:i}=t;if(!ia(n))throw new Ys(Qs.SIGNATURE_FAILED,"Invalid access token in response");if("number"!=typeof a||a<=0)throw new Ys(Qs.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 Ys(Qs.SIGNATURE_FAILED,""!==It(e)?It(e):"Failed to get session");return un(e,"No data in session response")}}class ar 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"}(Js||(Js={}));class sr{constructor(e){this.providerType="privateKey",this.connected=!0;try{this.wallet=new n(e)}catch(e){throw new ar("Invalid private key provided",Js.INVALID_CONFIG,e instanceof Error?e:void 0)}}static fromWallet(e){return new sr(e.privateKey)}async signMessage(e){try{return await this.wallet.signMessage(e)}catch(e){throw new ar("Failed to sign message",Js.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 ar("Failed to sign typed data",Js.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 rr{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{sa(e.messagePrefix,"messagePrefix",!1)}catch{throw new Ys(Qs.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=sr.fromWallet(this.wallet),this.cachedAddress=this.wallet.address,this.cachedGalaAddress=Ia(this.wallet.address)}catch(e){if(e instanceof Ys)throw e;if(e instanceof Wt&&("INVALID_ADDRESS"===e.code||"INVALID_FORMAT"===e.code||"address"===e.field))throw new Ys(Qs.INVALID_ADDRESS,e.message);if(null!==e&&"object"==typeof e&&"message"in e)throw new Ys(Qs.WALLET_NOT_CONNECTED,e.message);throw e}}setWallet(e){if(void 0!==e){if("object"!=typeof e||!("address"in e))throw new Ys(Qs.WALLET_NOT_CONNECTED,"Invalid wallet: must be an ethers Wallet instance or undefined");if("string"!=typeof e.address||""===e.address)throw new Ys(Qs.INVALID_ADDRESS,"Wallet address is not available");this.walletProvider=sr.fromWallet(e),this.cachedAddress=e.address,this.cachedGalaAddress=Ia(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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,"Failed to generate signature for authentication",Nt(e)?e:new Error(It(e)))}}getAddress(){if(this.validateWallet(),this.cachedGalaAddress)return this.cachedGalaAddress;if(this.wallet)return this.formatAddress(this.wallet.address);throw new Ys(Qs.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 Ys(Qs.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 Ys(Qs.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 Ys(Qs.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 Ys(Qs.WALLET_NOT_CONNECTED,"Private key not available with this wallet provider");try{return await this.walletProvider.getPrivateKey()}catch(e){throw new Ys(Qs.WALLET_NOT_CONNECTED,"Private key not available. External wallet providers cannot access private keys. Use PrivateKeyProvider for @gala-chain signing operations.",Nt(e)?e:void 0)}}formatAddress(e){try{return Ia(e)}catch{throw new Ys(Qs.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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,It(e),Nt(e)?e:new Error(It(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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,"Failed to generate authentication headers",Nt(e)?e:new Error(It(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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,"Failed to sign typed data",Nt(e)?e:new Error(It(e)))}}async generateCustomSignature(e){if(!ia(e))throw new Ys(Qs.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 Ys)throw e;throw new Ys(Qs.SIGNATURE_FAILED,"Failed to generate custom message signature",Nt(e)?e:new Error(It(e)))}}validateWallet(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ys(Qs.WALLET_NOT_CONNECTED,"Wallet is required for authentication")}async validateWalletAsync(){if(this.ensureWalletProvider(),!this.walletProvider)throw new Ys(Qs.WALLET_NOT_CONNECTED,"Wallet is required for authentication");if(!this.walletProvider.isConnected())throw new Ys(Qs.WALLET_NOT_CONNECTED,"Wallet is not connected. Call connect() on the wallet provider first.")}}const ir={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",gdexWebSocketUrl:"wss://dex-backend-prod1.defi.gala.com/ws",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",gdexWebSocketUrl:"wss://swap-backend.stage.defi.ovh.gala.com/ws",dexApiBaseUrl:"https://dex-api-platform-dex-stage-gala.gala.com",launchpadFrontendUrl:"https://lpad-frontend-test1.defi.gala.com"}};function or(e){return ir[e]}function cr(e){return`${e.collection}|${e.category}|${e.type}|${e.additionalKey}`}function lr(e){return`${e.collection}$${e.category}$${e.type}$${e.additionalKey}`}const dr=1,ur=2,hr=1002,gr=1,mr=3,pr=[{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}],fr=[{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 yr(e){return"prod"===e?pr:fr}function vr(e){return"prod"===e?"0x9f452b7cC24e6e6FA690fe77CF5dD2ba3DbF1ED9":"0x6a1734E09f3099a3675645D214ce547080ea67e0"}const kr=pr,br=[{symbol:"GALA",amount:"1",mintAddress:"eEUiUs4JWYZrp72djAGF1A8PhpR6rHphGeGN7GbVLp6",isNative:!1,decimals:8},{symbol:"GSOL",amount:"0.001",mintAddress:"So11111111111111111111111111111111111111111",isNative:!0,decimals:9}],wr={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"}},Sr=["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)"],Ar=["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"],Er={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 Tr(e){return/^0x[a-fA-F0-9]{64}$/.test(e)}function Cr(e){const t=new Map;for(const n of e)t.set(vn(n.symbol),n);return t}function Nr(e,t,n){const a=function(e,t){return e.get(vn(t))}(e,t);if(!a){throw Yt(`Token ${t} not supported for ${n}. Supported: ${Array.from(e.keys()).join(", ")}`,"tokenSymbol")}return a}function Ir(e){if(null==e||!Tr(e))throw Qt("privateKey","a 0x-prefixed 64-character hex string (e.g., 0x1234...abcd)","Ethereum private key")}function Dr(e,t,n){return{symbol:e,quantity:t,decimals:n,contractAddress:null,isNative:!0}}function _r(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??18,contractAddress:e.contractAddress,isNative:!1}}function xr(e,t){return{symbol:e.symbol,quantity:t,decimals:e.decimals??9,contractAddress:e.mintAddress,isNative:e.isNative??!1}}function Rr(e,t,n){const a=e.find(e=>e.symbol===t);if(!a){const a=e.map(e=>e.symbol).join(", ");throw Xt("tokenSymbol",`Unsupported ${n} token: ${t}. Supported: ${a}`)}return a}const Fr={Ethereum:"Ethereum bridging not configured. Provide ethereumPrivateKey in config.",Solana:"Solana bridging not configured. Provide solanaPrivateKey in config."};function Br(e,t,n){if(void 0===e)throw Yt(n??Fr[t],`${t.toLowerCase()}Strategy`);return e}function Or(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 Ur="Token symbol resolution failed. This is an internal error - BridgeService should resolve tokenId to symbol before calling strategy.",Pr="Bridge request ID missing from RequestTokenBridgeOut response",Mr="BridgeTokenOut response missing transaction hash";function $r(e){if(void 0===e||""===e)throw Yt(Ur,"tokenSymbol");return e}function Lr(e,t){if(!a(e)){throw Qt(t??"address","a valid 0x-prefixed Ethereum address",e)}}function Kr(e,t){try{return new y(e)}catch{throw Qt(t??"address","a valid Solana address (base58)",e)}}function Gr(e){try{return new y(e)}catch{throw Qt("address","a valid Solana address (base58)",e)}}function Wr(e){const t={};for(const[n,a]of Object.entries(e))void 0!==a&&(a&&"object"==typeof a&&!Array.isArray(a)?t[n]=Wr(a):t[n]=a);return t}function Hr(e,t){const n=Vn(e,-1);if(n<=0)throw new Error(`Invalid bridge amount for ${t}: "${e}". Amount must be a positive number.`);return n}var qr=Object.freeze({__proto__:null,default:{}});let jr=null;if("undefined"==typeof window&&"undefined"!=typeof require)try{jr=qr}catch{}function Vr(){if(void 0!==jr?.randomUUID)try{return jr.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 zr={name:"GalaConnect",chainId:1},Xr=[{name:"destinationChainId",type:"uint256"},{name:"destinationChainTxFee",type:"destinationChainTxFee"},{name:"quantity",type:"string"},{name:"recipient",type:"string"},{name:"tokenInstance",type:"tokenInstance"},{name:"uniqueKey",type:"string"}],Qr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"}],Jr=[{name:"collection",type:"string"},{name:"category",type:"string"},{name:"type",type:"string"},{name:"additionalKey",type:"string"},{name:"instance",type:"string"}],Yr=[{name:"name",type:"string"},{name:"symbol",type:"string"}],Zr={GalaTransaction:Xr,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:Qr,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:Jr,externalQuoteToken:Yr,tokenInstance:Jr},ei={GalaTransaction:Xr,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:Qr,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:Yr,externalQuoteToken:Yr,externalCrossRateToken:Yr,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:Jr,tokenInstance:Jr};async function ti(e,t){const{wallet:n}=t,a=e.uniqueKey??`galaconnect-operation-${Vr()}`,s="string"==typeof e.destinationChainId?Xn(e.destinationChainId,1):e.destinationChainId,r=function(e){const t={...e,galaDecimals:"string"==typeof e.galaDecimals?Xn(e.galaDecimals,0):e.galaDecimals,timestamp:"string"==typeof e.timestamp?Xn(e.timestamp,0):e.timestamp};if(e.galaExchangeRate&&(t.galaExchangeRate={...e.galaExchangeRate,timestamp:"string"==typeof e.galaExchangeRate.timestamp?Xn(e.galaExchangeRate.timestamp,0):e.galaExchangeRate.timestamp}),e.galaExchangeCrossRate){const n=e.galaExchangeCrossRate;t.galaExchangeCrossRate={...n,timestamp:"string"==typeof n.timestamp?Xn(n.timestamp,0):n.timestamp},n.baseTokenCrossRate&&(t.galaExchangeCrossRate.baseTokenCrossRate={...n.baseTokenCrossRate,timestamp:"string"==typeof n.baseTokenCrossRate.timestamp?Xn(n.baseTokenCrossRate.timestamp,0):n.baseTokenCrossRate.timestamp}),n.quoteTokenCrossRate&&(t.galaExchangeCrossRate.quoteTokenCrossRate={...n.quoteTokenCrossRate,timestamp:"string"==typeof n.quoteTokenCrossRate.timestamp?Xn(n.quoteTokenCrossRate.timestamp,0):n.quoteTokenCrossRate.timestamp})}return t}(e.destinationChainTxFee),i=Boolean(r.galaExchangeCrossRate),o={destinationChainId:s,destinationChainTxFee:Wr(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?ei:Zr}(i),l=await n.signTypedData(zr,c,o),d=`Ethereum Signed Message:\n${T({domain:zr,message:o,primaryType:"GalaTransaction",types:c}).length}`;return{...o,signature:l,prefix:d,types:c,domain:zr}}async function ni(e,t){const{amount:n,recipientAddress:a,tokenSymbol:s}=e,{galaConnectClient:r,tokenMetadataResolver:i,ethereumWallet:o,destinationChainId:c,destinationChain:l,validateRecipientAddress:d}=t,u=$r(s);Hr(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 ti(m,{wallet:o}),f=function(e){if(void 0===e||""===e)throw Yt(Pr,"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 Yt(Mr,"transactionHash");return t}(await r.bridgeTokenOut({bridgeFromChannel:"asset",bridgeRequestId:f})),tokenSymbol:u,amount:n,feePaid:g.estimatedTotalTxFeeInGala,baseUrl:r.getBaseUrl()})}var ai;!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"}(ai||(ai={}));const si=ai.COMPLETED,ri=ai.FAILED,ii=ai.DELIVERY_FAILED;class oi{constructor(e){if(this.lastTimestamp=0,this.pendingPromise=Promise.resolve(),this.chainLength=0,this.maxChainLength=1e3,e<=0)throw nn("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(Nt(e)?e:new Error(It(e)))}}),this.chainLength++,this.chainLength>=this.maxChainLength){this.chainLength=0;const e=this.pendingPromise;this.pendingPromise=e.then(()=>Promise.resolve())}return a}}const ci={maxRetries:3,initialDelayMs:1e3,maxDelayMs:3e4,backoffMultiplier:2,jitterFactor:.1},li=new Set([408,429,500,502,503,504]),di=[/ECONNRESET/i,/ECONNREFUSED/i,/ETIMEDOUT/i,/ENOTFOUND/i,/EAI_AGAIN/i,/socket hang up/i,/network/i,/timeout/i,/aborted/i];function ui(e){if(null!=e&&"object"==typeof e){const t=e;if("number"==typeof t.status)return li.has(t.status);if("number"==typeof t.statusCode)return li.has(t.statusCode);const n=_t(e);if("string"==typeof n&&("ECONNRESET"===n||"ECONNREFUSED"===n||"ETIMEDOUT"===n||"ENOTFOUND"===n||"EAI_AGAIN"===n))return!0}const t=It(e);return di.some(e=>e.test(t))}function hi(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 gi(e){return new Promise(t=>setTimeout(t,e))}function mi(e,t){return Br(e.get("Ethereum"),"Ethereum",t)}function pi(e,t){return Br(e.get("Solana"),"Solana",t)}function fi(e,t){return e??t.getWalletAddress()}async function yi(e,t,n,a,s){const r=await t.getTokenMetadata(a);return function(e){const t="string"==typeof e.timestamp?Xn(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 vi(e,t){return function(e){const t=Xn(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===si,isFailed:t===ri||t===ii}}(await e.getBridgeStatus(t))}function ki(e,t,n){try{const n=function(e,t){if(!ia(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}(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 function(e,t,n,a){const s=e?.split?.(t)??[],r=void 0!==n?` (${n})`:"";return new Wt(`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: ${It(a)}`,"token",`INVALID_${"|"===t?"PIPE":"DOLLAR"}_DELIMITED_TOKEN`)}(e,t,n,a)}}function bi(e){return ki(e,"|","pipe-delimited token")}function wi(e){return"string"==typeof e&&e.includes("$")}function Si(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=bi(e);else{if(!Si(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:cr(t)}}function Ei(e,t){let n;try{n=Qn(e,"amount")}catch(t){throw rn("amount",`${e} (${It(t)})`)}if(!n.isFinite())throw rn("amount",e);const a=n.multipliedBy(Cs(10).pow(t));if(!a.isInteger())throw rn("amount",`${e} (cannot be represented with ${t} decimals)`);return BigInt(a.toFixed(0))}function Ti(e,t){return Cs(e.toString()).dividedBy(Cs(10).pow(t)).toFixed(t).replace(/\.?0+$/,"")}class Ci{constructor(e){this.cache=new Map,this.galaConnectClient=e.galaConnectClient}async getTokenMetadata(e){const t=kn(e),n=this.cache.get(t);if(n)return n;const a=wr[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=kn(e);return this.cache.has(t)||t in wr}clearCache(){this.cache.clear()}async fetchFromApi(e){let t=e,n=await this.galaConnectClient.getBridgeConfigurations(t),a=n.find(e=>kn(e.symbol)===kn(t)&&e.verified);if(a||e.startsWith("G")||(t=`G${e}`,n=await this.galaConnectClient.getBridgeConfigurations(t),a=n.find(e=>kn(e.symbol)===kn(t)&&e.verified)),!a)throw new Error(`Unable to locate token metadata for ${e}`);return s={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey},r=a.decimals,i=a.channel,{descriptor:{collection:s.collection,category:s.category,type:s.type,additionalKey:s.additionalKey},decimals:r,...void 0!==i?{channel:i}:{}};var s,r,i}}class Ni 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 Ii="https://dex-api-platform-dex-prod-gala.gala.com",Di="https://galachain-gateway-chain-platform-galachain-mainnet.gala.com",_i=12,xi=!0,Ri=3,Fi=1e3;class Bi{constructor(e){this.baseUrl=e.baseUrl??Ii,this.galachainBaseUrl=e.galachainBaseUrl??Di,this.walletAddress=e.walletAddress,this.rateLimiter=new oi(e.requestsPerSecond??_i),this.defaultHeaders={"Content-Type":"application/json","X-Wallet-Address":this.walletAddress};const t=e.enableRetry??xi;this.retryOptions=t?{maxRetries:e.maxRetries??Ri,initialDelayMs:e.retryInitialDelayMs??Fi,...e.onRetry&&{onRetry:e.onRetry},shouldRetry:e=>ui(e instanceof Ni?{status:e.status}:e)}:null}getBaseUrl(){return this.baseUrl}async getBridgeConfigurations(e){return er(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?jn(e,{rawBody:e}):{message:"Failed to fetch bridge configurations"},new Ni(n.status,"/v1/connect/bridge-configurations",t)}return(await n.json()).data.tokens},"GalaConnectClient.getBridgeConfigurations",void 0,e=>{if(e instanceof Ni)throw e;throw en(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 er(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=jn(t,{rawBody:t.slice(0,n)});throw new Ni(i.status,e,a)}const o=await i.text();if(""!==o){const t=function(e){if(Sn(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: ${It(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 Ni)throw e;throw en(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 Ni(t,e,s)}}return a});return this.retryOptions?async function(e,t={}){const n={...ci,...t},a=t.shouldRetry??(e=>ui(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=hi(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 Oi{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===ai.COMPLETED||t.status===ai.FAILED||t.status===ai.DELIVERY_FAILED)return t;if(Nn(r)>a)throw Zt(`Bridge transaction timed out after ${a}ms. Last status: ${t.status}`,e,"TIMEOUT");await new Promise(e=>setTimeout(e,n))}}}class Ui extends Oi{constructor(e,t){super(),this.galaConnectClient=e,this.tokenConfigs=t}async getStatus(e){return vi(this.galaConnectClient,e)}getSupportedTokens(){return e=this.tokenConfigs,Array.from(e.keys());var e}isTokenSupported(e){return function(e,t){return e.has(vn(t))}(this.tokenConfigs,e)}}async function Pi(e,t,...n){const a=e[t];return"function"==typeof a?await a(...n):await e.getFunction(t)(...n)}class Mi extends Ui{constructor(e){const t=e.tokenConfigs??kr;super(e.galaConnectClient,Cr(t)),this.network="Ethereum",this.galaChainWalletAddress=e.galaChainWalletAddress,Ir(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 Ci({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return yi(this.galaConnectClient,this.tokenMetadataResolver,"Ethereum",e)}async bridgeOut(e){return ni(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:ur,destinationChain:"Ethereum",validateRecipientAddress:Lr})}async bridgeIn(e){const{amount:a,sourcePrivateKey:s,recipientAddress:i,tokenSymbol:o}=e,c=$r(o);if(Hr(a,c),void 0!==s&&""!==s&&!Tr(s))throw Qt("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=Nr(this.tokenConfigs,c,"Ethereum bridge"),u=await this.tokenMetadataResolver.getTokenMetadata(c),h=new r(d.contractAddress,Sr,l),g=await Pi(h,"decimals"),m=Xn("string"==typeof g||"number"==typeof g||"bigint"==typeof g?g:void 0,18),p=Ei(a,m),f=await Pi(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 Yt(`Insufficient ${c} balance on Ethereum. Needed ${Ti(p,m)}, have ${Ti(y,m)}`,"amount")}const v=function(e){const n=new Ta;if("client"===n.detectFormat(e))return e;const a=n.normalizeInput(e);if(null==a)throw Qt("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 Or({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 ra.ETH_ADDRESS.test(e)}getWalletAddress(){return this.ethereumWalletAddress}async getEthereumTokenBalance(e,t){const n=Nr(this.tokenConfigs,e,"Ethereum"),a=t??this.ethereumWalletAddress;Lr(a);const s=new r(n.contractAddress,Sr,this.ethereumProvider),i=await Pi(s,"balanceOf",a);if("bigint"!=typeof i)throw new Error("Ethereum balance response was not a bigint");return Ti(i,n.decimals??18)}async getEthereumNativeBalance(e){const t=e??this.ethereumWalletAddress;Lr(t);return Ti(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 Qt("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>=Mi.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: ${It(e)}`}}}async executeBridgeDeposit(e){const t=new r(this.ethereumBridgeContract,Ar,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 Yt("Bridge transaction receipt not available","ethereumRpcUrl");await gi(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:Ti(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 Pi(t,"name");if("string"!=typeof c)throw new Error("Ethereum token name response was not a string");const l=c,d=await Pi(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:Xn(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 Pi(a,"bridgeOutWithPermit",n.contractAddress,s,dr,r,h,m.v,m.r,m.s)}async bridgeWithApproval(e,t,n,a,s,r){const i=await Pi(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 Pi(t,"approve",this.ethereumBridgeContract,s);await e.wait()}return await Pi(n,"bridgeOut",a.contractAddress,s,0,dr,r)}}Mi.ETHEREUM_FINALITY_THRESHOLD=12;function $i(e,t,n,a,s){const[r]=y.findProgramAddressSync([t.toBuffer(),a.toBuffer(),e.toBuffer()],s);return r}class Li extends Ui{constructor(e){const t=e.tokenConfigs??br;super(e.galaConnectClient,Cr(t)),this.network="Solana",this.solanaBridgeAccountCache=new Map,this.galaChainWalletAddress=e.galaChainWalletAddress,Ir(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 v(r,"confirmed");try{i=D.decode(e.solanaPrivateKeyBase58)}catch{throw Qt("solanaPrivateKeyBase58","base58-encoded string",e.solanaPrivateKeyBase58.slice(0,20)+"...")}if(64!==i.length)throw Qt("solanaPrivateKeyBase58","64 bytes when decoded",`${i.length} bytes`);this.solanaKeypair=k.fromSecretKey(i);const o=e.solanaBridgeProgram??"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS";this.solanaBridgeProgramId=new y(o),[this.solanaBridgeTokenAuthority]=y.findProgramAddressSync([Buffer.from("bridge_token_authority")],this.solanaBridgeProgramId),[this.solanaBridgeConfigPda]=y.findProgramAddressSync([Buffer.from("configv1")],this.solanaBridgeProgramId),[this.solanaNativeBridgePda]=y.findProgramAddressSync([Buffer.from("native_sol_bridge")],this.solanaBridgeProgramId),this.tokenMetadataResolver=new Ci({galaConnectClient:this.galaConnectClient})}async estimateFee(e,t){return yi(this.galaConnectClient,this.tokenMetadataResolver,"Solana",e)}async bridgeOut(e){return ni(e,{galaConnectClient:this.galaConnectClient,tokenMetadataResolver:this.tokenMetadataResolver,ethereumWallet:this.ethereumWallet,destinationChainId:hr,destinationChain:"Solana",validateRecipientAddress:Kr})}async bridgeIn(e){const{amount:t,sourcePrivateKey:n,recipientAddress:a,tokenSymbol:s}=e,r=$r(s);Hr(t,r);let i=this.solanaKeypair;if(void 0!==n&&""!==n){let e;try{e=D.decode(n)}catch{throw Qt("sourcePrivateKey","base58-encoded string",n.slice(0,20)+"...")}if(64!==e.length)throw Qt("sourcePrivateKey","64 bytes when decoded",`${e.length} bytes`);i=k.fromSecretKey(e)}const o=Nr(this.tokenConfigs,r,"Solana bridge"),c=await this.tokenMetadataResolver.getTokenMetadata(r),l=Ei(t,c.decimals),d=a??this.galaChainWalletAddress;return Or({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 y(e),!0}catch{return!1}}getWalletAddress(){return this.solanaKeypair.publicKey.toBase58()}async getSolanaTokenBalance(e,t){const n=Nr(this.tokenConfigs,e,"Solana");if(n.isNative)return this.getSolanaNativeBalance(t);const a=t??this.solanaKeypair.publicKey.toBase58(),s=Gr(a),r=$i(new y(n.mintAddress),s,0,C,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:N.decode(s.data).amount,decimals:0}}(this.solanaConnection,r,0,C),t=n.decimals??8;return Ti(e.amount,t)}catch(t){if(Nt(t)&&t.message.includes("could not find")){return Ti(0n,n.decimals??8)}throw Yt(`Failed to fetch ${e} balance for ${a}: ${It(t)}`,`${e}Account`)}}async getSolanaNativeBalance(e){const t=Gr(e??this.solanaKeypair.publicKey.toBase58()),n=await this.solanaConnection.getBalance(t,"confirmed");return Ti(BigInt(n),9)}async requestDevnetAirdrop(e=1,t){ta(e,1e-5,2,"amount");const n=void 0!==t&&""!==t?Gr(t):this.solanaKeypair.publicKey,a=this.solanaConnection.rpcEndpoint;if(!a.includes("devnet"))throw Yt(`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*E);return await this.solanaConnection.requestAirdrop(n,s)}async getSolanaTransactionStatus(e){if(!ia(e))throw Qt("signature","a non-empty string");if(!/^[1-9A-HJ-NP-Za-km-z]{80,90}$/.test(e))throw Qt("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 y(e.tokenConfig.mintAddress),n=Boolean(e.tokenConfig.isNative),a=n?void 0:await this.getSolanaBridgeAccounts(t),s=n?void 0:$i(t,e.keypair.publicKey,0,C,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 b;l.add(w.setComputeUnitPrice({microLamports:375e3}),w.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=Nt(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=Nt(e)?e:new Error(It(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 gi(r)}throw a??new Error("Transaction confirmation failed after max retries")}buildNativeBridgeInstruction(e,t,n,a){const s=Buffer.concat([Er.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:A.programId,isSigner:!1,isWritable:!1}],data:s})}buildTokenBridgeInstruction(e,t,n,a,s,r,i){const o=Buffer.concat([Er.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:A.programId,isSigner:!1,isWritable:!1},{pubkey:C,isSigner:!1,isWritable:!1}],data:o})}async getSolanaBridgeAccounts(e){const t=e.toBase58(),n=this.solanaBridgeAccountCache.get(t);if(n)return n;const[a]=y.findProgramAddressSync([Buffer.from("mint_lookup_v1"),e.toBuffer()],this.solanaBridgeProgramId),s=await this.solanaConnection.getAccountInfo(a,"confirmed");if(!s)throw Yt(`Mint lookup account not found for ${a.toBase58()}`,"solanaBridgeProgram");if(!s.owner.equals(this.solanaBridgeProgramId))throw Yt("Mint lookup account owner mismatch for Solana bridge program","solanaBridgeProgram");if(s.data.length<40)throw Yt("Mint lookup account data is unexpectedly short","solanaBridgeProgram");const r={mintLookup:a,tokenBridge:new y(s.data.slice(8,40)),bridgeTokenAccount:$i(e,this.solanaBridgeTokenAuthority,0,C,I)};return this.solanaBridgeAccountCache.set(t,r),r}}const Ki={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"}},Gi={solanaBridgeProgram:"AaE4dTnL75XqgUJpdxBKg6vS9sTJgBPJwBQRVhD29WwS",rateLimit:12,pollInterval:15e3,pollTimeout:27e5};class Wi{static normalizeGalaChainAddress(e){const t=new Ta;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 Yt(`Invalid GalaChain address format: ${e}`,"galaChainWalletAddress");const s=t.extractHex(a);return`eth|${Wi.checksumAddress(s)}`}static checksumAddress(e){const t=e.toLowerCase(),n=Aa(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=ir["stage"===n?"stage":"prod"],s=Ki[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??vr(n),solanaBridgeProgram:e.solanaBridgeProgram??Gi.solanaBridgeProgram,rateLimit:e.rateLimit??Gi.rateLimit,pollInterval:e.pollInterval??Gi.pollInterval,pollTimeout:e.pollTimeout??Gi.pollTimeout,galaChainWalletAddress:t,ethereumPrivateKey:e.ethereumPrivateKey,environment:n};this.config=e.solanaPrivateKey?{...r,solanaPrivateKey:e.solanaPrivateKey}:r,this.galaConnectClient=new Bi({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=yr(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 Mi(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:br};this.strategies.set("Solana",new Li(e))}}async resolveTokenSymbol(e,t){return er(async()=>{if(!this.bridgeableTokenService)throw Yt("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 Yt([`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 er(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 er(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.destinationChain),n=this.getStrategy(e.destinationChain);if(!n.isValidAddress(e.recipientAddress))throw Yt(`Invalid recipient address for ${e.destinationChain}: ${e.recipientAddress}`,"recipientAddress");if(!n.isTokenSupported(t))throw Yt(`Token ${t} is not supported for ${e.destinationChain} bridging`,"tokenSymbol");return n.bridgeOut({...e,tokenSymbol:t})},"BridgeService.bridgeOut")}async bridgeIn(e){return er(async()=>{const t=await this.resolveTokenSymbol(e.tokenId,e.sourceChain),n=this.getStrategy(e.sourceChain);if(!n.isTokenSupported(t))throw Yt(`Token ${t} is not supported for ${e.sourceChain} bridging`,"tokenSymbol");return n.bridgeIn({...e,tokenSymbol:t})},"BridgeService.bridgeIn")}async getBridgeStatus(e,t){return er(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=Nt(e)?e:new Error(It(e))}const s=this.strategies.get("Solana");if(s)try{return await s.getStatus(e)}catch(e){a=Nt(e)?e:new Error(It(e))}const r=a?` (last error: ${a.message})`:"";throw Zt(`Unable to get status for transaction ${e}${r}`,e)},"BridgeService.getBridgeStatus")}async waitForBridgeCompletion(e,t){return er(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 Zt(`Unable to wait for transaction ${e}: no suitable strategy found`,e)},"BridgeService.waitForBridgeCompletion")}getSupportedBridgeTokens(e){const t=[],n=yr(this.config.environment);if(null==e||"Ethereum"===e)for(const e of n)t.push({symbol:e.symbol,decimals:e.decimals??18,verified:!0,supportedChains:["Ethereum"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{ethereum:e.contractAddress}});if(null==e||"Solana"===e)for(const e of br){const n=t.find(t=>t.symbol===e.symbol);n?(n.supportedChains.push("Solana"),n.externalAddresses.solana=e.mintAddress):t.push({symbol:e.symbol,decimals:e.decimals??9,verified:!0,supportedChains:["Solana"],galaChainDescriptor:{collection:e.symbol.startsWith("G")?e.symbol:`G${e.symbol}`,category:"Unit",type:"none",additionalKey:"none"},externalAddresses:{solana:e.mintAddress}})}return t}getSupportedBridgeChains(){return Array.from(this.strategies.keys())}isTokenSupported(e,t){if(null!=t){const n=this.strategies.get(t);return n?.isTokenSupported(e)??!1}for(const t of this.strategies.values())if(t.isTokenSupported(e))return!0;return!1}isValidAddress(e,t){const n=this.strategies.get(t);return n?.isValidAddress(e)??!1}async getEthereumTokenBalance(e,t){return er(async()=>mi(this.strategies).getEthereumTokenBalance(e,t),"BridgeService.getEthereumTokenBalance")}async getEthereumNativeBalance(e){return er(async()=>mi(this.strategies).getEthereumNativeBalance(e),"BridgeService.getEthereumNativeBalance")}async getSolanaTokenBalance(e,t){return er(async()=>pi(this.strategies).getSolanaTokenBalance(e,t),"BridgeService.getSolanaTokenBalance")}async getSolanaNativeBalance(e){return er(async()=>pi(this.strategies).getSolanaNativeBalance(e),"BridgeService.getSolanaNativeBalance")}async fetchEthereumWalletTokenBalance(e,t){return er(async()=>{const n=mi(this.strategies),a=Rr(yr(this.config.environment),e,"Ethereum"),s=fi(t,n);return _r(a,await n.getEthereumTokenBalance(e,s))},"BridgeService.fetchEthereumWalletTokenBalance")}async fetchEthereumWalletNativeBalance(e){return er(async()=>{const t=mi(this.strategies),n=fi(e,t);return Dr("ETH",await t.getEthereumNativeBalance(n),18)},"BridgeService.fetchEthereumWalletNativeBalance")}async fetchSolanaWalletTokenBalance(e,t){return er(async()=>{const n=pi(this.strategies),a=Rr(br,e,"Solana"),s=fi(t,n);return xr(a,await n.getSolanaTokenBalance(e,s))},"BridgeService.fetchSolanaWalletTokenBalance")}async fetchSolanaWalletNativeBalance(e){return er(async()=>{const t=pi(this.strategies),n=fi(e,t);return Dr("SOL",await t.getSolanaNativeBalance(n),9)},"BridgeService.fetchSolanaWalletNativeBalance")}async requestSolanaDevnetAirdrop(e,t){return er(async()=>pi(this.strategies).requestDevnetAirdrop(e,t),"BridgeService.requestSolanaDevnetAirdrop")}async getSolanaTransactionStatus(e){return er(async()=>pi(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 er(async()=>mi(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 er(async()=>{const t=mi(this.strategies),n=fi(e,t),a=yr(this.config.environment),[s,...r]=await Promise.all([t.getEthereumNativeBalance(n),...a.map(async e=>_r(e,await t.getEthereumTokenBalance(e.symbol,n)))]);return{address:n,native:Dr("ETH",s,18),tokens:r,timestamp:Date.now()}},"BridgeService.fetchEthereumWalletAllBalances")}async fetchSolanaWalletAllBalances(e){return er(async()=>{const t=pi(this.strategies),n=fi(e,t),[a,...s]=await Promise.all([t.getSolanaNativeBalance(n),...br.map(async e=>xr(e,await t.getSolanaTokenBalance(e.symbol,n)))]);return{address:n,native:Dr("SOL",a,9),tokens:s,timestamp:Date.now()}},"BridgeService.fetchSolanaWalletAllBalances")}getStrategy(e){const t=this.strategies.get(e);if(!t)throw Yt(`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="7.0.0-beta.2",zi={DEFAULT_LIMIT:10,BACKEND_MAX_PAGE_SIZE:20};function Xi(e,t){if("number"!=typeof e||!Number.isInteger(e))throw sn("total","a non-negative integer",e);if(e<0)throw tn("total",0,1/0,e);if("number"!=typeof t||!Number.isInteger(t))throw sn("limit","a non-negative integer",t);if(t<0)throw tn("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 ka{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(!ia(e))throw Xt("tokenName","Token name");const n=yn(e);if(!t.PATTERN.test(n))throw Qt("tokenName",`${t.MIN_LENGTH}-${t.MAX_LENGTH} alphanumeric characters`,"Token name")}(e,t)}validateRequiredString(e,t,n){!function(e,t,n){if(!ia(e))throw Xt(t,n)}(e,t,n)}validateOptionalString(e,t,n,a){!function(e,t,n,a){if(null!=e){if("string"!=typeof e)throw sn(t,"string",typeof e,n);if(e.length>a)throw an(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 sn(t,"number",typeof e,n);if(e<a||e>s)throw tn(t,a,s,e,n)}}(e,t,n,a,s)}validateOptionalDate(e,t,n){!function(e,t,n){if(null!=e&&!Cn(e))throw Qt(t,"a valid ISO 8601 date string",n)}(e,t,n)}validatePositiveInteger(e,t,n){ya(e,t,n)}validateStatusFilter(e,t,n="status"){va(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 qt("Admin API key required for this operation. Set streamAdminApiKey in SDK config.");return{[Zi]:this.adminApiKey}}getJwtHeaders(){if(!this.jwtAuth)throw new qt("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 ln(e,"Backend request failed",!0),un(e,"No data in backend response")}extractDataOrNull(e){return ln(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??yn(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(gt.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(gt.UPDATE_SETTINGS,t,this.getDualAuthHeaders())).settings}}async getModeration(e){this.validatePositiveInteger(e.flagId,"flagId","Flag ID");const t=gt.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=gt.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(gt.GET_STATUS,{},this.getDualAuthHeaders())).status}}}const no=da({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(Bt(t,()=>{pa(e.description,"description",255)}),t.length>a&&(t[a]="Description must be 255 characters or less"),void 0!==e.tokenNames){const n=t.length;Bt(t,()=>{if(!Array.isArray(e.tokenNames))throw sn("tokenNames","an array",e.tokenNames);if(!e.tokenNames.every(e=>"string"==typeof e))throw sn("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;Bt(t,()=>{fa(e.expiresAt,"expiresAt")}),t.length>n&&(t[n]="expiresAt must be a valid ISO 8601 date string")}}class ro extends ka{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),ln(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 Wt(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(we.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>xn))throw sn("pageSize",`number between 1 and ${xn}`,typeof e.pageSize);if(void 0!==e.cursor&&("string"!=typeof e.cursor||""===e.cursor.trim()))throw sn("cursor","non-empty string",typeof e.cursor)}(e),this.logger.debug("Listing API keys",e);const t=Ji(e,xn),n=await this.http.get(we.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=we.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 Wt(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=we.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=we.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=la(io);function co(e){if(!ia(e.userAddress))throw Xt("userAddress");if(!(null==(t=e.reason)||""===t||"string"==typeof t&&!ma(t)&&t.length<=On.BAN_REASON.MAX_LENGTH))throw new Wt(`reason must be at most ${On.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t,n;if(n=e.durationSeconds,!(oa(n)||"number"==typeof n&&n>=Pn&&n<=Mn))throw new Wt(`durationSeconds must be between ${Pn} and ${Mn} 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){ha(e.tokenName,"tokenName",In),co(e)}(e);const t=this.buildEndpoint(he,{tokenName:e.tokenName}),n=uo(e),a=await this.http.post(t,n,this.getMultiAuthHeaders());return{ban:this.extractData(a),tokenName:yn(e.tokenName)}}async removeBan(e){!function(e){if(ha(e.tokenName,"tokenName",In),!ia(e.userAddress))throw Xt("userAddress")}(e);const t=this.buildEndpoint(pe,{tokenName:e.tokenName,userAddress:e.userAddress}),n=await this.http.delete(t,{},this.getMultiAuthHeaders()),a=this.extractDataOrNull(n);return{removed:a?.removed??!0,tokenName:yn(e.tokenName),userAddress:a?.userAddress??e.userAddress.toLowerCase()}}async listBans(e){!function(e){ha(e.tokenName,"tokenName",In),ca(0,void 0,xn,e.pageSize)}(e);const t=this.buildEndpoint(ge,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,xn);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(ha(e.tokenName,"tokenName",In),!ia(e.userAddress))throw Xt("userAddress")}(e);const t=this.buildEndpoint(me,{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:yn(e.tokenName),userAddress:e.userAddress.toLowerCase()}}async getActiveUsers(e){!function(e){if(ha(e.tokenName,"tokenName",In),void 0!==e.type&&!oo(e.type))throw new Wt(`type must be one of: ${Object.values(io).join(", ")}`,"type",$t)}(e);const t=this.buildEndpoint(fe,{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(ye,t,this.getDualAuthHeaders());return{ban:this.extractData(n)}}async removeGlobalBan(e){!function(e){if(!ia(e.userAddress))throw Xt("userAddress")}(e);const t=this.buildEndpoint(be,{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){ca(0,void 0,xn,e.pageSize)}(t);const n=this.buildPaginationParams(t,xn);this.addOptionalFilterParams(n,t,["search","name","userAddress"]);const a=await this.http.get(ve,n,this.getDualAuthHeaders()),s=this.extractData(a);return{items:s.bans,pageInfo:s.pageInfo}}async getGlobalBan(e){!function(e){if(!ia(e.userAddress))throw Xt("userAddress")}(e);const t=this.buildEndpoint(ke,{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(!ia(t=e)||!t.includes("|"))throw new Wt(`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(!Si(e))throw new Wt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) must be non-empty strings","tokenId","INVALID_TOKEN_ID_FORMAT");return e}if(!Si(e))throw new Wt("Invalid tokenId object format. All fields (collection, category, type, additionalKey) are required","tokenId","INVALID_TOKEN_ID_FORMAT");return{...e,instance:"0"}}throw new Wt(`Invalid tokenId type: ${typeof e}. Expected string, TokenClassKey, or TokenInstanceKey`,"tokenId","INVALID_TOKEN_ID_TYPE")}function mo(e){return function(e){try{if(!ia(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("$");if(n.length<4)throw new Error(`Invalid vault address format: expected at least 4 parts separated by $, got ${n.length}`);const[a,s,r,...i]=n;if(""===a||""===s||""===r)throw new Error("Collection, category, and type must be non-empty");const o=i.slice(0,-1),c=o.length>0?o.join("$"):i[0];if(void 0===a||void 0===s||void 0===r||""===c||void 0===c)throw new Error("AdditionalKey must be non-empty");return{collection:a,category:s,type:r,additionalKey:c}}catch(t){throw new Wt(`Invalid vault address: "${e}". Expected format: "service|Token$Unit$SYMBOL$additionalKey$launchpad". Error: ${It(t)}`,"vaultAddress","INVALID_VAULT_ADDRESS_FORMAT")}}(e)}function po(e){return{...mo(e),instance:"0"}}function fo(e){return mo(e).type}function yo(e){return cr(go(e))}var vo=Object.freeze({__proto__:null,extractTokenSymbolFromVault:fo,isTokenClassKeyStrict:Si,normalizeToTokenInstanceKey:go,normalizeTokenIdToString:yo,parseVaultAddressToTokenClassKey:mo,parseVaultAddressToTokenInstance:po});class ko{constructor(e,t=!1,n){this.dexApiHttp=e,this.logger=new wn({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(oa(r)||!Array.isArray(r.tokens))throw new Wt("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 en(e,t,this.logger)}}class bo extends ba{constructor(e=!1){super(e),this.primaryIndex=new Map,this.secondaryIndex=new Map,this.fetchTimestamps=new Map}normalizeKey(e){return vn(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 So 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 Ao extends ko{constructor(e,t=!1){super(e,t,"BridgeableTokenService"),this.cache=new So(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})`),er(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 er(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,tokenSymbol:s?.symbol??bi(a).collection,network:n};return 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:Zn(e.maxAcceptableReverseBondingCurveFee)}}const To={BuyNativeDto:class extends _{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Zn(t),this.expectedToken=ea(n),this.extraFees=Eo(a)}},BuyExactDto:class extends _{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=ea(t),this.expectedNativeToken=Zn(n),this.extraFees=Eo(a)}},SellExactDto:class extends _{constructor(e,t,n="0",a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.tokenQuantity=ea(t),this.expectedNativeToken=Zn(n),this.extraFees=Eo(a)}},SellNativeDto:class extends _{constructor(e,t,n,a={maxAcceptableReverseBondingCurveFee:"0"}){super(),this.vaultAddress=e,this.nativeTokenQuantity=Zn(t),this.expectedToken=ea(n),this.extraFees=Eo(a)}}};function Co(e,t,n){let a;ta(t,0,1,"slippageToleranceFactor");try{a=Qn(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 Cs(r).isLessThan(0)&&(r=Cs(0)),Ns(r)}function No(e){return`${e}-${Date.now()}_${B().replace(/-/gu,"").substring(0,26)}`}function Io(){return No("galaconnect-operation")}function Do(e,t){const n={[e]:[]},a=new Set;function s(e){const t=n[e];if(void 0===t)throw new Error("Missing EIP-712 type "+e);return t}function r(e,t,i,o=!1){if(void 0===t)return;if(Array.isArray(t)){const n=r(e,t[0],i,!0);return o||(a.add(e),s(i).push({name:e,type:(n??e)+"[]"})),void 0===n?void 0:n+"[]"}if("object"==typeof t&&null!==t){if(void 0!==n[e]||a.has(e))throw new Error("Name collisions not yet supported");n[e]=[];for(const[n,s]of Object.entries(t)){if(a.has(n))throw new Error("Name collisions not yet supported");r(n,s,e)}return o||(a.add(e),s(i).push({name:e,type:e})),e}let c;switch(typeof t){case"string":c="string";break;case"number":c="uint256";break;case"boolean":c="bool";break;case"bigint":case"symbol":case"function":case"undefined":case"object":throw new Error("Unsupported type for fieldName "+e+", "+typeof t);default:throw new Error("Unsupported type: "+typeof t)}return o||(a.add(e),s(i).push({name:e,type:c})),c}for(const[n,a]of Object.entries(t))r(n,a,e);return n}const _o={name:"GalaChain"},xo={name:"ethereum",chainId:1};function Ro(e){if("string"!=typeof e)throw new Error("Wallet returned an invalid signature");return e}function Fo(e,t,n,a){return{...e,signature:t,types:n,domain:a}}class Bo extends p{constructor(e){super(e),this.typedDataClient=new R(e)}async signTypedData(e,t){const n=await this.typedDataClient.sign(e,t,F.SIGN_TYPED_DATA),a=Do(e,t);return{...Fo(t,n.signature,a,_o)}}}class Oo extends m{async signTypedData(e,t){const n=Do(e,t),a=x(t),s={domain:xo,types:n,message:{...t,prefix:a},Primary_type:e};return Fo(t,Ro(await function(){const e=globalThis.window,t=e?.gala;if(void 0===t)throw new Error("Gala wallet is not available");return t}().request({method:"eth_signTypedData",params:[JSON.stringify(s),this.walletAddress]})),n,xo)}}class Uo extends g{constructor(e,t){super(e,t),this.typedDataProvider=e}async signTypedData(e,t){const n=this.typedDataProvider,a=await n.getNetwork(),s={name:a.name,chainId:Number(a.chainId)},r=Do(e,t),i=x(t),o=await n.getSigner();return Fo(t,Ro(await o.signTypedData(s,r,{...t,prefix:i})),r,s)}}function Po(e){if(!ia(e))throw new Error("Invalid token format: token must be a non-empty string");return e.replace(/\|/g,"$")}function Mo(e){return ki(e,"$","dollar-delimited token")}class $o extends ba{constructor(e=!1){super(e)}generateStringsInstructions(e){try{this.logger.debug("🔧 Generating stringsInstructions for:",e);const t=this.extractTokenSymbolFromVault(e),n=this.createTokenInstance(t),a=this.createGalaInstance(),s=`$service$${n.toStringKey()}$launchpad`,r=`$tokenBalance$${n.toStringKey()}$${e}`,i=`$tokenBalance$${n.toStringKey()}$${e}`,o=`$tokenBalance$${a.toStringKey()}$${e}`,c=[s,r,i,o,`$tokenBalance$${a.toStringKey()}$${e}`];return this.logger.debug("✅ Generated stringsInstructions:",c),c}catch(e){this.logger.error("❌ Failed to generate stringsInstructions:",e);const t=It(e);throw new Wt(`Failed to generate stringsInstructions: ${t}`,"vaultAddress","INVALID_VAULT_ADDRESS")}}createTokenInstance(e){const t=new O;return t.collection=e.toLowerCase(),t.category="Unit",t.type="none",t.additionalKey="none",this.logger.debug("🪙 Created token instance:",{symbol:e,lowercaseCollection:e.toLowerCase(),stringKey:t.toStringKey()}),t}createGalaInstance(){const e=new O;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(!ia(e))throw Xt("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 Wt)throw Qt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad");throw e}}validateVaultAddress(e){if(!ia(e))throw Xt("vaultAddress","Vault address");if(!e.startsWith("service|Token$Unit$"))throw Qt("vaultAddress",'starting with "service|Token$Unit$"');if(!e.endsWith("$launchpad"))throw Qt("vaultAddress",'ending with "$launchpad"');const t=function(e){if(!ia(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 Qt("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 Qt("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 Mo(e)}catch(e){if(e instanceof Wt)throw Qt("stringKey","format: collection$category$type$additionalKey (4 parts)");throw e}}}function Lo(e){return"object"==typeof e&&null!==e?e:void 0}class Ko extends ka{constructor(e,t,n=!1,a,s,r=.05,i=.01){if(super(e,n),this.tokenResolver=t,this._walletProvider=a,this.userAddress=s,this.defaultSlippageToleranceFactor=r,this.defaultMaxAcceptableReverseBondingCurveFeeSlippageFactor=i,this.bundleEndpoint="/bundle",null!==this._walletProvider&&void 0!==this._walletProvider&&null!=s){const e=Lo(this._walletProvider),t=e?.privateKey;"string"==typeof t?this.signer=new Bo(t):function(e){const t=Lo(e);return"function"==typeof t?.request}(this._walletProvider)&&void 0!==this.userAddress&&(this.signer=new Uo(this._walletProvider,this.userAddress)),this.tokenKeyService=new $o(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 gn(()=>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:cn(n),error:n.error}),this.handleBundleResponse(n))}catch(e){if(e instanceof Wt)return{success:!1,error:It(e)};throw e}}validateBundleData(e){if(null==e)throw Xt("bundleData","Bundle data");if(null===e.signedDto||void 0===e.signedDto)throw Xt("signedDto","Signed DTO");if(!ia(e.method))throw Xt("method","Method name");if(!Array.isArray(e.stringsInstructions))throw Qt("stringsInstructions","an array of resource tracking strings");if(0===e.stringsInstructions.length)throw new Wt("stringsInstructions cannot be empty","stringsInstructions","EMPTY_ARRAY");const t=["BuyWithNative","BuyExactToken","SellExactToken","SellWithNative"];if(!t.includes(e.method))throw Qt("method",`one of: ${t.join(", ")}`);e.stringsInstructions.forEach((e,t)=>{if(!ia(e))throw new Wt(`stringsInstructions[${t}] must be a non-empty string`,`stringsInstructions[${t}]`,"INVALID_INSTRUCTION");if(!wi(e))throw new Wt(`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=dn(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(xt(e)&&null!==e.response&&void 0!==e.response){const t=dn(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 It(e)??"Unknown bundle transaction error"}async getBundlerTransactionResult(e){try{if(!ia(e))throw Xt("transactionId","Transaction ID");let t;this.logger.debug("🔍 Checking bundler transaction result:",e);try{t=await gn(()=>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 Wt)return{success:!1,error:It(e)};throw e}}async cancelTransaction(e){try{if(!ia(e))throw Xt("transactionId","Transaction ID");let t;this.logger.debug("🚫 Cancelling transaction:",e);try{t=await gn(()=>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 Wt)return{success:!1,error:It(e)};throw e}}async getHealthStatus(){this.logger.debug("🏥 Checking bundle service health");try{const e=await gn(()=>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 Wt("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 Wt("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);if("exact"===a){if(null==s||""===s)throw new Wt("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=new To.SellExactDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"SellExactToken",o)}{if(null==s||""===s)throw new Wt("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=new To.SellNativeDto(o,n,e,{maxAcceptableReverseBondingCurveFee:i});return await this.executeBundleTransaction(t,"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 zt(e);return{effectiveSlippageFactor:s,effectiveMaxFee:r,vaultAddress:i}}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 Yt("Trading services not available. BundleService requires walletProvider and userAddress for trading operations.","walletProvider");if(null===this.userAddress||void 0===this.userAddress)throw Xt("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=dn(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 jt("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 Go extends ka{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(Et),t=this.extractData(e);return this.logger.debug("Fetched client feature flags",{flagCount:Object.keys(t.flags).length}),{flags:t.flags}}}var Wo,Ho,qo,jo;!function(e){e.CHAT_MESSAGE="CHAT_MESSAGE",e.COMMENT="COMMENT",e.STREAM="STREAM",e.RECORDING="RECORDING"}(Wo||(Wo={})),function(e){e.INAPPROPRIATE_CONTENT="INAPPROPRIATE_CONTENT",e.SPAM="SPAM",e.HARASSMENT="HARASSMENT",e.SCAM="SCAM",e.OTHER="OTHER"}(Ho||(Ho={})),function(e){e.PENDING="PENDING",e.DISMISSED="DISMISSED",e.ACTIONED="ACTIONED"}(qo||(qo={})),function(e){e.DELETE_CONTENT="DELETE_CONTENT",e.BAN_USER="BAN_USER",e.DELETE_AND_BAN="DELETE_AND_BAN"}(jo||(jo={})),Ho.INAPPROPRIATE_CONTENT,Ho.SPAM,Ho.HARASSMENT,Ho.SCAM,Ho.OTHER,qo.PENDING,qo.DISMISSED,qo.ACTIONED,jo.DELETE_CONTENT,jo.BAN_USER,jo.DELETE_AND_BAN,Wo.CHAT_MESSAGE,Wo.COMMENT,Wo.STREAM,Wo.RECORDING;const Vo=la(Wo),zo=la(Ho),Xo=la(qo),Qo=la(jo),Jo={TOKEN_NAME:Dn,CONTENT_ID:On.CONTENT_ID,DETAILS:On.FLAG_DETAILS,PAGINATION:{MAX_LIMIT:xn}};function Yo(e,t="tokenName"){ha(e,t,Jo.TOKEN_NAME)}function Zo(e){if(void 0!==e.contentType&&!Vo(e.contentType))throw Qt("contentType",`one of: ${Object.values(Wo).join(", ")}`,"Content type");if(void 0!==e.status&&!Xo(e.status))throw Qt("status",`one of: ${Object.values(qo).join(", ")}`);if(void 0!==e.reason&&!zo(e.reason))throw Qt("reason",`one of: ${Object.values(Ho).join(", ")}`);if(void 0!==e.reporterAddress&&!ia(e.reporterAddress))throw sn("reporterAddress","a non-empty string",typeof e.reporterAddress);if(void 0!==e.reporterAddress&&xa(e.reporterAddress,"reporterAddress"),void 0!==e.reportedUserAddress&&!ia(e.reportedUserAddress))throw sn("reportedUserAddress","a non-empty string",typeof e.reportedUserAddress);void 0!==e.reportedUserAddress&&xa(e.reportedUserAddress,"reportedUserAddress"),ca(0,void 0,Jo.PAGINATION.MAX_LIMIT,e.pageSize)}class ec extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async createFlag(e){!function(e){if(Yo(e.tokenName),void 0===e.contentType)throw Xt("contentType","Content type");if(!Vo(e.contentType))throw Qt("contentType",`one of: ${Object.values(Wo).join(", ")}`,"Content type");if(!ia(e.contentId))throw Xt("contentId","Content ID");if(e.contentId.length>Jo.CONTENT_ID.MAX_LENGTH)throw an("contentId",Jo.CONTENT_ID.MAX_LENGTH,e.contentId.length,"Content ID");if(!ia(e.reportedUserAddress))throw Xt("reportedUserAddress","Reported user address");if(xa(e.reportedUserAddress,"reportedUserAddress"),!(e.contentType!==Wo.STREAM&&e.contentType!==Wo.RECORDING||void 0!==e.reason&&null!==e.reason))throw Xt("reason","Reason");if(void 0!==e.reason&&!zo(e.reason))throw Qt("reason",`one of: ${Object.values(Ho).join(", ")}`,"Reason");if(void 0!==e.details&&!ia(e.details))throw sn("details","a non-empty string",typeof e.details);if(void 0!==e.details&&e.details.length>Jo.DETAILS.MAX_LENGTH)throw an("details",Jo.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(_e.CREATE,t,this.getMultiAuthHeaders());return{flag:this.extractData(n).flag}}async listFlags(e){return function(e){Yo(e.tokenName),Zo(e)}(e),this.fetchFlagList(e)}async listGlobalFlags(e={}){return function(e){void 0!==e.tokenName&&Yo(e.tokenName),Zo(e)}(e),this.fetchFlagList(e)}async dismissFlag(e){!function(e){if(void 0===e.flagId||null===e.flagId)throw Xt("flagId","Flag ID");try{aa(e.flagId,"flagId")}catch{throw Qt("flagId","a positive integer","Flag ID")}}(e);const t=_e.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 Xt("flagId","Flag ID");try{aa(e.flagId,"flagId")}catch{throw Qt("flagId","a positive integer","Flag ID")}if(void 0===e.action)throw Xt("action","Action");if(!Qo(e.action))throw Qt("action",`one of: ${Object.values(jo).join(", ")}`,"Action")}(e);const t=_e.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,xn);Yi(t,e,["tokenName","contentType","status","reason","reporterAddress","reportedUserAddress"]);const n=await this.http.get(_e.LIST,t,this.getMultiAuthHeaders()),a=this.extractData(n);return{items:a.flags,pageInfo:a.pageInfo}}}const tc=["heart","fire","laugh","wow","thumbs_up"];class nc extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateReactionTokenName(e){this.validateTokenName(e,Dn)}validateMessageId(e){if(!ia(e))throw Xt("messageId","Message ID");if(na(e,Un.CONTENT_REACTION.MAX_LENGTH,"messageId"),!Un.CONTENT_REACTION.PATTERN.test(e))throw Qt("messageId","msg-{timestamp}-{uuid} or chat-{timestamp}-{uuid} format","Message ID")}validateReactionType(e){if(!ia(e))throw Xt("reactionType","Reaction type");if(!tc.includes(e))throw Qt("reactionType",`one of: ${tc.join(", ")}`,"Reaction type")}async addContentReaction(e){void 0!==e.tokenName&&this.validateReactionTokenName(e.tokenName),this.validateMessageId(e.messageId),this.validateReactionType(e.reactionType);const t=at,n={messageId:e.messageId,reactionType:e.reactionType};void 0!==e.tokenName&&(n.tokenName=yn(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=`${st}?${new URLSearchParams({messageId:e.messageId,reactionType:e.reactionType}).toString()}`;return await this.http.delete(t,{},this.getMultiAuthHeaders()),{success:!0}}async addReactionToChatMessage(e){return this.addContentReaction(e)}async removeReactionFromChatMessage(e){return this.removeContentReaction(e)}async addReactionToComment(e){return this.addContentReaction(e)}async removeReactionFromComment(e){return this.removeContentReaction(e)}}class ac extends ba{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}=ua(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 Wt("tokenName parameter requires LaunchpadSDK routing - call LaunchpadSDK.fetchTokenPrice({tokenName}) instead","tokenName","INVALID_PARAMS")}async _fetchDexTokenSpotPrice(e){if(null==e)throw Xt("tokenId","Token ID");try{const t=go(e),n=cr(t),a=Po(n);if(this.logger.debug(`Fetching DEX spot price for token: ${a}`),!this.dexBackendHttp)throw Jt("DEX Backend API client not configured");const s=await this.dexBackendHttp.request({method:"GET",url:"/market/price",params:{assetIds:a}}),r=null!==s&&"object"==typeof s?s:{},i=[t.type,t.collection].filter(e=>"string"==typeof e&&""!==e&&"none"!==e).map(e=>e.toUpperCase()).map(e=>r[e]).find(e=>void 0!==e)??(1===Object.keys(r).length?Object.values(r)[0]:void 0),o=i?.price;if("number"!=typeof o||!Number.isFinite(o))throw new Wt(`Invalid price response: no market price for ${a}`,"data","INVALID_RESPONSE");const c=n;let l;try{if(null!==this.cache&&void 0!==this.cache){const e=this.cache.getByTokenId(c);if(null!=e?.symbol)return l=e.symbol,this.logger.debug(`DEX spot price for ${l} (cached): $${o}`),{symbol:l,price:o}}this.logger.debug(`Symbol cache miss for ${c}, fetching from API`);l=(await this.fetchTokenDetails(e)).symbol,this.cache&&(this.cache.setByTokenId(c,{symbol:l}),this.logger.debug(`Cached symbol for ${c}: ${l}`)),this.logger.debug(`DEX spot price for ${l}: $${o}`)}catch(e){this.logger.debug(`Could not fetch token details for symbol, falling back to token format parsing: ${Nt(e)?e.message:String(e)}`),l=kn("Token"===t.collection?t.type:t.collection),this.logger.debug(`DEX spot price for ${l} (fallback): $${o}`)}return{symbol:l,price:o}}catch(e){if(e instanceof Wt)throw e;throw Jt(`Failed to fetch DEX spot price: ${It(e)}`)}}async fetchLaunchpadTokenSpotPrice(e,t,n){if(!ia(e))throw new Wt(Ot,"tokenName",Pt);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=cr(t.sellingToken);return this._fetchDexTokenSpotPrice(n)}}catch(t){this.logger.debug(`Could not determine graduation status for ${e}, falling back to bonding curve: ${It(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 Jt("GALA price not available");const r=Vn(a.amount,0)/1e18;if(r<=0)throw new Wt(`Invalid token amount calculation: ${r}`,"amount","INVALID_CALCULATION");const i=s.price/r;return{symbol:kn(e),price:i}}catch(t){if(Nt(t))throw Jt(`Failed to calculate launchpad token spot price for ${e}: ${It(t)}`);throw Jt(`Failed to calculate launchpad token spot price for ${e}: ${It(t)}`)}}async fetchTokenDetails(e){this.logger.debug("Fetching token details from GalaChain for tokenId:",e);try{if(!this.galaChainService)throw Jt("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 Wt||Nt(t))&&("NetworkError"===t.name||It(t).includes("Token not found")))throw t;throw Jt(`Failed to fetch token details from GalaChain for ${String(e)}: ${It(t)}`,500)}}async fetchAllDexSeasons(){try{if(!this.dexBackendHttp)throw Jt("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=dn(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:Tn(t?.start??null),end:Tn(t?.end??null),rulesId:t?.rules_id??0}});return this.logger.debug(`Fetched ${n.length} DEX seasons`),n}catch(e){if(Nt(e)&&It(e).includes("not configured"))throw e;if(xt(e)&&404===e.response?.status)return this.logger.warn("Seasons endpoint not available"),[];throw Jt(`Failed to fetch DEX seasons: ${It(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{aa(e,"seasonId")}catch{throw Xt("seasonId","Season ID must be a positive number")}try{if(!this.dexBackendHttp)throw Jt("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=dn(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(Nt(t)&&It(t).includes("must be a positive number"))throw t;throw Jt(`Failed to fetch DEX leaderboard for season ${e}: ${It(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 Jt("DEX Backend API client not configured");const e=dn(await this.dexBackendHttp.request({method:"GET",url:"/v2/trade/volume"}));if(!e)throw Jt("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 Jt(`Failed to fetch DEX volume summary: ${It(e)}`)}}}const sc=20,rc=3e3,ic=1e3,oc=!0,cc=!0,lc=!1,dc={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 uc{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 wn({debug:t.debug??!1,context:"EventsBatcherService"}),this.config={batchSize:t.batchSize??sc,flushIntervalMs:t.flushIntervalMs??rc,maxQueueSize:t.maxQueueSize??ic,flushOnPageHide:t.flushOnPageHide??oc,flushOnPageUnload:t.flushOnPageUnload??cc,debug:t.debug??lc},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 hc(e){return 0===(e?.length??0)?"0":e.reduce((e,t)=>U(e).plus(t.quantity).toString(),"0")}function gc(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 mc extends ka{constructor(e,t=!1){super(e,t)}getChannelForCollection(e){return"MUSIC"===(wi(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{Rt(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=cr(s),i={quantity:s.quantity,collection:s.collection,category:s.category,tokenId:r};if((s.inUseHolds?.length??0)>0){const e=gc(s.inUseHolds??[],t);e.length>0&&(i.inUseHolds=e,i.inUseQuantity=hc(e))}if((s.lockedHolds?.length??0)>0){const e=gc(s.lockedHolds??[],t);e.length>0&&(i.lockedHolds=e,i.lockedQuantity=hc(e))}return void 0===i.lockedQuantity&&void 0===i.inUseQuantity||(i.availableQuantity=function(e,t="0",n="0"){return U(e).minus(t).minus(n).toString()}(i.quantity,i.lockedQuantity,i.inUseQuantity)),i}catch(e){throw Jt(`Failed to fetch token balance from GalaChain: ${It(e)}`,void 0,Nt(e)?e:void 0)}}}function pc(e){return"string"==typeof e?{...Mo(e),instance:"0"}:{collection:e.collection,category:e.category,type:e.type,additionalKey:e.additionalKey,instance:"0"}}function fc(e){return lr(e)}function yc(e){const t=e[0];return void 0===t?void 0:fc(t.tokenInstanceKey)}class vc extends _{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=pc(a);return new vc({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 vc({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 yc(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 kc extends _{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=pc(n);return new kc({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 kc({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 yc(this.tokenInstances)}toSigningPayload(){return{tokenInstances:this.tokenInstances,...void 0!==this.name&&{name:this.name},uniqueKey:this.uniqueKey}}}function bc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ia(t.amount)&&(void 0!==t.tokenId||ia(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 wc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ia(t.amount)&&(void 0!==t.tokenId||ia(t.tokenName))&&(void 0===t.name||"string"==typeof t.name)}var Sc,Ac;!function(e){e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.WALLET_REQUIRED="WALLET_REQUIRED",e.VALIDATION_ERROR="VALIDATION_ERROR",e.LOCK_NOT_FOUND="LOCK_NOT_FOUND",e.LOCK_EXPIRED="LOCK_EXPIRED",e.INSUFFICIENT_LOCKED_BALANCE="INSUFFICIENT_LOCKED_BALANCE",e.NOT_LOCK_AUTHORITY="NOT_LOCK_AUTHORITY",e.LOCK_NAME_MISMATCH="LOCK_NAME_MISMATCH"}(Sc||(Sc={}));class Ec extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="LockError"}}!function(e){e.INVALID_RECIPIENT="INVALID_RECIPIENT",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",e.TOKEN_NOT_FOUND="TOKEN_NOT_FOUND",e.SIGNATURE_FAILED="SIGNATURE_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.DUPLICATE_TRANSFER="DUPLICATE_TRANSFER",e.TRANSFER_LIMIT_EXCEEDED="TRANSFER_LIMIT_EXCEEDED",e.WALLET_REQUIRED="WALLET_REQUIRED"}(Ac||(Ac={}));class Tc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="TransferError"}}function Cc(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 Nc(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}const r={collection:vn(e),category:"Unit",type:"none",additionalKey:"none",instance:"0"};return n.debug("[DEBUG] Token resolution (standard format)",{tokenName:e,tokenInstance:{collection:r.collection,category:r.category,type:r.type}}),r}const Ic=100,Dc=100;class _c extends ka{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new Bo(t.privateKey):void 0}async lockTokens(e){if(this.validateLockTokensData(e),!this.wallet||!this.nativeSigner)throw new Ec("Wallet required for token lock operations",Sc.WALLET_REQUIRED);return er(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=Ia(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?Ia(r.lockAuthority):s})}const c=new vc({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 vc({...c.toSigningPayload(),signedPayload:l}),u=await this.http.post("/api/asset/token-contract/LockToken",d);try{Rt(u,"Token lock failed")}catch(e){const t=Ft(u);throw new Ec(`${It(e)}${t}`,Sc.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 Ec("Wallet required for token unlock operations",Sc.WALLET_REQUIRED);return er(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 kc({tokenInstances:n,...void 0!==s?.name&&{name:s.name},uniqueKey:e.uniqueKey??Io()}),i=await this.nativeSigner.signObject("UnlockToken",r.toSigningPayload()),o=new kc({...r.toSigningPayload(),signedPayload:i}),c=await this.http.post("/api/asset/token-contract/UnlockToken",o);try{Rt(c,"Token unlock failed")}catch(e){const t=Ft(c);throw new Ec(`${It(e)}${t}`,Sc.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 Ec("Must provide either tokenId or tokenName for token identification",Sc.TOKEN_NOT_FOUND);if(void 0!==e.tokenName)try{ga(e.tokenName,"tokenName")}catch{throw new Ec("Invalid token name format",Sc.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}try{_s(Cs(e.amount))}catch{throw new Ec(Qt(t,"a positive number",n).message,Sc.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(bc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ec("Invalid lock data: missing required fields",Sc.VALIDATION_ERROR);if(e.tokens.length>Ic)throw new Ec(`Batch size exceeds maximum limit of ${Ic} tokens per lock operation`,Sc.VALIDATION_ERROR);for(const t of e.tokens){if(this.validateSharedTokenEntry(t,"lockAmount","Lock amount"),void 0!==t.lockAuthority&&!_a(t.lockAuthority))throw new Ec("Invalid lock authority address format",Sc.VALIDATION_ERROR,{lockAuthority:t.lockAuthority});if(void 0!==t.expires)try{aa(t.expires,"expires")}catch{throw new Ec(Qt("expires","a positive integer (epoch milliseconds)","Expires").message,Sc.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(wc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Ec("Invalid unlock data: missing required fields",Sc.VALIDATION_ERROR);if(e.tokens.length>Dc)throw new Ec(`Batch size exceeds maximum limit of ${Dc} tokens per unlock operation`,Sc.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 Ec)return e;let a=t,s=Sc.NETWORK_ERROR;if(xt(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=Sc.INSUFFICIENT_BALANCE:r.includes("lock")&&r.includes("not found")?s=Sc.LOCK_NOT_FOUND:r.includes("not found")||r.includes("token")?s=Sc.TOKEN_NOT_FOUND:r.includes("authority")?s=Sc.NOT_LOCK_AUTHORITY:r.includes("expired")&&(s=Sc.LOCK_EXPIRED)}}else Nt(e)&&(a=`${t}: ${It(e)}`);return new Ec(a,s,Cc(n))}async resolveTokenInstance(e){return er(async()=>Nc(e,this.tokenResolver,this.logger),`Failed to resolve token '${e}'`,this.logger,t=>{if(t instanceof Tc)throw new Ec(It(t),Sc.TOKEN_NOT_FOUND);throw new Ec(`Failed to resolve token '${e}': ${It(t)}`,Sc.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 Ec("Must provide either tokenId or tokenName for token identification",Sc.TOKEN_NOT_FOUND)}createTokenOperationContext(){return{ownerAddress:Ia(this.wallet.address),tokenInstances:[]}}}class xc extends ka{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 Xt("publicAxios","Public Axios instance");const a=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClasses",n)).data;if(Rt(a,"Failed to fetch token class from GalaChain"),null===a.Data||void 0===a.Data||0===a.Data.length)throw Jt(`Token not found on GalaChain: ${cr(t)}`,404);const s=a.Data[0];if(void 0===s)throw Jt(`Token not found on GalaChain: ${cr(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 Xt("tokenClasses","Token classes array");const t={tokenClasses:e};if(!this.publicAxios)throw Xt("publicAxios","Public Axios instance");const n=(await this.publicAxios.post("/api/asset/token-contract/FetchTokenClassesWithSupply",t)).data;if(Rt(n,"Failed to fetch token classes with supply from GalaChain"),!n.Data||0===n.Data.length)throw Jt("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 Wt)throw e;if(xt(e)&&404===e.response?.status)throw Jt(t,404,Nt(e)?e:void 0);if(Nt(e)&&"Error"===e.name&&It(e).includes("status indicates failure"))throw Jt(It(e),400,Nt(e)?e:void 0);const a=It(e);if(a.includes("Token not found")){if(e instanceof Error)throw e;throw new Error(a)}throw Jt(`${n}: ${a}`,void 0,Nt(e)?e:void 0)}}class Rc extends _{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=pc(e.tokenClassKey);return{quantity:e.quantity,tokenInstanceKey:t}});return new Rc({tokenInstances:n,uniqueKey:t?.uniqueKey??Io()})}static fromTokenClassKey(e,t,n){return Rc.fromTokens([{tokenClassKey:t,quantity:e}],n)}static forGALA(e,t){return new Rc({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?fc(e.tokenInstanceKey):void 0}toSigningPayload(){return{tokenInstances:this.tokenInstances,uniqueKey:this.uniqueKey}}}class Fc extends _{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={...Mo(a),instance:"0"}}else r={collection:a.collection,category:a.category,type:a.type,additionalKey:a.additionalKey,instance:"0"};return new Fc({from:e,to:t,quantity:n,tokenInstance:r,uniqueKey:s??Io()})}static forGALA(e,t,n,a){return new Fc({from:e,to:t,quantity:n,tokenInstance:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none",instance:"0"},uniqueKey:a??Io()})}getTokenClassKey(){return lr(this.tokenInstance)}toSigningPayload(){return{from:this.from,to:this.to,quantity:this.quantity,tokenInstance:this.tokenInstance,uniqueKey:this.uniqueKey}}}function Bc(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ia(t.amount)&&(void 0!==t.tokenId||ia(t.tokenName))}var Oc;!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"}(Oc||(Oc={}));class Uc extends Error{constructor(e,t,n){super(e),this.type=t,this.details=n,this.name="BurnError"}}const Pc={validateAmount(e){const t=Cs(e);try{!function(e,t){if(e.isNaN())throw rn(t,"NaN");if(!e.isFinite())throw an(t,"finite");if(e.isLessThanOrEqualTo(0))throw nn(t,"0",e.toString())}(t,"amount")}catch(t){throw new Tc(t.message,Ac.INVALID_AMOUNT,{amount:e})}},validateUniqueKey(e){if(!oa(e)&&ia(e)){if(e.length>$n.MAX_LENGTH)throw new Wt(`Unique key too long. Maximum length: ${$n.MAX_LENGTH}`);if(!$n.PATTERN.test(e))throw new Tc('Invalid unique key format. Must start with "galaswap-operation-" or "galaconnect-operation-"',Ac.INVALID_AMOUNT,{uniqueKey:e})}}},Mc="gala-transfer-successful",$c="token-transfer-successful",Lc="token-locked-successfully",Kc="token-unlocked-successfully",Gc="transfer-successful-no-id",Wc=50;class Hc extends ka{constructor(e,t,n,a=!1){super(e,a),this.wallet=t,this.tokenResolver=n,this.nativeSigner=t?new Bo(t.privateKey):void 0}async transferGala(e){if(this.validateTransferGalaData(e),!this.wallet||!this.nativeSigner)throw new Tc("Wallet required for GALA transfer operations",Ac.WALLET_REQUIRED);try{const t=Ia(e.recipientAddress),n=Ia(this.wallet.address),a=Fc.forGALA(n,t,e.amount,e.uniqueKey),s=await this.nativeSigner.signObject("TransferToken",a.toSigningPayload()),r=new Fc({...a.toSigningPayload(),signedPayload:s}),{data:i,headers:o}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",r);if(null==i)throw new Tc("No response from GalaChain transfer service",Ac.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 Tc("Wallet required for token transfer operations",Ac.WALLET_REQUIRED);try{const t=Ia(e.to),n=Ia(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 Tc("Must provide either tokenId or tokenName for token identification",Ac.TOKEN_NOT_FOUND);a=await this.resolveTokenInstance(e.tokenName)}const s=new Fc({from:n,to:t,quantity:e.amount,tokenInstance:a,uniqueKey:e.uniqueKey??Io()}),r=await this.nativeSigner.signObject("TransferToken",s.toSigningPayload()),i=new Fc({...s.toSigningPayload(),signedPayload:r}),{data:o,headers:c}=await this.http.postWithMeta("/api/asset/token-contract/TransferToken",i);if(null==o)throw new Tc("No response from GalaChain transfer service",Ac.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 Tc)throw t;throw new Tc(`Failed to resolve token class key for '${e}': ${It(t)}`,Ac.TOKEN_NOT_FOUND,{tokenName:e})}}async burnTokens(e){if(this.validateBurnTokensData(e),!this.wallet||!this.nativeSigner)throw new Uc("Wallet required for token burn operations",Oc.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 Uc("Must provide either tokenId or tokenName for token identification",Oc.TOKEN_NOT_FOUND);e=await this.resolveTokenInstance(n.tokenName)}t.push({quantity:n.amount,tokenInstanceKey:e})}const n=new Rc({tokenInstances:t,uniqueKey:e.uniqueKey??Io()}),a=await this.nativeSigner.signObject("BurnTokens",n.toSigningPayload()),s=new Rc({...n.toSigningPayload(),signedPayload:a}),r=await this.http.post("/api/asset/token-contract/BurnTokens",s);if(null==r)throw new Uc("No response from GalaChain burn service",Oc.NETWORK_ERROR);try{Rt(r,"Token burn operation")}catch(e){throw new Ht(It(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 ia(t.recipientAddress)&&ia(t.amount)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Wt("Invalid GALA transfer data: missing required fields");if(!_a(e.recipientAddress))throw new Tc("Invalid recipient address format",Ac.INVALID_RECIPIENT,{recipientAddress:e.recipientAddress});Pc.validateAmount(e.amount),Pc.validateUniqueKey(e.uniqueKey)}validateTransferTokenData(e){if(!function(e){if(null==e||"object"!=typeof e)return!1;const t=e;return ia(t.to)&&ia(t.amount)&&(void 0!==t.tokenId||ia(t.tokenName))&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)}(e))throw new Wt("Invalid token transfer data: missing required fields");if(!_a(e.to))throw new Tc("Invalid recipient address format",Ac.INVALID_RECIPIENT,{recipientAddress:e.to});if(!(null!==e.tokenId&&void 0!==e.tokenId||null!==e.tokenName&&void 0!==e.tokenName))throw new Tc("Must provide either tokenId or tokenName for token identification",Ac.TOKEN_NOT_FOUND);if(null!==e.tokenName&&void 0!==e.tokenName)try{ga(e.tokenName,"tokenName")}catch{throw new Tc("Invalid token name format",Ac.TOKEN_NOT_FOUND,{tokenName:e.tokenName})}Pc.validateAmount(e.amount),Pc.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(Bc)&&(void 0===t.uniqueKey||"string"==typeof t.uniqueKey)&&(void 0===t.privateKey||"string"==typeof t.privateKey)}(e))throw new Uc("Invalid burn data: missing required fields",Oc.VALIDATION_ERROR);if(e.tokens.length>Wc)throw new Uc(`Batch size exceeds maximum limit of ${Wc} tokens per burn operation`,Oc.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 Uc("Must provide either tokenId or tokenName for token identification",Oc.TOKEN_NOT_FOUND);const e=Cs(t.amount);try{_s(e)}catch{throw new Uc("Burn amount must be a positive number",Oc.INVALID_AMOUNT,{amount:t.amount})}}}async resolveTokenInstance(e){try{return await Nc(e,this.tokenResolver,this.logger,`[DEBUG] Token resolution for '${e}' (launchpad):`)}catch(t){if(t instanceof Tc)throw t;throw new Tc(`Failed to resolve token '${e}': ${It(t)}`,Ac.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&&Rt(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=Gc;if(t.Data.length>0)switch(n){case"gala":e=Mc;break;case"token":e=$c;break;case"lock":e=Lc;break;case"unlock":e=Kc}return{transactionId:e,...void 0!==s?{blockNumber:s}:{}}}}}throw new Tc("Operation succeeded but transaction ID could not be extracted (missing x-transaction-id header and body fields)",Ac.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 Tc)return e;if(e instanceof Wt)return new Tc(It(e),Ac.INVALID_AMOUNT);if(xt(e)&&e.response){const t=e.response.status,a=e.response.data;if(400===t){const e=a?.message;return new Tc(("string"==typeof e?e:void 0)??"Invalid transfer request",Ac.INVALID_AMOUNT)}if(403===t)return new Tc("Insufficient balance for transfer",Ac.INSUFFICIENT_BALANCE);if(404===t){const e={};return"tokenName"in n&&(e.tokenName=n.tokenName),new Tc("Token not found",Ac.TOKEN_NOT_FOUND,e)}}if("object"==typeof e&&null!==e&&"code"in e&&("ECONNABORTED"===_t(e)||"ETIMEDOUT"===_t(e)))return new Tc("Transfer request timed out",Ac.NETWORK_ERROR);const a=""!==It(e)?It(e):t;return new Tc(a,Ac.NETWORK_ERROR)}handleBurnError(e,t,n){if(e instanceof Uc)return e;let a=t,s=Oc.NETWORK_ERROR;if(xt(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=Oc.INSUFFICIENT_BALANCE:(n.includes("not found")||n.includes("token"))&&(s=Oc.TOKEN_NOT_FOUND)}}}else Nt(e)&&(a=`${t}: ${It(e)}`);return new Uc(a,s,Cc(n))}}class qc extends ka{constructor(e,t,n,a=!1,s){super(e,a),this.balanceService=new mc(e,a),this.tokenService=new xc(e,a,s),this.lockService=new _c(e,t,n,a),this.transferService=new Hc(e,t,n,a)}async fetchPoolDetails(e){this.validateFetchPoolDetailsData(e);const t=await this.http.post("/api/asset/launchpad-contract/FetchSaleDetails",e);tr(()=>Rt(t,"Failed to fetch pool details"),"Failed to fetch pool details",this.logger,e=>{throw Jt(It(e),500)});const n=t.Data.reverseBondingCurveConfiguration,a=n?.minFeePortion??"0",s=n?.maxFeePortion??"0",r=!Is(a)||!Is(s),i=t.Data;return i.reverseBondingCurveMinFeePortion=a,i.reverseBondingCurveMaxFeePortion=s,i.hasReverseBondingCurveFee=r,i.isGraduated="Finished"===t.Data.saleStatus,delete i.reverseBondingCurveConfiguration,t}async fetchLaunchTokenFee(){const e=await this.http.post("/api/asset/launchpad-contract/FetchLaunchpadFeeAmount",{});return tr(()=>Rt(e,"Failed to fetch launch token fee"),"Failed to fetch launch token fee",this.logger,e=>{throw Jt(It(e),500)}),e.Data.feeAmount}validateFetchPoolDetailsData(e){if(!As(e))throw Xt("data","Fetch pool details data");if("string"!=typeof e.vaultAddress||""===e.vaultAddress)throw Xt("vaultAddress","Vault address");if(!e.vaultAddress.startsWith("service|Token$Unit$"))throw new Wt("Vault address must be in service format: service|Token$Unit$...","vaultAddress","INVALID_VAULT_ADDRESS")}async fetchGalaBalance(e){return this.balanceService.fetchGalaBalance(e)}async fetchTokenBalance(e,t=!1){return this.balanceService.fetchTokenBalance(e,t)}async fetchTokenClassFromChain(e){return this.tokenService.fetchTokenClassFromChain(e)}async fetchTokenClassesWithSupply(e){return this.tokenService.fetchTokenClassesWithSupply(e)}async transferGala(e){return this.transferService.transferGala(e)}async transferToken(e){return this.transferService.transferToken(e)}async resolveTokenClassKey(e){return this.transferService.resolveTokenClassKey(e)}async lockTokens(e){return this.lockService.lockTokens(e)}async unlockTokens(e){return this.lockService.unlockTokens(e)}async burnTokens(e){return this.transferService.burnTokens(e)}}class jc{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 Vc extends Error{constructor(e,t,n){super(t),this.name="GdexStreamError",this.code=e,void 0!==n&&(this.data=n)}}class zc extends ba{constructor(e={}){super(),this.nextRequestId=0,this.pending=new Map,this.subscriptionsByServerId=new Map,this.activeSubscriptions=new Set,this.intentionalClose=!1,this.reconnecting=!1,this.url=e.url??or("prod").gdexWebSocketUrl,this.requestTimeoutMs=e.requestTimeoutMs??15e3,this.reconnectionManager=new jc({maxAttempts:e.reconnectAttempts??5,baseDelayMs:e.reconnectDelayMs??2e3,useExponentialBackoff:!0});const t=e.webSocketImpl??globalThis.WebSocket;if("function"!=typeof t)throw new Error('GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).');this.webSocketConstructor=t}connect(){return this.isConnected()?Promise.resolve():(this.connectPromise||(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket()),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(new Error("GDEX stream disconnected"));const e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,"client disconnect")}isConnected(){return 1===this.socket?.readyState}request(e,t){if(!this.isConnected()||!this.socket)return Promise.reject(new Error("GDEX stream is not connected. Call connect() first."));const n=++this.nextRequestId,a={jsonrpc:"2.0",id:n,method:e};return void 0!==t&&(a.params=t),new Promise((t,s)=>{const r=setTimeout(()=>{this.pending.delete(n),s(new Error(`GDEX request "${e}" timed out after ${this.requestTimeoutMs}ms`))},this.requestTimeoutMs);this.pending.set(n,{resolve:e=>t(e),reject:s,timeout:r});try{this.socket?.send(JSON.stringify(a))}catch(e){clearTimeout(r),this.pending.delete(n),s(e instanceof Error?e:new Error(String(e)))}})}serverInfo(){return this.request("gdex_serverInfo")}ping(){return this.request("gdex_ping")}getPool(e){return this.request("gdex_getPool",e)}getBalance(e,t){return this.request("gdex_getBalance",void 0===t?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request("gdex_getPositions",e)}getBlockHeight(){return this.request("gdex_getBlockHeight")}quote(e){return this.request("gdex_quote",e)}getToken(e){return this.request("gdex_getToken",{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe("swap",e,t)}subscribePool(e,t,n={}){return this.subscribe("pool",t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe("balance",t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe("poolCreated",e,t)}subscribeBlocks(e,t={}){return this.subscribe("blocks",e,t)}openSocket(){return new Promise((e,t)=>{let n=!1;const a=new this.webSocketConstructor(this.url,"gdex.jsonrpc.v1");this.socket=a,a.onopen=()=>{this.socket===a&&(n=!0,this.connectPromise=void 0,this.reconnecting||this.reconnectionManager.reset(),this.logger.info("Connected to GDEX stream"),e())},a.onmessage=e=>this.handleMessage(e.data),a.onerror=()=>{n||t(new Error(`Failed to connect to GDEX stream at ${this.url}`))},a.onclose=e=>{this.socket===a&&(this.socket=void 0,this.connectPromise=void 0,n||t(new Error(`GDEX stream closed before connecting (code ${e.code??0})`)),this.rejectPending(new Error(`GDEX stream connection closed (code ${e.code??0})`)),this.intentionalClose||this.reconnecting||this.startReconnectLoop())}})}handleMessage(e){if("string"!=typeof e)return void this.logger.warn("Ignoring non-text GDEX WebSocket frame");let t;try{t=JSON.parse(e)}catch{return void this.logger.warn("Ignoring invalid JSON from GDEX stream")}if("number"==typeof t.id){const e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){const n="number"==typeof t.error.code?t.error.code:-32603,a="string"==typeof t.error.message?t.error.message:"GDEX request failed";e.reject(new Vc(n,a,t.error.data))}else e.resolve(t.result);return}if("gdex_subscription"!==t.method||!this.isRecord(t.params))return;const n=t.params.subscription,a=t.params.result;if("string"!=typeof n||!this.isRecord(a))return;const s=this.subscriptionsByServerId.get(n);if(s?.active)try{s.callback(a)}catch(e){this.logger.error("GDEX subscription callback failed",e)}}async subscribe(e,t,n){const a={channel:e,...n},s=await this.request("gdex_subscribe",a);let r;const i={subscriptionId:s.subscriptionId,unsubscribe:async()=>this.unsubscribe(r)};return r={serverId:s.subscriptionId,params:a,callback:t,handle:i,active:!0},this.activeSubscriptions.add(r),this.subscriptionsByServerId.set(r.serverId,r),i}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request("gdex_unsubscribe",{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.reconnectionManager.shouldRetry();){const e=this.reconnectionManager.getNextDelay();if(this.reconnectionManager.recordAttempt(),this.logger.warn(`GDEX reconnect attempt ${this.reconnectionManager.getAttempts()}/${this.reconnectionManager.getMaxAttempts()} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{return await this.openSocket(),await this.resubscribeAll(),this.reconnectionManager.reset(),void(this.reconnecting=!1)}catch(e){this.logger.warn(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||this.logger.error("GDEX reconnection attempts exhausted")}async resubscribeAll(){this.subscriptionsByServerId.clear();for(const e of this.activeSubscriptions){if(!e.active)continue;const t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t);e.active?(e.serverId=n.subscriptionId,e.handle.subscriptionId=n.subscriptionId,this.subscriptionsByServerId.set(n.subscriptionId,e)):await this.request("gdex_unsubscribe",{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e){for(let t=0;;t++)try{return await this.request("gdex_subscribe",e)}catch(e){if(!(e instanceof Vc)||-32003!==e.code||t>=5)throw e;const n=this.readRetryAfterMs(e.data);this.logger.warn(`GDEX resubscribe rate limited; retrying in ${n}ms`),await new Promise(e=>setTimeout(e,n))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){void 0!==this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(const t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||"number"!=typeof e.retryAfterMs||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}}function Xc(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 Qt("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 Qc extends ka{constructor(e,t,n=!1){super(e,n,t)}async uploadImageByTokenName(e){const{tokenName:t,options:n}=e;Ps(t);const a=`${t}.png`;Bs(n.file,a,"image/png");try{const e=`${n.tokenName??t}.png`,a=Xc(n.file,"image",e),s=await hn(()=>this.http.request({method:"POST",url:`${$.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 qt)throw e;if(Nt(e)&&It(e).includes("FormData"))throw Yt("File upload failed: FormData not supported in this environment. Ensure you have proper polyfills for Node.js environments.","FormData");throw e}}}const Jc={CHAT_MESSAGE:"CHAT_MESSAGE",COMMENT:"COMMENT"};function Yc(e,t){if(null==e)return[];if(Array.isArray(e))return e;const n=e[t];return Array.isArray(n)?n:[]}class Zc extends ka{constructor(e,t,n=!1){super(e,n,t)}buildPoolFilters(e){return{...!oa(e.search)&&{search:e.search},...!oa(e.tokenName)&&{tokenName:e.tokenName},...!oa(e.type)&&{type:e.type},...!oa(e.hasUpcomingShows)&&{hasUpcomingShows:e.hasUpcomingShows},...!oa(e.language)&&{language:e.language},...!oa(e.recentlyStreamed)&&{recentlyStreamed:e.recentlyStreamed},...!oa(e.hasRecordings)&&{hasRecordings:e.hasRecordings},...!oa(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),oa(e.type)||(a.type=e.type),oa(e.tokenName)||(a.tokenName=e.tokenName),oa(e.search)||(a.search=e.search),oa(e.hasUpcomingShows)||(a.hasUpcomingShows=e.hasUpcomingShows.toString()),oa(e.language)||(a.language=e.language),oa(e.recentlyStreamed)||(a.recentlyStreamed=e.recentlyStreamed.toString()),oa(e.hasRecordings)||(a.hasRecordings=e.hasRecordings.toString()),oa(e.streamStatus)||(a.streamStatus=e.streamStatus);const s=Ts(a),r=dn(await mn(()=>this.http.get($.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;ia(e?.tokenName)&&Ps(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=fs(e);!t.success&&t.errors&&Us(t.errors,"options")}(e),ia(e.tokenName)&&Ps(e.tokenName);try{const t=await this.http.post($.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===ia(e.symbol)){return!n.symbolAvailable}if(!0===ia(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 vs(t,"tokenName")&&bs(t,"from")&&bs(t,"to")&&bs(t,"resolution")}(e))throw new Wt("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(Ps(t),null==n||null==a||null==s)throw new Wt("Graph options (from, to, resolution) are required","options","MISSING_GRAPH_OPTIONS");const r={tokenName:t,from:n,to:a,resolution:s};Ms(r);const i=Ts(r);return{dataPoints:await hn(()=>this.http.get($.CHART,i),{errorContext:"Failed to fetch graph data"})}}async fetchTokenDistribution(e){if(""===e||null==e)throw Xt("tokenName","Token name");let t;Ps(e);try{t=await mn(()=>this.http.get(`${$.GET_TOKEN_DISTRIBUTION}?tokenName=${e}`),{errorContext:"Failed to fetch token distribution"})}catch(t){if(xt(t)&&500===t.response?.status)throw Jt(`Token distribution data temporarily unavailable for ${e}. This is a backend issue - please try again later.`,500);throw t}return Ks(dn(t),t.status,e=>e.toFixed())}async fetchUserHolderContext(e,t){if(""===e||null==e)throw Xt("tokenName","Token name");if(""===t||null==t)throw Xt("userAddress","User address");return Ps(e),hn(()=>this.http.get(`${$.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");Ps(e);try{const t=$.GET_TOKEN.replace(":tokenName",e.toLowerCase().trim()),n=dn(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&&Ps(e.tokenName);try{const t=await this.http.post($.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(!ia(e))throw Xt("tokenName","Token name");Ps(e);const t=$.TOKEN_STATS.replace(":tokenName",e.toLowerCase().trim());try{const e=dn(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 Xt("tokenName","Token name");Ps(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 Wt("At least one config option must be provided (messagesEnabled, commentsEnabled, streamingEnabled, nextLiveStreamAt, streamLanguage, or social URLs)","options",Pt);if(void 0!==e.messagesEnabled&&"boolean"!=typeof e.messagesEnabled)throw sn("messagesEnabled","boolean");if(void 0!==e.commentsEnabled&&"boolean"!=typeof e.commentsEnabled)throw sn("commentsEnabled","boolean");if(void 0!==e.streamingEnabled&&"boolean"!=typeof e.streamingEnabled)throw sn("streamingEnabled","boolean");if(void 0!==e.streamLanguage&&"string"!=typeof e.streamLanguage)throw sn("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 sn(n,"string or null")}if(void 0!==e.nextLiveStreamAt&&null!==e.nextLiveStreamAt){if("string"!=typeof e.nextLiveStreamAt)throw sn("nextLiveStreamAt","string or null");const t=new Date(e.nextLiveStreamAt);if(isNaN(t.getTime()))throw new Wt("nextLiveStreamAt must be a valid ISO date string","nextLiveStreamAt",Lt)}}(t);const n=$.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())}}const el=Fn,tl=_n,nl={MAX_LENGTH:100};function al(e){if(void 0!==e.tokenName){if(!ia(e.tokenName))throw sn("tokenName","a non-empty string",typeof e.tokenName);if(e.tokenName.length>tl.MAX_LENGTH)throw an("tokenName",tl.MAX_LENGTH,e.tokenName.length)}if(void 0!==e.userAddress){if(!ia(e.userAddress))throw sn("userAddress","a non-empty string",typeof e.userAddress);if(e.userAddress.length>nl.MAX_LENGTH)throw an("userAddress",nl.MAX_LENGTH,e.userAddress.length)}if(void 0!==e.search){if("string"!=typeof e.search)throw sn("search","a string",typeof e.search);if(e.search.length>256)throw an("search",256,e.search.length)}if(ca(0,void 0,el.MAX_LIMIT,e.pageSize),void 0!==e.txnType&&"BUY"!==e.txnType&&"SELL"!==e.txnType)throw Qt("txnType",'"BUY" or "SELL"');if(void 0!==e.startDate){if(!ia(e.startDate))throw sn("startDate","a non-empty string",typeof e.startDate);if(isNaN(Date.parse(e.startDate)))throw Qt("startDate","a valid ISO 8601 date")}if(void 0!==e.endDate){if(!ia(e.endDate))throw sn("endDate","a non-empty string",typeof e.endDate);if(isNaN(Date.parse(e.endDate)))throw Qt("endDate","a valid ISO 8601 date")}if(void 0!==e.minAmount)try{ta(e.minAmount,0,Number.MAX_SAFE_INTEGER,"minAmount")}catch{throw Qt("minAmount","a non-negative number")}if(void 0!==e.maxAmount)try{ta(e.maxAmount,0,Number.MAX_SAFE_INTEGER,"maxAmount")}catch{throw Qt("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 sn(n,"numeric values",void 0,n);if(a>s)throw new Wt(`Minimum value (${a}) must be less than or equal to maximum value (${s}) for ${n}`,n,Gt)}(e.minAmount,e.maxAmount,"amountRange")}class sl extends ka{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 vs(t,"tokenName")&&(void 0===t.tradeType||"buy"===t.tradeType||"sell"===t.tradeType)&&ks(t,"userAddress")&&bs(t,"offset")&&bs(t,"pageSize")&&bs(t,"page")&&bs(t,"limit")}(e))throw new Wt("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(!ia(t))throw Xt("tokenName","Token name");const s={pageSize:String(Math.min(a,Rn))};void 0!==n&&(s.cursor=n);const r={...s};r.tokenName=t;const i=await this.http.get($.GET_TRADES,r);if(null==i)throw new Wt("No response from trade service","response","NO_RESPONSE");const o=dn(i),c=Yc(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=yn(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,el.MAX_LIMIT):el.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){al(e);const t=this.buildTradesQueryParams(e);return hn(()=>this.http.get(rt,t),{errorContext:"Failed to fetch trades"})}}function rl(e){return!!ia(e)&&Bn.PATTERN.test(e)}function il(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}la({ALL:"all",DEFI:"DEFI",ASSET:"ASSET",COLLECTION:"COLLECTION",CREATED:"created"});class ol extends ka{constructor(e,t,n=!1){super(e,n,t)}async fetchProfile(e){const t=e??this.http.getAddress();if(""===t||null==t||!rl(t))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=null==e,a=n?$.GET_CURRENT_USER:$.GET_PROFILE.replace(":address",t),s=await this.http.get(a,void 0,n?this.getJwtHeaders():void 0);if(null==s)throw new Wt("No response from user service","response","NO_RESPONSE");return s}async updateProfile(e){this.validateUpdateProfileData(e);let t=e.profileImage;if(!ia(t))try{const n=await this.fetchProfile(e.address);t=n.data?.profileImage??""}catch{t=""}const n={profileImage:t,fullName:e.fullName};await hn(()=>this.http.put($.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 Wt("Wallet address not available - wallet not configured","address","NO_WALLET");try{const n=`profile-image-${t}.png`,a=Xc(e.file,"image",n),s=await hn(()=>this.http.request({method:"POST",url:`${$.UPLOAD_IMAGE}?tokenName=${encodeURIComponent(t)}`,data:a,headers:this.getJwtHeaders()}),{errorContext:"Image upload failed"});return"string"==typeof s?s:""}catch(e){if(e instanceof Wt||e instanceof qt)throw e;throw new Wt(`Profile image upload failed: ${It(e)}`,"file","UPLOAD_FAILED")}}async fetchTokenList(e){return this.buildFetchRequest($.GET_TOKEN_LIST,e,{includeType:!0,errorMessage:"Failed to fetch token list"})}async fetchTokensHeld(e){return this.buildFetchRequest($.GET_TOKENS_HELD,e,{includeType:!1,errorMessage:"Failed to fetch tokens held"})}async fetchTokensCreated(e){const{cursor:t,pageSize:n,search:a,tokenName:s,status:r}=e??{},i=e?.type??(void 0!==r?"created":"DEFI"),o=this.http.getAddress();if(null==o||""===o)throw new Wt("Wallet address not available - wallet not configured","address","NO_WALLET");const c={type:i,address:o,pageSize:n??zi.DEFAULT_LIMIT};return void 0!==t&&(c.cursor=t),void 0!==a&&(c.search=a),void 0!==s&&(c.tokenName=s),void 0!==r&&(c.status=r),this.fetchTokenList(c)}async getManagedTokens(e={}){const t=Ji({pageSize:e.pageSize??zi.DEFAULT_LIMIT,...void 0!==e.cursor&&{cursor:e.cursor}},Rn);return hn(()=>this.http.get($.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}},Rn);Yi(a,t,["address","search","tokenName","status"]),n.includeType&&!e.includes("?type=")&&(a.type="all"===(t.type??"DEFI")?"DEFI":t.type??"DEFI");let s=e;if(e.includes(":address")){const n=t.address??this.http.getAddress();if(0===n.length)throw Xt("address","User address");s=e.replace(":address",n),delete a.address}const r=dn(await mn(()=>this.http.get(s,a),{errorContext:n.errorMessage})),i=Yc(r,"token"),o={hasNextPage:r.hasNextPage??!1},c=r.count??r.total;void 0!==c&&(o.totalCount=c),void 0!==r.nextCursor&&(o.nextCursor=r.nextCursor),void 0!==r.prevCursor&&(o.prevCursor=r.prevCursor),void 0!==r.hasPrevPage&&(o.hasPrevPage=r.hasPrevPage);const l={tokens:i,pageInfo:o};return void 0!==c&&(l.total=c),l}validateGetTokenListOptions(e){const t=e.pageSize??zi.DEFAULT_LIMIT;if(t<1||t>Rn)throw new Wt(`pageSize must be between 1 and ${Rn}`,"pageSize","OUT_OF_RANGE");if(void 0!==e.address&&!rl(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");const n=il(e.search);if(null!==n&&!(ia(a=n)&&a.length>=Wn&&a.length<=Hn))throw tn("search",Wn,Hn,n.length,"Search query");var a;const s=il(e.tokenName);if(null!==s&&!(ia(r=s)&&r.length>=_n.MIN_LENGTH&&r.length<=_n.MAX_LENGTH))throw tn("tokenName",_n.MIN_LENGTH,_n.MAX_LENGTH,s.length,"Token name");var r}validateUpdateProfileData(e){if(!rl(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address");if(t=e.fullName,!(ia(t)&&t.length>=qn.FULL_NAME.MIN_LENGTH&&t.length<=qn.FULL_NAME.MAX_LENGTH&&qn.FULL_NAME.ALPHABETS_ONLY_PATTERN.test(t)))throw tn("fullName",qn.FULL_NAME.MIN_LENGTH,qn.FULL_NAME.MAX_LENGTH,e.fullName.length,"Full name");var t}validateUploadProfileImageOptions(e){if(void 0!==e.address&&!rl(e.address))throw Qt("address","eth|[40-hex-chars] or client|[identifier]","Address")}}class cl{constructor(e,t,n=!1){this.http=e,this.poolService=new Zc(e,t,n),this.tradeService=new sl(e,n),this.userService=new ol(e,t,n),this.imageService=new Qc(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 Ps(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)}}class ll extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateContent(e,t){if(!ia(e))throw Xt("content","Message content");if(0===e.trim().length)throw Xt("content","Message content");na(e,t===Jc.CHAT_MESSAGE?On.CHAT_MESSAGES_V1.MAX_LENGTH:On.COMMENTS_V1.MAX_LENGTH,"content")}validateMessageId(e){if(!ia(e))throw Xt("id","Message ID");if(e.length<10||e.length>64)throw Qt("id","valid message ID format","Message ID")}validateMessageType(e){if(e!==Jc.CHAT_MESSAGE&&e!==Jc.COMMENT)throw new Wt(`type must be one of: ${Object.values(Jc).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,Dn);const a={};void 0!==e.cursor&&(a.cursor=e.cursor),a.pageSize=e.pageSize??zi.DEFAULT_LIMIT;const s=Ji(a,Fn.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=yn(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(it.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,Dn),this.validateContent(e.content,e.type);const t={type:e.type,tokenName:yn(e.tokenName),content:e.content.trim()},n=await this.http.post(it.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(it.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(it.DELETE_MESSAGE,e);return await this.http.delete(t,void 0,this.getDualAuthHeaders()),{success:!0}}async getPinnedMessage(e){this.validateTokenName(e,Dn);const t=await this.http.get(it.GET_PINNED,{tokenName:yn(e)});return{message:this.extractData(t)}}async pinMessage(e){this.validateMessageId(e);const t=it.PIN_MESSAGE.replace(":id",e);return await this.http.post(t,{},this.getDualAuthHeaders()),{success:!0}}async unpinMessage(e){this.validateMessageId(e);const t=it.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(it.GET_MESSAGE_STATS,void 0,this.getDualAuthHeaders());return this.extractData(e)}}const dl=da({MODERATOR:"MODERATOR",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MANAGER:"MANAGER"}),ul={TOKEN:"TOKEN",ALL_OWNER_TOKENS:"ALL_OWNER_TOKENS"},hl=da(ul),gl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"};da(gl);class ml extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateRole(e){if(!ia(e))throw Xt("role","Role");if(!function(e){return dl.includes(e)}(e))throw Qt("role",`one of: ${dl.join(", ")}`,"Role")}validateInviteCodeFormat(e){if(!ia(e))throw Xt("inviteCode","Invite code");if(t=e,!Ln.PATTERN.test(t))throw Qt("inviteCode","valid invite code format","Invite code");var t}validateInviteScope(e){if(void 0!==e&&(t=e,!hl.includes(t)))throw new Wt(`Invalid invite scope. Must be one of: ${hl.join(", ")}`,"inviteScope","INVALID_VALUE");var t}async createInvite(e){this.validateInviteScope(e.inviteScope);const t=e.inviteScope??ul.TOKEN;if(t===ul.TOKEN){if(void 0===e.tokenName||""===e.tokenName)throw new Wt("Token name is required for TOKEN scope invites","tokenName","REQUIRED");this.validateTokenName(e.tokenName,In)}else if(t===ul.ALL_OWNER_TOKENS&&e.tokenName)throw new Wt("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",On.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const n=Se,a={inviteScope:t,role:e.role};t===ul.TOKEN&&null!==e.tokenName&&void 0!==e.tokenName&&""!==e.tokenName&&(a.tokenName=yn(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,In),this.validateStatusFilter(e.status,gl);const t=Te,n={...this.buildPaginationParams(e,Fn.MAX_LIMIT)};void 0!==e.tokenName&&""!==e.tokenName&&(n.tokenName=yn(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(Ce,{id:String(e)});ln(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(Ne,{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 Wt("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",On.DESCRIPTION.MAX_LENGTH);const t=this.buildEndpoint(Ie,{id:String(e.inviteId)}),n={};void 0!==e.role&&(n.role=e.role),void 0!==e.description&&(n.description=e.description);const 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=Ee,n=this.buildPaginationParams(e??{},Fn.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(De,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}}const pl="10000",fl="1000";function yl(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function vl(){return Date.now()+6e4}function kl(e){return""!==e&&"string"==typeof e&&/^[a-zA-Z0-9]{3,50}$/.test(e)}function bl(e){try{return Math.floor(parseFloat(String(e))??0).toString()}catch{return"0"}}function wl(e){return""!==e&&"string"==typeof e&&/^eth\|[0-9a-fA-F]{40}$/.test(e)}class Sl extends ka{constructor(e){super(e)}getCollectionClaimFee(){return pl}getTokenClassCreateFee(){return fl}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(!wl(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=pl;n.collectionClaim=e,t=String(BigInt(t)+BigInt(e))}if((e.createTokenClasses??0)>0){const a=fl,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),!kl(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:vl(),uniqueKey:yl("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),!wl(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),!kl(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(!kl(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?bl(e.maxSupply):void 0,maxCapacity:void 0!==e.maxCapacity?bl(e.maxCapacity):void 0,additionalKey:e.additionalKey,expiresAt:vl(),uniqueKey:yl("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),!kl(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(!wl(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:vl(),uniqueKey:yl("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}),!wl(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 Al extends ka{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(bt,{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:wt,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(St,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 El extends ka{constructor(e,t=!1){super(e,t)}async getHomeOEmbedJson(e={}){this.logger.debug("Fetching home oEmbed (JSON)");const t=await this.http.get($.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($.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 Wt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (JSON)",{tokenName:t});const n=$.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 Wt("tokenName is required","tokenName","REQUIRED_FIELD");this.logger.debug("Fetching pool oEmbed (HTML)",{tokenName:t});const n=$.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 Wt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (JSON)",{address:t});const n=$.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 Wt("address is required","address","REQUIRED_FIELD");this.logger.debug("Fetching profile oEmbed (HTML)",{address:t});const n=$.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 Tl(e){if(!ia(e))throw Xt("address","Address")}const Cl={PENDING:"PENDING",CLAIMED:"CLAIMED",REVOKED:"REVOKED",EXPIRED:"EXPIRED"},Nl={ACTIVE:"ACTIVE",REVOKED:"REVOKED"},Il=la(Cl),Dl=la(Nl);function _l(e){if(!ia(e))throw new Error("Address must be a non-empty string");try{xa(e,"address")}catch{throw new Error("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}}function xl(e){try{aa(e,"id")}catch(e){if(e instanceof Wt)throw new Error("Invite ID must be a positive integer");throw e}}class Rl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}validateInviteCodeFormat(e){if(!ia(e))throw Xt("inviteCode","Invite code");!function(e){if(!ia(e))throw new Error("Invite code must be a non-empty string");na(e,100,"code")}(e)}validateWalletAddressFormat(e){if(!ia(e))throw Xt("address","Address");_l(e)}async createInvite(e={}){!function(e){try{pa(e.description,"description",255)}catch(e){if(e instanceof Wt)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(!ia(e.expiresAt))throw new Error("expiresAt must be a non-empty string");try{fa(e.expiresAt,"expiresAt")}catch(e){if(e instanceof Wt)throw new Error("expiresAt must be a valid ISO 8601 date string");throw e}if(Cn(e.expiresAt)&&Tn(e.expiresAt)<=new Date)throw new Error("expiresAt must be in the future")}}(e),this.validateOptionalString(e.description,"description","Description",On.DESCRIPTION.MAX_LENGTH),this.validateOptionalDate(e.expiresAt,"expiresAt","Expiration date");const t=xe,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&&!Il(e.status))throw on("status",e.status,Object.values(Cl),"status");ca(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Cl);const t=Re,n={...this.buildPaginationParams(e,Fn.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(Fe,{code:e}),n=await this.http.get(t,{});return this.extractData(n)}async revokeInvite(e){xl(e);const t=this.buildEndpoint(Oe,{id:String(e)});ln(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke invite")}async claimInvite(e){this.validateInviteCodeFormat(e);const t=Be,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&&!Dl(e.status))throw on("status",e.status,Object.values(Nl),"status");ca(0,void 0,50,e.pageSize,e.cursor)}(e),this.validateStatusFilter(e.status,Nl);const t=Ue,n={...this.buildPaginationParams(e,Fn.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 Wt("Options are required");if(!ia(e.userAddress))throw new Wt("userAddress is required and must be a non-empty string");try{xa(e.userAddress,"userAddress")}catch{throw new Wt("Invalid wallet address format. Must be eth|..., 0x..., or client|... format")}if(void 0!==e.description){if("string"!=typeof e.description)throw new Wt("description must be a string");if(e.description.length>255)throw new Wt("description must be at most 255 characters")}}(e),this.validateWalletAddressFormat(e.userAddress),this.validateOptionalString(e.description,"description","Description",On.DESCRIPTION.MAX_LENGTH);const t=Pe,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(Me,{address:e});ln(await this.http.delete(t,this.getDualAuthHeaders()),"Failed to revoke overseer")}async getMyStatus(){const e=$e,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=Ke,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getTokenBanStats(){const e=Ge,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getInviteStats(){const e=We,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getFlagStats(){const e=He,t=await this.http.get(e,{},this.getDualAuthHeaders());return this.extractData(t)}async getUserStats(){const e=qe,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 Wt("Options are required");if(void 0!==e.search){if("string"!=typeof e.search)throw new Wt("Search must be a string");if(0===e.search.length)throw new Wt("Search query cannot be empty string")}if(void 0!==e.sortBy){if("string"!=typeof e.sortBy)throw new Wt("Sort field must be a string");if(0===e.sortBy.length)throw new Wt("Sort field cannot be empty string")}if(void 0!==e.sortOrder&&"asc"!==e.sortOrder&&"desc"!==e.sortOrder)throw new Wt('Sort order must be "asc" or "desc"')}(t);const n=je,a=this.buildPaginationParams(t,Fn.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(!ia(e))throw Xt("address","User address");_l(e);const t=this.buildEndpoint(Ve,{address:e}),n=await this.http.get(t,{},this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByAddress(e){Tl(e);const t=this.buildEndpoint(ze,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}async flushCacheByToken(e){!function(e){if(!ia(e))throw Xt("tokenName","Token name")}(e);const t=this.buildEndpoint(Xe,{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 Wt("Safety confirmation required: must pass confirm=true to flush all cache","confirm","CONFIRMATION_REQUIRED")}(e);const t=Qe,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}async flushWalletAliasCache(e){if(void 0!==e){Tl(e);const t=this.buildEndpoint(Je,{address:e}),n=await this.http.delete(t,void 0,this.getDualAuthHeaders());return this.extractData(n)}const t=Ye,n=await this.http.delete(t,{confirm:"true"},this.getDualAuthHeaders());return this.extractData(n)}}class Fl extends ka{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),ln(t,"Platform config operation failed",!0),e.data}async getPlatformConfig(){const e=await this.http.get(te);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 Wt(t.join("; "),"options","VALIDATION_FAILED");const n=await this.http.put(ne,e,this.getJwtHeaders());return this.extractData(n)}async getAvailableRoles(){const e=await this.http.get(re);return this.extractData(e)}}class Bl extends ka{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(mt),t=this.extractData(e);return this.logger.debug("Fetched platform stats",{totalTokens:t.totalTokens,timestamp:t.timestamp}),{stats:t}}}class Ol extends ka{constructor(e,t=!1,n){super(e,t),this.tokenResolverService=n}async fetchTokenClassKeyByTokenName(e){if(""===e)throw Xt("tokenName","Token name");if(!this.tokenResolverService)throw Yt("TokenResolverService is required for token name resolution. Ensure it is passed to PriceHistoryService constructor.","tokenResolverService");try{ha(e)}catch(e){throw Yt(It(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 Yt(`Token '${e}' not found or could not be resolved to vault address`,"tokenName");this.logger.debug(`Resolved '${e}' to vault address: ${t}`);const n=cr(mo(t));return this.logger.debug(`Extracted token class key: ${n}`),n}catch(t){if(Nt(t)&&It(t).includes("ConfigurationError"))throw t;throw Jt(`Failed to resolve token name '${e}': ${It(t)}`,500)}}async fetchPriceHistory(e){if(null==e)throw Xt("options","Fetch options");return this.logger.debug("Fetching price history from DEX Backend API with options:",e),this.validateOptions(e),await er(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 Yt("Token ID is required but was not provided or resolved","tokenId");const{normalizeToTokenInstanceKey:n}=await Promise.resolve().then(function(){return vo}),a=Po(cr(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(W,c);if(null==l)throw Jt("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 Jt("Invalid API response: missing price series",500);const a="string"==typeof t.tokenId?t.tokenId:t.tokenName??cr(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=zn(t.offset,0),c=zn(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 Xt("options","Fetch options");return this.logger.debug("Fetching all price history with options:",e),er(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(ua(e,"tokenName","tokenId",{description:"token identifier"}),t&&!Cn(t))throw Yt("from must be a valid Date","from");if(void 0!==n&&!Cn(n))throw Yt("to must be a valid Date","to");null!=a&&function(e,t){if("ASC"!==e&&"DESC"!==e)throw new Wt(`${t} must be either 'ASC' or 'DESC'`,t,"INVALID_ENUM_VALUE")}(a,"sortOrder"),ca(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 Ul extends eo{constructor(e,t,n,a){super(e,t,n,!1,a)}async getRestrictedNames(){try{return{success:!0,data:(await this.http.get(ot)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async updateRestrictedNames(e){try{if(!ia(e.content))throw new Wt("Content is required");return{success:!0,data:(await this.http.put(ct,e)).data}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}}class Pl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async getChatStatus(e){if(null==e||""===e)throw Xt("tokenName","Token name");return this.validateTokenName(e,In),er(async()=>{const t=this.buildEndpoint(lt,{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 Xt("tokenName","Token name");return this.validateTokenName(e,In),er(async()=>{const t=this.buildEndpoint(ut,{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 Xt("tokenName","Token name");return this.validateTokenName(e,In),er(async()=>{const t=this.buildEndpoint(dt,{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??yn(e)};return void 0!==t.status&&null!==t.status&&(n.status=t.status),n}async setSlowMode(e,t){if(null==e||""===e)throw Xt("tokenName","Token name");if(this.validateTokenName(e,In),"number"!=typeof t||t<0||t>600)throw new Error("slowModeSeconds must be a number between 0 and 600");return er(async()=>{const n=this.buildEndpoint(ht,{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 Ml extends ba{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)}}la({IDLE:"IDLE",ACTIVE:"ACTIVE",DISABLED:"DISABLED"}),la({READY:"READY",PROCESSING:"PROCESSING",ERRORED:"ERRORED",DELETED:"DELETED"});const $l=la({YOUTUBE:"YOUTUBE",TWITCH:"TWITCH",FACEBOOK:"FACEBOOK",CUSTOM:"CUSTOM"});const Ll={OWNER:"OWNER",MANAGER:"MANAGER",TECHNICAL_PRODUCER:"TECHNICAL_PRODUCER",MODERATOR:"MODERATOR"};la(Ll),la({OWNER:"OWNER",MODERATOR:"MODERATOR"});function Kl(e,t="tokenName"){ha(e,t,In)}function Gl(e){if(Kl(e.tokenName),!ia(e.language))throw Xt("language");if(t=e.language,!ia(t)||!/^[a-z]{2}(-[A-Z]{2})?$/.test(t))throw new Wt('language must be a valid ISO 639-1 code (e.g., "en", "es", "zh-CN")',"language",Lt);var t}la({...Ll,OVERSEER:"OVERSEER"});class Wl extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async startStream(e){this.validateTokenName(e,In);const t=this.buildEndpoint(H,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async stopStream(e){this.validateTokenName(e,In);const t=this.buildEndpoint(q,{tokenName:e});await this.http.post(t,{},this.getJwtHeaders())}async disableStream(e){return this.toggleFeature(e,j,In)}async enableStream(e){return this.toggleFeature(e,V,In)}async resetStreamKey(e){this.validateTokenName(e,In);const t=this.buildEndpoint(z,{tokenName:e}),n=await this.http.post(t,{},this.getJwtHeaders());return this.extractData(n)}async getStreamCredentials(e){this.validateTokenName(e,In);const t=this.buildEndpoint(oe,{tokenName:e}),n=await this.http.get(t,{},this.getJwtHeaders());return this.extractData(n)}async getRecordings(e){!function(e){Kl(e.tokenName),ca(0,void 0,Gn,e.pageSize)}(e);const t=this.buildEndpoint(X,{tokenName:e.tokenName}),n=this.buildPaginationParams(e,Gn),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:yn(e.tokenName),page:r.page??l,limit:o,total:r.total,hasNext:r.recordings.length===o}}async getRecordingDownload(e,t){this.validateTokenName(e,In),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(Q,{tokenName:e,assetId:t}),a=await this.http.get(n,{},this.getJwtHeaders());return this.extractData(a)}async deleteRecording(e,t){this.validateTokenName(e,In),this.validateRequiredString(t,"assetId","Asset ID");const n=this.buildEndpoint(J,{tokenName:e,assetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getSimulcastTargets(e){this.validateTokenName(e,In);const t=this.buildEndpoint(Y,{tokenName:e}),n=await this.http.get(t);return this.extractData(n)}async addSimulcastTarget(e){!function(e){if(Kl(e.tokenName),!ia(e.platform))throw Xt("platform");if(!$l(e.platform))throw new Wt("platform must be one of: 'YOUTUBE', 'TWITCH', 'FACEBOOK', 'CUSTOM'","platform",$t);if(!ia(e.rtmpUrl))throw Xt("rtmpUrl");if(!Kn.STREAM_URL_PATTERN.test(e.rtmpUrl))throw new Wt("rtmpUrl must be a valid RTMP, RTMPS, or SRT URL","rtmpUrl",Lt);if(!ia(e.streamKey))throw Xt("streamKey");if(void 0!==e.name&&"string"!=typeof e.name)throw new Wt("name must be a string","name",Mt)}(e);const t=this.buildEndpoint(Z,{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,In),this.validateRequiredString(t,"targetId","Target ID");const n=this.buildEndpoint(ee,{tokenName:e,targetId:t});await this.http.delete(n,void 0,this.getJwtHeaders())}async getGlobalStreamingStatus(){const e=await this.http.get(te);return this.extractData(e)}async disableGlobalStreaming(){const e=await this.http.put(ne,{},this.getAdminHeaders());return this.extractData(e)}async enableGlobalStreaming(){const e=await this.http.put(ae,{},this.getAdminHeaders());return this.extractData(e)}async setNextLiveStream(e){let t;!function(e){if(Kl(e.tokenName),null!==e.nextLiveStreamAt){if(!(e.nextLiveStreamAt instanceof Date||ia(e.nextLiveStreamAt)))throw new Wt("nextLiveStreamAt must be a Date, ISO 8601 string, or null","nextLiveStreamAt",Mt);if("string"==typeof e.nextLiveStreamAt){const t=Date.parse(e.nextLiveStreamAt);if(isNaN(t))throw new Wt("nextLiveStreamAt must be a valid ISO 8601 date string","nextLiveStreamAt",Lt)}}}(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,In);const t=`/v1/tokens/${e.toLowerCase().trim()}`;await this.http.patch(t,{nextLiveStreamAt:null},this.getJwtHeaders())}async setStreamLanguage(e){Gl(e);const t=`/v1/tokens/${e.tokenName.toLowerCase().trim()}`;await this.http.patch(t,{streamLanguage:e.language},this.getJwtHeaders())}async getStreamRole(e){!function(e){Kl(e.tokenName)}(e);const t=this.buildEndpoint(se,{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(re);return this.extractData(e)}async getTokenAccess(e){!function(e){Kl(e.tokenName)}(e);const t=await this.http.get(ie,{tokenName:yn(e.tokenName)},this.getJwtHeaders());return this.extractData(t)}async setNextLiveStreamCountdown(e,t){return this.setNextLiveStream({tokenName:e,nextLiveStreamAt:t})}}const Hl="subscribe_token",ql="unsubscribe_token",jl="authenticate",Vl="send_stream_chat",zl="SEND_STREAM_REACTION",Xl="typing_start",Ql="typing_stop",Jl="STREAM_STATUS",Yl="STREAM_COUNTDOWN_UPDATED",Zl="STREAM_LANGUAGE_UPDATED",ed="VIEWER_COUNT",td="token_subscribed",nd="token_unsubscribed",ad="STREAM_GLOBAL_STATUS",sd="ENGAGEMENT_STATS_UPDATED",rd="STREAM_CHAT_MESSAGE",id="STREAM_CHAT_SENT",od="stream_chat_error",cd="CHAT_STATUS_CHANGED",ld="STREAM_CHAT_GLOBAL_STATUS",dd="authenticated",ud="stream_chat_auth_error",hd="STREAM_REACTION",gd="stream_reaction_error",md="USER_TYPING",pd="STREAM_CHAT_PINNED",fd="STREAM_CHAT_UNPINNED",yd="COMMENT_CREATED",vd="TOKEN_BANNED",kd="TOKEN_UNBANNED",bd="MODERATOR_INVITE_CREATED",wd="MODERATOR_ADDED",Sd="MODERATOR_REMOVED",Ad="MODERATOR_ROLE_UPDATED",Ed="OVERSEER_ADDED",Td="OVERSEER_REMOVED",Cd="TRADE_EXECUTED",Nd="BALANCE_UPDATED",Id="STATS_UPDATED",Dd="POOL_METADATA_UPDATED",_d="POOL_SOCIAL_LINKS_UPDATED",xd="POOL_BADGE_ASSIGNED",Rd="HOLDER_COUNT_UPDATED",Fd="USER_PROFILE_UPDATED",Bd="API_KEY_CREATED",Od="API_KEY_UPDATED",Ud="API_KEY_REVOKED",Pd="TOKEN_CONFIG_UPDATED",Md="SITE_CONFIG_CHANGED",$d="COMMENTS_GLOBAL_STATUS",Ld="WEBHOOKS_GLOBAL_STATUS",Kd="subscribe_global_feed",Gd="unsubscribe_global_feed",Wd="global_feed_subscribed",Hd="global_feed_unsubscribed";class qd extends ba{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 qt("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 jc({maxAttempts:this.config.reconnectAttempts,baseDelayMs:this.config.reconnectDelay}),this.isSocketIOAvailable=this.checkSocketIOAvailability()}checkSocketIOAvailability(){try{return"function"==typeof P||(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:",It(e)),!1}}getRoomName(e){return`token:${yn(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=yn(e),a=[{key:`${Jl}:${n}`,callback:t.onStreamStatus},{key:`${ed}:${n}`,callback:t.onViewerCount},{key:`${rd}:${n}`,callback:t.onChatMessage},{key:`${cd}:${n}`,callback:t.onChatStatus},{key:`${pd}:${n}`,callback:t.onChatPinned},{key:`${fd}:${n}`,callback:t.onChatUnpinned},{key:`${Yl}:${n}`,callback:t.onCountdownUpdated},{key:`${Zl}:${n}`,callback:t.onLanguageUpdated},{key:`${vd}:${n}`,callback:t.onTokenBanned},{key:`${kd}:${n}`,callback:t.onTokenUnbanned},{key:`${bd}:${n}`,callback:t.onModeratorInviteCreated},{key:`${wd}:${n}`,callback:t.onModeratorAdded},{key:`${Sd}:${n}`,callback:t.onModeratorRemoved},{key:`${Ad}:${n}`,callback:t.onModeratorRoleUpdated},{key:`${Cd}:${n}`,callback:t.onTradeExecuted},{key:`${Nd}:${n}`,callback:t.onBalanceUpdated},{key:`${Dd}:${n}`,callback:t.onPoolMetadataUpdated},{key:`${_d}:${n}`,callback:t.onPoolSocialLinksUpdated},{key:`${xd}:${n}`,callback:t.onPoolBadgeAssigned},{key:`${Rd}:${n}`,callback:t.onHolderCountUpdated},{key:`${yd}:${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(Jl,e=>{this.logger.debug(`📡 [Stream Status] ${e.tokenName}: ${e.status}`),this.bufferEvent(Jl,e.tokenName,e);const t=this.roomCallbacks.get(yn(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(td,e=>{this.logger.debug(`📡 [Subscribed] ${e.tokenName}`);const t=yn(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(nd,e=>{const t=e.room.replace("token:","");this.logger.debug(`📡 [Unsubscribed] ${t}`);const n=this.roomCallbacks.get(yn(t));n?.onStreamUnsubscribed&&n.onStreamUnsubscribed(e)}),this.socket.on(ed,e=>{this.logger.debug(`📡 [Viewer Count] ${e.tokenName}: ${e.viewerCount}`),this.bufferEvent(ed,e.tokenName,e);const t=this.roomCallbacks.get(yn(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(ad,e=>{this.logger.debug(`📡 [Global Stream Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onStreamGlobalStatus&&this.globalCallbacks.onStreamGlobalStatus(e)}),this.socket.on(rd,e=>{this.logger.debug(`📡 [Chat Message] ${e.tokenName}: ${e.content.slice(0,50)}...`),this.bufferEvent(rd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onChatMessage&&t.onChatMessage(e),this.globalCallbacks.onChatMessage&&this.globalCallbacks.onChatMessage(e)}),this.socket.on(id,e=>{this.logger.debug(`📡 [Chat Sent] ${e.tokenName}: ${e.messageId}`);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onChatSent&&t.onChatSent(e)}),this.socket.on(od,e=>{this.logger.error(`📡 [Chat Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onChatError&&t.onChatError(e),this.globalCallbacks.onChatError&&this.globalCallbacks.onChatError(e)}),this.socket.on(cd,e=>{this.logger.debug(`📡 [Chat Status] ${e.tokenName}: ${String(e.enabled)}`),this.bufferEvent(cd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onChatStatus&&t.onChatStatus(e),this.globalCallbacks.onChatStatus&&this.globalCallbacks.onChatStatus(e)}),this.socket.on(ld,e=>{this.logger.debug(`📡 [Global Chat Status] enabled: ${String(e.enabled)}`),this.globalCallbacks.onChatGlobalStatus&&this.globalCallbacks.onChatGlobalStatus(e)}),this.socket.on(dd,e=>{this.logger.debug(`📡 [Authenticated] ${e.address}`),this.isAuthenticated=!0,this.globalCallbacks.onChatAuthenticated&&this.globalCallbacks.onChatAuthenticated(e)}),this.socket.on(ud,e=>{this.logger.error(`📡 [Auth Error] ${e.message}`),this.isAuthenticated=!1,this.globalCallbacks.onChatAuthError&&this.globalCallbacks.onChatAuthError(e)}),this.socket.on(hd,e=>{this.logger.debug(`📡 [Reaction] ${e.tokenName}: ${e.emoji}`);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onReaction&&t.onReaction(e),this.globalCallbacks.onReaction&&this.globalCallbacks.onReaction(e)}),this.socket.on(gd,e=>{this.logger.error(`📡 [Reaction Error] ${e.tokenName}: ${e.message}`);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onReactionError&&t.onReactionError(e),this.globalCallbacks.onReactionError&&this.globalCallbacks.onReactionError(e)}),this.socket.on(md,e=>{const t=e.typingUsers.length;this.logger.debug(`📡 [Typing] ${e.tokenName}: ${t} user(s) typing`);const n=this.roomCallbacks.get(yn(e.tokenName));n?.onTypingIndicator&&n.onTypingIndicator(e),this.globalCallbacks.onTypingIndicator&&this.globalCallbacks.onTypingIndicator(e)}),this.socket.on(pd,e=>{this.logger.debug(`📡 [Chat Pinned] ${e.tokenName}: ${e.pinnedMessage.messageId}`),this.bufferEvent(pd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onChatPinned&&t.onChatPinned(e),this.globalCallbacks.onChatPinned&&this.globalCallbacks.onChatPinned(e)}),this.socket.on(fd,e=>{this.logger.debug(`📡 [Chat Unpinned] ${e.tokenName}: ${e.unpinnedMessageId}`),this.bufferEvent(fd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onChatUnpinned&&t.onChatUnpinned(e),this.globalCallbacks.onChatUnpinned&&this.globalCallbacks.onChatUnpinned(e)}),this.socket.on(Yl,e=>{const t=e.nextLiveStreamAt??"cleared";this.logger.debug(`📡 [Countdown Updated] ${e.tokenName}: ${t}`),this.bufferEvent(Yl,e.tokenName,e);const n=this.roomCallbacks.get(yn(e.tokenName));n?.onCountdownUpdated&&n.onCountdownUpdated(e),this.globalCallbacks.onCountdownUpdated&&this.globalCallbacks.onCountdownUpdated(e)}),this.socket.on(Zl,e=>{this.logger.debug(`📡 [Language Updated] ${e.tokenName}: ${e.language}`),this.bufferEvent(Zl,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onLanguageUpdated&&t.onLanguageUpdated(e),this.globalCallbacks.onLanguageUpdated&&this.globalCallbacks.onLanguageUpdated(e)}),this.socket.on(vd,e=>{this.logger.debug(`📡 [Token Banned] ${e.tokenName}`),this.bufferEvent(vd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onTokenBanned&&t.onTokenBanned(e),this.globalCallbacks.onTokenBanned&&this.globalCallbacks.onTokenBanned(e)}),this.socket.on(kd,e=>{this.logger.debug(`📡 [Token Unbanned] ${e.tokenName}`),this.bufferEvent(kd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onTokenUnbanned&&t.onTokenUnbanned(e),this.globalCallbacks.onTokenUnbanned&&this.globalCallbacks.onTokenUnbanned(e)}),this.socket.on(bd,e=>{this.logger.debug(`📡 [Moderator Invite Created] ${e.tokenName}: by ${e.invitedBy}`),this.bufferEvent(bd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onModeratorInviteCreated&&t.onModeratorInviteCreated(e)}),this.socket.on(wd,e=>{this.logger.debug(`📡 [Moderator Added] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(wd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onModeratorAdded&&t.onModeratorAdded(e)}),this.socket.on(Sd,e=>{this.logger.debug(`📡 [Moderator Removed] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Sd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onModeratorRemoved&&t.onModeratorRemoved(e)}),this.socket.on(Ad,e=>{this.logger.debug(`📡 [Moderator Role Updated] ${e.tokenName}: ${e.userAddress}`),this.bufferEvent(Ad,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onModeratorRoleUpdated&&t.onModeratorRoleUpdated(e)}),this.socket.on(Ed,e=>{this.logger.debug(`📡 [Overseer Added] ${e.userAddress}`),this.globalCallbacks.onOverseerAdded&&this.globalCallbacks.onOverseerAdded(e)}),this.socket.on(Td,e=>{this.logger.debug(`📡 [Overseer Removed] ${e.userAddress}`),this.globalCallbacks.onOverseerRemoved&&this.globalCallbacks.onOverseerRemoved(e)}),this.socket.on(Cd,e=>{this.logger.debug(`📡 [Trade Executed] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Cd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onTradeExecuted&&t.onTradeExecuted(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTradeExecuted&&this.globalFeedCallbacks.onTradeExecuted(e)}),this.socket.on(Nd,e=>{this.logger.debug(`📡 [Balance Updated] ${e.tokenName}: ${e.tradeType}`),this.bufferEvent(Nd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onBalanceUpdated&&t.onBalanceUpdated(e)}),this.socket.on(Dd,e=>{this.logger.debug(`📡 [Pool Metadata Updated] ${e.tokenName}`),this.bufferEvent(Dd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onPoolMetadataUpdated&&t.onPoolMetadataUpdated(e)}),this.socket.on(_d,e=>{this.logger.debug(`📡 [Pool Social Links Updated] ${e.tokenName}`),this.bufferEvent(_d,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onPoolSocialLinksUpdated&&t.onPoolSocialLinksUpdated(e)}),this.socket.on(xd,e=>{this.logger.debug(`📡 [Pool Badge Assigned] ${e.tokenName}: ${e.badge}`),this.bufferEvent(xd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onPoolBadgeAssigned&&t.onPoolBadgeAssigned(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onPoolBadgeAssigned&&this.globalFeedCallbacks.onPoolBadgeAssigned(e)}),this.socket.on(Rd,e=>{this.logger.debug(`📡 [Holder Count Updated] ${e.tokenName}: ${e.holderCount}`),this.bufferEvent(Rd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onHolderCountUpdated&&t.onHolderCountUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onHolderCountUpdated&&this.globalFeedCallbacks.onHolderCountUpdated(e)}),this.socket.on(yd,e=>{this.logger.debug(`📡 [Comment Created] ${e.tokenName}: ID ${e.id}`),this.bufferEvent(yd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onCommentCreated&&t.onCommentCreated(e)}),this.socket.on(Fd,e=>{this.logger.debug(`📡 [User Profile Updated] ${e.userAddress}`),this.globalCallbacks.onUserProfileUpdated&&this.globalCallbacks.onUserProfileUpdated(e)}),this.socket.on(Bd,e=>{this.logger.debug(`📡 [API Key Created] ${e.keyId}`),this.globalCallbacks.onApiKeyCreated&&this.globalCallbacks.onApiKeyCreated(e)}),this.socket.on(Od,e=>{this.logger.debug(`📡 [API Key Updated] ${e.keyId}`),this.globalCallbacks.onApiKeyUpdated&&this.globalCallbacks.onApiKeyUpdated(e)}),this.socket.on(Ud,e=>{this.logger.debug(`📡 [API Key Revoked] ${e.keyId}`),this.globalCallbacks.onApiKeyRevoked&&this.globalCallbacks.onApiKeyRevoked(e)}),this.socket.on(Pd,e=>{this.logger.debug(`📡 [Token Config Updated] ${e.tokenName}`),this.bufferEvent(Pd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onTokenConfigUpdated&&t.onTokenConfigUpdated(e),this.isGlobalFeedSubscribed&&!t&&this.globalFeedCallbacks.onTokenConfigUpdated&&this.globalFeedCallbacks.onTokenConfigUpdated(e)}),this.socket.on(Id,e=>{this.logger.debug(`📡 [Stats Updated] ${e.tokenName} price=${e.galaPrice}`),this.bufferEvent(Id,e.tokenName,e);const t=this.roomCallbacks.get(yn(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(sd,e=>{this.logger.debug(`📡 [Engagement Stats Updated] ${e.tokenName} chatters=${e.chat.uniqueChatters}`),this.bufferEvent(sd,e.tokenName,e);const t=this.roomCallbacks.get(yn(e.tokenName));t?.onEngagementStatsUpdated&&t.onEngagementStatsUpdated(e),this.globalCallbacks.onEngagementStatsUpdated&&this.globalCallbacks.onEngagementStatsUpdated(e)}),this.socket.on(Wd,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(Hd,e=>{this.logger.debug("📡 [Global Feed Unsubscribed]"),this.isGlobalFeedSubscribed=!1,this.globalFeedCallbacks.onGlobalFeedUnsubscribed&&this.globalFeedCallbacks.onGlobalFeedUnsubscribed(e)}),this.socket.on(Md,e=>{this.logger.debug(`📡 [Site Config Changed] ${e.key}`),this.globalFeedCallbacks.onSiteConfigChanged&&this.globalFeedCallbacks.onSiteConfigChanged(e)}),this.socket.on(ad,e=>{this.logger.debug(`📡 [Stream Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamGlobalStatus&&this.globalFeedCallbacks.onStreamGlobalStatus(e)}),this.socket.on(ld,e=>{this.logger.debug(`📡 [Chat Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onStreamChatGlobalStatus&&this.globalFeedCallbacks.onStreamChatGlobalStatus(e)}),this.socket.on($d,e=>{this.logger.debug(`📡 [Comments Global Status] enabled=${String(e.enabled)}`),this.globalFeedCallbacks.onCommentsGlobalStatus&&this.globalFeedCallbacks.onCommentsGlobalStatus(e)}),this.socket.on(Ld,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(Hl,{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(Kd)}catch(e){this.logger.error("Failed to re-subscribe to global feed:",e)}}async connect(){return new Promise((e,t)=>{er(async()=>{if(!this.isSocketIOAvailable)throw new qt('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=P(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 Wt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(""===e)throw Xt("token","Authentication token");this.logger.debug("📡 Authenticating with stream server"),this.socket.emit(jl,{token:e}),this.config.authToken=e}async subscribeToStream(e,t={}){if(""===e)throw Xt("tokenName","Token name");if(!this.socket?.connected)throw new Wt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");const n=yn(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(Hl,{tokenName:n})})}unsubscribeFromStream(e){const t=yn(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(ql,{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 Xt("tokenName","Token name");if(""===t)throw Xt("content","Message content");if(!this.socket?.connected)throw new Wt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Wt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const n=yn(e);this.logger.debug(`📡 Sending chat message to ${n}: ${t.slice(0,30)}...`),this.socket.emit(Vl,{tokenName:n,content:t})}sendReaction(e,t,n=0){if(""===e)throw Xt("tokenName","Token name");if(""===t)throw Xt("emoji");if(!this.socket?.connected)throw new Wt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Wt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=yn(e);this.logger.debug(`📡 Sending reaction to ${a}: ${t}`),this.socket.emit(zl,{tokenName:a,emoji:t,streamTime:n})}sendTypingStart(e){this.sendTypingEvent(e,Xl,"typing_start")}sendTypingStop(e){this.sendTypingEvent(e,Ql,"typing_stop")}sendTypingEvent(e,t,n){if(""===e)throw Xt("tokenName","Token name");if(!this.socket?.connected)throw new Wt("WebSocket not connected. Call connect() first.","socket","NOT_CONNECTED");if(!this.isAuthenticated)throw new Wt("Not authenticated. Call authenticate() first.","auth","NOT_AUTHENTICATED");const a=yn(e);this.logger.debug(`📡 Sending ${n} to ${a}`),this.socket.emit(t,{tokenName:a})}subscribeTokenBanned(e,t){const n=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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=yn(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 Wt("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(Kd)})}unsubscribeFromGlobalFeed(){this.isGlobalFeedSubscribed?(this.logger.debug("📡 Unsubscribing from global feed"),this.socket?.connected&&this.socket.emit(Gd),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(ha(e.tokenName,"tokenName",In),!(null==(t=e.reason)||""===t||"string"==typeof t&&!ma(t)&&t.length<=On.BAN_REASON.MAX_LENGTH))throw new Wt(`reason must be at most ${On.BAN_REASON.MAX_LENGTH} characters`,"reason","TOO_LONG");var t}class Vd extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async banToken(e){jd(e);const t=Ze,n={tokenName:yn(e.tokenName)};if(void 0!==e.reason)try{sa(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:yn(e.tokenName)}}async unbanToken(e){!function(e){ha(e.tokenName,"tokenName",In)}(e);const t=this.buildEndpoint(nt,{tokenName:e.tokenName});return ln(await this.http.delete(t,void 0,this.getDualAuthHeaders()),"Failed to unban token",!1),{tokenName:yn(e.tokenName)}}async listTokenBans(e={}){!function(e){ca(0,void 0,xn,e.pageSize)}(e);const t=et,n=this.buildPaginationParams(e,xn);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){ha(e.tokenName,"tokenName",In)}(e);const t=this.buildEndpoint(tt,{tokenName:e.tokenName}),n=await this.http.get(t,{},this.getDualAuthHeaders()),a=this.extractDataOrNull(n);return{banned:null!==a,...null!==a&&{ban:a},tokenName:yn(e.tokenName)}}async isTokenBanned(e){return this.getTokenBan(e)}}class zd extends ba{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(!ia(e))throw Xt("tokenName","Token name");const t=yn(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(!ia(e))throw Xt("tokenName","Token name");const t=yn(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 zt(e);const s=this.parseVaultAddressToTokenClassKey(a);return this.setCacheEntry(t,{vaultAddress:a,tokenClassKey:s,cachedAt:Date.now()}),s}get(e){const t=this.getCacheEntry(yn(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=yn(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(yn(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=yn(t);this.setCacheEntry(e,{vaultAddress:n,tokenClassKey:a,cachedAt:Date.now()})}}parseVaultAddressToTokenClassKey(e){try{return mo(e)}catch(e){if(e instanceof Wt)throw Qt("vaultAddress","format: service|Token$Unit$SYMBOL$eth:address$launchpad","Vault address");throw e}}}zd.MAX_CACHE_SIZE=1e4;class Xd extends ka{constructor(e,t=!1){super(e,t)}async fetchLaunchpadFee(){return hn(()=>this.http.get(pt),{errorContext:"Failed to fetch launchpad fee"})}async fetchSaleDetails(e){return hn(()=>this.http.get(ft,{tokenName:e}),{errorContext:`Failed to fetch sale details for ${e}`})}async getTradeQuote(e){return hn(()=>this.http.get(yt,{tokenName:e.tokenName,amount:e.amount,type:e.type,method:e.method}),{errorContext:`Failed to get trade quote for ${e.tokenName}`})}async getPremintQuote(e){return hn(()=>this.http.get(vt,{amount:e}),{errorContext:"Failed to get premint quote"})}}class Qd extends eo{constructor(e,t,n,a=!1,s){super(e,t,n,a,s)}async emitTradeExecuted(e,t){this.validateTokenName(e,Dn);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,Dn);const a={action:"balance_updated",userAddress:e,tokenName:t,payload:n};await this.emitEvent(a)}async emitStreamStatus(e,t,n=!0){this.validateTokenName(e,Dn);const a={action:"stream_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitViewerCount(e,t,n=!1){this.validateTokenName(e,Dn);const a={action:"viewer_count",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitStreamCountdown(e,t,n=!0){this.validateTokenName(e,Dn);const a={action:"stream_countdown",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatMessage(e,t,n=!1){this.validateTokenName(e,Dn);const a={action:"chat_message",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitChatStatus(e,t,n=!1){this.validateTokenName(e,Dn);const a={action:"chat_status",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTypingIndicator(e,t,n=!1){this.validateTokenName(e,Dn);const a={action:"typing_indicator",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitTokenBanned(e,t){this.validateTokenName(e,Dn);const n={action:"token_banned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitTokenUnbanned(e,t){this.validateTokenName(e,Dn);const n={action:"token_unbanned",tokenName:e,payload:t,broadcast:!0};await this.emitEvent(n)}async emitModeratorAdded(e,t,n=!1){this.validateTokenName(e,Dn);const a={action:"moderator_added",tokenName:e,payload:t,broadcast:n};await this.emitEvent(a)}async emitModeratorRemoved(e,t,n=!1){this.validateTokenName(e,Dn);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 qt("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,Dn);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,Dn);const n={action:"recording_status",tokenName:e,payload:t};await this.emitEvent(n)}async emitRecordingsCountUpdated(e,t){this.validateTokenName(e,Dn);const n={action:"recordings_count_updated",tokenName:e,payload:t};await this.emitEvent(n)}async emitDownloadReady(e,t){this.validateTokenName(e,Dn);const n={action:"download_ready",tokenName:e,payload:t};await this.emitEvent(n)}}class Jd{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 Yd(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 Zd extends ba{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 jc({maxAttempts:this.config.reconnectAttempts??5,baseDelayMs:this.config.reconnectDelay??2e3}),this.eventBuffer=new Jd(3e4),this.isSocketIOAvailable=this.checkSocketIOAvailability(),Zd.instances.add(this)}checkSocketIOAvailability(){try{return"function"==typeof P||(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)=>{er(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:",It(e)),e}this.logger.debug("🔌 Connecting to Socket.IO server:",this.config.url),this.socket=P(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=Nt(e)?e:new Error(It(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;ia(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")),Zd.instances.delete(this)}static cleanupAll(e=!1){for(const e of Zd.instances)e.disconnect();Zd.instances.clear()}isConnected(){return this.socket?.connected??!1}getSocket(){return this.socket}}Zd.instances=new Set;class eu extends ka{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 Wt("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(kt.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 Wt("vaultAddress is required","vaultAddress","REQUIRED_FIELD");this.logger.debug("Fetching token weekly history",{vaultAddress:t});const n=kt.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 tu extends wa{constructor(e=!1){super(e),this.lastFetchedAt=null}normalizeKey(e){return vn(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 nu extends tu{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 au extends ko{constructor(e,t=!1){super(e,t,"WrappableTokenService"),this.cache=new nu(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())})`),er(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 er(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 Yd("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 Yd("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 su extends ba{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 Bo(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 Xt("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 Wt(`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 Xt("tokenId","Token identifier");if(0===t.length)throw Xt("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 Wt(`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 Wt("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-${Vr()}`,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=It(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:gr,authType:"cross_channel_authorization"}}return{sourceChannel:"asset",destinationChannelId:mr,authType:"automatic"}}async getCounterpartOrThrow(e,t){const n=await this.wrappableTokenService.getWrapCounterpart(e);if(null==n)throw new Wt(`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 Wt(`Token not found or not wrappable: ${this.formatTokenId(e)}`,"tokenId","TOKEN_NOT_WRAPPABLE");return t}formatTokenId(e){return"string"==typeof e?e:cr(e)}}class ru 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 iu{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 ou{constructor(e){this.bundleBaseUrl=pu(e.bundleBaseUrl),this.launchpadBaseUrl=pu(e.launchpadBaseUrl),this.signer=e.signer,this.walletAddress=e.walletAddress,this.requestor=e.httpRequestor??fetch.bind(globalThis),this.socketFactory=e.socketFactory??(e=>P(e,{transports:["websocket"]}))}async submit(e){let t;try{t=await this.signer.signTypedData(e.method,e.dto)}catch(e){if(e instanceof ru)throw e;const t=e instanceof Error?e.message:"Launchpad signing failed.";throw new ru(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 gu(s);if(!s.ok)throw lu(s.status,r,a);const i=function(e){if("string"==typeof e&&""!==e)return e;if(!mu(e))throw new ru("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE");const t=e.data,n=e.bundleId;if("string"==typeof t&&""!==t)return t;if(mu(t)&&"string"==typeof t.bundleId&&""!==t.bundleId)return t.bundleId;if("string"==typeof n&&""!==n)return n;throw new ru("Bundler returned no bundle id.","INVALID_BUNDLE_RESPONSE")}(r),o=hu(e.dto,"uniqueKey");return new iu({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(!mu(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(cu(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=hu(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 gu(e);if(r){if(e.ok)return{status:"PROCESSED",data:uu(t)};if(404!==e.status&&202!==e.status)throw lu(e.status,t,i)}else{if(!e.ok)throw lu(e.status,t,i);const n=mu(t)?t.status:void 0;if("COMPLETED"===n||"PROCESSED"===n)return{status:"PROCESSED",data:t};if("FAILED"===n)throw cu(t)}const o=a-(Date.now()-n);if(o<=0)break;await fu(Math.min(Math.max(0,s),o))}throw new ru(`Timed out waiting for bundle ${e.dto.uniqueKey}`,"BUNDLE_CONFIRMATION_TIMEOUT",{details:{method:e.method}})}}function cu(e){const t=du(e)??"Launchpad bundle failed on chain.";return new ru(t,"BUNDLE_FAILED",{chainMessage:t})}function lu(e,t,n){const a=du(t)??`Bundle request failed with HTTP ${e}`;return new ru(a,"BUNDLE_REQUEST_FAILED",{status:e,chainMessage:a,details:{body:t,url:n}})}function du(e){if("string"==typeof e&&""!==e)return e;if(mu(e))for(const t of["chainMessage","message","Message","error"]){const n=e[t];if("string"==typeof n&&""!==n)return n;if(mu(n)){const e=du(n);if(void 0!==e)return e}}}function uu(e){return mu(e)?e.data??e.Data??e:e}function hu(e,t){const n=e[t];if("string"!=typeof n||""===n)throw new ru(`Missing ${t} in launchpad DTO.`,"INVALID_LAUNCHPAD_DTO");return n}async function gu(e){try{return await e.json()}catch{return e.text()}}function mu(e){return"object"==typeof e&&null!==e}function pu(e){return e.replace(/\/$/u,"")}function fu(e){return new Promise(t=>setTimeout(t,e))}function yu(e){const{collection:t,category:n,type:a}=function(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,s,r,i,o,...c]=n.split("$");if(void 0===a||void 0===s||void 0===r||void 0===i||"launchpad"!==o||c.length>0||""===a||""===s||""===r||""===i)throw new Error(`Invalid vaultAddress format (expected service|<collection>$<category>$<type>$<additionalKey>$launchpad): ${e}`);return{collection:a,category:s,type:r,additionalKey:i}}(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 vu(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 ku{constructor(e){this.transport=e.transport,this.walletAddress=e.walletAddress}createSale(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??bu(t)};void 0!==e.reverseBondingCurveConfiguration&&(n.reverseBondingCurveConfiguration=e.reverseBondingCurveConfiguration);void 0!==e.saleStartTime&&(n.saleStartTime=e.saleStartTime);return n}(e,this.walletAddress);return this.transport.submit({method:"CreateSale",dto:t,stringsInstructions:vu(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})}submitTrade(e,t,n){const a={vaultAddress:t.vaultAddress,...n,extraFees:t.extraFees??{maxAcceptableReverseBondingCurveFee:"0"},uniqueKey:t.uniqueKey??bu(this.walletAddress)};return this.transport.submit({method:e,dto:a,stringsInstructions:yu(t.vaultAddress)})}}function bu(e){return`galaswap-operation-${B()}-${Date.now()}-${e}`}class wu{constructor(e){this.gatewayBaseUrl=e.gatewayBaseUrl.replace(/\/$/u,""),this.signer=e.signer,this.walletAddress=Iu(e.walletAddress),this.requestor=e.httpRequestor??fetch.bind(globalThis)}transfer(e){const t=Su(e),n={from:this.walletAddress,to:Iu(e.to),quantity:e.quantity,tokenInstance:t,uniqueKey:e.uniqueKey??Nu(this.walletAddress)};return this.direct("TransferToken",n)}burn(e){const t={tokenInstances:[{quantity:e.quantity,tokenInstanceKey:Su(e)}],uniqueKey:e.uniqueKey??Nu(this.walletAddress)};return this.direct("BurnTokens",t)}lock(e){const t={lockAuthority:e.lockAuthority??this.walletAddress,tokenInstances:[{owner:this.walletAddress,quantity:e.quantity,tokenInstanceKey:Su(e)}],uniqueKey:e.uniqueKey??Nu(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:Su(e)}],uniqueKey:e.uniqueKey??Nu(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=Cu(r);if(!s.ok||void 0!==i?.Status&&1!==i.Status)throw function(e,t,n){const a=Cu(t),s=Tu(a,"Message")??Tu(a,"message")??Tu(a,"ErrorKey")??`Gateway request failed with HTTP ${e}`,r=Tu(a,"ErrorKey")??"GATEWAY_REQUEST_FAILED";return new ru(s,r,{status:e,chainMessage:s,details:{body:t,url:n}})}(s.status,r,a);const o=Cu(Au(r))?.mode??i?.mode;if(void 0!==o&&"sync"!==o){throw new ru(`Unsupported gateway transaction mode: ${"string"==typeof o?o:"non-sync"}`,"INVALID_GATEWAY_RESPONSE",{status:s.status,details:{body:r,url:a}})}const c=Au(r),l=Du(s,"x-transaction-id")??Eu(c)??Eu(r),d=function(e){const t=Du(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 ru)throw e;const t=e instanceof Error?e.message:"Native GalaChain signing failed.";throw new ru(t,"NATIVE_SIGNING_FAILED",{chainMessage:t})}}}function Su(e){const t=e.tokenClassKey??e.symbol;if(void 0===t)throw new ru("tokenClassKey or symbol is required.","INVALID_TOKEN_IDENTIFIER");const n=function(e){if("string"!=typeof e)return e;const t=e.includes("|")?"|":e.includes("$")?"$":void 0;if(void 0===t)return"GALA"===e.toUpperCase()?{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}:{collection:"Token",category:"Unit",type:e,additionalKey:"none"};const[n,a,s,r]=e.split(t);if(void 0===n||void 0===a||void 0===s||void 0===r||[n,a,s,r].some(e=>""===e))throw new ru(`Invalid token class key: ${e}`,"INVALID_TOKEN_IDENTIFIER");return{collection:n,category:a,type:s,additionalKey:r}}(t);return{...n,instance:e.instance??"0"}}function Au(e){const t=Cu(e);return t?.Data??t?.data??e}function Eu(e){if("string"==typeof e&&""!==e)return e;const t=Cu(e);return Tu(t,"transactionId")??Tu(t,"txnId")??Tu(t,"id")}function Tu(e,t){const n=e?.[t];return"string"==typeof n&&""!==n?n:void 0}function Cu(e){return"object"==typeof e&&null!==e?e:void 0}function Nu(e){return`galaswap-operation-${B()}-${Date.now()}-${e}`}function Iu(e){return"eth|0x"===e.slice(0,6).toLowerCase()?`eth|${e.slice(6)}`:e}function Du(e,t){const n=e.headers;if(void 0===n)return;if("function"==typeof n.get)return _u(n.get(t));const a=t.toLowerCase();for(const[e,t]of Object.entries(n))if(e.toLowerCase()===a)return _u(t)}function _u(e){const t=e?.trim();return void 0===t||""===t?void 0:t}function xu(e,t=3e4){return M.create({baseURL:e,timeout:t,headers:{"Content-Type":"application/json"}})}const Ru=new Set(["accesstoken","refreshtoken","token","password","privatekey","secret","apikey","api_key","rawkey","authorization","x-api-key","bearer","streamadminapikey","userapikey","signature","signedpayload"]);function Fu(e,t=0){if(t>5)return"[...]";if(null==e)return e;if(Array.isArray(e))return e.map(e=>Fu(e,t+1));if(e instanceof Map){const n={};for(const[a,s]of e.entries()){const e=String(a);n[e]=Ru.has(e.toLowerCase())?"[REDACTED]":Fu(s,t+1)}return n}if("object"==typeof e){const n={};for(const[a,s]of Object.entries(e))n[a]=Ru.has(a.toLowerCase())?"[REDACTED]":Fu(s,t+1);return n}return e}class Bu{constructor(e,t={}){this.auth=e,this.debug=t.debug??!1,this.logger=new wn({debug:this.debug,context:"HttpClient"});const n=t.baseUrl??or("stage").launchpadBaseUrl,a=t.timeout??6e4;this.axios=xu(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 er(async()=>{const t={method:e.method,url:e.url,data:e.data,...void 0!==e.params&&{params:Ts(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]":Fu(e.data);this.logger.debug("Request:",{method:e.method,url:e.url?.split("?")[0],baseURL:this.axios.defaults.baseURL,params:Fu(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:Fu(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 er(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??It(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 Ou extends Error{constructor(e,t){super(e),this.cause=t,this.name="WebSocketError"}}class Uu extends Ou{constructor(e,t){super(`WebSocket confirmation timeout for transaction ${e} after ${t}ms`),this.name="WebSocketTimeoutError"}}class Pu 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 Mu(e,t){if(oa(e))throw new Ou(`Invalid WebSocket response received for transaction ${t}: response is null or undefined`);if("object"!=typeof e)throw new Ou(`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 Ou(`Invalid WebSocket response received for transaction ${t}: missing status field`)}function $u(e,t,n,a){Mu(e,t);const s=e,r=s.data??{};if(!function(e){if(oa(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 Ou(`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 Lu(e){if(e&&function(e){return"privateKey"===e.providerType}(e))return e.getWallet()}class Ku{constructor(e){let t,n;e.walletProvider?(t=e.walletProvider,n=Lu(e.walletProvider)):e.wallet&&(n=e.wallet,t=sr.fromWallet(e.wallet)),this.wallet=n;const a=e.env??"prod",s=or(a);this.environment=a,this.config={baseUrl:e.launchpadBaseUrl??s.launchpadBaseUrl,gatewayBaseUrl:s.gatewayBaseUrl,bundleBaseUrl:s.bundleBaseUrl,webSocketUrl:s.webSocketUrl,gdexWebSocketUrl:s.gdexWebSocketUrl,dexApiBaseUrl:s.dexApiBaseUrl,dexBackendBaseUrl:s.dexBackendBaseUrl,launchpadFrontendUrl:s.launchpadFrontendUrl,timeout:3e4,debug:!1,...e};const r=e.signer??(void 0!==n?new Bo(n.privateKey):void 0),i=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."))},o=e.walletAddress??e.galaChainAddress??(void 0!==n?`eth|${n.address.slice(2)}`:function(e){if(void 0===e||!("walletAddress"in e))return;const t=e.walletAddress;return"string"==typeof t&&""!==t?t:void 0}(r))??"",c=new ou({bundleBaseUrl:this.config.bundleBaseUrl,launchpadBaseUrl:this.config.baseUrl,signer:i,walletAddress:o,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}});if(this.launchpad=new ku({transport:c,walletAddress:o}),this.tokens=new wu({gatewayBaseUrl:this.config.gatewayBaseUrl,dexBackendBaseUrl:this.config.dexBackendBaseUrl,signer:i,walletAddress:o,...void 0!==e.httpRequestor&&{httpRequestor:e.httpRequestor}}),this.logger=new wn({debug:this.config.debug??!1,context:"LaunchpadSDK"}),this.validateConfiguration(),this.slippageToleranceFactor=void 0===e.slippageToleranceFactor?Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR:this.parseSlippageToleranceFactor(e.slippageToleranceFactor),this.maxAcceptableReverseBondingCurveFeeSlippageFactor=void 0===e.maxAcceptableReverseBondingCurveFeeSlippageFactor?Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR:this.parseFeeSlippageFactor(e.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.calculateAmountMode=e.calculateAmountMode??Ku.DEFAULT_CALCULATE_AMOUNT_MODE,this.galaChainAddressOverride=e.galaChainAddress,this.auth=new rr({wallet:n,walletProvider:t,messagePrefix:"Create a GalaChain Wallet"}),this.jwtAuth=new Zs,void 0!==e.accessToken&&""!==e.accessToken){const t=e.accessTokenExpiresIn??86400;this.jwtAuth.setToken(e.accessToken,t)}this.http=new Bu(this.auth,this.config),this.sessionAuth=new nr(this.http,this.auth,this.jwtAuth,e.debug??!1),this.galaChainHttp=new Bu(this.auth,{...this.config,baseUrl:this.config.gatewayBaseUrl}),this.bundleHttp=new Bu(this.auth,{...this.config,baseUrl:this.config.bundleBaseUrl}),this.dexApiHttp=new Bu(this.auth,{...this.config,baseUrl:this.config.dexApiBaseUrl}),this.dexBackendHttp=new Bu(this.auth,{...this.config,baseUrl:this.config.dexBackendBaseUrl}),this.galaChainPublicAxios=xu(this.config.gatewayBaseUrl,this.config.timeout??3e4),this.cache=new Sa(e.debug??!1),this.launchpadService=new cl(this.http,this.jwtAuth),this.tokenResolverService=new zd(this.launchpadService.poolService),this.launchpadAPI=new Hs(this.http,this.tokenResolverService,this.logger,this.bundleHttp,this.galaChainHttp,this.dexApiHttp,this.calculateAmountMode,this.launchpad),this.galaChainService=new qc(this.galaChainHttp,n,this.tokenResolverService,e.debug??!1,this.galaChainPublicAxios),this.dexService=new ac(this.dexBackendHttp,this.cache,this.galaChainService,e.debug??!1),this.bundleService=new Ko(this.bundleHttp,this.tokenResolverService,this.config.debug??!1,n,n?this.getAddress():void 0,this.slippageToleranceFactor,this.maxAcceptableReverseBondingCurveFeeSlippageFactor),this.websocketService=new Zd({url:this.config.webSocketUrl},this.config.debug),this.priceHistoryService=new Ol(this.dexBackendHttp,this.config.debug??!1,this.tokenResolverService);const l=e.signer??(void 0===n?void 0:new Bo(n.privateKey)),d=e.walletAddress??(void 0===n?void 0:this.getAddress());this.dexClient=new f({env:this.environment,...void 0===l?{}:{signer:l},...void 0===d?{}:{walletAddress:d},...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 Xd(this.http,e.debug??!1)}createOverrideSdk(e){if(!ia(e))throw Yt("Invalid privateKey: must be a non-empty string","privateKey");if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Yt('Invalid privateKey format: must be "0x" followed by 64 hexadecimal characters',"privateKey");const t=new n(e),a={...this.config,wallet:t};return new Ku(a)}get dex(){return this.dexClient}getAddress(){return void 0!==this.galaChainAddressOverride&&""!==this.galaChainAddressOverride?this.galaChainAddressOverride:(this.validateWallet(),this.auth.getAddress())}getEthereumAddress(){return this.validateWallet(),this.wallet.address}validateWallet(){if(!this.wallet)throw Xt("wallet","Wallet");return this.wallet}setWallet(e){if(null==e||"object"!=typeof e||!("address"in e))throw new Wt("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?Lu(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:fn.GAS_FEE}}getVersion(){return Vi}getUrlByTokenName(e){const t=this.config.launchpadFrontendUrl;if(void 0===t||""===t)throw Yt("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}=ua(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(xt(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=yn((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: ${It(t)}`),e}}throw e}}async fetchGalaPrice(){return this.fetchTokenPrice({tokenId:{collection:"GALA",category:"Unit",type:"none",additionalKey:"none"}})}async fetchTokenDetails(e){return this.dexService.fetchTokenDetails(e)}async fetchAllDexSeasons(){return this.dexService.fetchAllDexSeasons()}async fetchCurrentDexSeason(){return this.dexService.fetchCurrentDexSeason()}async fetchDexLeaderboardBySeasonId(e){return this.dexService.fetchDexLeaderboardBySeasonId(e)}async fetchCurrentDexLeaderboard(){return this.dexService.fetchCurrentDexLeaderboard()}async fetchDexAggregatedVolumeSummary(){return this.dexService.fetchDexAggregatedVolumeSummary()}async fetchLaunchTokenFee(){return this.galaChainService.fetchLaunchTokenFee()}async fetchTokenClassesWithSupply(e){return this.galaChainService.fetchTokenClassesWithSupply(e)}async fetchPoolDetails(e){const t=await this.resolveVaultAddress(e);if(null==t)throw new Error(Ut(e));const n=(await this.galaChainService.fetchPoolDetails({vaultAddress:t})).Data,a=await this.launchpadAPI.fetchPoolDetailsForCalculation(e);return n.currentSupply=a.currentSupply,n.reverseBondingCurveMaxFeeFactor=a.reverseBondingCurveMaxFeeFactor,n.reverseBondingCurveMinFeeFactor=a.reverseBondingCurveMinFeeFactor,n.reverseBondingCurveNetFeeFactor=a.reverseBondingCurveNetFeeFactor,n.tokenName=e,n}async fetchPoolDetailsForCalculation(e){return this.launchpadAPI.fetchPoolDetailsForCalculation(e)}async isTokenGraduated(e){return(await this.fetchPoolDetails(e)).isGraduated}async fetchVolumeData(e){return this.launchpadService.fetchVolumeData(e)}async fetchTrades(e){return this.launchpadService.fetchTrades(e)}async fetchGalaBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Fa}),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 Ao(this.dexApiHttp,this.config.debug??!1)),this._bridgeableTokenService}getWrappableTokenService(){return this._wrappableTokenService??(this._wrappableTokenService=new au(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 Bi({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 su({galaConnectClient:this.getGalaConnectClient(),wrappableTokenService:this.getWrappableTokenService(),...e&&{walletAddress:this.getAddress(),wallet:e}})}return this._wrapService}getStreamingService(){return this._streamingService??(this._streamingService=new Wl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._streamingService}getStreamChatService(){return this._streamChatService??(this._streamChatService=new Pl(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 Vd(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 eu(this.http,this.config.debug??!1)),this._weeklyChallengeService}getOEmbedService(){return this._oembedService??(this._oembedService=new El(this.http,this.config.debug??!1)),this._oembedService}getPlatformStatsService(){return this._platformStatsService??(this._platformStatsService=new Bl(this.http,this.config.debug??!1)),this._platformStatsService}getNotificationService(){return this._notificationService??(this._notificationService=new Al(this.http,this.config.debug??!1,this.jwtAuth)),this._notificationService}getClientConfigService(){return this._clientConfigService??(this._clientConfigService=new Go(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 ml(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._moderatorService}getFlagService(){return this._flagService??(this._flagService=new ec(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._flagService}getOverseerService(){return this._overseerService??(this._overseerService=new Rl(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._overseerService}getWebSocketAdminService(){return this._websocketAdminService??(this._websocketAdminService=new Qd(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._websocketAdminService}getContentReactionService(){return this._contentReactionService??(this._contentReactionService=new nc(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 Fa}),n=t(e);if(void 0===n)throw new Wt(`Invalid address format: "${e}". Expected formats: eth|0x..., 0x..., or client|...`);return n}getMessagesService(){return this._messagesService??(this._messagesService=new ll(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.debug??!1,this.config.userApiKey)),this._messagesService}getRestrictedNamesService(){return this._restrictedNamesService??(this._restrictedNamesService=new Ul(this.http,this.config.streamAdminApiKey,this.jwtAuth,this.config.userApiKey)),this._restrictedNamesService}getPlatformConfigService(){return this._platformConfigService??(this._platformConfigService=new Fl(this.http,this.jwtAuth,this.config.debug??!1)),this._platformConfigService}getEventsBatcherService(){return this._eventsBatcherService??(this._eventsBatcherService=new uc(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)}return this._streamWebSocketService}getGdexStreamService(){return this._gdexStreamService??(this._gdexStreamService=new zc({url:this.config.gdexWebSocketUrl})),this._gdexStreamService}getStreamingEventService(){return this._streamingEventService??(this._streamingEventService=new Ml(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 revokeModeratorInvite(e){return this.getModeratorService().revokeInvite(e)}async updateModeratorInviteRole(e){return this.getModeratorService().updateInviteRole(e)}async updateModeratorInvite(e){return this.getModeratorService().updateInvite(e)}async getModeratorInviteByCode(e){return this.getModeratorService().getInviteByCode(e)}async createFlag(e){return this.getFlagService().createFlag(e)}async listFlags(e){return this.getFlagService().listFlags(e)}async listGlobalFlags(e={}){return this.getFlagService().listGlobalFlags(e)}async dismissFlag(e){return this.getFlagService().dismissFlag(e)}async actionFlag(e){return this.getFlagService().actionFlag(e)}async createOverseerInvite(e={}){return this.getOverseerService().createInvite(e)}async listOverseerInvites(e={}){return this.getOverseerService().listInvites(e)}async getOverseerInviteByCode(e){return this.getOverseerService().getInviteByCode(e)}async claimOverseerInvite(e){return this.getOverseerService().claimInvite(e)}async revokeOverseerInvite(e){return this.getOverseerService().revokeInvite(e)}async listOverseers(e={}){return this.getOverseerService().listOverseers(e)}async createOverseerDirect(e){return this.getOverseerService().createOverseerDirect(e)}async revokeOverseer(e){return this.getOverseerService().revokeOverseer(e)}async getMyOverseerStatus(){return this.getOverseerService().getMyStatus()}async getOverseerSummary(){return this.getOverseerService().getSummary()}async getBanStats(){return this.getOverseerService().getBanStats()}async getTokenBanStats(){return this.getOverseerService().getTokenBanStats()}async getInviteStats(){return this.getOverseerService().getInviteStats()}async getFlagStats(){return this.getOverseerService().getFlagStats()}async getUserStats(){return this.getOverseerService().getUserStats()}async listOverseerUsers(e){return this.getOverseerService().listOverseerUsers(e)}async getOverseerUserSummary(e){return this.getOverseerService().getOverseerUserSummary(e)}async flushCacheByAddress(e){return this.getOverseerService().flushCacheByAddress(e)}async flushCacheByToken(e){return this.getOverseerService().flushCacheByToken(e)}async flushAllCache(e){return this.getOverseerService().flushAllCache(e)}async flushWalletAliasCache(e){return this.getOverseerService().flushWalletAliasCache(e)}async emitTradeExecuted(e,t){return this.getWebSocketAdminService().emitTradeExecuted(e,t)}async emitBalanceUpdated(e,t,n){return this.getWebSocketAdminService().emitBalanceUpdated(e,t,n)}async emitStreamStatus(e,t){return this.getWebSocketAdminService().emitStreamStatus(e,t)}async emitViewerCount(e,t){return this.getWebSocketAdminService().emitViewerCount(e,t)}async emitStreamCountdown(e,t){return this.getWebSocketAdminService().emitStreamCountdown(e,t)}async emitChatMessage(e,t){return this.getWebSocketAdminService().emitChatMessage(e,t)}async emitChatStatus(e,t){return this.getWebSocketAdminService().emitChatStatus(e,t)}async emitTypingIndicator(e,t){return this.getWebSocketAdminService().emitTypingIndicator(e,t)}async emitTokenBanned(e,t){return this.getWebSocketAdminService().emitTokenBanned(e,t)}async emitTokenUnbanned(e,t){return this.getWebSocketAdminService().emitTokenUnbanned(e,t)}async emitModeratorAdded(e,t){return this.getWebSocketAdminService().emitModeratorAdded(e,t)}async emitModeratorRemoved(e,t){return this.getWebSocketAdminService().emitModeratorRemoved(e,t)}async emitUserProfileUpdated(e,t){return this.getWebSocketAdminService().emitUserProfileUpdated(e,t)}async emitSiteConfigChanged(e){return this.getWebSocketAdminService().emitSiteConfigChanged(e)}async emitFeatureStatus(e){return this.getWebSocketAdminService().emitFeatureStatus(e)}async emitRecordingStatus(e,t){return this.getWebSocketAdminService().emitRecordingStatus(e,t)}async emitRecordingsCountUpdated(e,t){return this.getWebSocketAdminService().emitRecordingsCountUpdated(e,t)}async emitDownloadReady(e,t){return this.getWebSocketAdminService().emitDownloadReady(e,t)}async getConnectedClients(e){return this.getWebSocketAdminService().getConnectedClients(e)}async isUserOnline(e){return this.getWebSocketAdminService().isUserOnline(e)}async getOnlineUsers(e){return this.getWebSocketAdminService().getOnlineUsers(e)}async getTokenViewers(e,t){return this.getWebSocketAdminService().getTokenViewers(e,t)}async getOnlineOverseers(){return this.getWebSocketAdminService().getOnlineOverseers()}async banToken(e){return this.getTokenBanService().banToken(e)}async unbanToken(e){return this.getTokenBanService().unbanToken(e)}async listTokenBans(e={}){return this.getTokenBanService().listTokenBans(e)}async getTokenBan(e){return this.getTokenBanService().getTokenBan(e)}async isTokenBanned(e){return this.getTokenBanService().isTokenBanned(e)}async getAIModerationSettings(){return this.getAIModerationService().getSettings()}async updateAIModerationSettings(e){return this.getAIModerationService().updateSettings(e)}async getAIModeration(e){return this.getAIModerationService().getModeration(e)}async triggerAIModeration(e){return this.getAIModerationService().triggerModeration(e)}async getAIModerationStatus(){return this.getAIModerationService().getStatus()}async getWeeklyChallengeLeaderboard(e={}){return this.getWeeklyChallengeService().getLeaderboard(e)}async getTokenWeeklyHistory(e){return this.getWeeklyChallengeService().getTokenHistory(e)}async getHomeOEmbed(e={}){return this.getOEmbedService().getHomeOEmbedJson(e)}async getPoolOEmbed(e){return this.getOEmbedService().getPoolOEmbedJson(e)}async getProfileOEmbed(e){return this.getOEmbedService().getProfileOEmbedJson(e)}async getPlatformStats(){return this.getPlatformStatsService().getStats()}async registerPushToken(e){return this.getNotificationService().registerPushToken(e)}async unregisterPushToken(e){return this.getNotificationService().unregisterPushToken(e)}async fetchNotificationPreferences(){return this.getNotificationService().getPreferences()}async updateNotificationPreferences(e){return this.getNotificationService().updatePreferences(e)}async fetchClientFlags(){return this.getClientConfigService().getClientFlags()}async addContentReaction(e){return this.getContentReactionService().addContentReaction(e)}async removeContentReaction(e){return this.getContentReactionService().removeContentReaction(e)}async addReactionToChatMessage(e){return this.getContentReactionService().addReactionToChatMessage(e)}async removeReactionFromChatMessage(e){return this.getContentReactionService().removeReactionFromChatMessage(e)}async addReactionToComment(e){return this.getContentReactionService().addReactionToComment(e)}async removeReactionFromComment(e){return this.getContentReactionService().removeReactionFromComment(e)}async getComments(e){const t=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 getTrades(e){return this.launchpadService.getTrades(e)}async getRecentTrades(e,t=50){return this.getTrades({...void 0!==e&&{tokenName:e},pageSize:Math.min(t,500)})}async fetchLaunchpadFee(){return this.tradingQuotesService.fetchLaunchpadFee()}async fetchSaleDetails(e){return this.tradingQuotesService.fetchSaleDetails(e)}async getTradeQuote(e){return this.tradingQuotesService.getTradeQuote(e)}async getPremintQuote(e){return this.tradingQuotesService.getPremintQuote(e)}async connectStreamWebSocket(e){const t=this.getStreamWebSocketService();await t.connect(),e&&t.setGlobalCallbacks(e)}async authenticateStreamWebSocket(){const e=this.getStreamWebSocketService(),t=await this.ensureValidToken();e.authenticate(t)}async subscribeToStream(e,t){return this.getStreamWebSocketService().subscribeToStream(e,t)}unsubscribeFromStream(e){this.getStreamWebSocketService().unsubscribeFromStream(e)}sendStreamChatViaWebSocket(e,t){this.getStreamWebSocketService().sendChatMessage(e,t)}sendStreamReaction(e,t,n=0){this.getStreamWebSocketService().sendReaction(e,t,n)}sendTypingStart(e){return this.getStreamWebSocketService().sendTypingStart(e)}sendTypingStop(e){return this.getStreamWebSocketService().sendTypingStop(e)}disconnectStreamWebSocket(){this._streamWebSocketService&&this._streamWebSocketService.disconnect()}isStreamWebSocketConnected(){return!!this._streamWebSocketService&&this._streamWebSocketService.isConnected()}onStreamStatusChanged(e){return this.getStreamingEventService().onStreamStatusChanged(e)}onUserBanned(e){return this.getStreamingEventService().onUserBanned(e)}onUserUnbanned(e){return this.getStreamingEventService().onUserUnbanned(e)}onBanEnforcement(e){return this.getStreamingEventService().onBanEnforcement(e)}onContentFlagged(e){return this.getStreamingEventService().onContentFlagged(e)}onFlagResolved(e){return this.getStreamingEventService().onFlagResolved(e)}onStreamChatMessage(e){return this.getStreamingEventService().onStreamChatMessage(e)}onStreamChatUpdated(e){return this.getStreamingEventService().onStreamChatUpdated(e)}onStreamChatDeleted(e){return this.getStreamingEventService().onStreamChatDeleted(e)}onStreamChatPinned(e){return this.getStreamingEventService().onStreamChatPinned(e)}onStreamChatUnpinned(e){return this.getStreamingEventService().onStreamChatUnpinned(e)}onChatStatusChanged(e){return this.getStreamingEventService().onChatStatusChanged(e)}onViewerCountChanged(e){return this.getStreamingEventService().onViewerCountChanged(e)}onRecordingStatusChanged(e){return this.getStreamingEventService().onRecordingStatusChanged(e)}onSimulcastStatusChanged(e){return this.getStreamingEventService().onSimulcastStatusChanged(e)}onDownloadReady(e){return this.getStreamingEventService().onDownloadReady(e)}onRecordingsCountUpdated(e){return this.getStreamingEventService().onRecordingsCountUpdated(e)}onUserTyping(e){return this.getStreamingEventService().onUserTyping(e)}onStreamReaction(e){return this.getStreamingEventService().onStreamReaction(e)}onContentReactionAdded(e){return this.getStreamingEventService().onContentReactionAdded(e)}onContentReactionRemoved(e){return this.getStreamingEventService().onContentReactionRemoved(e)}onStreamCountdownUpdated(e){return this.getStreamingEventService().onStreamCountdownUpdated(e)}onStreamLanguageUpdated(e){return this.getStreamingEventService().onStreamLanguageUpdated(e)}onStreamControlStatusChanged(e){return this.getStreamingEventService().onStreamControlStatusChanged(e)}onConnection(e){return this.getStreamingEventService().onConnection(e)}onAuthenticated(e){return this.getStreamingEventService().onAuthenticated(e)}onTokenSubscribed(e){return this.getStreamingEventService().onTokenSubscribed(e)}onTokenUnsubscribed(e){return this.getStreamingEventService().onTokenUnsubscribed(e)}onRoomSubscribed(e){return this.getStreamingEventService().onRoomSubscribed(e)}onRoomLeft(e){return this.getStreamingEventService().onRoomLeft(e)}onEngagementStatsUpdated(e){return this.getStreamWebSocketService().subscribeEngagementStatsUpdated(e)}async estimateBridgeFee(e){return this.getBridgeService().estimateBridgeFee(e)}async bridgeOut(e){return this.getBridgeService().bridgeOut(e)}async bridgeIn(e){return this.getBridgeService().bridgeIn(e)}async getBridgeStatus(e,t){return this.getBridgeService().getBridgeStatus(e,t)}getSupportedBridgeTokens(){const e=this.getBridgeService(),t=e.getSupportedBridgeTokens();return Promise.resolve({tokens:t,totalCount:t.length,supportedChains:e.getSupportedBridgeChains()})}async fetchTokenBalance(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Fa}),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=kn(e.tokenName);if("MUSIC"===t||"GMUSIC"===t){const a=`$${t}`;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=t.collection??"Token",s={collection:a,category:"Unit",type:t.symbol,additionalKey:"none"};return{quantity:t.balance,collection:a,category:"Unit",tokenId:cr(s)}}throw Xt("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 Zt("No transaction ID returned from buy operation");return this.waitForConfirmation(n,t=>$u(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 Zt("No transaction ID returned from sell operation");return this.waitForConfirmation(n,t=>$u(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=>{Mu(n,t);const a=n.data??{};if(!function(e){if(oa(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 Ou(`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 Fa}),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(K,s,{"x-wallet-address":t});if(!Array.isArray(r))throw new Ht("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(G,void 0,{"x-wallet-address":t});if(void 0===n||"number"!=typeof n.referralCount||void 0===n.rewardTotals)throw new Ht(`Unexpected API response: expected { referralCount, rewardTotals }, got ${JSON.stringify(n)}`);return n}async updateProfile(e){const{normalizeAddressInput:t}=await Promise.resolve().then(function(){return Fa}),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 Fa}),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 Fa}),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 Fa}),n=t(e?.address)??this.getAddress(),a={type:void 0!==e?.status?"created":"DEFI",address:n,pageSize:e?.pageSize??10};return void 0!==e?.cursor&&(a.cursor=e.cursor),void 0!==e?.tokenName&&""!==e.tokenName&&(a.tokenName=e.tokenName),void 0!==e?.search&&""!==e.search&&(a.search=e.search),void 0!==e?.status&&(a.status=e.status),this.launchpadService.fetchTokenList(a)}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 Fa}),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 Fa}),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 Fa});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)}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{ta(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 Yt("baseUrl is required in configuration","baseUrl");if(void 0===this.config.webSocketUrl||""===this.config.webSocketUrl)throw Yt("webSocketUrl is required in configuration","webSocketUrl");try{new URL(this.config.baseUrl)}catch{throw Yt(`Invalid baseUrl format: ${this.config.baseUrl}`,"baseUrl")}try{new URL(this.config.webSocketUrl)}catch{throw Yt(`Invalid webSocketUrl format: ${this.config.webSocketUrl}`,"webSocketUrl")}if(void 0!==this.config.gatewayBaseUrl&&""!==this.config.gatewayBaseUrl)try{new URL(this.config.gatewayBaseUrl)}catch{throw Yt(`Invalid gatewayBaseUrl format: ${this.config.gatewayBaseUrl}`,"gatewayBaseUrl")}if(void 0!==this.config.bundleBaseUrl&&""!==this.config.bundleBaseUrl)try{new URL(this.config.bundleBaseUrl)}catch{throw Yt(`Invalid bundleBaseUrl format: ${this.config.bundleBaseUrl}`,"bundleBaseUrl")}if(void 0!==this.config.launchpadFrontendUrl&&""!==this.config.launchpadFrontendUrl)try{new URL(this.config.launchpadFrontendUrl)}catch{throw Yt(`Invalid launchpadFrontendUrl format: ${this.config.launchpadFrontendUrl}`,"launchpadFrontendUrl")}}parseSlippageToleranceFactor(e){const t=Vn("string"==typeof e||"number"==typeof e?e:String(e),Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR);return t<0||t>1?(this.logger.warn(`Invalid slippage tolerance factor: ${String(e)}, using default: ${Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR}`),Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR):t}parseFeeSlippageFactor(e){const t=Vn("string"==typeof e||"number"==typeof e?e:String(e),Ku.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: ${Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR}`),Ku.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 Pu(e,n.status,n.message);let a;try{a=t(n)}catch(t){if(t instanceof Ou)throw t;throw new Ou(`Failed to transform WebSocket response for transaction ${e}`,Nt(t)?t:new Error(It(t)))}return this.logger.debug(`Transaction confirmed: ${e}`,a),a}catch(t){if(this.logger.error(`Transaction confirmation failed: ${e}`,t),t instanceof Pu||t instanceof Ou)throw t;throw new Ou(`WebSocket confirmation failed for transaction ${e}`,Nt(t)?t:new Error(It(t)))}}async warmCacheFromPools(e){if(void 0===e||!Array.isArray(e))return;const{extractMetadataFromPoolData:t,isValidPoolForCaching:n}=await Promise.resolve().then(function(){return Xu});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=It(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 Yt("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: ${It(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: ${It(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<Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS)return e++,void(a=setTimeout(()=>i(),Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS));if(!r&&e>=Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS){const e=new Error(`WebSocket not available after ${Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS*Ku.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 wn({debug:e,context:"LaunchpadSDK"});t.debug("Starting global cleanup..."),Zd.cleanupAll(e),t.debug("Global cleanup completed")}}function Gu(){const e=globalThis;return e.process?.env??{}}Ku.DEFAULT_SLIPPAGE_TOLERANCE_FACTOR=.15,Ku.DEFAULT_MAX_ACCEPTABLE_REVERSE_BONDING_CURVE_FEE_SLIPPAGE_FACTOR=.01,Ku.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY=fn.DEFAULT_LAUNCHPAD_TOKEN_MAX_SUPPLY,Ku.DEFAULT_CALCULATE_AMOUNT_MODE="local",Ku.TOKEN_CREATION_SOCKET_WAIT_ATTEMPTS=30,Ku.TOKEN_CREATION_SOCKET_POLL_INTERVAL_MS=100;let Wu=0;class Hu{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 Xt("mnemonic","Mnemonic phrase");const t=Hu.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"===Gu().NODE_ENV){const e=`test-wallet-${Date.now()}-${++Wu}`,t="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64),a=new n(t),s=Hu.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=Hu.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=Hu.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}catch(a){if("test"===Gu().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=Hu.toGalaAddress(r.address);return{privateKey:r.privateKey,address:r.address,galaAddress:i,mnemonic:e,wallet:r}}throw a}}static toGalaAddress(e){const n=Na(e);if(!/^[a-fA-F0-9]{40}$/.test(n))throw Qt("address","a valid Ethereum address (40 hex characters)");return`eth|${t(`0x${n}`).slice(2)}`}static toEthereumAddress(e){try{return Da(e)}catch(t){const n=It(t);if(n.includes("required")||!e?.startsWith("eth|"))throw Xt("galaAddress","Gala address starting with eth|");if(n.includes("Invalid backend"))throw Qt("galaAddress","Gala format (eth|{40-hex-chars})");throw t}}static isValidEthereumAddress(e){try{const t=Na(e);return/^[a-fA-F0-9]{40}$/.test(t)}catch{return!1}}static isValidGalaAddress(e){return""!==e&&"backend"===Ra(e)}static generateMultipleWallets(e=1){ta(e,1,100,"count");const t=[];if("test"===Gu().NODE_ENV)for(let n=0;n<e;n++){const e=`test-multi-${n}-${Date.now()}-${++Wu}`,a="0x"+Buffer.from(e).toString("hex").padStart(64,"1").slice(0,64);t.push(Hu.fromPrivateKey(a))}else for(let n=0;n<e;n++)t.push(Hu.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 qu(e){if(void 0===e)return Hu.generateWallet();const t=e.trim();if(!ia(t))throw Qt("input","a non-empty string");if(function(e){const t=Na(e);return/^[a-fA-F0-9]{64}$/.test(t)}(t))return Hu.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 Hu.fromMnemonic(t);throw Qt("input","a private key (64 hex characters) or mnemonic (12/24 words)","Wallet input")}function ju(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Qt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");const t=new h(e);return{publicKey:t.publicKey,compressedPublicKey:t.compressedPublicKey}}function Vu(e){if(!e.match(/^0x[a-fA-F0-9]{64}$/))throw Qt("privateKey","0x-prefixed 64 hexadecimal characters","Private key");return t(u(e))}function zu(e){oa(e)&&(e={});const{wallet:t,env:a,config:s={},...r}=e,i={...{...r,...s}};let o;if(delete i.wallet,delete i.env,delete i.config,oa(t)){o=qu().wallet}else if("string"==typeof t){o=qu(t).wallet}else{if(!(t instanceof n))throw Yt("Invalid wallet input. Expected string (private key or mnemonic) or Wallet instance.","wallet");o=t}const c={wallet:o,...void 0!==a?{env:a}:{},debug:!1,timeout:3e4,...i};return new Ku(c)}var Xu=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=Vn(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=Vn(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{Uo as BrowserWalletSigner,dc as EVENT_TYPES,Oo as GalaWalletSigner,Ku as LaunchpadSDK,ru as LaunchpadSDKError,Bo as PrivateKeySigner,Vi as SDK_VERSION,Pu as TransactionFailedError,Ou as WebSocketError,Uu as WebSocketTimeoutError,zu as createLaunchpadSDK,qu as createWallet,Do as generateEIP712Types,Vu as getEthereumAddressFromPrivateKey,ju as getPublicKeyFromPrivateKey};
|