@metamask/core-backend 4.1.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/CHANGELOG.md +35 -6
  2. package/README.md +252 -1
  3. package/dist/AccountActivityService.cjs +1 -1
  4. package/dist/AccountActivityService.cjs.map +1 -1
  5. package/dist/AccountActivityService.mjs +1 -1
  6. package/dist/AccountActivityService.mjs.map +1 -1
  7. package/dist/BackendWebSocketService-method-action-types.cjs.map +1 -1
  8. package/dist/BackendWebSocketService-method-action-types.d.cts +106 -20
  9. package/dist/BackendWebSocketService-method-action-types.d.cts.map +1 -1
  10. package/dist/BackendWebSocketService-method-action-types.d.mts +106 -20
  11. package/dist/BackendWebSocketService-method-action-types.d.mts.map +1 -1
  12. package/dist/BackendWebSocketService-method-action-types.mjs.map +1 -1
  13. package/dist/BackendWebSocketService.cjs +5 -3
  14. package/dist/BackendWebSocketService.cjs.map +1 -1
  15. package/dist/BackendWebSocketService.d.cts +2 -2
  16. package/dist/BackendWebSocketService.d.cts.map +1 -1
  17. package/dist/BackendWebSocketService.d.mts +2 -2
  18. package/dist/BackendWebSocketService.d.mts.map +1 -1
  19. package/dist/BackendWebSocketService.mjs +5 -3
  20. package/dist/BackendWebSocketService.mjs.map +1 -1
  21. package/dist/api/ApiPlatformClient.cjs +177 -0
  22. package/dist/api/ApiPlatformClient.cjs.map +1 -0
  23. package/dist/api/ApiPlatformClient.d.cts +127 -0
  24. package/dist/api/ApiPlatformClient.d.cts.map +1 -0
  25. package/dist/api/ApiPlatformClient.d.mts +127 -0
  26. package/dist/api/ApiPlatformClient.d.mts.map +1 -0
  27. package/dist/api/ApiPlatformClient.mjs +172 -0
  28. package/dist/api/ApiPlatformClient.mjs.map +1 -0
  29. package/dist/api/accounts/client.cjs +492 -0
  30. package/dist/api/accounts/client.cjs.map +1 -0
  31. package/dist/api/accounts/client.d.cts +213 -0
  32. package/dist/api/accounts/client.d.cts.map +1 -0
  33. package/dist/api/accounts/client.d.mts +213 -0
  34. package/dist/api/accounts/client.d.mts.map +1 -0
  35. package/dist/api/accounts/client.mjs +488 -0
  36. package/dist/api/accounts/client.mjs.map +1 -0
  37. package/dist/api/accounts/index.cjs +9 -0
  38. package/dist/api/accounts/index.cjs.map +1 -0
  39. package/dist/api/accounts/index.d.cts +6 -0
  40. package/dist/api/accounts/index.d.cts.map +1 -0
  41. package/dist/api/accounts/index.d.mts +6 -0
  42. package/dist/api/accounts/index.d.mts.map +1 -0
  43. package/dist/api/accounts/index.mjs +5 -0
  44. package/dist/api/accounts/index.mjs.map +1 -0
  45. package/dist/api/accounts/types.cjs +7 -0
  46. package/dist/api/accounts/types.cjs.map +1 -0
  47. package/dist/api/accounts/types.d.cts +195 -0
  48. package/dist/api/accounts/types.d.cts.map +1 -0
  49. package/dist/api/accounts/types.d.mts +195 -0
  50. package/dist/api/accounts/types.d.mts.map +1 -0
  51. package/dist/api/accounts/types.mjs +6 -0
  52. package/dist/api/accounts/types.mjs.map +1 -0
  53. package/dist/api/base-client.cjs +149 -0
  54. package/dist/api/base-client.cjs.map +1 -0
  55. package/dist/api/base-client.d.cts +54 -0
  56. package/dist/api/base-client.d.cts.map +1 -0
  57. package/dist/api/base-client.d.mts +54 -0
  58. package/dist/api/base-client.d.mts.map +1 -0
  59. package/dist/api/base-client.mjs +143 -0
  60. package/dist/api/base-client.mjs.map +1 -0
  61. package/dist/api/index.cjs +35 -0
  62. package/dist/api/index.cjs.map +1 -0
  63. package/dist/api/index.d.cts +18 -0
  64. package/dist/api/index.d.cts.map +1 -0
  65. package/dist/api/index.d.mts +18 -0
  66. package/dist/api/index.d.mts.map +1 -0
  67. package/dist/api/index.mjs +18 -0
  68. package/dist/api/index.mjs.map +1 -0
  69. package/dist/api/prices/client.cjs +521 -0
  70. package/dist/api/prices/client.cjs.map +1 -0
  71. package/dist/api/prices/client.d.cts +235 -0
  72. package/dist/api/prices/client.d.cts.map +1 -0
  73. package/dist/api/prices/client.d.mts +235 -0
  74. package/dist/api/prices/client.d.mts.map +1 -0
  75. package/dist/api/prices/client.mjs +517 -0
  76. package/dist/api/prices/client.mjs.map +1 -0
  77. package/dist/api/prices/index.cjs +9 -0
  78. package/dist/api/prices/index.cjs.map +1 -0
  79. package/dist/api/prices/index.d.cts +6 -0
  80. package/dist/api/prices/index.d.cts.map +1 -0
  81. package/dist/api/prices/index.d.mts +6 -0
  82. package/dist/api/prices/index.d.mts.map +1 -0
  83. package/dist/api/prices/index.mjs +5 -0
  84. package/dist/api/prices/index.mjs.map +1 -0
  85. package/dist/api/prices/types.cjs +7 -0
  86. package/dist/api/prices/types.cjs.map +1 -0
  87. package/dist/api/prices/types.d.cts +61 -0
  88. package/dist/api/prices/types.d.cts.map +1 -0
  89. package/dist/api/prices/types.d.mts +61 -0
  90. package/dist/api/prices/types.d.mts.map +1 -0
  91. package/dist/api/prices/types.mjs +6 -0
  92. package/dist/api/prices/types.mjs.map +1 -0
  93. package/dist/api/shared-types.cjs +93 -0
  94. package/dist/api/shared-types.cjs.map +1 -0
  95. package/dist/api/shared-types.d.cts +131 -0
  96. package/dist/api/shared-types.d.cts.map +1 -0
  97. package/dist/api/shared-types.d.mts +131 -0
  98. package/dist/api/shared-types.d.mts.map +1 -0
  99. package/dist/api/shared-types.mjs +87 -0
  100. package/dist/api/shared-types.mjs.map +1 -0
  101. package/dist/api/test-utils.cjs +70 -0
  102. package/dist/api/test-utils.cjs.map +1 -0
  103. package/dist/api/test-utils.d.cts +30 -0
  104. package/dist/api/test-utils.d.cts.map +1 -0
  105. package/dist/api/test-utils.d.mts +30 -0
  106. package/dist/api/test-utils.d.mts.map +1 -0
  107. package/dist/api/test-utils.mjs +64 -0
  108. package/dist/api/test-utils.mjs.map +1 -0
  109. package/dist/api/token/client.cjs +342 -0
  110. package/dist/api/token/client.cjs.map +1 -0
  111. package/dist/api/token/client.d.cts +193 -0
  112. package/dist/api/token/client.d.cts.map +1 -0
  113. package/dist/api/token/client.d.mts +193 -0
  114. package/dist/api/token/client.d.mts.map +1 -0
  115. package/dist/api/token/client.mjs +338 -0
  116. package/dist/api/token/client.mjs.map +1 -0
  117. package/dist/api/token/index.cjs +9 -0
  118. package/dist/api/token/index.cjs.map +1 -0
  119. package/dist/api/token/index.d.cts +6 -0
  120. package/dist/api/token/index.d.cts.map +1 -0
  121. package/dist/api/token/index.d.mts +6 -0
  122. package/dist/api/token/index.d.mts.map +1 -0
  123. package/dist/api/token/index.mjs +5 -0
  124. package/dist/api/token/index.mjs.map +1 -0
  125. package/dist/api/token/types.cjs +7 -0
  126. package/dist/api/token/types.cjs.map +1 -0
  127. package/dist/api/token/types.d.cts +75 -0
  128. package/dist/api/token/types.d.cts.map +1 -0
  129. package/dist/api/token/types.d.mts +75 -0
  130. package/dist/api/token/types.d.mts.map +1 -0
  131. package/dist/api/token/types.mjs +6 -0
  132. package/dist/api/token/types.mjs.map +1 -0
  133. package/dist/api/tokens/client.cjs +91 -0
  134. package/dist/api/tokens/client.cjs.map +1 -0
  135. package/dist/api/tokens/client.d.cts +45 -0
  136. package/dist/api/tokens/client.d.cts.map +1 -0
  137. package/dist/api/tokens/client.d.mts +45 -0
  138. package/dist/api/tokens/client.d.mts.map +1 -0
  139. package/dist/api/tokens/client.mjs +87 -0
  140. package/dist/api/tokens/client.mjs.map +1 -0
  141. package/dist/api/tokens/index.cjs +9 -0
  142. package/dist/api/tokens/index.cjs.map +1 -0
  143. package/dist/api/tokens/index.d.cts +6 -0
  144. package/dist/api/tokens/index.d.cts.map +1 -0
  145. package/dist/api/tokens/index.d.mts +6 -0
  146. package/dist/api/tokens/index.d.mts.map +1 -0
  147. package/dist/api/tokens/index.mjs +5 -0
  148. package/dist/api/tokens/index.mjs.map +1 -0
  149. package/dist/api/tokens/types.cjs +7 -0
  150. package/dist/api/tokens/types.cjs.map +1 -0
  151. package/dist/api/tokens/types.d.cts +83 -0
  152. package/dist/api/tokens/types.d.cts.map +1 -0
  153. package/dist/api/tokens/types.d.mts +83 -0
  154. package/dist/api/tokens/types.d.mts.map +1 -0
  155. package/dist/api/tokens/types.mjs +6 -0
  156. package/dist/api/tokens/types.mjs.map +1 -0
  157. package/dist/index.cjs +33 -4
  158. package/dist/index.cjs.map +1 -1
  159. package/dist/index.d.cts +6 -7
  160. package/dist/index.d.cts.map +1 -1
  161. package/dist/index.d.mts +6 -7
  162. package/dist/index.d.mts.map +1 -1
  163. package/dist/index.mjs +21 -5
  164. package/dist/index.mjs.map +1 -1
  165. package/package.json +9 -12
@@ -1 +1 @@
1
- {"version":3,"file":"AccountActivityService.mjs","sourceRoot":"","sources":["../src/AccountActivityService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;;;;;;;;;;;;AAgBH,OAAO,EAAE,cAAc,EAAE,sCAAkC;AAE3D,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,qBAAiB;AAuB7D,MAAM,YAAY,GAAG,wBAAwB,CAAC;AAE9C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,yBAAyB,GAAG,CAAC,WAAW,EAAE,aAAa,CAAU,CAAC;AAExE,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AA0BrD,4EAA4E;AAC5E,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACtD,uCAAuC;IACvC,iCAAiC;IACjC,2CAA2C;IAC3C,mCAAmC;IACnC,2CAA2C;IAC3C,gDAAgD;IAChD,mDAAmD;IACnD,0DAA0D;IAC1D,4CAA4C;IAC5C,+CAA+C;CACvC,CAAC;AAEX,2DAA2D;AAC3D,MAAM,CAAC,MAAM,uCAAuC,GAAG;IACrD,0CAA0C;IAC1C,gDAAgD;CACxC,CAAC;AAkDX,gFAAgF;AAChF,qBAAqB;AACrB,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,OAAO,sBAAsB;IAejC,gFAAgF;IAChF,iCAAiC;IACjC,gFAAgF;IAEh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KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAChE,iEAAiE;QACjE,OAAO,YAAY,OAAO,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;IAED,qCAAqC;IACrC,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAChE,oEAAoE;QACpE,OAAO,YAAY,OAAO,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;IAED,yDAAyD;IACzD,OAAO,OAAO,CAAC,OAAO,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,KAAK;IACH,GAAG,CAAC,+DAA+D,CAAC,CAAC;IAErE,yEAAyE;IACzE,kEAAkE;IAClE,MAAM,uBAAA,IAAI,yCAAW,CAAC,IAAI,CAAC,2CAA2C,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Account Activity Service for monitoring account transactions and balance changes\n *\n * This service subscribes to account activity and receives all transactions\n * and balance updates for those accounts via the comprehensive AccountActivityMessage format.\n */\n\nimport type {\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { AccountActivityServiceMethodActions } from './AccountActivityService-method-action-types';\nimport type {\n WebSocketConnectionInfo,\n BackendWebSocketServiceConnectionStateChangedEvent,\n ServerNotificationMessage,\n} from './BackendWebSocketService';\nimport { WebSocketState } from './BackendWebSocketService';\nimport type { BackendWebSocketServiceMethodActions } from './BackendWebSocketService-method-action-types';\nimport { projectLogger, createModuleLogger } from './logger';\nimport type {\n Transaction,\n AccountActivityMessage,\n BalanceUpdate,\n} from './types';\n\n// =============================================================================\n// Types and Constants\n// =============================================================================\n\n/**\n * System notification data for chain status updates\n */\nexport type SystemNotificationData = {\n /** Array of chain IDs affected (e.g., ['eip155:137', 'eip155:1']) */\n chainIds: string[];\n /** Status of the chains: 'down' or 'up' */\n status: 'down' | 'up';\n /** Timestamp of the notification */\n timestamp?: number;\n};\n\nconst SERVICE_NAME = 'AccountActivityService';\n\nconst log = createModuleLogger(projectLogger, SERVICE_NAME);\n\nconst MESSENGER_EXPOSED_METHODS = ['subscribe', 'unsubscribe'] as const;\n\nconst SUBSCRIPTION_NAMESPACE = 'account-activity.v1';\n\n/**\n * Account subscription options\n */\nexport type SubscriptionOptions = {\n address: string; // Should be in CAIP-10 format, e.g., \"eip155:0:0x1234...\" or \"solana:0:ABC123...\"\n};\n\n/**\n * Configuration options for the account activity service\n */\nexport type AccountActivityServiceOptions = {\n /** Custom subscription namespace (default: 'account-activity.v1') */\n subscriptionNamespace?: string;\n /** Optional callback to trace performance of account activity operations (default: no-op) */\n traceFn?: TraceCallback;\n};\n\n// =============================================================================\n// Action and Event Types\n// =============================================================================\n\n// Action types for the messaging system - using generated method actions\nexport type AccountActivityServiceActions = AccountActivityServiceMethodActions;\n\n// Allowed actions that AccountActivityService can call on other controllers\nexport const ACCOUNT_ACTIVITY_SERVICE_ALLOWED_ACTIONS = [\n 'AccountsController:getSelectedAccount',\n 'BackendWebSocketService:connect',\n 'BackendWebSocketService:forceReconnection',\n 'BackendWebSocketService:subscribe',\n 'BackendWebSocketService:getConnectionInfo',\n 'BackendWebSocketService:channelHasSubscription',\n 'BackendWebSocketService:getSubscriptionsByChannel',\n 'BackendWebSocketService:findSubscriptionsByChannelPrefix',\n 'BackendWebSocketService:addChannelCallback',\n 'BackendWebSocketService:removeChannelCallback',\n] as const;\n\n// Allowed events that AccountActivityService can listen to\nexport const ACCOUNT_ACTIVITY_SERVICE_ALLOWED_EVENTS = [\n 'AccountsController:selectedAccountChange',\n 'BackendWebSocketService:connectionStateChanged',\n] as const;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | BackendWebSocketServiceMethodActions;\n\n// Event types for the messaging system\n\nexport type AccountActivityServiceTransactionUpdatedEvent = {\n type: `AccountActivityService:transactionUpdated`;\n payload: [Transaction];\n};\n\nexport type AccountActivityServiceBalanceUpdatedEvent = {\n type: `AccountActivityService:balanceUpdated`;\n payload: [{ address: string; chain: string; updates: BalanceUpdate[] }];\n};\n\nexport type AccountActivityServiceSubscriptionErrorEvent = {\n type: `AccountActivityService:subscriptionError`;\n payload: [{ addresses: string[]; error: string; operation: string }];\n};\n\nexport type AccountActivityServiceStatusChangedEvent = {\n type: `AccountActivityService:statusChanged`;\n payload: [\n {\n chainIds: string[];\n status: 'up' | 'down';\n timestamp?: number;\n },\n ];\n};\n\nexport type AccountActivityServiceEvents =\n | AccountActivityServiceTransactionUpdatedEvent\n | AccountActivityServiceBalanceUpdatedEvent\n | AccountActivityServiceSubscriptionErrorEvent\n | AccountActivityServiceStatusChangedEvent;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | BackendWebSocketServiceConnectionStateChangedEvent;\n\nexport type AccountActivityServiceMessenger = Messenger<\n typeof SERVICE_NAME,\n AccountActivityServiceActions | AllowedActions,\n AccountActivityServiceEvents | AllowedEvents\n>;\n\n// =============================================================================\n// Main Service Class\n// =============================================================================\n\n/**\n * High-performance service for real-time account activity monitoring using optimized\n * WebSocket subscriptions with direct callback routing. Automatically subscribes to\n * the currently selected account and switches subscriptions when the selected account changes.\n * Receives transactions and balance updates using the comprehensive AccountActivityMessage format.\n *\n * Performance Features:\n * - Direct callback routing (no EventEmitter overhead)\n * - Minimal subscription tracking (no duplication with BackendWebSocketService)\n * - Optimized cleanup for mobile environments\n * - Single-account subscription (only selected account)\n * - Comprehensive balance updates with transfer tracking\n *\n * Architecture:\n * - Uses messenger pattern to communicate with BackendWebSocketService\n * - AccountActivityService tracks channel-to-subscriptionId mappings via messenger calls\n * - Automatically subscribes to selected account on initialization\n * - Switches subscriptions when selected account changes\n * - No direct dependency on BackendWebSocketService (uses messenger instead)\n *\n * @example\n * ```typescript\n * const service = new AccountActivityService({\n * messenger: activityMessenger,\n * });\n *\n * // Service automatically subscribes to the currently selected account\n * // When user switches accounts, service automatically resubscribes\n *\n * // All transactions and balance updates are received via optimized\n * // WebSocket callbacks and processed with zero-allocation routing\n * // Balance updates include comprehensive transfer details and post-transaction balances\n * ```\n */\nexport class AccountActivityService {\n /**\n * The name of the service.\n */\n readonly name = SERVICE_NAME;\n\n readonly #messenger: AccountActivityServiceMessenger;\n\n readonly #options: Required<Omit<AccountActivityServiceOptions, 'traceFn'>>;\n\n readonly #trace: TraceCallback;\n\n // Track chains that are currently up (based on system notifications)\n readonly #chainsUp: Set<string> = new Set();\n\n // =============================================================================\n // Constructor and Initialization\n // =============================================================================\n\n /**\n * Creates a new Account Activity service instance\n *\n * @param options - Configuration options including messenger\n */\n constructor(\n options: AccountActivityServiceOptions & {\n messenger: AccountActivityServiceMessenger;\n },\n ) {\n this.#messenger = options.messenger;\n\n // Set configuration with defaults\n this.#options = {\n subscriptionNamespace:\n options.subscriptionNamespace ?? SUBSCRIPTION_NAMESPACE,\n };\n\n // Default to no-op trace function to keep core platform-agnostic\n this.#trace =\n options.traceFn ??\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (((_request: any, fn?: any) => fn?.()) as TraceCallback);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n this.#messenger.subscribe(\n 'AccountsController:selectedAccountChange',\n // Promise result intentionally not awaited\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account: InternalAccount) =>\n await this.#handleSelectedAccountChange(account),\n );\n this.#messenger.subscribe(\n 'BackendWebSocketService:connectionStateChanged',\n // Promise result intentionally not awaited\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n (connectionInfo: WebSocketConnectionInfo) =>\n this.#handleWebSocketStateChange(connectionInfo),\n );\n this.#messenger.call('BackendWebSocketService:addChannelCallback', {\n channelName: `system-notifications.v1.${this.#options.subscriptionNamespace}`,\n callback: (notification: ServerNotificationMessage) =>\n this.#handleSystemNotification(notification),\n });\n }\n\n // =============================================================================\n // Account Subscription Methods\n // =============================================================================\n\n /**\n * Subscribe to account activity (transactions and balance updates)\n * Address should be in CAIP-10 format (e.g., \"eip155:0:0x1234...\" or \"solana:0:ABC123...\")\n *\n * @param subscription - Account subscription configuration with address\n */\n async subscribe(subscription: SubscriptionOptions): Promise<void> {\n try {\n await this.#messenger.call('BackendWebSocketService:connect');\n\n // Create channel name from address\n const channel = `${this.#options.subscriptionNamespace}.${subscription.address}`;\n\n // Check if already subscribed\n if (\n this.#messenger.call(\n 'BackendWebSocketService:channelHasSubscription',\n channel,\n )\n ) {\n return;\n }\n\n // Create subscription using the proper subscribe method (this will be stored in WebSocketService's internal tracking)\n await this.#messenger.call('BackendWebSocketService:subscribe', {\n channels: [channel],\n channelType: this.#options.subscriptionNamespace, // e.g., 'account-activity.v1'\n callback: (notification: ServerNotificationMessage) => {\n this.#handleAccountActivityUpdate(\n notification.data as AccountActivityMessage,\n );\n },\n });\n } catch (error) {\n log('Subscription failed, forcing reconnection', { error });\n await this.#forceReconnection();\n }\n }\n\n /**\n * Unsubscribe from account activity for specified address\n * Address should be in CAIP-10 format (e.g., \"eip155:0:0x1234...\" or \"solana:0:ABC123...\")\n *\n * @param subscription - Account subscription configuration with address to unsubscribe\n */\n async unsubscribe(subscription: SubscriptionOptions): Promise<void> {\n const { address } = subscription;\n try {\n // Find channel for the specified address\n const channel = `${this.#options.subscriptionNamespace}.${address}`;\n const subscriptions = this.#messenger.call(\n 'BackendWebSocketService:getSubscriptionsByChannel',\n channel,\n );\n\n if (subscriptions.length === 0) {\n return;\n }\n\n // Fast path: Direct unsubscribe using stored unsubscribe function\n // Unsubscribe from all matching subscriptions\n for (const subscriptionInfo of subscriptions) {\n await subscriptionInfo.unsubscribe();\n }\n } catch (error) {\n log('Unsubscription failed, forcing reconnection', { error });\n await this.#forceReconnection();\n }\n }\n\n // =============================================================================\n // Private Methods - Event Handlers\n // =============================================================================\n\n /**\n * Handle account activity updates (transactions + balance changes)\n * Processes the comprehensive AccountActivityMessage format with detailed balance updates and transfers\n *\n * @param payload - The account activity message containing transaction and balance updates\n * @example AccountActivityMessage format handling:\n * Input: {\n * address: \"0xd14b52362b5b777ffa754c666ddec6722aaeee08\",\n * tx: { id: \"0x1cde...\", chain: \"eip155:8453\", status: \"confirmed\", timestamp: 1760099871, ... },\n * updates: [{\n * asset: { fungible: true, type: \"eip155:8453/erc20:0x833...\", unit: \"USDC\", decimals: 6 },\n * postBalance: { amount: \"0xc350\" },\n * transfers: [{ from: \"0x7b07...\", to: \"0xd14b...\", amount: \"0x2710\" }]\n * }]\n * }\n * Output: Transaction and balance updates published separately\n */\n #handleAccountActivityUpdate(payload: AccountActivityMessage): void {\n const { address, tx, updates } = payload;\n\n // Calculate time elapsed between transaction time and message receipt\n const txTimestampMs = tx.timestamp * 1000; // Convert Unix timestamp (seconds) to milliseconds\n const elapsedMs = Date.now() - txTimestampMs;\n\n log('Handling account activity update', {\n address,\n updateCount: updates.length,\n elapsedMs,\n });\n\n // Trace message receipt with latency from transaction time to now\n // Promise result intentionally not awaited\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#trace(\n {\n name: `${SERVICE_NAME} Transaction Message`,\n data: {\n chain: tx.chain,\n status: tx.status,\n elapsed_ms: elapsedMs,\n },\n tags: {\n service: SERVICE_NAME,\n notification_type: this.#options.subscriptionNamespace,\n },\n },\n () => {\n // Process transaction update\n this.#messenger.publish(\n `AccountActivityService:transactionUpdated`,\n tx,\n );\n\n // Publish comprehensive balance updates with transfer details\n this.#messenger.publish(`AccountActivityService:balanceUpdated`, {\n address,\n chain: tx.chain,\n updates,\n });\n },\n );\n }\n\n /**\n * Handle selected account change event\n *\n * @param newAccount - The newly selected account\n */\n async #handleSelectedAccountChange(\n newAccount: InternalAccount | null,\n ): Promise<void> {\n if (!newAccount?.address) {\n return;\n }\n\n try {\n // Convert new account to CAIP-10 format\n const newAddress = this.#convertToCaip10Address(newAccount);\n\n // First, unsubscribe from all current account activity subscriptions to avoid multiple subscriptions\n await this.#unsubscribeFromAllAccountActivity();\n\n // Then, subscribe to the new selected account\n await this.subscribe({ address: newAddress });\n } catch (error) {\n log('Account change failed', { error });\n }\n }\n\n /**\n * Handle system notification for chain status changes\n * Publishes only the status change (delta) for affected chains\n *\n * @param notification - Server notification message containing chain status updates and timestamp\n */\n #handleSystemNotification(notification: ServerNotificationMessage): void {\n const data = notification.data as SystemNotificationData;\n const { timestamp } = notification;\n\n // Validate required fields\n if (!data.chainIds || !Array.isArray(data.chainIds) || !data.status) {\n throw new Error(\n 'Invalid system notification data: missing chainIds or status',\n );\n }\n\n // Track chain status\n if (data.status === 'up') {\n for (const chainId of data.chainIds) {\n this.#chainsUp.add(chainId);\n }\n } else {\n for (const chainId of data.chainIds) {\n this.#chainsUp.delete(chainId);\n }\n }\n\n // Publish status change directly (delta update)\n this.#messenger.publish(`AccountActivityService:statusChanged`, {\n chainIds: data.chainIds,\n status: data.status,\n timestamp,\n });\n\n log(\n `WebSocket status change - Published tracked chains as ${data.status}`,\n {\n count: data.chainIds.length,\n chains: data.chainIds,\n status: data.status,\n },\n );\n }\n\n /**\n * Handle WebSocket connection state changes for fallback polling and resubscription\n *\n * @param connectionInfo - WebSocket connection state information\n */\n async #handleWebSocketStateChange(\n connectionInfo: WebSocketConnectionInfo,\n ): Promise<void> {\n const { state } = connectionInfo;\n\n if (state === WebSocketState.CONNECTED) {\n // WebSocket connected - resubscribe to selected account\n // The system notification will automatically provide the list of chains that are up\n await this.#subscribeToSelectedAccount();\n } else if (state === WebSocketState.DISCONNECTED) {\n // On disconnect, flush all tracked chains as down\n const chainsToMarkDown = Array.from(this.#chainsUp);\n\n if (chainsToMarkDown.length > 0) {\n this.#messenger.publish(`AccountActivityService:statusChanged`, {\n chainIds: chainsToMarkDown,\n status: 'down',\n timestamp: Date.now(),\n });\n\n log('WebSocket disconnection - Published tracked chains as down', {\n count: chainsToMarkDown.length,\n chains: chainsToMarkDown,\n });\n\n // Clear the tracking set since all chains are now down\n this.#chainsUp.clear();\n }\n }\n }\n\n // =============================================================================\n // Private Methods - Subscription Management\n // =============================================================================\n\n /**\n * Subscribe to the currently selected account only\n */\n async #subscribeToSelectedAccount(): Promise<void> {\n const selectedAccount = this.#messenger.call(\n 'AccountsController:getSelectedAccount',\n );\n\n if (!selectedAccount || !selectedAccount.address) {\n return;\n }\n\n // Convert to CAIP-10 format and subscribe\n const address = this.#convertToCaip10Address(selectedAccount);\n await this.subscribe({ address });\n }\n\n /**\n * Unsubscribe from all account activity subscriptions for this service\n * Finds all channels matching the service's namespace and unsubscribes from them\n */\n async #unsubscribeFromAllAccountActivity(): Promise<void> {\n const accountActivitySubscriptions = this.#messenger.call(\n 'BackendWebSocketService:findSubscriptionsByChannelPrefix',\n this.#options.subscriptionNamespace,\n );\n\n // Unsubscribe from all matching subscriptions\n for (const subscription of accountActivitySubscriptions) {\n await subscription.unsubscribe();\n }\n }\n\n // =============================================================================\n // Private Methods - Utility Functions\n // =============================================================================\n\n /**\n * Convert an InternalAccount address to CAIP-10 format or raw address\n *\n * @param account - The internal account to convert\n * @returns The CAIP-10 formatted address or raw address\n */\n #convertToCaip10Address(account: InternalAccount): string {\n // Check if account has EVM scopes\n if (account.scopes.some((scope) => scope.startsWith('eip155:'))) {\n // CAIP-10 format: eip155:0:address (subscribe to all EVM chains)\n return `eip155:0:${account.address}`;\n }\n\n // Check if account has Solana scopes\n if (account.scopes.some((scope) => scope.startsWith('solana:'))) {\n // CAIP-10 format: solana:0:address (subscribe to all Solana chains)\n return `solana:0:${account.address}`;\n }\n\n // For other chains or unknown scopes, return raw address\n return account.address;\n }\n\n /**\n * Force WebSocket reconnection to clean up subscription state\n */\n async #forceReconnection(): Promise<void> {\n log('Forcing WebSocket reconnection to clean up subscription state');\n\n // Use the dedicated forceReconnection method which performs a controlled\n // disconnect-then-connect sequence to clean up subscription state\n await this.#messenger.call('BackendWebSocketService:forceReconnection');\n }\n\n // =============================================================================\n // Public Methods - Cleanup\n // =============================================================================\n\n /**\n * Destroy the service and clean up all resources\n * Optimized for fast cleanup during service destruction or mobile app termination\n */\n destroy(): void {\n // Clean up system notification callback\n this.#messenger.call(\n 'BackendWebSocketService:removeChannelCallback',\n `system-notifications.v1.${this.#options.subscriptionNamespace}`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"AccountActivityService.mjs","sourceRoot":"","sources":["../src/AccountActivityService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;;;;;;;;;;;;;AAgBH,OAAO,EAAE,cAAc,EAAE,sCAAkC;AAE3D,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,qBAAiB;AAuB7D,MAAM,YAAY,GAAG,wBAAwB,CAAC;AAE9C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,yBAAyB,GAAG,CAAC,WAAW,EAAE,aAAa,CAAU,CAAC;AAExE,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;AA0BrD,4EAA4E;AAC5E,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACtD,uCAAuC;IACvC,iCAAiC;IACjC,2CAA2C;IAC3C,mCAAmC;IACnC,2CAA2C;IAC3C,gDAAgD;IAChD,mDAAmD;IACnD,0DAA0D;IAC1D,4CAA4C;IAC5C,+CAA+C;CACvC,CAAC;AAEX,2DAA2D;AAC3D,MAAM,CAAC,MAAM,uCAAuC,GAAG;IACrD,0CAA0C;IAC1C,gDAAgD;CACxC,CAAC;AAkDX,gFAAgF;AAChF,qBAAqB;AACrB,gFAAgF;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,OAAO,sBAAsB;IAejC,gFAAgF;IAChF,iCAAiC;IACjC,gFAAgF;IAEhF;;;;OAIG;IACH,YACE,OAEC;;QA1BH;;WAEG;QACM,SAAI,GAAG,YAAY,CAAC;QAEpB,o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,OAAO,YAAY,OAAO,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;IAED,qCAAqC;IACrC,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAChE,oEAAoE;QACpE,OAAO,YAAY,OAAO,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC;IAED,yDAAyD;IACzD,OAAO,OAAO,CAAC,OAAO,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,KAAK;IACH,GAAG,CAAC,+DAA+D,CAAC,CAAC;IAErE,yEAAyE;IACzE,kEAAkE;IAClE,MAAM,uBAAA,IAAI,yCAAW,CAAC,IAAI,CAAC,2CAA2C,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * Account Activity Service for monitoring account transactions and balance changes\n *\n * This service subscribes to account activity and receives all transactions\n * and balance updates for those accounts via the comprehensive AccountActivityMessage format.\n */\n\nimport type {\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { AccountActivityServiceMethodActions } from './AccountActivityService-method-action-types';\nimport type {\n WebSocketConnectionInfo,\n BackendWebSocketServiceConnectionStateChangedEvent,\n ServerNotificationMessage,\n} from './BackendWebSocketService';\nimport { WebSocketState } from './BackendWebSocketService';\nimport type { BackendWebSocketServiceMethodActions } from './BackendWebSocketService-method-action-types';\nimport { projectLogger, createModuleLogger } from './logger';\nimport type {\n Transaction,\n AccountActivityMessage,\n BalanceUpdate,\n} from './types';\n\n// =============================================================================\n// Types and Constants\n// =============================================================================\n\n/**\n * System notification data for chain status updates\n */\nexport type SystemNotificationData = {\n /** Array of chain IDs affected (e.g., ['eip155:137', 'eip155:1']) */\n chainIds: string[];\n /** Status of the chains: 'down' or 'up' */\n status: 'down' | 'up';\n /** Timestamp of the notification */\n timestamp?: number;\n};\n\nconst SERVICE_NAME = 'AccountActivityService';\n\nconst log = createModuleLogger(projectLogger, SERVICE_NAME);\n\nconst MESSENGER_EXPOSED_METHODS = ['subscribe', 'unsubscribe'] as const;\n\nconst SUBSCRIPTION_NAMESPACE = 'account-activity.v1';\n\n/**\n * Account subscription options\n */\nexport type SubscriptionOptions = {\n address: string; // Should be in CAIP-10 format, e.g., \"eip155:0:0x1234...\" or \"solana:0:ABC123...\"\n};\n\n/**\n * Configuration options for the account activity service\n */\nexport type AccountActivityServiceOptions = {\n /** Custom subscription namespace (default: 'account-activity.v1') */\n subscriptionNamespace?: string;\n /** Optional callback to trace performance of account activity operations (default: no-op) */\n traceFn?: TraceCallback;\n};\n\n// =============================================================================\n// Action and Event Types\n// =============================================================================\n\n// Action types for the messaging system - using generated method actions\nexport type AccountActivityServiceActions = AccountActivityServiceMethodActions;\n\n// Allowed actions that AccountActivityService can call on other controllers\nexport const ACCOUNT_ACTIVITY_SERVICE_ALLOWED_ACTIONS = [\n 'AccountsController:getSelectedAccount',\n 'BackendWebSocketService:connect',\n 'BackendWebSocketService:forceReconnection',\n 'BackendWebSocketService:subscribe',\n 'BackendWebSocketService:getConnectionInfo',\n 'BackendWebSocketService:channelHasSubscription',\n 'BackendWebSocketService:getSubscriptionsByChannel',\n 'BackendWebSocketService:findSubscriptionsByChannelPrefix',\n 'BackendWebSocketService:addChannelCallback',\n 'BackendWebSocketService:removeChannelCallback',\n] as const;\n\n// Allowed events that AccountActivityService can listen to\nexport const ACCOUNT_ACTIVITY_SERVICE_ALLOWED_EVENTS = [\n 'AccountsController:selectedAccountChange',\n 'BackendWebSocketService:connectionStateChanged',\n] as const;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | BackendWebSocketServiceMethodActions;\n\n// Event types for the messaging system\n\nexport type AccountActivityServiceTransactionUpdatedEvent = {\n type: `AccountActivityService:transactionUpdated`;\n payload: [Transaction];\n};\n\nexport type AccountActivityServiceBalanceUpdatedEvent = {\n type: `AccountActivityService:balanceUpdated`;\n payload: [{ address: string; chain: string; updates: BalanceUpdate[] }];\n};\n\nexport type AccountActivityServiceSubscriptionErrorEvent = {\n type: `AccountActivityService:subscriptionError`;\n payload: [{ addresses: string[]; error: string; operation: string }];\n};\n\nexport type AccountActivityServiceStatusChangedEvent = {\n type: `AccountActivityService:statusChanged`;\n payload: [\n {\n chainIds: string[];\n status: 'up' | 'down';\n timestamp?: number;\n },\n ];\n};\n\nexport type AccountActivityServiceEvents =\n | AccountActivityServiceTransactionUpdatedEvent\n | AccountActivityServiceBalanceUpdatedEvent\n | AccountActivityServiceSubscriptionErrorEvent\n | AccountActivityServiceStatusChangedEvent;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | BackendWebSocketServiceConnectionStateChangedEvent;\n\nexport type AccountActivityServiceMessenger = Messenger<\n typeof SERVICE_NAME,\n AccountActivityServiceActions | AllowedActions,\n AccountActivityServiceEvents | AllowedEvents\n>;\n\n// =============================================================================\n// Main Service Class\n// =============================================================================\n\n/**\n * High-performance service for real-time account activity monitoring using optimized\n * WebSocket subscriptions with direct callback routing. Automatically subscribes to\n * the currently selected account and switches subscriptions when the selected account changes.\n * Receives transactions and balance updates using the comprehensive AccountActivityMessage format.\n *\n * Performance Features:\n * - Direct callback routing (no EventEmitter overhead)\n * - Minimal subscription tracking (no duplication with BackendWebSocketService)\n * - Optimized cleanup for mobile environments\n * - Single-account subscription (only selected account)\n * - Comprehensive balance updates with transfer tracking\n *\n * Architecture:\n * - Uses messenger pattern to communicate with BackendWebSocketService\n * - AccountActivityService tracks channel-to-subscriptionId mappings via messenger calls\n * - Automatically subscribes to selected account on initialization\n * - Switches subscriptions when selected account changes\n * - No direct dependency on BackendWebSocketService (uses messenger instead)\n *\n * @example\n * ```typescript\n * const service = new AccountActivityService({\n * messenger: activityMessenger,\n * });\n *\n * // Service automatically subscribes to the currently selected account\n * // When user switches accounts, service automatically resubscribes\n *\n * // All transactions and balance updates are received via optimized\n * // WebSocket callbacks and processed with zero-allocation routing\n * // Balance updates include comprehensive transfer details and post-transaction balances\n * ```\n */\nexport class AccountActivityService {\n /**\n * The name of the service.\n */\n readonly name = SERVICE_NAME;\n\n readonly #messenger: AccountActivityServiceMessenger;\n\n readonly #options: Required<Omit<AccountActivityServiceOptions, 'traceFn'>>;\n\n readonly #trace: TraceCallback;\n\n // Track chains that are currently up (based on system notifications)\n readonly #chainsUp: Set<string> = new Set();\n\n // =============================================================================\n // Constructor and Initialization\n // =============================================================================\n\n /**\n * Creates a new Account Activity service instance\n *\n * @param options - Configuration options including messenger\n */\n constructor(\n options: AccountActivityServiceOptions & {\n messenger: AccountActivityServiceMessenger;\n },\n ) {\n this.#messenger = options.messenger;\n\n // Set configuration with defaults\n this.#options = {\n subscriptionNamespace:\n options.subscriptionNamespace ?? SUBSCRIPTION_NAMESPACE,\n };\n\n // Default to no-op trace function to keep core platform-agnostic\n this.#trace =\n options.traceFn ??\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (((_request: any, fn?: any) => fn?.()) as TraceCallback);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n this.#messenger.subscribe(\n 'AccountsController:selectedAccountChange',\n // Promise result intentionally not awaited\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account: InternalAccount) =>\n await this.#handleSelectedAccountChange(account),\n );\n this.#messenger.subscribe(\n 'BackendWebSocketService:connectionStateChanged',\n // Promise result intentionally not awaited\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n (connectionInfo: WebSocketConnectionInfo) =>\n this.#handleWebSocketStateChange(connectionInfo),\n );\n this.#messenger.call('BackendWebSocketService:addChannelCallback', {\n channelName: `system-notifications.v1.${this.#options.subscriptionNamespace}`,\n callback: (notification: ServerNotificationMessage) =>\n this.#handleSystemNotification(notification),\n });\n }\n\n // =============================================================================\n // Account Subscription Methods\n // =============================================================================\n\n /**\n * Subscribe to account activity (transactions and balance updates)\n * Address should be in CAIP-10 format (e.g., \"eip155:0:0x1234...\" or \"solana:0:ABC123...\")\n *\n * @param subscription - Account subscription configuration with address\n */\n async subscribe(subscription: SubscriptionOptions): Promise<void> {\n try {\n await this.#messenger.call('BackendWebSocketService:connect');\n\n // Create channel name from address\n const channel = `${this.#options.subscriptionNamespace}.${subscription.address}`;\n\n // Check if already subscribed\n if (\n this.#messenger.call(\n 'BackendWebSocketService:channelHasSubscription',\n channel,\n )\n ) {\n return;\n }\n\n // Create subscription using the proper subscribe method (this will be stored in WebSocketService's internal tracking)\n await this.#messenger.call('BackendWebSocketService:subscribe', {\n channels: [channel],\n channelType: this.#options.subscriptionNamespace, // e.g., 'account-activity.v1'\n callback: (notification: ServerNotificationMessage) => {\n this.#handleAccountActivityUpdate(\n notification.data as AccountActivityMessage,\n );\n },\n });\n } catch (error) {\n log('Subscription failed, forcing reconnection', { error });\n await this.#forceReconnection();\n }\n }\n\n /**\n * Unsubscribe from account activity for specified address\n * Address should be in CAIP-10 format (e.g., \"eip155:0:0x1234...\" or \"solana:0:ABC123...\")\n *\n * @param subscription - Account subscription configuration with address to unsubscribe\n */\n async unsubscribe(subscription: SubscriptionOptions): Promise<void> {\n const { address } = subscription;\n try {\n // Find channel for the specified address\n const channel = `${this.#options.subscriptionNamespace}.${address}`;\n const subscriptions = this.#messenger.call(\n 'BackendWebSocketService:getSubscriptionsByChannel',\n channel,\n );\n\n if (subscriptions.length === 0) {\n return;\n }\n\n // Fast path: Direct unsubscribe using stored unsubscribe function\n // Unsubscribe from all matching subscriptions\n for (const subscriptionInfo of subscriptions) {\n await subscriptionInfo.unsubscribe();\n }\n } catch (error) {\n log('Unsubscription failed, forcing reconnection', { error });\n await this.#forceReconnection();\n }\n }\n\n // =============================================================================\n // Private Methods - Event Handlers\n // =============================================================================\n\n /**\n * Handle account activity updates (transactions + balance changes)\n * Processes the comprehensive AccountActivityMessage format with detailed balance updates and transfers\n *\n * @param payload - The account activity message containing transaction and balance updates\n * @example AccountActivityMessage format handling:\n * Input: {\n * address: \"0xd14b52362b5b777ffa754c666ddec6722aaeee08\",\n * tx: { id: \"0x1cde...\", chain: \"eip155:8453\", status: \"confirmed\", timestamp: 1760099871, ... },\n * updates: [{\n * asset: { fungible: true, type: \"eip155:8453/erc20:0x833...\", unit: \"USDC\", decimals: 6 },\n * postBalance: { amount: \"0xc350\" },\n * transfers: [{ from: \"0x7b07...\", to: \"0xd14b...\", amount: \"0x2710\" }]\n * }]\n * }\n * Output: Transaction and balance updates published separately\n */\n #handleAccountActivityUpdate(payload: AccountActivityMessage): void {\n const { address, tx, updates } = payload;\n\n // Calculate time elapsed between transaction time and message receipt\n const txTimestampMs = tx.timestamp * 1000; // Convert Unix timestamp (seconds) to milliseconds\n const elapsedMs = Date.now() - txTimestampMs;\n\n log('Handling account activity update', {\n address,\n updateCount: updates.length,\n elapsedMs,\n });\n\n // Trace message receipt with latency from transaction time to now\n // Promise result intentionally not awaited\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#trace(\n {\n name: `${SERVICE_NAME} Transaction Message`,\n data: {\n chain: tx.chain,\n status: tx.status,\n elapsed_ms: elapsedMs,\n },\n tags: {\n service: SERVICE_NAME,\n notification_type: this.#options.subscriptionNamespace,\n },\n },\n () => {\n // Process transaction update\n this.#messenger.publish(\n `AccountActivityService:transactionUpdated`,\n tx,\n );\n\n // Publish comprehensive balance updates with transfer details\n this.#messenger.publish(`AccountActivityService:balanceUpdated`, {\n address,\n chain: tx.chain,\n updates,\n });\n },\n );\n }\n\n /**\n * Handle selected account change event\n *\n * @param newAccount - The newly selected account\n */\n async #handleSelectedAccountChange(\n newAccount: InternalAccount | null,\n ): Promise<void> {\n if (!newAccount?.address) {\n return;\n }\n\n try {\n // Convert new account to CAIP-10 format\n const newAddress = this.#convertToCaip10Address(newAccount);\n\n // First, unsubscribe from all current account activity subscriptions to avoid multiple subscriptions\n await this.#unsubscribeFromAllAccountActivity();\n\n // Then, subscribe to the new selected account\n await this.subscribe({ address: newAddress });\n } catch (error) {\n log('Account change failed', { error });\n }\n }\n\n /**\n * Handle system notification for chain status changes\n * Publishes only the status change (delta) for affected chains\n *\n * @param notification - Server notification message containing chain status updates and timestamp\n */\n #handleSystemNotification(notification: ServerNotificationMessage): void {\n const data = notification.data as SystemNotificationData;\n const { timestamp } = notification;\n\n // Validate required fields\n if (!data.chainIds || !Array.isArray(data.chainIds) || !data.status) {\n throw new Error(\n 'Invalid system notification data: missing chainIds or status',\n );\n }\n\n // Track chain status\n if (data.status === 'up') {\n for (const chainId of data.chainIds) {\n this.#chainsUp.add(chainId);\n }\n } else {\n for (const chainId of data.chainIds) {\n this.#chainsUp.delete(chainId);\n }\n }\n\n // Publish status change directly (delta update)\n this.#messenger.publish(`AccountActivityService:statusChanged`, {\n chainIds: data.chainIds,\n status: data.status,\n timestamp,\n });\n\n log(\n `WebSocket status change - Published tracked chains as ${data.status}`,\n {\n count: data.chainIds.length,\n chains: data.chainIds,\n status: data.status,\n },\n );\n }\n\n /**\n * Handle WebSocket connection state changes for fallback polling and resubscription\n *\n * @param connectionInfo - WebSocket connection state information\n */\n async #handleWebSocketStateChange(\n connectionInfo: WebSocketConnectionInfo,\n ): Promise<void> {\n const { state } = connectionInfo;\n\n if (state === WebSocketState.CONNECTED) {\n // WebSocket connected - resubscribe to selected account\n // The system notification will automatically provide the list of chains that are up\n await this.#subscribeToSelectedAccount();\n } else if (state === WebSocketState.DISCONNECTED) {\n // On disconnect, flush all tracked chains as down\n const chainsToMarkDown = Array.from(this.#chainsUp);\n\n if (chainsToMarkDown.length > 0) {\n this.#messenger.publish(`AccountActivityService:statusChanged`, {\n chainIds: chainsToMarkDown,\n status: 'down',\n timestamp: Date.now(),\n });\n\n log('WebSocket disconnection - Published tracked chains as down', {\n count: chainsToMarkDown.length,\n chains: chainsToMarkDown,\n });\n\n // Clear the tracking set since all chains are now down\n this.#chainsUp.clear();\n }\n }\n }\n\n // =============================================================================\n // Private Methods - Subscription Management\n // =============================================================================\n\n /**\n * Subscribe to the currently selected account only\n */\n async #subscribeToSelectedAccount(): Promise<void> {\n const selectedAccount = this.#messenger.call(\n 'AccountsController:getSelectedAccount',\n );\n\n if (!selectedAccount?.address) {\n return;\n }\n\n // Convert to CAIP-10 format and subscribe\n const address = this.#convertToCaip10Address(selectedAccount);\n await this.subscribe({ address });\n }\n\n /**\n * Unsubscribe from all account activity subscriptions for this service\n * Finds all channels matching the service's namespace and unsubscribes from them\n */\n async #unsubscribeFromAllAccountActivity(): Promise<void> {\n const accountActivitySubscriptions = this.#messenger.call(\n 'BackendWebSocketService:findSubscriptionsByChannelPrefix',\n this.#options.subscriptionNamespace,\n );\n\n // Unsubscribe from all matching subscriptions\n for (const subscription of accountActivitySubscriptions) {\n await subscription.unsubscribe();\n }\n }\n\n // =============================================================================\n // Private Methods - Utility Functions\n // =============================================================================\n\n /**\n * Convert an InternalAccount address to CAIP-10 format or raw address\n *\n * @param account - The internal account to convert\n * @returns The CAIP-10 formatted address or raw address\n */\n #convertToCaip10Address(account: InternalAccount): string {\n // Check if account has EVM scopes\n if (account.scopes.some((scope) => scope.startsWith('eip155:'))) {\n // CAIP-10 format: eip155:0:address (subscribe to all EVM chains)\n return `eip155:0:${account.address}`;\n }\n\n // Check if account has Solana scopes\n if (account.scopes.some((scope) => scope.startsWith('solana:'))) {\n // CAIP-10 format: solana:0:address (subscribe to all Solana chains)\n return `solana:0:${account.address}`;\n }\n\n // For other chains or unknown scopes, return raw address\n return account.address;\n }\n\n /**\n * Force WebSocket reconnection to clean up subscription state\n */\n async #forceReconnection(): Promise<void> {\n log('Forcing WebSocket reconnection to clean up subscription state');\n\n // Use the dedicated forceReconnection method which performs a controlled\n // disconnect-then-connect sequence to clean up subscription state\n await this.#messenger.call('BackendWebSocketService:forceReconnection');\n }\n\n // =============================================================================\n // Public Methods - Cleanup\n // =============================================================================\n\n /**\n * Destroy the service and clean up all resources\n * Optimized for fast cleanup during service destruction or mobile app termination\n */\n destroy(): void {\n // Clean up system notification callback\n this.#messenger.call(\n 'BackendWebSocketService:removeChannelCallback',\n `system-notifications.v1.${this.#options.subscriptionNamespace}`,\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"BackendWebSocketService-method-action-types.cjs","sourceRoot":"","sources":["../src/BackendWebSocketService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { BackendWebSocketService } from './BackendWebSocketService';\n\n/**\n * Establishes WebSocket connection\n *\n * @returns Promise that resolves when connection is established\n */\nexport type BackendWebSocketServiceConnectAction = {\n type: `BackendWebSocketService:connect`;\n handler: BackendWebSocketService['connect'];\n};\n\n/**\n * Closes WebSocket connection\n *\n * @returns Promise that resolves when disconnection is complete\n */\nexport type BackendWebSocketServiceDisconnectAction = {\n type: `BackendWebSocketService:disconnect`;\n handler: BackendWebSocketService['disconnect'];\n};\n\n/**\n * Forces a WebSocket reconnection to clean up subscription state\n *\n * This method is useful when subscription state may be out of sync and needs to be reset.\n * It performs a controlled disconnect-then-reconnect sequence:\n * - Disconnects cleanly to trigger subscription cleanup\n * - Schedules reconnection with exponential backoff to prevent rapid loops\n * - All subscriptions will be cleaned up automatically on disconnect\n *\n * Use cases:\n * - Recovering from subscription/unsubscription issues\n * - Cleaning up orphaned subscriptions\n * - Forcing a fresh subscription state\n *\n * @returns Promise that resolves when disconnection is complete (reconnection is scheduled)\n */\nexport type BackendWebSocketServiceForceReconnectionAction = {\n type: `BackendWebSocketService:forceReconnection`;\n handler: BackendWebSocketService['forceReconnection'];\n};\n\n/**\n * Sends a message through the WebSocket\n *\n * @param message - The message to send\n * @returns Promise that resolves when message is sent\n */\nexport type BackendWebSocketServiceSendMessageAction = {\n type: `BackendWebSocketService:sendMessage`;\n handler: BackendWebSocketService['sendMessage'];\n};\n\n/**\n * Sends a request and waits for a correlated response\n *\n * @param message - The request message\n * @returns Promise that resolves with the response data\n */\nexport type BackendWebSocketServiceSendRequestAction = {\n type: `BackendWebSocketService:sendRequest`;\n handler: BackendWebSocketService['sendRequest'];\n};\n\n/**\n * Gets current connection information\n *\n * @returns Current connection status and details\n */\nexport type BackendWebSocketServiceGetConnectionInfoAction = {\n type: `BackendWebSocketService:getConnectionInfo`;\n handler: BackendWebSocketService['getConnectionInfo'];\n};\n\n/**\n * Gets all subscription information for a specific channel\n *\n * @param channel - The channel name to look up\n * @returns Array of subscription details for all subscriptions containing the channel\n */\nexport type BackendWebSocketServiceGetSubscriptionsByChannelAction = {\n type: `BackendWebSocketService:getSubscriptionsByChannel`;\n handler: BackendWebSocketService['getSubscriptionsByChannel'];\n};\n\n/**\n * Checks if a channel has a subscription\n *\n * @param channel - The channel name to check\n * @returns True if the channel has a subscription, false otherwise\n */\nexport type BackendWebSocketServiceChannelHasSubscriptionAction = {\n type: `BackendWebSocketService:channelHasSubscription`;\n handler: BackendWebSocketService['channelHasSubscription'];\n};\n\n/**\n * Finds all subscriptions that have channels starting with the specified prefix\n *\n * @param channelPrefix - The channel prefix to search for (e.g., \"account-activity.v1\")\n * @returns Array of subscription info for matching subscriptions\n */\nexport type BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction = {\n type: `BackendWebSocketService:findSubscriptionsByChannelPrefix`;\n handler: BackendWebSocketService['findSubscriptionsByChannelPrefix'];\n};\n\n/**\n * Register a callback for specific channels\n *\n * @param options - Channel callback configuration\n * @param options.channelName - Channel name to match exactly\n * @param options.callback - Function to call when channel matches\n *\n * @example\n * ```typescript\n * // Listen to specific account activity channel\n * webSocketService.addChannelCallback({\n * channelName: 'account-activity.v1.eip155:0:0x1234...',\n * callback: (notification) => {\n * console.log('Account activity:', notification.data);\n * }\n * });\n *\n * // Listen to system notifications channel\n * webSocketService.addChannelCallback({\n * channelName: 'system-notifications.v1',\n * callback: (notification) => {\n * console.log('System notification:', notification.data);\n * }\n * });\n * ```\n */\nexport type BackendWebSocketServiceAddChannelCallbackAction = {\n type: `BackendWebSocketService:addChannelCallback`;\n handler: BackendWebSocketService['addChannelCallback'];\n};\n\n/**\n * Remove a channel callback\n *\n * @param channelName - The channel name to remove callback for\n * @returns True if callback was found and removed, false otherwise\n */\nexport type BackendWebSocketServiceRemoveChannelCallbackAction = {\n type: `BackendWebSocketService:removeChannelCallback`;\n handler: BackendWebSocketService['removeChannelCallback'];\n};\n\n/**\n * Get all registered channel callbacks (for debugging)\n */\nexport type BackendWebSocketServiceGetChannelCallbacksAction = {\n type: `BackendWebSocketService:getChannelCallbacks`;\n handler: BackendWebSocketService['getChannelCallbacks'];\n};\n\n/**\n * Create and manage a subscription with direct callback routing\n *\n * @param options - Subscription configuration\n * @param options.channels - Array of channel names to subscribe to\n * @param options.callback - Callback function for handling notifications\n * @returns Promise that resolves with subscription object containing unsubscribe method\n */\nexport type BackendWebSocketServiceSubscribeAction = {\n type: `BackendWebSocketService:subscribe`;\n handler: BackendWebSocketService['subscribe'];\n};\n\n/**\n * Union of all BackendWebSocketService action types.\n */\nexport type BackendWebSocketServiceMethodActions =\n | BackendWebSocketServiceConnectAction\n | BackendWebSocketServiceDisconnectAction\n | BackendWebSocketServiceForceReconnectionAction\n | BackendWebSocketServiceSendMessageAction\n | BackendWebSocketServiceSendRequestAction\n | BackendWebSocketServiceGetConnectionInfoAction\n | BackendWebSocketServiceGetSubscriptionsByChannelAction\n | BackendWebSocketServiceChannelHasSubscriptionAction\n | BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction\n | BackendWebSocketServiceAddChannelCallbackAction\n | BackendWebSocketServiceRemoveChannelCallbackAction\n | BackendWebSocketServiceGetChannelCallbacksAction\n | BackendWebSocketServiceSubscribeAction;\n"]}
1
+ {"version":3,"file":"BackendWebSocketService-method-action-types.cjs","sourceRoot":"","sources":["../src/BackendWebSocketService-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { BackendWebSocketService } from './BackendWebSocketService';\n\n/**\n * Establishes WebSocket connection with smart reconnection behavior\n *\n * Connection Requirements (all must be true):\n * 1. Feature enabled (isEnabled() = true)\n * 2. Wallet unlocked (checked by getBearerToken)\n * 3. User signed in (checked by getBearerToken)\n *\n * Platform code should call this when app opens/foregrounds.\n * Automatically called on KeyringController:unlock event.\n *\n * @returns Promise that resolves when connection is established\n */\nexport type BackendWebSocketServiceConnectAction = {\n type: `BackendWebSocketService:connect`;\n handler: BackendWebSocketService['connect'];\n};\n\n/**\n * Closes WebSocket connection\n */\nexport type BackendWebSocketServiceDisconnectAction = {\n type: `BackendWebSocketService:disconnect`;\n handler: BackendWebSocketService['disconnect'];\n};\n\n/**\n * Forces a WebSocket reconnection to clean up subscription state\n *\n * This method is useful when subscription state may be out of sync and needs to be reset.\n * It performs a controlled disconnect-then-reconnect sequence:\n * - Disconnects cleanly to trigger subscription cleanup\n * - Schedules reconnection with exponential backoff to prevent rapid loops\n * - All subscriptions will be cleaned up automatically on disconnect\n *\n * Use cases:\n * - Recovering from subscription/unsubscription issues\n * - Cleaning up orphaned subscriptions\n * - Forcing a fresh subscription state\n *\n * @returns Promise that resolves when disconnection is complete (reconnection is scheduled)\n */\nexport type BackendWebSocketServiceForceReconnectionAction = {\n type: `BackendWebSocketService:forceReconnection`;\n handler: BackendWebSocketService['forceReconnection'];\n};\n\n/**\n * Sends a message through the WebSocket (fire-and-forget, no response expected)\n *\n * This is a low-level method for sending messages without waiting for a response.\n * Most consumers should use `sendRequest()` instead, which handles request-response\n * correlation and provides proper error handling with timeouts.\n *\n * Use this method only when:\n * - You don't need a response from the server\n * - You're implementing custom message protocols\n * - You need fine-grained control over message timing\n *\n * @param message - The message to send\n * @throws Error if WebSocket is not connected or send fails\n *\n * @see sendRequest for request-response pattern with automatic correlation\n */\nexport type BackendWebSocketServiceSendMessageAction = {\n type: `BackendWebSocketService:sendMessage`;\n handler: BackendWebSocketService['sendMessage'];\n};\n\n/**\n * Sends a request and waits for a correlated response (recommended for most use cases)\n *\n * This is the recommended high-level method for request-response communication.\n * It automatically handles:\n * - Request ID generation and correlation\n * - Response matching with timeout protection\n * - Automatic reconnection on timeout\n * - Proper cleanup of pending requests\n *\n * @param message - The request message (can include optional requestId for testing)\n * @returns Promise that resolves with the response data\n * @throws Error if WebSocket is not connected, request times out, or response indicates failure\n *\n * @see sendMessage for fire-and-forget messaging without response handling\n */\nexport type BackendWebSocketServiceSendRequestAction = {\n type: `BackendWebSocketService:sendRequest`;\n handler: BackendWebSocketService['sendRequest'];\n};\n\n/**\n * Gets current connection information\n *\n * @returns Current connection status and details\n */\nexport type BackendWebSocketServiceGetConnectionInfoAction = {\n type: `BackendWebSocketService:getConnectionInfo`;\n handler: BackendWebSocketService['getConnectionInfo'];\n};\n\n/**\n * Gets all subscription information for a specific channel\n *\n * @param channel - The channel name to look up\n * @returns Array of subscription details for all subscriptions containing the channel\n */\nexport type BackendWebSocketServiceGetSubscriptionsByChannelAction = {\n type: `BackendWebSocketService:getSubscriptionsByChannel`;\n handler: BackendWebSocketService['getSubscriptionsByChannel'];\n};\n\n/**\n * Checks if a channel has a subscription\n *\n * @param channel - The channel name to check\n * @returns True if the channel has a subscription, false otherwise\n */\nexport type BackendWebSocketServiceChannelHasSubscriptionAction = {\n type: `BackendWebSocketService:channelHasSubscription`;\n handler: BackendWebSocketService['channelHasSubscription'];\n};\n\n/**\n * Finds all subscriptions that have channels starting with the specified prefix\n *\n * @param channelPrefix - The channel prefix to search for (e.g., \"account-activity.v1\")\n * @returns Array of subscription info for matching subscriptions\n */\nexport type BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction = {\n type: `BackendWebSocketService:findSubscriptionsByChannelPrefix`;\n handler: BackendWebSocketService['findSubscriptionsByChannelPrefix'];\n};\n\n/**\n * Register a callback for specific channels (local callback only, no server subscription)\n *\n * **Key Difference from `subscribe()`:**\n * - `addChannelCallback()`: Registers a local callback without creating a server-side subscription.\n * The callback triggers on ANY message matching the channel name, regardless of subscriptionId.\n * Useful for system-wide notifications or when you don't control the subscription lifecycle.\n *\n * - `subscribe()`: Creates a proper server-side subscription with a subscriptionId.\n * The callback only triggers for messages with the matching subscriptionId.\n * Includes proper lifecycle management (unsubscribe, automatic cleanup on disconnect).\n *\n * **When to use `addChannelCallback()`:**\n * - Listening to system-wide notifications (e.g., 'system-notifications.v1')\n * - Monitoring channels where subscriptions are managed elsewhere\n * - Debug/logging scenarios where you want to observe all channel messages\n *\n * **When to use `subscribe()` instead:**\n * - Creating new subscriptions that need server-side registration\n * - When you need proper cleanup via unsubscribe\n * - Most application use cases (recommended approach)\n *\n * @param options - Channel callback configuration\n * @param options.channelName - Channel name to match exactly\n * @param options.callback - Function to call when channel matches\n *\n * @example\n * ```typescript\n * // Listen to system notifications (no server subscription needed)\n * webSocketService.addChannelCallback({\n * channelName: 'system-notifications.v1',\n * callback: (notification) => {\n * console.log('System notification:', notification.data);\n * }\n * });\n *\n * // For account-specific subscriptions, use subscribe() instead:\n * // const sub = await webSocketService.subscribe({\n * // channels: ['account-activity.v1.eip155:0:0x1234...'],\n * // callback: (notification) => { ... }\n * // });\n * ```\n *\n * @see subscribe for creating proper server-side subscriptions with lifecycle management\n */\nexport type BackendWebSocketServiceAddChannelCallbackAction = {\n type: `BackendWebSocketService:addChannelCallback`;\n handler: BackendWebSocketService['addChannelCallback'];\n};\n\n/**\n * Remove a channel callback\n *\n * @param channelName - The channel name returned from addChannelCallback\n * @returns True if callback was found and removed, false otherwise\n */\nexport type BackendWebSocketServiceRemoveChannelCallbackAction = {\n type: `BackendWebSocketService:removeChannelCallback`;\n handler: BackendWebSocketService['removeChannelCallback'];\n};\n\n/**\n * Get all registered channel callbacks (for debugging)\n *\n * @returns Array of all registered channel callbacks\n */\nexport type BackendWebSocketServiceGetChannelCallbacksAction = {\n type: `BackendWebSocketService:getChannelCallbacks`;\n handler: BackendWebSocketService['getChannelCallbacks'];\n};\n\n/**\n * Create and manage a subscription with server-side registration (recommended for most use cases)\n *\n * This is the recommended subscription API for high-level services. It creates a proper\n * server-side subscription and routes notifications based on subscriptionId.\n *\n * **Key Features:**\n * - Creates server-side subscription with unique subscriptionId\n * - Callback triggered only for messages with matching subscriptionId\n * - Automatic lifecycle management (cleanup on disconnect)\n * - Includes unsubscribe method for proper cleanup\n * - Request-response pattern with error handling\n *\n * **When to use `subscribe()`:**\n * - Creating new subscriptions (account activity, price updates, etc.)\n * - When you need proper cleanup/unsubscribe functionality\n * - Most application use cases\n *\n * **When to use `addChannelCallback()` instead:**\n * - System-wide notifications without server-side subscription\n * - Observing channels managed elsewhere\n * - Debug/logging scenarios\n *\n * @param options - Subscription configuration\n * @param options.channels - Array of channel names to subscribe to\n * @param options.callback - Callback function for handling notifications\n * @param options.requestId - Optional request ID for testing (will generate UUID if not provided)\n * @param options.channelType - Channel type identifier\n * @returns Subscription object with unsubscribe method\n *\n * @example\n * ```typescript\n * // AccountActivityService usage\n * const subscription = await webSocketService.subscribe({\n * channels: ['account-activity.v1.eip155:0:0x1234...'],\n * callback: (notification) => {\n * this.handleAccountActivity(notification.data);\n * }\n * });\n *\n * // Later, clean up\n * await subscription.unsubscribe();\n * ```\n *\n * @see addChannelCallback for local callbacks without server-side subscription\n */\nexport type BackendWebSocketServiceSubscribeAction = {\n type: `BackendWebSocketService:subscribe`;\n handler: BackendWebSocketService['subscribe'];\n};\n\n/**\n * Union of all BackendWebSocketService action types.\n */\nexport type BackendWebSocketServiceMethodActions =\n | BackendWebSocketServiceConnectAction\n | BackendWebSocketServiceDisconnectAction\n | BackendWebSocketServiceForceReconnectionAction\n | BackendWebSocketServiceSendMessageAction\n | BackendWebSocketServiceSendRequestAction\n | BackendWebSocketServiceGetConnectionInfoAction\n | BackendWebSocketServiceGetSubscriptionsByChannelAction\n | BackendWebSocketServiceChannelHasSubscriptionAction\n | BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction\n | BackendWebSocketServiceAddChannelCallbackAction\n | BackendWebSocketServiceRemoveChannelCallbackAction\n | BackendWebSocketServiceGetChannelCallbacksAction\n | BackendWebSocketServiceSubscribeAction;\n"]}
@@ -4,7 +4,15 @@
4
4
  */
5
5
  import type { BackendWebSocketService } from "./BackendWebSocketService.cjs";
6
6
  /**
7
- * Establishes WebSocket connection
7
+ * Establishes WebSocket connection with smart reconnection behavior
8
+ *
9
+ * Connection Requirements (all must be true):
10
+ * 1. Feature enabled (isEnabled() = true)
11
+ * 2. Wallet unlocked (checked by getBearerToken)
12
+ * 3. User signed in (checked by getBearerToken)
13
+ *
14
+ * Platform code should call this when app opens/foregrounds.
15
+ * Automatically called on KeyringController:unlock event.
8
16
  *
9
17
  * @returns Promise that resolves when connection is established
10
18
  */
@@ -14,8 +22,6 @@ export type BackendWebSocketServiceConnectAction = {
14
22
  };
15
23
  /**
16
24
  * Closes WebSocket connection
17
- *
18
- * @returns Promise that resolves when disconnection is complete
19
25
  */
20
26
  export type BackendWebSocketServiceDisconnectAction = {
21
27
  type: `BackendWebSocketService:disconnect`;
@@ -42,20 +48,41 @@ export type BackendWebSocketServiceForceReconnectionAction = {
42
48
  handler: BackendWebSocketService['forceReconnection'];
43
49
  };
44
50
  /**
45
- * Sends a message through the WebSocket
51
+ * Sends a message through the WebSocket (fire-and-forget, no response expected)
52
+ *
53
+ * This is a low-level method for sending messages without waiting for a response.
54
+ * Most consumers should use `sendRequest()` instead, which handles request-response
55
+ * correlation and provides proper error handling with timeouts.
56
+ *
57
+ * Use this method only when:
58
+ * - You don't need a response from the server
59
+ * - You're implementing custom message protocols
60
+ * - You need fine-grained control over message timing
46
61
  *
47
62
  * @param message - The message to send
48
- * @returns Promise that resolves when message is sent
63
+ * @throws Error if WebSocket is not connected or send fails
64
+ *
65
+ * @see sendRequest for request-response pattern with automatic correlation
49
66
  */
50
67
  export type BackendWebSocketServiceSendMessageAction = {
51
68
  type: `BackendWebSocketService:sendMessage`;
52
69
  handler: BackendWebSocketService['sendMessage'];
53
70
  };
54
71
  /**
55
- * Sends a request and waits for a correlated response
72
+ * Sends a request and waits for a correlated response (recommended for most use cases)
73
+ *
74
+ * This is the recommended high-level method for request-response communication.
75
+ * It automatically handles:
76
+ * - Request ID generation and correlation
77
+ * - Response matching with timeout protection
78
+ * - Automatic reconnection on timeout
79
+ * - Proper cleanup of pending requests
56
80
  *
57
- * @param message - The request message
81
+ * @param message - The request message (can include optional requestId for testing)
58
82
  * @returns Promise that resolves with the response data
83
+ * @throws Error if WebSocket is not connected, request times out, or response indicates failure
84
+ *
85
+ * @see sendMessage for fire-and-forget messaging without response handling
59
86
  */
60
87
  export type BackendWebSocketServiceSendRequestAction = {
61
88
  type: `BackendWebSocketService:sendRequest`;
@@ -101,7 +128,26 @@ export type BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction = {
101
128
  handler: BackendWebSocketService['findSubscriptionsByChannelPrefix'];
102
129
  };
103
130
  /**
104
- * Register a callback for specific channels
131
+ * Register a callback for specific channels (local callback only, no server subscription)
132
+ *
133
+ * **Key Difference from `subscribe()`:**
134
+ * - `addChannelCallback()`: Registers a local callback without creating a server-side subscription.
135
+ * The callback triggers on ANY message matching the channel name, regardless of subscriptionId.
136
+ * Useful for system-wide notifications or when you don't control the subscription lifecycle.
137
+ *
138
+ * - `subscribe()`: Creates a proper server-side subscription with a subscriptionId.
139
+ * The callback only triggers for messages with the matching subscriptionId.
140
+ * Includes proper lifecycle management (unsubscribe, automatic cleanup on disconnect).
141
+ *
142
+ * **When to use `addChannelCallback()`:**
143
+ * - Listening to system-wide notifications (e.g., 'system-notifications.v1')
144
+ * - Monitoring channels where subscriptions are managed elsewhere
145
+ * - Debug/logging scenarios where you want to observe all channel messages
146
+ *
147
+ * **When to use `subscribe()` instead:**
148
+ * - Creating new subscriptions that need server-side registration
149
+ * - When you need proper cleanup via unsubscribe
150
+ * - Most application use cases (recommended approach)
105
151
  *
106
152
  * @param options - Channel callback configuration
107
153
  * @param options.channelName - Channel name to match exactly
@@ -109,22 +155,22 @@ export type BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction = {
109
155
  *
110
156
  * @example
111
157
  * ```typescript
112
- * // Listen to specific account activity channel
113
- * webSocketService.addChannelCallback({
114
- * channelName: 'account-activity.v1.eip155:0:0x1234...',
115
- * callback: (notification) => {
116
- * console.log('Account activity:', notification.data);
117
- * }
118
- * });
119
- *
120
- * // Listen to system notifications channel
158
+ * // Listen to system notifications (no server subscription needed)
121
159
  * webSocketService.addChannelCallback({
122
160
  * channelName: 'system-notifications.v1',
123
161
  * callback: (notification) => {
124
162
  * console.log('System notification:', notification.data);
125
163
  * }
126
164
  * });
165
+ *
166
+ * // For account-specific subscriptions, use subscribe() instead:
167
+ * // const sub = await webSocketService.subscribe({
168
+ * // channels: ['account-activity.v1.eip155:0:0x1234...'],
169
+ * // callback: (notification) => { ... }
170
+ * // });
127
171
  * ```
172
+ *
173
+ * @see subscribe for creating proper server-side subscriptions with lifecycle management
128
174
  */
129
175
  export type BackendWebSocketServiceAddChannelCallbackAction = {
130
176
  type: `BackendWebSocketService:addChannelCallback`;
@@ -133,7 +179,7 @@ export type BackendWebSocketServiceAddChannelCallbackAction = {
133
179
  /**
134
180
  * Remove a channel callback
135
181
  *
136
- * @param channelName - The channel name to remove callback for
182
+ * @param channelName - The channel name returned from addChannelCallback
137
183
  * @returns True if callback was found and removed, false otherwise
138
184
  */
139
185
  export type BackendWebSocketServiceRemoveChannelCallbackAction = {
@@ -142,18 +188,58 @@ export type BackendWebSocketServiceRemoveChannelCallbackAction = {
142
188
  };
143
189
  /**
144
190
  * Get all registered channel callbacks (for debugging)
191
+ *
192
+ * @returns Array of all registered channel callbacks
145
193
  */
146
194
  export type BackendWebSocketServiceGetChannelCallbacksAction = {
147
195
  type: `BackendWebSocketService:getChannelCallbacks`;
148
196
  handler: BackendWebSocketService['getChannelCallbacks'];
149
197
  };
150
198
  /**
151
- * Create and manage a subscription with direct callback routing
199
+ * Create and manage a subscription with server-side registration (recommended for most use cases)
200
+ *
201
+ * This is the recommended subscription API for high-level services. It creates a proper
202
+ * server-side subscription and routes notifications based on subscriptionId.
203
+ *
204
+ * **Key Features:**
205
+ * - Creates server-side subscription with unique subscriptionId
206
+ * - Callback triggered only for messages with matching subscriptionId
207
+ * - Automatic lifecycle management (cleanup on disconnect)
208
+ * - Includes unsubscribe method for proper cleanup
209
+ * - Request-response pattern with error handling
210
+ *
211
+ * **When to use `subscribe()`:**
212
+ * - Creating new subscriptions (account activity, price updates, etc.)
213
+ * - When you need proper cleanup/unsubscribe functionality
214
+ * - Most application use cases
215
+ *
216
+ * **When to use `addChannelCallback()` instead:**
217
+ * - System-wide notifications without server-side subscription
218
+ * - Observing channels managed elsewhere
219
+ * - Debug/logging scenarios
152
220
  *
153
221
  * @param options - Subscription configuration
154
222
  * @param options.channels - Array of channel names to subscribe to
155
223
  * @param options.callback - Callback function for handling notifications
156
- * @returns Promise that resolves with subscription object containing unsubscribe method
224
+ * @param options.requestId - Optional request ID for testing (will generate UUID if not provided)
225
+ * @param options.channelType - Channel type identifier
226
+ * @returns Subscription object with unsubscribe method
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * // AccountActivityService usage
231
+ * const subscription = await webSocketService.subscribe({
232
+ * channels: ['account-activity.v1.eip155:0:0x1234...'],
233
+ * callback: (notification) => {
234
+ * this.handleAccountActivity(notification.data);
235
+ * }
236
+ * });
237
+ *
238
+ * // Later, clean up
239
+ * await subscription.unsubscribe();
240
+ * ```
241
+ *
242
+ * @see addChannelCallback for local callbacks without server-side subscription
157
243
  */
158
244
  export type BackendWebSocketServiceSubscribeAction = {
159
245
  type: `BackendWebSocketService:subscribe`;
@@ -1 +1 @@
1
- {"version":3,"file":"BackendWebSocketService-method-action-types.d.cts","sourceRoot":"","sources":["../src/BackendWebSocketService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAkC;AAEzE;;;;GAIG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,i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AAC,CAAC;CACtE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,MAAM,+CAA+C,GAAG;IAC5D,IAAI,EAAE,4CAA4C,CAAC;IACnD,OAAO,EAAE,uBAAuB,CAAC,oBAAoB,CAAC,CAAC;CACxD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;IACtD,OAAO,EAAE,uBAAuB,CAAC,uBAAuB,CAAC,CAAC;CAC3D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gDAAgD,GAAG;IAC7D,IAAI,EAAE,6CAA6C,CAAC;IACpD,OAAO,EAAE,uBAAuB,CAAC,qBAAqB,CAAC,CAAC;CACzD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,uBAAuB,CAAC,WAAW,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,oCAAoC,GAC5C,oCAAoC,GACpC,uCAAuC,GACvC,8CAA8C,GAC9C,wCAAwC,GACxC,wCAAwC,GACxC,8CAA8C,GAC9C,sDAAsD,GACtD,mDAAmD,GACnD,6DAA6D,GAC7D,+CAA+C,GAC/C,kDAAkD,GAClD,gDAAgD,GAChD,sCAAsC,CAAC"}
1
+ {"version":3,"file":"BackendWebSocketService-method-action-types.d.cts","sourceRoot":"","sources":["../src/BackendWebSocketService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAkC;AAEzE;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,iCAAiC,CAAC;IACxC,OAAO,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uCAAuC,GAAG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M,MAAM,+CAA+C,GAAG;IAC5D,IAAI,EAAE,4CAA4C,CAAC;IACnD,OAAO,EAAE,uBAAuB,CAAC,oBAAoB,CAAC,CAAC;CACxD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,kDAAkD,GAAG;IAC/D,IAAI,EAAE,+CAA+C,CAAC;IACtD,OAAO,EAAE,uBAAuB,CAAC,uBAAuB,CAAC,CAAC;CAC3D,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,gDAAgD,GAAG;IAC7D,IAAI,EAAE,6CAA6C,CAAC;IACpD,OAAO,EAAE,uBAAuB,CAAC,qBAAqB,CAAC,CAAC;CACzD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,uBAAuB,CAAC,WAAW,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,oCAAoC,GAC5C,oCAAoC,GACpC,uCAAuC,GACvC,8CAA8C,GAC9C,wCAAwC,GACxC,wCAAwC,GACxC,8CAA8C,GAC9C,sDAAsD,GACtD,mDAAmD,GACnD,6DAA6D,GAC7D,+CAA+C,GAC/C,kDAAkD,GAClD,gDAAgD,GAChD,sCAAsC,CAAC"}
@@ -4,7 +4,15 @@
4
4
  */
5
5
  import type { BackendWebSocketService } from "./BackendWebSocketService.mjs";
6
6
  /**
7
- * Establishes WebSocket connection
7
+ * Establishes WebSocket connection with smart reconnection behavior
8
+ *
9
+ * Connection Requirements (all must be true):
10
+ * 1. Feature enabled (isEnabled() = true)
11
+ * 2. Wallet unlocked (checked by getBearerToken)
12
+ * 3. User signed in (checked by getBearerToken)
13
+ *
14
+ * Platform code should call this when app opens/foregrounds.
15
+ * Automatically called on KeyringController:unlock event.
8
16
  *
9
17
  * @returns Promise that resolves when connection is established
10
18
  */
@@ -14,8 +22,6 @@ export type BackendWebSocketServiceConnectAction = {
14
22
  };
15
23
  /**
16
24
  * Closes WebSocket connection
17
- *
18
- * @returns Promise that resolves when disconnection is complete
19
25
  */
20
26
  export type BackendWebSocketServiceDisconnectAction = {
21
27
  type: `BackendWebSocketService:disconnect`;
@@ -42,20 +48,41 @@ export type BackendWebSocketServiceForceReconnectionAction = {
42
48
  handler: BackendWebSocketService['forceReconnection'];
43
49
  };
44
50
  /**
45
- * Sends a message through the WebSocket
51
+ * Sends a message through the WebSocket (fire-and-forget, no response expected)
52
+ *
53
+ * This is a low-level method for sending messages without waiting for a response.
54
+ * Most consumers should use `sendRequest()` instead, which handles request-response
55
+ * correlation and provides proper error handling with timeouts.
56
+ *
57
+ * Use this method only when:
58
+ * - You don't need a response from the server
59
+ * - You're implementing custom message protocols
60
+ * - You need fine-grained control over message timing
46
61
  *
47
62
  * @param message - The message to send
48
- * @returns Promise that resolves when message is sent
63
+ * @throws Error if WebSocket is not connected or send fails
64
+ *
65
+ * @see sendRequest for request-response pattern with automatic correlation
49
66
  */
50
67
  export type BackendWebSocketServiceSendMessageAction = {
51
68
  type: `BackendWebSocketService:sendMessage`;
52
69
  handler: BackendWebSocketService['sendMessage'];
53
70
  };
54
71
  /**
55
- * Sends a request and waits for a correlated response
72
+ * Sends a request and waits for a correlated response (recommended for most use cases)
73
+ *
74
+ * This is the recommended high-level method for request-response communication.
75
+ * It automatically handles:
76
+ * - Request ID generation and correlation
77
+ * - Response matching with timeout protection
78
+ * - Automatic reconnection on timeout
79
+ * - Proper cleanup of pending requests
56
80
  *
57
- * @param message - The request message
81
+ * @param message - The request message (can include optional requestId for testing)
58
82
  * @returns Promise that resolves with the response data
83
+ * @throws Error if WebSocket is not connected, request times out, or response indicates failure
84
+ *
85
+ * @see sendMessage for fire-and-forget messaging without response handling
59
86
  */
60
87
  export type BackendWebSocketServiceSendRequestAction = {
61
88
  type: `BackendWebSocketService:sendRequest`;
@@ -101,7 +128,26 @@ export type BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction = {
101
128
  handler: BackendWebSocketService['findSubscriptionsByChannelPrefix'];
102
129
  };
103
130
  /**
104
- * Register a callback for specific channels
131
+ * Register a callback for specific channels (local callback only, no server subscription)
132
+ *
133
+ * **Key Difference from `subscribe()`:**
134
+ * - `addChannelCallback()`: Registers a local callback without creating a server-side subscription.
135
+ * The callback triggers on ANY message matching the channel name, regardless of subscriptionId.
136
+ * Useful for system-wide notifications or when you don't control the subscription lifecycle.
137
+ *
138
+ * - `subscribe()`: Creates a proper server-side subscription with a subscriptionId.
139
+ * The callback only triggers for messages with the matching subscriptionId.
140
+ * Includes proper lifecycle management (unsubscribe, automatic cleanup on disconnect).
141
+ *
142
+ * **When to use `addChannelCallback()`:**
143
+ * - Listening to system-wide notifications (e.g., 'system-notifications.v1')
144
+ * - Monitoring channels where subscriptions are managed elsewhere
145
+ * - Debug/logging scenarios where you want to observe all channel messages
146
+ *
147
+ * **When to use `subscribe()` instead:**
148
+ * - Creating new subscriptions that need server-side registration
149
+ * - When you need proper cleanup via unsubscribe
150
+ * - Most application use cases (recommended approach)
105
151
  *
106
152
  * @param options - Channel callback configuration
107
153
  * @param options.channelName - Channel name to match exactly
@@ -109,22 +155,22 @@ export type BackendWebSocketServiceFindSubscriptionsByChannelPrefixAction = {
109
155
  *
110
156
  * @example
111
157
  * ```typescript
112
- * // Listen to specific account activity channel
113
- * webSocketService.addChannelCallback({
114
- * channelName: 'account-activity.v1.eip155:0:0x1234...',
115
- * callback: (notification) => {
116
- * console.log('Account activity:', notification.data);
117
- * }
118
- * });
119
- *
120
- * // Listen to system notifications channel
158
+ * // Listen to system notifications (no server subscription needed)
121
159
  * webSocketService.addChannelCallback({
122
160
  * channelName: 'system-notifications.v1',
123
161
  * callback: (notification) => {
124
162
  * console.log('System notification:', notification.data);
125
163
  * }
126
164
  * });
165
+ *
166
+ * // For account-specific subscriptions, use subscribe() instead:
167
+ * // const sub = await webSocketService.subscribe({
168
+ * // channels: ['account-activity.v1.eip155:0:0x1234...'],
169
+ * // callback: (notification) => { ... }
170
+ * // });
127
171
  * ```
172
+ *
173
+ * @see subscribe for creating proper server-side subscriptions with lifecycle management
128
174
  */
129
175
  export type BackendWebSocketServiceAddChannelCallbackAction = {
130
176
  type: `BackendWebSocketService:addChannelCallback`;
@@ -133,7 +179,7 @@ export type BackendWebSocketServiceAddChannelCallbackAction = {
133
179
  /**
134
180
  * Remove a channel callback
135
181
  *
136
- * @param channelName - The channel name to remove callback for
182
+ * @param channelName - The channel name returned from addChannelCallback
137
183
  * @returns True if callback was found and removed, false otherwise
138
184
  */
139
185
  export type BackendWebSocketServiceRemoveChannelCallbackAction = {
@@ -142,18 +188,58 @@ export type BackendWebSocketServiceRemoveChannelCallbackAction = {
142
188
  };
143
189
  /**
144
190
  * Get all registered channel callbacks (for debugging)
191
+ *
192
+ * @returns Array of all registered channel callbacks
145
193
  */
146
194
  export type BackendWebSocketServiceGetChannelCallbacksAction = {
147
195
  type: `BackendWebSocketService:getChannelCallbacks`;
148
196
  handler: BackendWebSocketService['getChannelCallbacks'];
149
197
  };
150
198
  /**
151
- * Create and manage a subscription with direct callback routing
199
+ * Create and manage a subscription with server-side registration (recommended for most use cases)
200
+ *
201
+ * This is the recommended subscription API for high-level services. It creates a proper
202
+ * server-side subscription and routes notifications based on subscriptionId.
203
+ *
204
+ * **Key Features:**
205
+ * - Creates server-side subscription with unique subscriptionId
206
+ * - Callback triggered only for messages with matching subscriptionId
207
+ * - Automatic lifecycle management (cleanup on disconnect)
208
+ * - Includes unsubscribe method for proper cleanup
209
+ * - Request-response pattern with error handling
210
+ *
211
+ * **When to use `subscribe()`:**
212
+ * - Creating new subscriptions (account activity, price updates, etc.)
213
+ * - When you need proper cleanup/unsubscribe functionality
214
+ * - Most application use cases
215
+ *
216
+ * **When to use `addChannelCallback()` instead:**
217
+ * - System-wide notifications without server-side subscription
218
+ * - Observing channels managed elsewhere
219
+ * - Debug/logging scenarios
152
220
  *
153
221
  * @param options - Subscription configuration
154
222
  * @param options.channels - Array of channel names to subscribe to
155
223
  * @param options.callback - Callback function for handling notifications
156
- * @returns Promise that resolves with subscription object containing unsubscribe method
224
+ * @param options.requestId - Optional request ID for testing (will generate UUID if not provided)
225
+ * @param options.channelType - Channel type identifier
226
+ * @returns Subscription object with unsubscribe method
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * // AccountActivityService usage
231
+ * const subscription = await webSocketService.subscribe({
232
+ * channels: ['account-activity.v1.eip155:0:0x1234...'],
233
+ * callback: (notification) => {
234
+ * this.handleAccountActivity(notification.data);
235
+ * }
236
+ * });
237
+ *
238
+ * // Later, clean up
239
+ * await subscription.unsubscribe();
240
+ * ```
241
+ *
242
+ * @see addChannelCallback for local callbacks without server-side subscription
157
243
  */
158
244
  export type BackendWebSocketServiceSubscribeAction = {
159
245
  type: `BackendWebSocketService:subscribe`;
@@ -1 +1 @@
1
- {"version":3,"file":"BackendWebSocketService-method-action-types.d.mts","sourceRoot":"","sources":["../src/BackendWebSocketService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAkC;AAEzE;;;;GAIG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,iCAAiC,CAAC;IACxC,OAAO,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,uCAAuC,GAAG;IACpD,IAAI,EAAE,oCAAoC,CAAC;IAC3C,OAAO,EAAE,uBAAuB,CAAC,YAAY,CAAC,CAAC;CAChD,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,2CAA2C,CAAC;IAClD,OAAO,EAAE,uBAAuB,CAAC,mBAAmB,CAAC,CAAC;CACvD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,wCAAwC,GAAG;IACrD,IAAI,EAAE,qCAAqC,CAAC;IAC5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AC,CAAC;CACzD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,uBAAuB,CAAC,WAAW,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,oCAAoC,GAC5C,oCAAoC,GACpC,uCAAuC,GACvC,8CAA8C,GAC9C,wCAAwC,GACxC,wCAAwC,GACxC,8CAA8C,GAC9C,sDAAsD,GACtD,mDAAmD,GACnD,6DAA6D,GAC7D,+CAA+C,GAC/C,kDAAkD,GAClD,gDAAgD,GAChD,sCAAsC,CAAC"}
1
+ {"version":3,"file":"BackendWebSocketService-method-action-types.d.mts","sourceRoot":"","sources":["../src/BackendWebSocketService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAkC;AAEzE;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,iCAAiC,CAAC;IACxC,OAAO,EAAE,uBAAuB,CAAC,SAAS,CAAC,CAAC;CAC7C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uCAAuC,GAAG;IACpD,IAAI,EAAE,oCAAoC,CAAC;IAC3C,OAAO,EAAE,uBAAuB,CAAC,YAAY,CAAC,CAAC;CAChD,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,2CAA2C,CAAC;IAClD,OAAO,EAAE,uBAAuB,CAAC,mBAAmB,CAAC,CAAC;CACvD,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,wCAAwC,GAAG;IACrD,IAAI,EAAE,qCAAqC,CAAC;IAC5C,OAAO,EAAE,uBAAuB,CAAC,aAAa,CAAC,CAAC;CACjD,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,wCA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