@metamask-previews/notification-services-controller 27.0.0-preview-6fd51644c → 27.0.1-preview-d8fceeabc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [27.0.1]
11
+
12
+ ### Fixed
13
+
14
+ - Wallet-activity notifications are no longer suppressed by the `walletActivity.inAppNotificationsEnabled` and `walletActivity.pushNotificationsEnabled` toggles in Authenticated User Storage ([#10113](https://github.com/MetaMask/core/pull/10113))
15
+ - Both channels are now always enabled and delivery is controlled exclusively by each address's Trigger API subscription, so a stored `false` can no longer leave a subscribed address without notifications. Clients no longer expose a way to change these toggles, which made a stored `false` unrecoverable.
16
+ - `enablePushNotifications` no longer unregisters the device when the stored push toggle is off, `createOnChainTriggers` no longer registers an empty address list for the same reason, and `fetchAndUpdateMetamaskNotifications` no longer skips the on-chain fetch when the stored in-app toggle is off.
17
+ - The fields are still written when initializing a fresh preferences blob, because the Authenticated User Storage schema requires them. Nothing reads them back.
18
+
10
19
  ## [27.0.0]
11
20
 
12
21
  ### Changed
@@ -877,7 +886,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
877
886
 
878
887
  - Initial release
879
888
 
880
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/notification-services-controller@27.0.0...HEAD
889
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/notification-services-controller@27.0.1...HEAD
890
+ [27.0.1]: https://github.com/MetaMask/core/compare/@metamask/notification-services-controller@27.0.0...@metamask/notification-services-controller@27.0.1
881
891
  [27.0.0]: https://github.com/MetaMask/core/compare/@metamask/notification-services-controller@26.0.1...@metamask/notification-services-controller@27.0.0
882
892
  [26.0.1]: https://github.com/MetaMask/core/compare/@metamask/notification-services-controller@26.0.0...@metamask/notification-services-controller@26.0.1
883
893
  [26.0.0]: https://github.com/MetaMask/core/compare/@metamask/notification-services-controller@25.0.0...@metamask/notification-services-controller@26.0.0
@@ -13,7 +13,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
13
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
- var _NotificationServicesController_instances, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_locale, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_env, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_enableAuth, _NotificationServicesController_getBearerToken, _NotificationServicesController_isWalletActivityPushEnabled, _NotificationServicesController_registerPushNotifications, _NotificationServicesController_setIsUpdatingMetamaskNotifications, _NotificationServicesController_setIsFetchingMetamaskNotifications, _NotificationServicesController_setIsCheckingAccountsPresence, _NotificationServicesController_updateUpdatingAccountsState, _NotificationServicesController_clearUpdatingAccountsState;
16
+ var _NotificationServicesController_instances, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_locale, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_env, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_enableAuth, _NotificationServicesController_getBearerToken, _NotificationServicesController_registerPushNotifications, _NotificationServicesController_setIsUpdatingMetamaskNotifications, _NotificationServicesController_setIsFetchingMetamaskNotifications, _NotificationServicesController_setIsCheckingAccountsPresence, _NotificationServicesController_updateUpdatingAccountsState, _NotificationServicesController_clearUpdatingAccountsState;
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.NotificationServicesController = exports.DEFAULT_PRICE_ALERT_PREFERENCES = exports.DEFAULT_AGENTIC_CLI_PREFERENCES = exports.DEFAULT_SOCIAL_AI_PREFERENCES = exports.DEFAULT_PERPS_PREFERENCES = exports.defaultState = exports.ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS = void 0;
19
19
  const authenticated_user_storage_1 = require("@metamask/authenticated-user-storage");
@@ -152,13 +152,14 @@ const getEnabledAccounts = async (bearerToken, accounts, env) => {
152
152
  };
153
153
  /**
154
154
  * Builds a fresh `NotificationPreferences` blob using hardcoded defaults for
155
- * Perps, Social AI, and Agentic CLI and the user's marketing/product-announcement
156
- * flags.
155
+ * Perps, Social AI, and Agentic CLI and the user's
156
+ * marketing/product-announcement flags.
157
157
  *
158
- * `walletActivity.accounts` is deliberately left empty. Addresses are scoped to a
159
- * keyring, but this blob is keyed by canonical profile ID, which pairing shares
160
- * across every SRP belonging to the same user so storing them here pools the
161
- * addresses of unrelated SRPs. Subscriptions live in the Trigger API instead.
158
+ * `walletActivity` is written only because the blob schema requires the field;
159
+ * nothing reads it back. Both channels are always on, and subscriptions are
160
+ * held per address by the Trigger API rather than here addresses are scoped
161
+ * to a keyring, but this blob is keyed by canonical profile ID, which pairing
162
+ * shares across every SRP belonging to the same user.
162
163
  *
163
164
  * @param hasMarketingConsent - Whether marketing push notifications should be enabled.
164
165
  * @param productAnnouncementEnabled - Whether marketing in-app notifications should be enabled.
@@ -470,10 +471,6 @@ class NotificationServicesController extends base_controller_1.BaseController {
470
471
  */
471
472
  async enablePushNotifications() {
472
473
  try {
473
- if (!(await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_isWalletActivityPushEnabled).call(this))) {
474
- await __classPrivateFieldGet(this, _NotificationServicesController_pushNotifications, "f").disablePushNotifications();
475
- return;
476
- }
477
474
  const { bearerToken } = await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_getBearerToken).call(this);
478
475
  const { accounts } = __classPrivateFieldGet(this, _NotificationServicesController_accounts, "f").listAccounts();
479
476
  const enabledAddresses = await getEnabledAccounts(bearerToken, accounts, __classPrivateFieldGet(this, _NotificationServicesController_env, "f"));
@@ -572,7 +569,6 @@ class NotificationServicesController extends base_controller_1.BaseController {
572
569
  const hasMarketingConsent = Boolean(opts?.hasMarketingConsent);
573
570
  const productAnnouncementEnabled = Boolean(opts?.productAnnouncementEnabled);
574
571
  const isFirstTimeSetup = preferences === null;
575
- const isPushEnabled = preferences?.walletActivity.pushNotificationsEnabled ?? true;
576
572
  // 2. Subscribe the keyring's accounts on first-time setup only.
577
573
  //
578
574
  // This method also runs on the daily re-subscribe, so the absence of a
@@ -607,7 +603,7 @@ class NotificationServicesController extends base_controller_1.BaseController {
607
603
  }
608
604
  if (opts.registerPushNotifications ?? true) {
609
605
  // Attempt FCM/device registration only; clients must request OS permission separately.
610
- __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_registerPushNotifications).call(this, isPushEnabled ? accountsWithNotifications : []).catch(() => {
606
+ __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_registerPushNotifications).call(this, accountsWithNotifications).catch(() => {
611
607
  // Do Nothing
612
608
  });
613
609
  }
@@ -769,9 +765,7 @@ class NotificationServicesController extends base_controller_1.BaseController {
769
765
  : [];
770
766
  // Raw On Chain Notifications
771
767
  const rawOnChainNotifications = [];
772
- const isWalletActivityInAppEnabled = notificationPreferences?.walletActivity.inAppNotificationsEnabled ??
773
- true;
774
- if (isGlobalNotifsEnabled && isWalletActivityInAppEnabled) {
768
+ if (isGlobalNotifsEnabled) {
775
769
  try {
776
770
  const { bearerToken } = await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_getBearerToken).call(this);
777
771
  // Addresses come from the keyring, so this installation can only ever
@@ -1006,27 +1000,6 @@ _NotificationServicesController_keyringController = new WeakMap(), _Notification
1006
1000
  throw new Error('Missing BearerToken');
1007
1001
  }
1008
1002
  return { bearerToken };
1009
- }, _NotificationServicesController_isWalletActivityPushEnabled =
1010
- /**
1011
- * Reads the global wallet-activity push toggle from
1012
- * {@link AuthenticatedUserStorageService}.
1013
- *
1014
- * Only the channel boolean is read. It is a user-level setting that contains
1015
- * no addresses, so sharing it across a paired profile is correct. The address
1016
- * list in the same blob is deliberately ignored — see
1017
- * {@link buildFreshPreferences}.
1018
- *
1019
- * A missing or unreadable blob counts as enabled, matching the API's "every
1020
- * toggle is on unless stated otherwise" default, so that a storage outage does
1021
- * not silently stop notifications.
1022
- *
1023
- * @returns Whether wallet-activity push notifications are enabled.
1024
- */
1025
- async function _NotificationServicesController_isWalletActivityPushEnabled() {
1026
- const preferences = await this.messenger
1027
- .call('AuthenticatedUserStorageService:getNotificationPreferences')
1028
- .catch(() => null);
1029
- return preferences?.walletActivity.pushNotificationsEnabled ?? true;
1030
1003
  }, _NotificationServicesController_registerPushNotifications =
1031
1004
  /**
1032
1005
  * Registers this device for push notifications on the given addresses.
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesController.cjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAOA,qFAG8C;AAM9C,+DAA2D;AAC3D,iEAGoC;AAUpC,2CAAyC;AACzC,mCAAkC;AAClC,wDAA2B;AAO3B,gFAAmE;AAGnE,qFAG+C;AAE/C,2EAKyC;AACzC,mFAA0F;AAC1F,6EAA+E;AAO/E,iCAAiC;AACjC,MAAM,cAAc,GAAG,gCAAgC,CAAC;AAE3C,QAAA,gCAAgC,GAAG,IAAI,CAAC;AAwDrD,MAAM,QAAQ,GAAuD;IACnE,wBAAwB,EAAE;QACxB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IAED,kCAAkC,EAAE;QAClC,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,6BAA6B,EAAE;QAC7B,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAA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AC,qIAQ4B,QAAkB;IAC7C,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;YAC7B,GAAG,KAAK,CAAC,sCAAsC;YAC/C,GAAG,QAAQ;SACZ,CAAC,CAAC;QACH,KAAK,CAAC,sCAAsC,GAAG,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC,mIAO2B,QAAkB;IAC5C,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,sCAAsC;YAC1C,KAAK,CAAC,sCAAsC,CAAC,MAAM,CACjD,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,eAAe,CAAC,CACzD,CAAC;IACN,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AuthenticatedUserStorageServiceGetNotificationPreferencesAction,\n AuthenticatedUserStorageServicePutNotificationPreferencesAction,\n NotificationPreferences,\n PerpsPreference,\n SocialAIPreference,\n} from '@metamask/authenticated-user-storage';\nimport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n isValidHexAddress,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerState,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport { debounce } from 'lodash';\nimport log from 'loglevel';\n\nimport type {\n NotificationServicesPushControllerStateChangeEvent,\n NotificationServicesPushControllerOnNewNotificationEvent,\n} from '../NotificationServicesPushController/index.js';\nimport type { NotificationServicesPushControllerMethodActions } from '../NotificationServicesPushController/NotificationServicesPushController-method-action-types.js';\nimport { TRIGGER_TYPES } from './constants/notification-schema.js';\nimport type { NormalisedAPINotification } from './index.js';\nimport type { NotificationServicesControllerMethodActions } from './NotificationServicesController-method-action-types.js';\nimport {\n processAndFilterNotifications,\n safeProcessNotification,\n} from './processors/process-notifications.js';\nimport type { ENV } from './services/api-notifications.js';\nimport {\n getAPINotifications,\n getNotificationsApiConfigCached,\n markNotificationsAsRead,\n updateOnChainNotifications,\n} from './services/api-notifications.js';\nimport { getFeatureAnnouncementNotifications } from './services/feature-announcements.js';\nimport { createPerpOrderNotification } from './services/perp-notifications.js';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n} from './types/notification/notification.js';\nimport type { OrderInput } from './types/perps/index.js';\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\nexport const ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS = 1000;\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visited through the\n * account subscription. This allows us to track and add notifications for new accounts and not previous accounts added.\n */\n subscriptionAccountsSeen: string[];\n\n /**\n * Flag that indicates if the metamask notifications feature has been seen\n */\n isMetamaskNotificationsFeatureSeen: boolean;\n\n /**\n * Flag that indicates if the metamask notifications are enabled\n */\n isNotificationServicesEnabled: boolean;\n\n /**\n * Flag that indicates if the feature announcements are enabled\n */\n isFeatureAnnouncementsEnabled: boolean;\n\n /**\n * List of metamask notifications\n */\n metamaskNotificationsList: INotification[];\n\n /**\n * List of read metamask notifications\n */\n metamaskNotificationsReadList: string[];\n /**\n * Flag that indicates that the creating notifications is in progress\n */\n isUpdatingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the fetching notifications is in progress\n * This is used to show a loading spinner in the UI\n * when fetching notifications\n */\n isFetchingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the updating notifications for a specific address is in progress\n */\n isUpdatingMetamaskNotificationsAccount: string[];\n /**\n * Flag that indicates that the checking accounts presence is in progress\n */\n isCheckingAccountsPresence: boolean;\n};\n\nconst metadata: StateMetadata<NotificationServicesControllerState> = {\n subscriptionAccountsSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isNotificationServicesEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFeatureAnnouncementsEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n metamaskNotificationsList: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n metamaskNotificationsReadList: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isUpdatingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFetchingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isUpdatingMetamaskNotificationsAccount: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isCheckingAccountsPresence: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\nexport const defaultState: NotificationServicesControllerState = {\n subscriptionAccountsSeen: [],\n isMetamaskNotificationsFeatureSeen: false,\n isNotificationServicesEnabled: false,\n isFeatureAnnouncementsEnabled: false,\n metamaskNotificationsList: [],\n metamaskNotificationsReadList: [],\n isUpdatingMetamaskNotifications: false,\n isFetchingMetamaskNotifications: false,\n isUpdatingMetamaskNotificationsAccount: [],\n isCheckingAccountsPresence: false,\n};\n\nexport type NotificationServicesControllerEnableNotificationsOptions = {\n /**\n * Whether the user has consented to marketing notifications. Used only when\n * notification preferences are being initialized for the first time to seed\n * marketing push notifications.\n */\n hasMarketingConsent?: boolean;\n /**\n * Whether product announcements are enabled. Used only when notification\n * preferences are being initialized for the first time to seed marketing\n * in-app notifications.\n */\n productAnnouncementEnabled?: boolean;\n /**\n * Whether to attempt FCM/device push registration after notification\n * preferences are initialized or refreshed. This does not request OS push\n * permission.\n *\n * @default true\n */\n registerPushNotifications?: boolean;\n};\n\nexport type NotificationServicesControllerCreateOnChainTriggersOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nexport type NotificationServicesControllerEnableMetamaskNotificationsOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\n/**\n * Hardcoded default Perps notification preferences. Applied when notification\n * preferences are initialized for the first time.\n */\nexport const DEFAULT_PERPS_PREFERENCES: PerpsPreference = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n};\n\n/**\n * Hardcoded default Social AI notification preferences. Applied when\n * notification preferences are initialized for the first time.\n */\nexport const DEFAULT_SOCIAL_AI_PREFERENCES: Required<SocialAIPreference> = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n txAmountLimit: 500,\n mutedTraderProfileIds: [],\n};\n\nexport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\n\n/**\n * Returns the subset of `accounts` that has a wallet-activity subscription in\n * the Trigger API, which is the source of truth for the per-address enabled bit.\n *\n * The address universe is always supplied by the caller from the keyring, so the\n * result cannot contain an address this installation does not hold.\n *\n * @param bearerToken - JWT used to query the Trigger API.\n * @param accounts - The keyring accounts to check.\n * @param env - The environment to use for the Trigger API call.\n * @returns The enabled addresses, as returned by the Trigger API, or `null` if\n * the Trigger API could not be read.\n */\nconst getEnabledAccounts = async (\n bearerToken: string,\n accounts: string[],\n env: ENV,\n): Promise<string[] | null> => {\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n env,\n );\n\n if (triggerConfig === null) {\n return null;\n }\n\n return triggerConfig\n .filter((addressConfig) => Boolean(addressConfig.enabled))\n .map((addressConfig) => addressConfig.address);\n};\n\n/**\n * Builds a fresh `NotificationPreferences` blob using hardcoded defaults for\n * Perps, Social AI, and Agentic CLI and the user's marketing/product-announcement\n * flags.\n *\n * `walletActivity.accounts` is deliberately left empty. Addresses are scoped to a\n * keyring, but this blob is keyed by canonical profile ID, which pairing shares\n * across every SRP belonging to the same user — so storing them here pools the\n * addresses of unrelated SRPs. Subscriptions live in the Trigger API instead.\n *\n * @param hasMarketingConsent - Whether marketing push notifications should be enabled.\n * @param productAnnouncementEnabled - Whether marketing in-app notifications should be enabled.\n * @returns A complete `NotificationPreferences` object.\n */\nconst buildFreshPreferences = (\n hasMarketingConsent: boolean,\n productAnnouncementEnabled: boolean,\n): NotificationPreferences => ({\n walletActivity: {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n accounts: [],\n },\n marketing: {\n inAppNotificationsEnabled: productAnnouncementEnabled,\n pushNotificationsEnabled: hasMarketingConsent,\n },\n perps: { ...DEFAULT_PERPS_PREFERENCES },\n socialAI: { ...DEFAULT_SOCIAL_AI_PREFERENCES },\n agenticCli: { ...DEFAULT_AGENTIC_CLI_PREFERENCES },\n priceAlerts: { ...DEFAULT_PRICE_ALERT_PREFERENCES },\n});\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'init',\n 'enablePushNotifications',\n 'disablePushNotifications',\n 'checkAccountsPresence',\n 'setFeatureAnnouncementsEnabled',\n 'createOnChainTriggers',\n 'enableMetamaskNotifications',\n 'disableNotificationServices',\n 'disableAccounts',\n 'enableAccounts',\n 'fetchAndUpdateMetamaskNotifications',\n 'getNotificationsByType',\n 'deleteNotificationById',\n 'deleteNotificationsById',\n 'markMetamaskNotificationsAsRead',\n 'updateMetamaskNotificationsList',\n 'sendPerpPlaceOrderNotification',\n] as const;\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerMethodActions;\n\n// Allowed Actions\ntype AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerIsSignedInAction\n | AuthenticationController.AuthenticationControllerPerformSignInAction\n // Authenticated User Storage Requests\n | AuthenticatedUserStorageServiceGetNotificationPreferencesAction\n | AuthenticatedUserStorageServicePutNotificationPreferencesAction\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerMethodActions;\n\n// Events\nexport type NotificationServicesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationListUpdatedEvent = {\n type: `${typeof controllerName}:notificationsListUpdated`;\n payload: [INotification[]];\n};\n\nexport type MarkNotificationsAsReadEvent = {\n type: `${typeof controllerName}:markNotificationsAsRead`;\n payload: [INotification[]];\n};\n\n// Events\nexport type Events =\n | NotificationServicesControllerStateChangeEvent\n | NotificationListUpdatedEvent\n | MarkNotificationsAsReadEvent;\n\n// Allowed Events\ntype AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerStateChangeEvent;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n platformVersion?: string;\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n readonly #keyringController = {\n isUnlocked: false,\n\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>): void => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#keyringController.isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', (): void => {\n this.#keyringController.isUnlocked = true;\n // messaging system cannot await promises\n // we don't need to wait for a result on this.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onUnlock();\n });\n\n this.messenger.subscribe('KeyringController:lock', (): void => {\n this.#keyringController.isUnlocked = false;\n });\n },\n };\n\n readonly #auth = {\n getBearerToken: async (): Promise<string | null> => {\n return await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: (): boolean => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async (): Promise<string[]> => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #pushNotifications = {\n // Flag to check is notifications have been setup when the browser/extension is initialized.\n // We want to re-initialize push notifications when the browser/extension is refreshed\n // To ensure we subscribe to the most up-to-date notifications\n isSetup: false,\n\n subscribeToPushNotifications: async (): Promise<void> => {\n await this.messenger.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:enablePushNotifications',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n addPushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:addPushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n disablePushNotifications: async (): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:disablePushNotifications',\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n deletePushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:deletePushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n subscribe: (): void => {\n // Coalesce pushes: at most one fetch in-flight, one queued.\n // Re-fetch after completion because the new row may not be visible yet when the push arrives.\n let pushFetchInFlight = false;\n let pendingPushRefetch = false;\n\n const fetchOnPush = async (): Promise<void> => {\n pushFetchInFlight = true;\n try {\n await this.fetchAndUpdateMetamaskNotifications();\n } finally {\n pushFetchInFlight = false;\n if (pendingPushRefetch) {\n pendingPushRefetch = false;\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n }\n }\n };\n\n this.messenger.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (): void => {\n if (pushFetchInFlight) {\n pendingPushRefetch = true;\n return;\n }\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n },\n );\n },\n initializePushNotifications: async (): Promise<void> => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#pushNotifications.isSetup) {\n return;\n }\n\n // If wallet is unlocked, we can create a fresh push subscription\n // Otherwise we can subscribe to original subscription\n try {\n if (!this.#keyringController.isUnlocked) {\n throw new Error('Keyring is locked');\n }\n await this.enablePushNotifications();\n this.#pushNotifications.isSetup = true;\n } catch {\n await this.#pushNotifications\n .subscribeToPushNotifications()\n .catch(() => {\n // do nothing\n });\n }\n },\n };\n\n readonly #accounts = {\n // Flag to ensure we only setup once\n isNotificationAccountsSetup: false,\n\n getNotificationAccounts: (): string[] | null => {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n const keyringAccounts = [\n ...new Set(\n keyrings\n .flatMap((keyring) => keyring.accounts)\n .map((address) => {\n try {\n return toChecksumHexAddress(address);\n } catch {\n return null;\n }\n })\n .filter(\n (address): address is string =>\n address !== null && isValidHexAddress(address),\n ),\n ),\n ];\n return keyringAccounts.length > 0 ? keyringAccounts : null;\n },\n\n /**\n * Used to get list of addresses from keyring (wallet addresses)\n *\n * @returns addresses removed, added, and latest list of addresses\n */\n listAccounts: (): {\n accountsAdded: string[];\n accountsRemoved: string[];\n accounts: string[];\n } => {\n // Get previous and current account sets\n const nonChecksumAccounts = this.#accounts.getNotificationAccounts();\n if (!nonChecksumAccounts) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n const accounts = nonChecksumAccounts\n .map((address) => toChecksumHexAddress(address))\n .filter((address) => isValidHexAddress(address));\n const currentAccountsSet = new Set(accounts);\n const prevAccountsSet = new Set(this.state.subscriptionAccountsSeen);\n\n // Invalid value you cannot have zero accounts\n // Only occurs when the Accounts controller is initializing.\n if (accounts.length === 0) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n // Calculate added and removed addresses\n const accountsAdded = accounts.filter(\n (account) => !prevAccountsSet.has(account),\n );\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (account) => !currentAccountsSet.has(account),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...currentAccountsSet];\n });\n\n return {\n accountsAdded,\n accountsRemoved,\n accounts,\n };\n },\n\n /**\n * Initializes the cache/previous list. This is handy so we have an accurate in-mem state of the previous list of accounts.\n */\n initialize: (): void => {\n if (\n this.#keyringController.isUnlocked &&\n !this.#accounts.isNotificationAccountsSetup\n ) {\n this.#accounts.listAccounts();\n this.#accounts.isNotificationAccountsSetup = true;\n }\n },\n\n /**\n * Subscription to any state change in the keyring controller (aka wallet accounts).\n * We can call the `listAccounts` defined above to find out about any accounts added, removed\n * And call effects to subscribe/unsubscribe to notifications.\n */\n subscribe: (): void => {\n const debouncedUpdateAccountNotifications = debounce(\n async (\n totalAccounts?: number,\n prevTotalAccounts?: number,\n ): Promise<void> => {\n const hasTotalAccountsChanged = totalAccounts !== prevTotalAccounts;\n if (\n !this.state.isNotificationServicesEnabled ||\n !hasTotalAccountsChanged\n ) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.enableAccounts(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.disableAccounts(accountsRemoved));\n }\n await Promise.allSettled(promises);\n },\n ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS,\n );\n\n this.messenger.subscribe(\n 'KeyringController:stateChange',\n // Using void return for async callback - result is intentionally ignored\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n debouncedUpdateAccountNotifications,\n (state: KeyringControllerState): number => {\n return (\n state?.keyrings?.flatMap?.((keyring) => keyring.accounts)?.length ??\n 0\n );\n },\n );\n },\n };\n\n readonly #locale: () => string;\n\n readonly #featureAnnouncementEnv: FeatureAnnouncementEnv;\n\n readonly #env: ENV;\n\n /**\n * Creates a NotificationServicesController instance.\n *\n * @param args - The arguments to this function.\n * @param args.messenger - Messenger used to communicate with BaseV2 controller.\n * @param args.state - Initial state to set on this controller.\n * @param args.env - environment variables for a given controller.\n * @param args.env.featureAnnouncements - env variables for feature announcements.\n * @param args.env.locale - users locale for better dynamic server notifications\n * @param args.env.env - the environment to use for the controller\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n locale?: () => string;\n env?: ENV;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#locale = env.locale ?? ((): string => 'en');\n this.#env = env.env ?? 'prd';\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.#clearLoadingStates();\n }\n\n init(): void {\n this.#keyringController.setupLockedStateSubscriptions(\n async (): Promise<void> => {\n this.#accounts.initialize();\n await this.#pushNotifications.initializePushNotifications();\n },\n );\n\n this.#accounts.initialize();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#pushNotifications.initializePushNotifications();\n this.#accounts.subscribe();\n this.#pushNotifications.subscribe();\n }\n\n #clearLoadingStates(): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = false;\n state.isCheckingAccountsPresence = false;\n state.isFetchingMetamaskNotifications = false;\n state.isUpdatingMetamaskNotificationsAccount = [];\n });\n }\n\n #assertAuthEnabled(): void {\n if (!this.#auth.isSignedIn()) {\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n });\n throw new Error('User is not signed in.');\n }\n }\n\n async #enableAuth(): Promise<void> {\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n async #getBearerToken(): Promise<{ bearerToken: string }> {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n\n if (!bearerToken) {\n throw new Error('Missing BearerToken');\n }\n\n return { bearerToken };\n }\n\n /**\n * Reads the global wallet-activity push toggle from\n * {@link AuthenticatedUserStorageService}.\n *\n * Only the channel boolean is read. It is a user-level setting that contains\n * no addresses, so sharing it across a paired profile is correct. The address\n * list in the same blob is deliberately ignored — see\n * {@link buildFreshPreferences}.\n *\n * A missing or unreadable blob counts as enabled, matching the API's \"every\n * toggle is on unless stated otherwise\" default, so that a storage outage does\n * not silently stop notifications.\n *\n * @returns Whether wallet-activity push notifications are enabled.\n */\n async #isWalletActivityPushEnabled(): Promise<boolean> {\n const preferences = await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch(() => null);\n\n return preferences?.walletActivity.pushNotificationsEnabled ?? true;\n }\n\n /**\n * Registers this device for push notifications on the given addresses.\n *\n * An empty list cannot be sent: the push API rejects a registration with no\n * addresses, and because that request is what performs the delete-and-reinsert\n * of the device's links, a rejection leaves the previous links in place and\n * push keeps arriving. So \"no addresses\" has to mean unregistering the device.\n *\n * @param addresses - The addresses to receive push notifications for.\n */\n async #registerPushNotifications(addresses: string[]): Promise<void> {\n if (addresses.length === 0) {\n await this.#pushNotifications.disablePushNotifications();\n return;\n }\n\n await this.#pushNotifications.enablePushNotifications(addresses);\n }\n\n /**\n * Sets the state of notification creation process.\n *\n * This method updates the `isUpdatingMetamaskNotifications` state, which can be used to indicate\n * whether the notification creation process is currently active or not. This is useful\n * for UI elements that need to reflect the state of ongoing operations, such as loading\n * indicators or disabled buttons during processing.\n *\n * @param isUpdatingMetamaskNotifications - A boolean value representing the new state of the notification creation process.\n */\n #setIsUpdatingMetamaskNotifications(\n isUpdatingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = isUpdatingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate whether fetching of MetaMask notifications is in progress.\n *\n * This method is used to set the `isFetchingMetamaskNotifications` state, which can be utilized\n * to show or hide loading indicators in the UI when notifications are being fetched.\n *\n * @param isFetchingMetamaskNotifications - A boolean value representing the fetching state.\n */\n #setIsFetchingMetamaskNotifications(\n isFetchingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isFetchingMetamaskNotifications = isFetchingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate that the checking of accounts presence is in progress.\n *\n * This method modifies the `isCheckingAccountsPresence` state, which can be used to manage UI elements\n * that depend on the status of account presence checks, such as displaying loading indicators or disabling\n * buttons while the check is ongoing.\n *\n * @param isCheckingAccountsPresence - A boolean value indicating whether the account presence check is currently active.\n */\n #setIsCheckingAccountsPresence(isCheckingAccountsPresence: boolean): void {\n this.update((state) => {\n state.isCheckingAccountsPresence = isCheckingAccountsPresence;\n });\n }\n\n /**\n * Updates the state to indicate that account updates are in progress.\n * Removes duplicate accounts before updating the state.\n *\n * @param accounts - The accounts being updated.\n */\n #updateUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n const uniqueAccounts = new Set([\n ...state.isUpdatingMetamaskNotificationsAccount,\n ...accounts,\n ]);\n state.isUpdatingMetamaskNotificationsAccount = Array.from(uniqueAccounts);\n });\n }\n\n /**\n * Clears the state indicating that account updates are complete.\n *\n * @param accounts - The accounts that have finished updating.\n */\n #clearUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n /**\n * Public method to expose enabling push notifications\n */\n public async enablePushNotifications(): Promise<void> {\n try {\n if (!(await this.#isWalletActivityPushEnabled())) {\n await this.#pushNotifications.disablePushNotifications();\n return;\n }\n\n const { bearerToken } = await this.#getBearerToken();\n const { accounts } = this.#accounts.listAccounts();\n const enabledAddresses = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (enabledAddresses === null) {\n // \"No addresses\" unregisters the device, so an unreadable subscription\n // list must not be treated as an empty one: leave the existing links\n // alone until we can read the real state.\n return;\n }\n\n await this.#registerPushNotifications(enabledAddresses);\n } catch {\n // Do nothing, failing silently.\n }\n }\n\n /**\n * Public method to expose disabling push notifications\n */\n public async disablePushNotifications(): Promise<void> {\n await this.#pushNotifications.disablePushNotifications();\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n const { bearerToken } = await this.#getBearerToken();\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (triggerConfig === null) {\n // Reporting every account as disabled would misrepresent the user's\n // settings, so surface the failure instead.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n const enabledByAddress = new Map(\n triggerConfig.map((addressConfig) => [\n addressConfig.address.toLowerCase(),\n Boolean(addressConfig.enabled),\n ]),\n );\n\n const result: Record<string, boolean> = {};\n for (const address of accounts) {\n result[address] = enabledByAddress.get(address.toLowerCase()) ?? false;\n }\n return result;\n } catch (error) {\n log.error('Failed to check accounts presence', error);\n throw error;\n } finally {\n this.#setIsCheckingAccountsPresence(false);\n }\n }\n\n /**\n * Sets the enabled state of feature announcements.\n *\n * **Action** - used in the notification settings to enable/disable feature announcements.\n *\n * @param featureAnnouncementsEnabled - A boolean value indicating the desired enabled state of the feature announcements.\n * @async\n * @throws {Error} If fails to update\n */\n public async setFeatureAnnouncementsEnabled(\n featureAnnouncementsEnabled: boolean,\n ): Promise<void> {\n try {\n this.update((state) => {\n state.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (error) {\n log.error('Unable to toggle feature announcements', error);\n throw new Error('Unable to toggle feature announcements');\n }\n }\n\n /**\n * This creates/re-creates on-chain triggers defined in User Storage.\n *\n * **Action** - Used during Sign In / Enabling of notifications.\n *\n * Notification preferences are initialized only when\n * {@link AuthenticatedUserStorageService} has no stored preferences yet.\n * Existing preferences are left as-is.\n *\n * @param opts - optional options to mutate this functionality\n * @param opts.hasMarketingConsent - The user's marketing-consent flag.\n * Used only during initialization to seed marketing push notifications.\n * @param opts.productAnnouncementEnabled - The user's product-announcement flag.\n * Used only during initialization to seed marketing in-app notifications.\n * @param opts.registerPushNotifications - Whether to attempt FCM/device push registration.\n * @returns The updated or newly created user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async createOnChainTriggers(\n opts: NotificationServicesControllerCreateOnChainTriggersOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const { bearerToken } = await this.#getBearerToken();\n\n const { accounts } = this.#accounts.listAccounts();\n\n // 1. Read existing AUS notification preferences. Their absence is what\n // marks a first-time setup, and they are initialized in step 3.\n const preferences = await this.messenger.call(\n 'AuthenticatedUserStorageService:getNotificationPreferences',\n );\n\n const hasMarketingConsent = Boolean(opts?.hasMarketingConsent);\n const productAnnouncementEnabled = Boolean(\n opts?.productAnnouncementEnabled,\n );\n\n const isFirstTimeSetup = preferences === null;\n\n const isPushEnabled =\n preferences?.walletActivity.pushNotificationsEnabled ?? true;\n\n // 2. Subscribe the keyring's accounts on first-time setup only.\n //\n // This method also runs on the daily re-subscribe, so the absence of a\n // preferences blob — not the absence of subscriptions — is what marks a\n // genuine first-time setup. Keying off \"no subscriptions\" would re-enable\n // every account daily for a user who had turned them all off.\n //\n // Even at first-time setup, existing subscriptions win: a user upgrading\n // from a client that never wrote a preferences blob keeps whichever\n // accounts they had already disabled.\n let accountsWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (accountsWithNotifications === null) {\n // An unreadable subscription list is not an empty one. Subscribing\n // every account here would re-enable ones the user had turned off, and\n // registering push for that guessed list would send activity for them,\n // so fail and let the caller retry.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n if (isFirstTimeSetup && accountsWithNotifications.length === 0) {\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n // Match the lower-case form the Trigger API echoes back, which is what\n // every other path feeding the push API uses.\n accountsWithNotifications = accounts.map((address) =>\n address.toLowerCase(),\n );\n }\n\n // 3. Initialize the preferences blob, only once the subscriptions above\n // are in place. Its existence is what makes the next run a re-subscribe\n // rather than a first-time setup, so writing it earlier would let a\n // failed subscribe leave the user enabled with no accounts subscribed\n // and no second chance to seed them.\n if (isFirstTimeSetup) {\n await this.messenger.call(\n 'AuthenticatedUserStorageService:putNotificationPreferences',\n buildFreshPreferences(\n hasMarketingConsent,\n productAnnouncementEnabled,\n ),\n this.#featureAnnouncementEnv.platform,\n );\n }\n\n if (opts.registerPushNotifications ?? true) {\n // Attempt FCM/device registration only; clients must request OS permission separately.\n this.#registerPushNotifications(\n isPushEnabled ? accountsWithNotifications : [],\n ).catch(() => {\n // Do Nothing\n });\n }\n\n // Update the state of the controller\n this.update((state) => {\n // User is re-subscribing (daily resub to get latest notifications)\n if (state.isNotificationServicesEnabled) {\n // Keep their existing preferences on re-subscribe\n // No state updates needed - preserving user's current settings\n } else {\n // User is turning on notifications from a disabled state\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n }\n });\n } catch (error) {\n log.error('Failed to create On Chain triggers', error);\n throw new Error('Failed to create On Chain triggers');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Enables all MetaMask notifications for the user.\n * This is identical flow when initializing notifications for the first time.\n *\n * @param opts - Optional options to mutate this functionality.\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications(\n opts: NotificationServicesControllerEnableMetamaskNotificationsOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n await this.#enableAuth();\n await this.createOnChainTriggers(opts);\n } catch (error) {\n log.error('Unable to enable notifications', error);\n throw new Error('Unable to enable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Disables all MetaMask notifications for the user.\n * This method ensures that the user is authenticated, retrieves all linked accounts,\n * and disables on-chain triggers for each account. It also sets the global notification\n * settings for MetaMask, feature announcements to false.\n *\n * @throws {Error} If the user is not authenticated or if there is an error during the process.\n */\n public async disableNotificationServices(): Promise<void> {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Attempt Disable Push Notifications\n try {\n await this.#pushNotifications.disablePushNotifications();\n } catch {\n // Do nothing\n }\n\n // Update State: remove non-permitted notifications & disable flags\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n state.isFeatureAnnouncementsEnabled = false;\n // reassigning the notifications list with just snaps\n // since the disable shouldn't affect snaps notifications\n state.metamaskNotificationsList = snapNotifications;\n });\n\n // Finish Updating State\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account/s.\n * This method performs several key operations:\n * 1. Validates Auth\n * 2. Deletes accounts\n * (note) We do not need to look through push notifications as we've deleted triggers\n *\n * **Action** - When a user disables notifications for a given account in settings.\n *\n * @param accounts - The account for which on-chain triggers are to be deleted.\n * @returns A promise that resolves to void or an object containing a success message.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async disableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n const { bearerToken } = await this.#getBearerToken();\n\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: false })),\n this.#env,\n );\n\n await this.#pushNotifications.deletePushNotificationLinks(accounts);\n } catch {\n throw new Error('Failed to delete OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Updates/Creates on-chain triggers for a specific account.\n *\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and creates any missing triggers associated with the account\n * 3. Enables any related push notifications\n * 4. Updates Storage to reflect new state.\n *\n * **Action** - When a user enables notifications for an account\n *\n * @param accounts - List of accounts you want to update.\n * @returns A promise that resolves to the updated user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async enableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n\n const { bearerToken } = await this.#getBearerToken();\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n\n await this.#pushNotifications.addPushNotificationLinks(accounts);\n } catch (error) {\n log.error('Failed to update OnChain triggers', error);\n throw new Error('Failed to update OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Fetches the list of metamask notifications.\n * This includes OnChain notifications; Feature Announcements; and Snap Notifications.\n *\n * **Action** - When a user views the notification list page/dropdown\n *\n * @param previewToken - the preview token to use if needed\n * @returns A promise that resolves to the list of notifications.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async fetchAndUpdateMetamaskNotifications(\n previewToken?: string,\n ): Promise<INotification[]> {\n try {\n this.#setIsFetchingMetamaskNotifications(true);\n\n // This is used by Feature Announcement & On Chain\n // Not used by Snaps\n const isGlobalNotifsEnabled = this.state.isNotificationServicesEnabled;\n const notificationPreferences = isGlobalNotifsEnabled\n ? await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch(() => null)\n : null;\n\n // Raw Feature Notifications\n const rawAnnouncements =\n isGlobalNotifsEnabled &&\n notificationPreferences?.marketing.inAppNotificationsEnabled\n ? await getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: NormalisedAPINotification[] = [];\n const isWalletActivityInAppEnabled =\n notificationPreferences?.walletActivity.inAppNotificationsEnabled ??\n true;\n if (isGlobalNotifsEnabled && isWalletActivityInAppEnabled) {\n try {\n const { bearerToken } = await this.#getBearerToken();\n // Addresses come from the keyring, so this installation can only ever\n // ask for activity on accounts it actually holds. The Trigger API\n // narrows that to the ones the user has enabled.\n const { accounts } = this.#accounts.listAccounts();\n const addressesWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n if (addressesWithNotifications !== null) {\n const notifications = await getAPINotifications(\n bearerToken,\n addressesWithNotifications,\n this.#locale(),\n this.#featureAnnouncementEnv.platform,\n this.#env,\n ).catch(() => []);\n rawOnChainNotifications.push(...notifications);\n }\n } catch {\n // Do nothing\n }\n }\n\n // Snap Notifications (original)\n // We do not want to remove them\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n const readIds = this.state.metamaskNotificationsReadList;\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...processAndFilterNotifications(rawAnnouncements, readIds),\n ...processAndFilterNotifications(rawOnChainNotifications, readIds),\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (notificationA, notificationB) =>\n new Date(notificationB.createdAt).getTime() -\n new Date(notificationA.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (error) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', error);\n throw new Error('Failed to fetch notifications');\n }\n }\n\n /**\n * Gets the specified type of notifications from state.\n *\n * @param type - The trigger type.\n * @returns An array of notifications of the passed in type.\n * @throws Throws an error if an invalid trigger type is passed.\n */\n public getNotificationsByType(type: TRIGGER_TYPES): INotification[] {\n assert(\n Object.values(TRIGGER_TYPES).includes(type),\n 'Invalid trigger type.',\n );\n return this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === type,\n );\n }\n\n /**\n * Used to delete a notification by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param id - The id of the notification to delete.\n */\n public async deleteNotificationById(id: string): Promise<void> {\n const fetchedNotification = this.state.metamaskNotificationsList.find(\n (notification) => notification.id === id,\n );\n\n assert(\n fetchedNotification,\n 'The notification to be deleted does not exist.',\n );\n\n assert(\n locallyPersistedNotificationTypes.has(fetchedNotification.type),\n `The notification type of \"${\n // notifications are guaranteed to have type properties which equate to strings\n fetchedNotification.type as string\n }\" is not locally persisted, only the following types can use this function: ${[\n ...locallyPersistedNotificationTypes,\n ].join(', ')}.`,\n );\n\n const newList = this.state.metamaskNotificationsList.filter(\n (notification) => notification.id !== id,\n );\n\n this.update((state) => {\n state.metamaskNotificationsList = newList;\n });\n }\n\n /**\n * Used to batch delete notifications by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param ids - The ids of the notifications to delete.\n */\n public async deleteNotificationsById(ids: string[]): Promise<void> {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Marks specified metamask notifications as read.\n *\n * @param notifications - An array of notifications to be marked as read. Each notification should include its type and read status.\n * @returns A promise that resolves when the operation is complete.\n */\n public async markMetamaskNotificationsAsRead(\n notifications: MarkAsReadNotificationsParam,\n ): Promise<void> {\n let onchainNotificationIds: string[] = [];\n let featureAnnouncementNotificationIds: string[] = [];\n let snapNotificationIds: string[] = [];\n\n try {\n const [\n onChainNotifications,\n featureAnnouncementNotifications,\n snapNotifications,\n ] = notifications.reduce<\n [\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n ]\n >(\n (allNotifications, notification) => {\n if (!notification.isRead) {\n switch (notification.type) {\n case TRIGGER_TYPES.FEATURES_ANNOUNCEMENT:\n allNotifications[1].push(notification);\n break;\n case TRIGGER_TYPES.SNAP:\n allNotifications[2].push(notification);\n break;\n default:\n allNotifications[0].push(notification);\n }\n }\n return allNotifications;\n },\n [[], [], []],\n );\n\n // Mark On-Chain Notifications as Read\n if (onChainNotifications.length > 0) {\n const bearerToken = await this.#auth.getBearerToken();\n\n if (bearerToken) {\n onchainNotificationIds = onChainNotifications.map(\n (notification) => notification.id,\n );\n await markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\n this.#env,\n ).catch(() => {\n onchainNotificationIds = [];\n log.warn('Unable to mark onchain notifications as read');\n });\n }\n }\n\n // Mark Off-Chain notifications as Read\n if (featureAnnouncementNotifications.length > 0) {\n featureAnnouncementNotificationIds =\n featureAnnouncementNotifications.map(\n (notification) => notification.id,\n );\n }\n\n if (snapNotifications.length > 0) {\n snapNotificationIds = snapNotifications.map(\n (notification) => notification.id,\n );\n }\n } catch (error) {\n log.warn('Something failed when marking notifications as read', error);\n }\n\n // Update the state (state is also used on counter & badge)\n this.update((state) => {\n const currentReadList = state.metamaskNotificationsReadList;\n const newReadIds = [\n ...featureAnnouncementNotificationIds,\n ...snapNotificationIds,\n ];\n state.metamaskNotificationsReadList = [\n ...new Set([...currentReadList, ...newReadIds]),\n ];\n\n state.metamaskNotificationsList = state.metamaskNotificationsList.map(\n (notification: INotification) => {\n if (\n newReadIds.includes(notification.id) ||\n onchainNotificationIds.includes(notification.id)\n ) {\n if (notification.type === TRIGGER_TYPES.SNAP) {\n return {\n ...notification,\n isRead: true,\n readDate: new Date().toISOString(),\n };\n }\n return { ...notification, isRead: true };\n }\n return notification;\n },\n );\n });\n\n this.messenger.publish(\n `${controllerName}:markNotificationsAsRead`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Updates the list of MetaMask notifications by adding a new notification at the beginning of the list.\n * This method ensures that the most recent notification is displayed first in the UI.\n *\n * @param notification - The new notification object to be added to the list.\n * @returns A promise that resolves when the notification list has been successfully updated.\n */\n public async updateMetamaskNotificationsList(\n notification: INotification,\n ): Promise<void> {\n if (\n this.state.metamaskNotificationsList.some(\n (existingNotification) => existingNotification.id === notification.id,\n )\n ) {\n return;\n }\n\n const processedNotification = safeProcessNotification(notification);\n\n if (processedNotification) {\n this.update((state) => {\n const existingNotificationIds = new Set(\n state.metamaskNotificationsList.map(\n (existingNotification) => existingNotification.id,\n ),\n );\n // Add the new notification only if its ID is not already present in the list\n if (!existingNotificationIds.has(processedNotification.id)) {\n state.metamaskNotificationsList = [\n processedNotification,\n ...state.metamaskNotificationsList,\n ];\n }\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n\n /**\n * Creates an perp order notification subscription.\n * Requires notifications and auth to be enabled to start receiving this notifications\n *\n * @param input perp input\n */\n public async sendPerpPlaceOrderNotification(\n input: OrderInput,\n ): Promise<void> {\n try {\n const { bearerToken } = await this.#getBearerToken();\n await createPerpOrderNotification(bearerToken, input);\n } catch {\n // Do Nothing\n }\n }\n}\n"]}
1
+ {"version":3,"file":"NotificationServicesController.cjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAOA,qF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AAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;YAC7B,GAAG,KAAK,CAAC,sCAAsC;YAC/C,GAAG,QAAQ;SACZ,CAAC,CAAC;QACH,KAAK,CAAC,sCAAsC,GAAG,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;AACL,CAAC,mIAO2B,QAAkB;IAC5C,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,sCAAsC;YAC1C,KAAK,CAAC,sCAAsC,CAAC,MAAM,CACjD,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,eAAe,CAAC,CACzD,CAAC;IACN,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AuthenticatedUserStorageServiceGetNotificationPreferencesAction,\n AuthenticatedUserStorageServicePutNotificationPreferencesAction,\n NotificationPreferences,\n PerpsPreference,\n SocialAIPreference,\n} from '@metamask/authenticated-user-storage';\nimport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n isValidHexAddress,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerState,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport { debounce } from 'lodash';\nimport log from 'loglevel';\n\nimport type {\n NotificationServicesPushControllerStateChangeEvent,\n NotificationServicesPushControllerOnNewNotificationEvent,\n} from '../NotificationServicesPushController/index.js';\nimport type { NotificationServicesPushControllerMethodActions } from '../NotificationServicesPushController/NotificationServicesPushController-method-action-types.js';\nimport { TRIGGER_TYPES } from './constants/notification-schema.js';\nimport type { NormalisedAPINotification } from './index.js';\nimport type { NotificationServicesControllerMethodActions } from './NotificationServicesController-method-action-types.js';\nimport {\n processAndFilterNotifications,\n safeProcessNotification,\n} from './processors/process-notifications.js';\nimport type { ENV } from './services/api-notifications.js';\nimport {\n getAPINotifications,\n getNotificationsApiConfigCached,\n markNotificationsAsRead,\n updateOnChainNotifications,\n} from './services/api-notifications.js';\nimport { getFeatureAnnouncementNotifications } from './services/feature-announcements.js';\nimport { createPerpOrderNotification } from './services/perp-notifications.js';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n} from './types/notification/notification.js';\nimport type { OrderInput } from './types/perps/index.js';\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\nexport const ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS = 1000;\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visited through the\n * account subscription. This allows us to track and add notifications for new accounts and not previous accounts added.\n */\n subscriptionAccountsSeen: string[];\n\n /**\n * Flag that indicates if the metamask notifications feature has been seen\n */\n isMetamaskNotificationsFeatureSeen: boolean;\n\n /**\n * Flag that indicates if the metamask notifications are enabled\n */\n isNotificationServicesEnabled: boolean;\n\n /**\n * Flag that indicates if the feature announcements are enabled\n */\n isFeatureAnnouncementsEnabled: boolean;\n\n /**\n * List of metamask notifications\n */\n metamaskNotificationsList: INotification[];\n\n /**\n * List of read metamask notifications\n */\n metamaskNotificationsReadList: string[];\n /**\n * Flag that indicates that the creating notifications is in progress\n */\n isUpdatingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the fetching notifications is in progress\n * This is used to show a loading spinner in the UI\n * when fetching notifications\n */\n isFetchingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the updating notifications for a specific address is in progress\n */\n isUpdatingMetamaskNotificationsAccount: string[];\n /**\n * Flag that indicates that the checking accounts presence is in progress\n */\n isCheckingAccountsPresence: boolean;\n};\n\nconst metadata: StateMetadata<NotificationServicesControllerState> = {\n subscriptionAccountsSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isNotificationServicesEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFeatureAnnouncementsEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n metamaskNotificationsList: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n metamaskNotificationsReadList: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isUpdatingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFetchingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isUpdatingMetamaskNotificationsAccount: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isCheckingAccountsPresence: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\nexport const defaultState: NotificationServicesControllerState = {\n subscriptionAccountsSeen: [],\n isMetamaskNotificationsFeatureSeen: false,\n isNotificationServicesEnabled: false,\n isFeatureAnnouncementsEnabled: false,\n metamaskNotificationsList: [],\n metamaskNotificationsReadList: [],\n isUpdatingMetamaskNotifications: false,\n isFetchingMetamaskNotifications: false,\n isUpdatingMetamaskNotificationsAccount: [],\n isCheckingAccountsPresence: false,\n};\n\nexport type NotificationServicesControllerEnableNotificationsOptions = {\n /**\n * Whether the user has consented to marketing notifications. Used only when\n * notification preferences are being initialized for the first time to seed\n * marketing push notifications.\n */\n hasMarketingConsent?: boolean;\n /**\n * Whether product announcements are enabled. Used only when notification\n * preferences are being initialized for the first time to seed marketing\n * in-app notifications.\n */\n productAnnouncementEnabled?: boolean;\n /**\n * Whether to attempt FCM/device push registration after notification\n * preferences are initialized or refreshed. This does not request OS push\n * permission.\n *\n * @default true\n */\n registerPushNotifications?: boolean;\n};\n\nexport type NotificationServicesControllerCreateOnChainTriggersOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nexport type NotificationServicesControllerEnableMetamaskNotificationsOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\n/**\n * Hardcoded default Perps notification preferences. Applied when notification\n * preferences are initialized for the first time.\n */\nexport const DEFAULT_PERPS_PREFERENCES: PerpsPreference = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n};\n\n/**\n * Hardcoded default Social AI notification preferences. Applied when\n * notification preferences are initialized for the first time.\n */\nexport const DEFAULT_SOCIAL_AI_PREFERENCES: Required<SocialAIPreference> = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n txAmountLimit: 500,\n mutedTraderProfileIds: [],\n};\n\nexport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\n\n/**\n * Returns the subset of `accounts` that has a wallet-activity subscription in\n * the Trigger API, which is the source of truth for the per-address enabled bit.\n *\n * The address universe is always supplied by the caller from the keyring, so the\n * result cannot contain an address this installation does not hold.\n *\n * @param bearerToken - JWT used to query the Trigger API.\n * @param accounts - The keyring accounts to check.\n * @param env - The environment to use for the Trigger API call.\n * @returns The enabled addresses, as returned by the Trigger API, or `null` if\n * the Trigger API could not be read.\n */\nconst getEnabledAccounts = async (\n bearerToken: string,\n accounts: string[],\n env: ENV,\n): Promise<string[] | null> => {\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n env,\n );\n\n if (triggerConfig === null) {\n return null;\n }\n\n return triggerConfig\n .filter((addressConfig) => Boolean(addressConfig.enabled))\n .map((addressConfig) => addressConfig.address);\n};\n\n/**\n * Builds a fresh `NotificationPreferences` blob using hardcoded defaults for\n * Perps, Social AI, and Agentic CLI and the user's\n * marketing/product-announcement flags.\n *\n * `walletActivity` is written only because the blob schema requires the field;\n * nothing reads it back. Both channels are always on, and subscriptions are\n * held per address by the Trigger API rather than here — addresses are scoped\n * to a keyring, but this blob is keyed by canonical profile ID, which pairing\n * shares across every SRP belonging to the same user.\n *\n * @param hasMarketingConsent - Whether marketing push notifications should be enabled.\n * @param productAnnouncementEnabled - Whether marketing in-app notifications should be enabled.\n * @returns A complete `NotificationPreferences` object.\n */\nconst buildFreshPreferences = (\n hasMarketingConsent: boolean,\n productAnnouncementEnabled: boolean,\n): NotificationPreferences => ({\n walletActivity: {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n accounts: [],\n },\n marketing: {\n inAppNotificationsEnabled: productAnnouncementEnabled,\n pushNotificationsEnabled: hasMarketingConsent,\n },\n perps: { ...DEFAULT_PERPS_PREFERENCES },\n socialAI: { ...DEFAULT_SOCIAL_AI_PREFERENCES },\n agenticCli: { ...DEFAULT_AGENTIC_CLI_PREFERENCES },\n priceAlerts: { ...DEFAULT_PRICE_ALERT_PREFERENCES },\n});\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'init',\n 'enablePushNotifications',\n 'disablePushNotifications',\n 'checkAccountsPresence',\n 'setFeatureAnnouncementsEnabled',\n 'createOnChainTriggers',\n 'enableMetamaskNotifications',\n 'disableNotificationServices',\n 'disableAccounts',\n 'enableAccounts',\n 'fetchAndUpdateMetamaskNotifications',\n 'getNotificationsByType',\n 'deleteNotificationById',\n 'deleteNotificationsById',\n 'markMetamaskNotificationsAsRead',\n 'updateMetamaskNotificationsList',\n 'sendPerpPlaceOrderNotification',\n] as const;\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerMethodActions;\n\n// Allowed Actions\ntype AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerIsSignedInAction\n | AuthenticationController.AuthenticationControllerPerformSignInAction\n // Authenticated User Storage Requests\n | AuthenticatedUserStorageServiceGetNotificationPreferencesAction\n | AuthenticatedUserStorageServicePutNotificationPreferencesAction\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerMethodActions;\n\n// Events\nexport type NotificationServicesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationListUpdatedEvent = {\n type: `${typeof controllerName}:notificationsListUpdated`;\n payload: [INotification[]];\n};\n\nexport type MarkNotificationsAsReadEvent = {\n type: `${typeof controllerName}:markNotificationsAsRead`;\n payload: [INotification[]];\n};\n\n// Events\nexport type Events =\n | NotificationServicesControllerStateChangeEvent\n | NotificationListUpdatedEvent\n | MarkNotificationsAsReadEvent;\n\n// Allowed Events\ntype AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerStateChangeEvent;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n platformVersion?: string;\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n readonly #keyringController = {\n isUnlocked: false,\n\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>): void => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#keyringController.isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', (): void => {\n this.#keyringController.isUnlocked = true;\n // messaging system cannot await promises\n // we don't need to wait for a result on this.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onUnlock();\n });\n\n this.messenger.subscribe('KeyringController:lock', (): void => {\n this.#keyringController.isUnlocked = false;\n });\n },\n };\n\n readonly #auth = {\n getBearerToken: async (): Promise<string | null> => {\n return await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: (): boolean => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async (): Promise<string[]> => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #pushNotifications = {\n // Flag to check is notifications have been setup when the browser/extension is initialized.\n // We want to re-initialize push notifications when the browser/extension is refreshed\n // To ensure we subscribe to the most up-to-date notifications\n isSetup: false,\n\n subscribeToPushNotifications: async (): Promise<void> => {\n await this.messenger.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:enablePushNotifications',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n addPushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:addPushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n disablePushNotifications: async (): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:disablePushNotifications',\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n deletePushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:deletePushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n subscribe: (): void => {\n // Coalesce pushes: at most one fetch in-flight, one queued.\n // Re-fetch after completion because the new row may not be visible yet when the push arrives.\n let pushFetchInFlight = false;\n let pendingPushRefetch = false;\n\n const fetchOnPush = async (): Promise<void> => {\n pushFetchInFlight = true;\n try {\n await this.fetchAndUpdateMetamaskNotifications();\n } finally {\n pushFetchInFlight = false;\n if (pendingPushRefetch) {\n pendingPushRefetch = false;\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n }\n }\n };\n\n this.messenger.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (): void => {\n if (pushFetchInFlight) {\n pendingPushRefetch = true;\n return;\n }\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n },\n );\n },\n initializePushNotifications: async (): Promise<void> => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#pushNotifications.isSetup) {\n return;\n }\n\n // If wallet is unlocked, we can create a fresh push subscription\n // Otherwise we can subscribe to original subscription\n try {\n if (!this.#keyringController.isUnlocked) {\n throw new Error('Keyring is locked');\n }\n await this.enablePushNotifications();\n this.#pushNotifications.isSetup = true;\n } catch {\n await this.#pushNotifications\n .subscribeToPushNotifications()\n .catch(() => {\n // do nothing\n });\n }\n },\n };\n\n readonly #accounts = {\n // Flag to ensure we only setup once\n isNotificationAccountsSetup: false,\n\n getNotificationAccounts: (): string[] | null => {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n const keyringAccounts = [\n ...new Set(\n keyrings\n .flatMap((keyring) => keyring.accounts)\n .map((address) => {\n try {\n return toChecksumHexAddress(address);\n } catch {\n return null;\n }\n })\n .filter(\n (address): address is string =>\n address !== null && isValidHexAddress(address),\n ),\n ),\n ];\n return keyringAccounts.length > 0 ? keyringAccounts : null;\n },\n\n /**\n * Used to get list of addresses from keyring (wallet addresses)\n *\n * @returns addresses removed, added, and latest list of addresses\n */\n listAccounts: (): {\n accountsAdded: string[];\n accountsRemoved: string[];\n accounts: string[];\n } => {\n // Get previous and current account sets\n const nonChecksumAccounts = this.#accounts.getNotificationAccounts();\n if (!nonChecksumAccounts) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n const accounts = nonChecksumAccounts\n .map((address) => toChecksumHexAddress(address))\n .filter((address) => isValidHexAddress(address));\n const currentAccountsSet = new Set(accounts);\n const prevAccountsSet = new Set(this.state.subscriptionAccountsSeen);\n\n // Invalid value you cannot have zero accounts\n // Only occurs when the Accounts controller is initializing.\n if (accounts.length === 0) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n // Calculate added and removed addresses\n const accountsAdded = accounts.filter(\n (account) => !prevAccountsSet.has(account),\n );\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (account) => !currentAccountsSet.has(account),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...currentAccountsSet];\n });\n\n return {\n accountsAdded,\n accountsRemoved,\n accounts,\n };\n },\n\n /**\n * Initializes the cache/previous list. This is handy so we have an accurate in-mem state of the previous list of accounts.\n */\n initialize: (): void => {\n if (\n this.#keyringController.isUnlocked &&\n !this.#accounts.isNotificationAccountsSetup\n ) {\n this.#accounts.listAccounts();\n this.#accounts.isNotificationAccountsSetup = true;\n }\n },\n\n /**\n * Subscription to any state change in the keyring controller (aka wallet accounts).\n * We can call the `listAccounts` defined above to find out about any accounts added, removed\n * And call effects to subscribe/unsubscribe to notifications.\n */\n subscribe: (): void => {\n const debouncedUpdateAccountNotifications = debounce(\n async (\n totalAccounts?: number,\n prevTotalAccounts?: number,\n ): Promise<void> => {\n const hasTotalAccountsChanged = totalAccounts !== prevTotalAccounts;\n if (\n !this.state.isNotificationServicesEnabled ||\n !hasTotalAccountsChanged\n ) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.enableAccounts(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.disableAccounts(accountsRemoved));\n }\n await Promise.allSettled(promises);\n },\n ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS,\n );\n\n this.messenger.subscribe(\n 'KeyringController:stateChange',\n // Using void return for async callback - result is intentionally ignored\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n debouncedUpdateAccountNotifications,\n (state: KeyringControllerState): number => {\n return (\n state?.keyrings?.flatMap?.((keyring) => keyring.accounts)?.length ??\n 0\n );\n },\n );\n },\n };\n\n readonly #locale: () => string;\n\n readonly #featureAnnouncementEnv: FeatureAnnouncementEnv;\n\n readonly #env: ENV;\n\n /**\n * Creates a NotificationServicesController instance.\n *\n * @param args - The arguments to this function.\n * @param args.messenger - Messenger used to communicate with BaseV2 controller.\n * @param args.state - Initial state to set on this controller.\n * @param args.env - environment variables for a given controller.\n * @param args.env.featureAnnouncements - env variables for feature announcements.\n * @param args.env.locale - users locale for better dynamic server notifications\n * @param args.env.env - the environment to use for the controller\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n locale?: () => string;\n env?: ENV;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#locale = env.locale ?? ((): string => 'en');\n this.#env = env.env ?? 'prd';\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.#clearLoadingStates();\n }\n\n init(): void {\n this.#keyringController.setupLockedStateSubscriptions(\n async (): Promise<void> => {\n this.#accounts.initialize();\n await this.#pushNotifications.initializePushNotifications();\n },\n );\n\n this.#accounts.initialize();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#pushNotifications.initializePushNotifications();\n this.#accounts.subscribe();\n this.#pushNotifications.subscribe();\n }\n\n #clearLoadingStates(): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = false;\n state.isCheckingAccountsPresence = false;\n state.isFetchingMetamaskNotifications = false;\n state.isUpdatingMetamaskNotificationsAccount = [];\n });\n }\n\n #assertAuthEnabled(): void {\n if (!this.#auth.isSignedIn()) {\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n });\n throw new Error('User is not signed in.');\n }\n }\n\n async #enableAuth(): Promise<void> {\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n async #getBearerToken(): Promise<{ bearerToken: string }> {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n\n if (!bearerToken) {\n throw new Error('Missing BearerToken');\n }\n\n return { bearerToken };\n }\n\n /**\n * Registers this device for push notifications on the given addresses.\n *\n * An empty list cannot be sent: the push API rejects a registration with no\n * addresses, and because that request is what performs the delete-and-reinsert\n * of the device's links, a rejection leaves the previous links in place and\n * push keeps arriving. So \"no addresses\" has to mean unregistering the device.\n *\n * @param addresses - The addresses to receive push notifications for.\n */\n async #registerPushNotifications(addresses: string[]): Promise<void> {\n if (addresses.length === 0) {\n await this.#pushNotifications.disablePushNotifications();\n return;\n }\n\n await this.#pushNotifications.enablePushNotifications(addresses);\n }\n\n /**\n * Sets the state of notification creation process.\n *\n * This method updates the `isUpdatingMetamaskNotifications` state, which can be used to indicate\n * whether the notification creation process is currently active or not. This is useful\n * for UI elements that need to reflect the state of ongoing operations, such as loading\n * indicators or disabled buttons during processing.\n *\n * @param isUpdatingMetamaskNotifications - A boolean value representing the new state of the notification creation process.\n */\n #setIsUpdatingMetamaskNotifications(\n isUpdatingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = isUpdatingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate whether fetching of MetaMask notifications is in progress.\n *\n * This method is used to set the `isFetchingMetamaskNotifications` state, which can be utilized\n * to show or hide loading indicators in the UI when notifications are being fetched.\n *\n * @param isFetchingMetamaskNotifications - A boolean value representing the fetching state.\n */\n #setIsFetchingMetamaskNotifications(\n isFetchingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isFetchingMetamaskNotifications = isFetchingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate that the checking of accounts presence is in progress.\n *\n * This method modifies the `isCheckingAccountsPresence` state, which can be used to manage UI elements\n * that depend on the status of account presence checks, such as displaying loading indicators or disabling\n * buttons while the check is ongoing.\n *\n * @param isCheckingAccountsPresence - A boolean value indicating whether the account presence check is currently active.\n */\n #setIsCheckingAccountsPresence(isCheckingAccountsPresence: boolean): void {\n this.update((state) => {\n state.isCheckingAccountsPresence = isCheckingAccountsPresence;\n });\n }\n\n /**\n * Updates the state to indicate that account updates are in progress.\n * Removes duplicate accounts before updating the state.\n *\n * @param accounts - The accounts being updated.\n */\n #updateUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n const uniqueAccounts = new Set([\n ...state.isUpdatingMetamaskNotificationsAccount,\n ...accounts,\n ]);\n state.isUpdatingMetamaskNotificationsAccount = Array.from(uniqueAccounts);\n });\n }\n\n /**\n * Clears the state indicating that account updates are complete.\n *\n * @param accounts - The accounts that have finished updating.\n */\n #clearUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n /**\n * Public method to expose enabling push notifications\n */\n public async enablePushNotifications(): Promise<void> {\n try {\n const { bearerToken } = await this.#getBearerToken();\n const { accounts } = this.#accounts.listAccounts();\n const enabledAddresses = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (enabledAddresses === null) {\n // \"No addresses\" unregisters the device, so an unreadable subscription\n // list must not be treated as an empty one: leave the existing links\n // alone until we can read the real state.\n return;\n }\n\n await this.#registerPushNotifications(enabledAddresses);\n } catch {\n // Do nothing, failing silently.\n }\n }\n\n /**\n * Public method to expose disabling push notifications\n */\n public async disablePushNotifications(): Promise<void> {\n await this.#pushNotifications.disablePushNotifications();\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n const { bearerToken } = await this.#getBearerToken();\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (triggerConfig === null) {\n // Reporting every account as disabled would misrepresent the user's\n // settings, so surface the failure instead.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n const enabledByAddress = new Map(\n triggerConfig.map((addressConfig) => [\n addressConfig.address.toLowerCase(),\n Boolean(addressConfig.enabled),\n ]),\n );\n\n const result: Record<string, boolean> = {};\n for (const address of accounts) {\n result[address] = enabledByAddress.get(address.toLowerCase()) ?? false;\n }\n return result;\n } catch (error) {\n log.error('Failed to check accounts presence', error);\n throw error;\n } finally {\n this.#setIsCheckingAccountsPresence(false);\n }\n }\n\n /**\n * Sets the enabled state of feature announcements.\n *\n * **Action** - used in the notification settings to enable/disable feature announcements.\n *\n * @param featureAnnouncementsEnabled - A boolean value indicating the desired enabled state of the feature announcements.\n * @async\n * @throws {Error} If fails to update\n */\n public async setFeatureAnnouncementsEnabled(\n featureAnnouncementsEnabled: boolean,\n ): Promise<void> {\n try {\n this.update((state) => {\n state.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (error) {\n log.error('Unable to toggle feature announcements', error);\n throw new Error('Unable to toggle feature announcements');\n }\n }\n\n /**\n * This creates/re-creates on-chain triggers defined in User Storage.\n *\n * **Action** - Used during Sign In / Enabling of notifications.\n *\n * Notification preferences are initialized only when\n * {@link AuthenticatedUserStorageService} has no stored preferences yet.\n * Existing preferences are left as-is.\n *\n * @param opts - optional options to mutate this functionality\n * @param opts.hasMarketingConsent - The user's marketing-consent flag.\n * Used only during initialization to seed marketing push notifications.\n * @param opts.productAnnouncementEnabled - The user's product-announcement flag.\n * Used only during initialization to seed marketing in-app notifications.\n * @param opts.registerPushNotifications - Whether to attempt FCM/device push registration.\n * @returns The updated or newly created user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async createOnChainTriggers(\n opts: NotificationServicesControllerCreateOnChainTriggersOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const { bearerToken } = await this.#getBearerToken();\n\n const { accounts } = this.#accounts.listAccounts();\n\n // 1. Read existing AUS notification preferences. Their absence is what\n // marks a first-time setup, and they are initialized in step 3.\n const preferences = await this.messenger.call(\n 'AuthenticatedUserStorageService:getNotificationPreferences',\n );\n\n const hasMarketingConsent = Boolean(opts?.hasMarketingConsent);\n const productAnnouncementEnabled = Boolean(\n opts?.productAnnouncementEnabled,\n );\n\n const isFirstTimeSetup = preferences === null;\n\n // 2. Subscribe the keyring's accounts on first-time setup only.\n //\n // This method also runs on the daily re-subscribe, so the absence of a\n // preferences blob — not the absence of subscriptions — is what marks a\n // genuine first-time setup. Keying off \"no subscriptions\" would re-enable\n // every account daily for a user who had turned them all off.\n //\n // Even at first-time setup, existing subscriptions win: a user upgrading\n // from a client that never wrote a preferences blob keeps whichever\n // accounts they had already disabled.\n let accountsWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (accountsWithNotifications === null) {\n // An unreadable subscription list is not an empty one. Subscribing\n // every account here would re-enable ones the user had turned off, and\n // registering push for that guessed list would send activity for them,\n // so fail and let the caller retry.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n if (isFirstTimeSetup && accountsWithNotifications.length === 0) {\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n // Match the lower-case form the Trigger API echoes back, which is what\n // every other path feeding the push API uses.\n accountsWithNotifications = accounts.map((address) =>\n address.toLowerCase(),\n );\n }\n\n // 3. Initialize the preferences blob, only once the subscriptions above\n // are in place. Its existence is what makes the next run a re-subscribe\n // rather than a first-time setup, so writing it earlier would let a\n // failed subscribe leave the user enabled with no accounts subscribed\n // and no second chance to seed them.\n if (isFirstTimeSetup) {\n await this.messenger.call(\n 'AuthenticatedUserStorageService:putNotificationPreferences',\n buildFreshPreferences(\n hasMarketingConsent,\n productAnnouncementEnabled,\n ),\n this.#featureAnnouncementEnv.platform,\n );\n }\n\n if (opts.registerPushNotifications ?? true) {\n // Attempt FCM/device registration only; clients must request OS permission separately.\n this.#registerPushNotifications(accountsWithNotifications).catch(() => {\n // Do Nothing\n });\n }\n\n // Update the state of the controller\n this.update((state) => {\n // User is re-subscribing (daily resub to get latest notifications)\n if (state.isNotificationServicesEnabled) {\n // Keep their existing preferences on re-subscribe\n // No state updates needed - preserving user's current settings\n } else {\n // User is turning on notifications from a disabled state\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n }\n });\n } catch (error) {\n log.error('Failed to create On Chain triggers', error);\n throw new Error('Failed to create On Chain triggers');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Enables all MetaMask notifications for the user.\n * This is identical flow when initializing notifications for the first time.\n *\n * @param opts - Optional options to mutate this functionality.\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications(\n opts: NotificationServicesControllerEnableMetamaskNotificationsOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n await this.#enableAuth();\n await this.createOnChainTriggers(opts);\n } catch (error) {\n log.error('Unable to enable notifications', error);\n throw new Error('Unable to enable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Disables all MetaMask notifications for the user.\n * This method ensures that the user is authenticated, retrieves all linked accounts,\n * and disables on-chain triggers for each account. It also sets the global notification\n * settings for MetaMask, feature announcements to false.\n *\n * @throws {Error} If the user is not authenticated or if there is an error during the process.\n */\n public async disableNotificationServices(): Promise<void> {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Attempt Disable Push Notifications\n try {\n await this.#pushNotifications.disablePushNotifications();\n } catch {\n // Do nothing\n }\n\n // Update State: remove non-permitted notifications & disable flags\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n state.isFeatureAnnouncementsEnabled = false;\n // reassigning the notifications list with just snaps\n // since the disable shouldn't affect snaps notifications\n state.metamaskNotificationsList = snapNotifications;\n });\n\n // Finish Updating State\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account/s.\n * This method performs several key operations:\n * 1. Validates Auth\n * 2. Deletes accounts\n * (note) We do not need to look through push notifications as we've deleted triggers\n *\n * **Action** - When a user disables notifications for a given account in settings.\n *\n * @param accounts - The account for which on-chain triggers are to be deleted.\n * @returns A promise that resolves to void or an object containing a success message.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async disableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n const { bearerToken } = await this.#getBearerToken();\n\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: false })),\n this.#env,\n );\n\n await this.#pushNotifications.deletePushNotificationLinks(accounts);\n } catch {\n throw new Error('Failed to delete OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Updates/Creates on-chain triggers for a specific account.\n *\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and creates any missing triggers associated with the account\n * 3. Enables any related push notifications\n * 4. Updates Storage to reflect new state.\n *\n * **Action** - When a user enables notifications for an account\n *\n * @param accounts - List of accounts you want to update.\n * @returns A promise that resolves to the updated user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async enableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n\n const { bearerToken } = await this.#getBearerToken();\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n\n await this.#pushNotifications.addPushNotificationLinks(accounts);\n } catch (error) {\n log.error('Failed to update OnChain triggers', error);\n throw new Error('Failed to update OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Fetches the list of metamask notifications.\n * This includes OnChain notifications; Feature Announcements; and Snap Notifications.\n *\n * **Action** - When a user views the notification list page/dropdown\n *\n * @param previewToken - the preview token to use if needed\n * @returns A promise that resolves to the list of notifications.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async fetchAndUpdateMetamaskNotifications(\n previewToken?: string,\n ): Promise<INotification[]> {\n try {\n this.#setIsFetchingMetamaskNotifications(true);\n\n // This is used by Feature Announcement & On Chain\n // Not used by Snaps\n const isGlobalNotifsEnabled = this.state.isNotificationServicesEnabled;\n const notificationPreferences = isGlobalNotifsEnabled\n ? await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch(() => null)\n : null;\n\n // Raw Feature Notifications\n const rawAnnouncements =\n isGlobalNotifsEnabled &&\n notificationPreferences?.marketing.inAppNotificationsEnabled\n ? await getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: NormalisedAPINotification[] = [];\n if (isGlobalNotifsEnabled) {\n try {\n const { bearerToken } = await this.#getBearerToken();\n // Addresses come from the keyring, so this installation can only ever\n // ask for activity on accounts it actually holds. The Trigger API\n // narrows that to the ones the user has enabled.\n const { accounts } = this.#accounts.listAccounts();\n const addressesWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n if (addressesWithNotifications !== null) {\n const notifications = await getAPINotifications(\n bearerToken,\n addressesWithNotifications,\n this.#locale(),\n this.#featureAnnouncementEnv.platform,\n this.#env,\n ).catch(() => []);\n rawOnChainNotifications.push(...notifications);\n }\n } catch {\n // Do nothing\n }\n }\n\n // Snap Notifications (original)\n // We do not want to remove them\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n const readIds = this.state.metamaskNotificationsReadList;\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...processAndFilterNotifications(rawAnnouncements, readIds),\n ...processAndFilterNotifications(rawOnChainNotifications, readIds),\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (notificationA, notificationB) =>\n new Date(notificationB.createdAt).getTime() -\n new Date(notificationA.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (error) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', error);\n throw new Error('Failed to fetch notifications');\n }\n }\n\n /**\n * Gets the specified type of notifications from state.\n *\n * @param type - The trigger type.\n * @returns An array of notifications of the passed in type.\n * @throws Throws an error if an invalid trigger type is passed.\n */\n public getNotificationsByType(type: TRIGGER_TYPES): INotification[] {\n assert(\n Object.values(TRIGGER_TYPES).includes(type),\n 'Invalid trigger type.',\n );\n return this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === type,\n );\n }\n\n /**\n * Used to delete a notification by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param id - The id of the notification to delete.\n */\n public async deleteNotificationById(id: string): Promise<void> {\n const fetchedNotification = this.state.metamaskNotificationsList.find(\n (notification) => notification.id === id,\n );\n\n assert(\n fetchedNotification,\n 'The notification to be deleted does not exist.',\n );\n\n assert(\n locallyPersistedNotificationTypes.has(fetchedNotification.type),\n `The notification type of \"${\n // notifications are guaranteed to have type properties which equate to strings\n fetchedNotification.type as string\n }\" is not locally persisted, only the following types can use this function: ${[\n ...locallyPersistedNotificationTypes,\n ].join(', ')}.`,\n );\n\n const newList = this.state.metamaskNotificationsList.filter(\n (notification) => notification.id !== id,\n );\n\n this.update((state) => {\n state.metamaskNotificationsList = newList;\n });\n }\n\n /**\n * Used to batch delete notifications by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param ids - The ids of the notifications to delete.\n */\n public async deleteNotificationsById(ids: string[]): Promise<void> {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Marks specified metamask notifications as read.\n *\n * @param notifications - An array of notifications to be marked as read. Each notification should include its type and read status.\n * @returns A promise that resolves when the operation is complete.\n */\n public async markMetamaskNotificationsAsRead(\n notifications: MarkAsReadNotificationsParam,\n ): Promise<void> {\n let onchainNotificationIds: string[] = [];\n let featureAnnouncementNotificationIds: string[] = [];\n let snapNotificationIds: string[] = [];\n\n try {\n const [\n onChainNotifications,\n featureAnnouncementNotifications,\n snapNotifications,\n ] = notifications.reduce<\n [\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n ]\n >(\n (allNotifications, notification) => {\n if (!notification.isRead) {\n switch (notification.type) {\n case TRIGGER_TYPES.FEATURES_ANNOUNCEMENT:\n allNotifications[1].push(notification);\n break;\n case TRIGGER_TYPES.SNAP:\n allNotifications[2].push(notification);\n break;\n default:\n allNotifications[0].push(notification);\n }\n }\n return allNotifications;\n },\n [[], [], []],\n );\n\n // Mark On-Chain Notifications as Read\n if (onChainNotifications.length > 0) {\n const bearerToken = await this.#auth.getBearerToken();\n\n if (bearerToken) {\n onchainNotificationIds = onChainNotifications.map(\n (notification) => notification.id,\n );\n await markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\n this.#env,\n ).catch(() => {\n onchainNotificationIds = [];\n log.warn('Unable to mark onchain notifications as read');\n });\n }\n }\n\n // Mark Off-Chain notifications as Read\n if (featureAnnouncementNotifications.length > 0) {\n featureAnnouncementNotificationIds =\n featureAnnouncementNotifications.map(\n (notification) => notification.id,\n );\n }\n\n if (snapNotifications.length > 0) {\n snapNotificationIds = snapNotifications.map(\n (notification) => notification.id,\n );\n }\n } catch (error) {\n log.warn('Something failed when marking notifications as read', error);\n }\n\n // Update the state (state is also used on counter & badge)\n this.update((state) => {\n const currentReadList = state.metamaskNotificationsReadList;\n const newReadIds = [\n ...featureAnnouncementNotificationIds,\n ...snapNotificationIds,\n ];\n state.metamaskNotificationsReadList = [\n ...new Set([...currentReadList, ...newReadIds]),\n ];\n\n state.metamaskNotificationsList = state.metamaskNotificationsList.map(\n (notification: INotification) => {\n if (\n newReadIds.includes(notification.id) ||\n onchainNotificationIds.includes(notification.id)\n ) {\n if (notification.type === TRIGGER_TYPES.SNAP) {\n return {\n ...notification,\n isRead: true,\n readDate: new Date().toISOString(),\n };\n }\n return { ...notification, isRead: true };\n }\n return notification;\n },\n );\n });\n\n this.messenger.publish(\n `${controllerName}:markNotificationsAsRead`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Updates the list of MetaMask notifications by adding a new notification at the beginning of the list.\n * This method ensures that the most recent notification is displayed first in the UI.\n *\n * @param notification - The new notification object to be added to the list.\n * @returns A promise that resolves when the notification list has been successfully updated.\n */\n public async updateMetamaskNotificationsList(\n notification: INotification,\n ): Promise<void> {\n if (\n this.state.metamaskNotificationsList.some(\n (existingNotification) => existingNotification.id === notification.id,\n )\n ) {\n return;\n }\n\n const processedNotification = safeProcessNotification(notification);\n\n if (processedNotification) {\n this.update((state) => {\n const existingNotificationIds = new Set(\n state.metamaskNotificationsList.map(\n (existingNotification) => existingNotification.id,\n ),\n );\n // Add the new notification only if its ID is not already present in the list\n if (!existingNotificationIds.has(processedNotification.id)) {\n state.metamaskNotificationsList = [\n processedNotification,\n ...state.metamaskNotificationsList,\n ];\n }\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n\n /**\n * Creates an perp order notification subscription.\n * Requires notifications and auth to be enabled to start receiving this notifications\n *\n * @param input perp input\n */\n public async sendPerpPlaceOrderNotification(\n input: OrderInput,\n ): Promise<void> {\n try {\n const { bearerToken } = await this.#getBearerToken();\n await createPerpOrderNotification(bearerToken, input);\n } catch {\n // Do Nothing\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesController.d.cts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+DAA+D,EAC/D,+DAA+D,EAE/D,eAAe,EACf,kBAAkB,EACnB,6CAA6C;AAK9C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAK3D,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAE7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAKlF,OAAO,KAAK,EACV,kDAAkD,EAClD,wDAAwD,EACzD,wDAAuD;AACxD,OAAO,KAAK,EAAE,+CAA+C,EAAE,yGAAwG;AACvK,OAAO,EAAE,aAAa,EAAE,4CAA2C;AAEnE,OAAO,KAAK,EAAE,2CAA2C,EAAE,iEAAgE;AAK3H,OAAO,KAAK,EAAE,GAAG,EAAE,yCAAwC;AAS3D,OAAO,KAAK,EACV,aAAa,EACb,4BAA4B,EAC7B,8CAA6C;AAC9C,OA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;;;;OAMG;IACI,sBAAsB,CAAC,IAAI,EAAE,aAAa,GAAG,aAAa,EAAE;IAUnE;;;;;;;OAOG;IACU,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B9D;;;;;;;OAOG;IACU,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAWlE;;;;;OAKG;IACU,+BAA+B,CAC1C,aAAa,EAAE,4BAA4B,GAC1C,OAAO,CAAC,IAAI,CAAC;IA4GhB;;;;;;OAMG;IACU,+BAA+B,CAC1C,YAAY,EAAE,aAAa,GAC1B,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;;OAKG;IACU,8BAA8B,CACzC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,IAAI,CAAC;CAQjB"}
1
+ {"version":3,"file":"NotificationServicesController.d.cts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+DAA+D,EAC/D,+DAA+D,EAE/D,eAAe,EACf,kBAAkB,EACnB,6CAA6C;AAK9C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAK3D,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAE7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAKlF,OAAO,KAAK,EACV,kDAAkD,EAClD,wDAAwD,EACzD,wDAAuD;AACxD,OAAO,KAAK,EAAE,+CAA+C,EAAE,yGAAwG;AACvK,OAAO,EAAE,aAAa,EAAE,4CAA2C;AAEnE,OAAO,KAAK,EAAE,2CAA2C,EAAE,iEAAgE;AAK3H,OAAO,KAAK,EAAE,GAAG,EAAE,yCAAwC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YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,EAAE,CAAC;IA6F3B;;;;;;OAMG;IACI,sBAAsB,CAAC,IAAI,EAAE,aAAa,GAAG,aAAa,EAAE;IAUnE;;;;;;;OAOG;IACU,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B9D;;;;;;;OAOG;IACU,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAWlE;;;;;OAKG;IACU,+BAA+B,CAC1C,aAAa,EAAE,4BAA4B,GAC1C,OAAO,CAAC,IAAI,CAAC;IA4GhB;;;;;;OAMG;IACU,+BAA+B,CAC1C,YAAY,EAAE,aAAa,GAC1B,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;;OAKG;IACU,8BAA8B,CACzC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,IAAI,CAAC;CAQjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesController.d.mts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+DAA+D,EAC/D,+DAA+D,EAE/D,eAAe,EACf,kBAAkB,EACnB,6CAA6C;AAK9C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAK3D,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAE7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAKlF,OAAO,KAAK,EACV,kDAAkD,EAClD,wDAAwD,EACzD,wDAAuD;AACxD,OAAO,KAAK,EAAE,+CAA+C,EAAE,yGAAwG;AACvK,OAAO,EAAE,aAAa,EAAE,4CAA2C;AAEnE,OA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AM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB9D;;;;;;;;;OASG;IACU,mCAAmC,CAC9C,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,EAAE,CAAC;IAgG3B;;;;;;OAMG;IACI,sBAAsB,CAAC,IAAI,EAAE,aAAa,GAAG,aAAa,EAAE;IAUnE;;;;;;;OAOG;IACU,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B9D;;;;;;;OAOG;IACU,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAWlE;;;;;OAKG;IACU,+BAA+B,CAC1C,aAAa,EAAE,4BAA4B,GAC1C,OAAO,CAAC,IAAI,CAAC;IA4GhB;;;;;;OAMG;IACU,+BAA+B,CAC1C,YAAY,EAAE,aAAa,GAC1B,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;;OAKG;IACU,8BAA8B,CACzC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,IAAI,CAAC;CAQjB"}
1
+ {"version":3,"file":"NotificationServicesController.d.mts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+DAA+D,EAC/D,+DAA+D,EAE/D,eAAe,EACf,kBAAkB,EACnB,6CAA6C;AAK9C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAK3D,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAE7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,0CAA0C;AAKlF,OAAO,KAAK,EACV,kDAAkD,EAClD,wDAAwD,EACzD,wDAAuD;AACxD,OAAO,KAAK,EAAE,+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,CAAC;IAmB/D;;;;;;;;;;;;;;OAcG;IACU,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB9D;;;;;;;;;OASG;IACU,mCAAmC,CAC9C,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,EAAE,CAAC;IA6F3B;;;;;;OAMG;IACI,sBAAsB,CAAC,IAAI,EAAE,aAAa,GAAG,aAAa,EAAE;IAUnE;;;;;;;OAOG;IACU,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA6B9D;;;;;;;OAOG;IACU,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAWlE;;;;;OAKG;IACU,+BAA+B,CAC1C,aAAa,EAAE,4BAA4B,GAC1C,OAAO,CAAC,IAAI,CAAC;IA4GhB;;;;;;OAMG;IACU,+BAA+B,CAC1C,YAAY,EAAE,aAAa,GAC1B,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;;OAKG;IACU,8BAA8B,CACzC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,IAAI,CAAC;CAQjB"}
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _NotificationServicesController_instances, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_locale, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_env, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_enableAuth, _NotificationServicesController_getBearerToken, _NotificationServicesController_isWalletActivityPushEnabled, _NotificationServicesController_registerPushNotifications, _NotificationServicesController_setIsUpdatingMetamaskNotifications, _NotificationServicesController_setIsFetchingMetamaskNotifications, _NotificationServicesController_setIsCheckingAccountsPresence, _NotificationServicesController_updateUpdatingAccountsState, _NotificationServicesController_clearUpdatingAccountsState;
12
+ var _NotificationServicesController_instances, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_locale, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_env, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_enableAuth, _NotificationServicesController_getBearerToken, _NotificationServicesController_registerPushNotifications, _NotificationServicesController_setIsUpdatingMetamaskNotifications, _NotificationServicesController_setIsFetchingMetamaskNotifications, _NotificationServicesController_setIsCheckingAccountsPresence, _NotificationServicesController_updateUpdatingAccountsState, _NotificationServicesController_clearUpdatingAccountsState;
13
13
  function $importDefault(module) {
14
14
  if (module?.__esModule) {
15
15
  return module.default;
@@ -152,13 +152,14 @@ const getEnabledAccounts = async (bearerToken, accounts, env) => {
152
152
  };
153
153
  /**
154
154
  * Builds a fresh `NotificationPreferences` blob using hardcoded defaults for
155
- * Perps, Social AI, and Agentic CLI and the user's marketing/product-announcement
156
- * flags.
155
+ * Perps, Social AI, and Agentic CLI and the user's
156
+ * marketing/product-announcement flags.
157
157
  *
158
- * `walletActivity.accounts` is deliberately left empty. Addresses are scoped to a
159
- * keyring, but this blob is keyed by canonical profile ID, which pairing shares
160
- * across every SRP belonging to the same user so storing them here pools the
161
- * addresses of unrelated SRPs. Subscriptions live in the Trigger API instead.
158
+ * `walletActivity` is written only because the blob schema requires the field;
159
+ * nothing reads it back. Both channels are always on, and subscriptions are
160
+ * held per address by the Trigger API rather than here addresses are scoped
161
+ * to a keyring, but this blob is keyed by canonical profile ID, which pairing
162
+ * shares across every SRP belonging to the same user.
162
163
  *
163
164
  * @param hasMarketingConsent - Whether marketing push notifications should be enabled.
164
165
  * @param productAnnouncementEnabled - Whether marketing in-app notifications should be enabled.
@@ -470,10 +471,6 @@ export class NotificationServicesController extends BaseController {
470
471
  */
471
472
  async enablePushNotifications() {
472
473
  try {
473
- if (!(await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_isWalletActivityPushEnabled).call(this))) {
474
- await __classPrivateFieldGet(this, _NotificationServicesController_pushNotifications, "f").disablePushNotifications();
475
- return;
476
- }
477
474
  const { bearerToken } = await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_getBearerToken).call(this);
478
475
  const { accounts } = __classPrivateFieldGet(this, _NotificationServicesController_accounts, "f").listAccounts();
479
476
  const enabledAddresses = await getEnabledAccounts(bearerToken, accounts, __classPrivateFieldGet(this, _NotificationServicesController_env, "f"));
@@ -572,7 +569,6 @@ export class NotificationServicesController extends BaseController {
572
569
  const hasMarketingConsent = Boolean(opts?.hasMarketingConsent);
573
570
  const productAnnouncementEnabled = Boolean(opts?.productAnnouncementEnabled);
574
571
  const isFirstTimeSetup = preferences === null;
575
- const isPushEnabled = preferences?.walletActivity.pushNotificationsEnabled ?? true;
576
572
  // 2. Subscribe the keyring's accounts on first-time setup only.
577
573
  //
578
574
  // This method also runs on the daily re-subscribe, so the absence of a
@@ -607,7 +603,7 @@ export class NotificationServicesController extends BaseController {
607
603
  }
608
604
  if (opts.registerPushNotifications ?? true) {
609
605
  // Attempt FCM/device registration only; clients must request OS permission separately.
610
- __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_registerPushNotifications).call(this, isPushEnabled ? accountsWithNotifications : []).catch(() => {
606
+ __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_registerPushNotifications).call(this, accountsWithNotifications).catch(() => {
611
607
  // Do Nothing
612
608
  });
613
609
  }
@@ -769,9 +765,7 @@ export class NotificationServicesController extends BaseController {
769
765
  : [];
770
766
  // Raw On Chain Notifications
771
767
  const rawOnChainNotifications = [];
772
- const isWalletActivityInAppEnabled = notificationPreferences?.walletActivity.inAppNotificationsEnabled ??
773
- true;
774
- if (isGlobalNotifsEnabled && isWalletActivityInAppEnabled) {
768
+ if (isGlobalNotifsEnabled) {
775
769
  try {
776
770
  const { bearerToken } = await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_getBearerToken).call(this);
777
771
  // Addresses come from the keyring, so this installation can only ever
@@ -1005,27 +999,6 @@ _NotificationServicesController_keyringController = new WeakMap(), _Notification
1005
999
  throw new Error('Missing BearerToken');
1006
1000
  }
1007
1001
  return { bearerToken };
1008
- }, _NotificationServicesController_isWalletActivityPushEnabled =
1009
- /**
1010
- * Reads the global wallet-activity push toggle from
1011
- * {@link AuthenticatedUserStorageService}.
1012
- *
1013
- * Only the channel boolean is read. It is a user-level setting that contains
1014
- * no addresses, so sharing it across a paired profile is correct. The address
1015
- * list in the same blob is deliberately ignored — see
1016
- * {@link buildFreshPreferences}.
1017
- *
1018
- * A missing or unreadable blob counts as enabled, matching the API's "every
1019
- * toggle is on unless stated otherwise" default, so that a storage outage does
1020
- * not silently stop notifications.
1021
- *
1022
- * @returns Whether wallet-activity push notifications are enabled.
1023
- */
1024
- async function _NotificationServicesController_isWalletActivityPushEnabled() {
1025
- const preferences = await this.messenger
1026
- .call('AuthenticatedUserStorageService:getNotificationPreferences')
1027
- .catch(() => null);
1028
- return preferences?.walletActivity.pushNotificationsEnabled ?? true;
1029
1002
  }, _NotificationServicesController_registerPushNotifications =
1030
1003
  /**
1031
1004
  * Registers this device for push notifications on the given addresses.
@@ -1 +1 @@
1
- {"version":3,"file":"NotificationServicesController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAOA,OAAO,EACL,+BAA+B,EAC/B,+BAA+B,EAChC,6CAA6C;AAM9C,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACrB,mCAAmC;AA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{\n AuthenticatedUserStorageServiceGetNotificationPreferencesAction,\n AuthenticatedUserStorageServicePutNotificationPreferencesAction,\n NotificationPreferences,\n PerpsPreference,\n SocialAIPreference,\n} from '@metamask/authenticated-user-storage';\nimport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n isValidHexAddress,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerState,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport { debounce } from 'lodash';\nimport log from 'loglevel';\n\nimport type {\n NotificationServicesPushControllerStateChangeEvent,\n NotificationServicesPushControllerOnNewNotificationEvent,\n} from '../NotificationServicesPushController/index.js';\nimport type { NotificationServicesPushControllerMethodActions } from '../NotificationServicesPushController/NotificationServicesPushController-method-action-types.js';\nimport { TRIGGER_TYPES } from './constants/notification-schema.js';\nimport type { NormalisedAPINotification } from './index.js';\nimport type { NotificationServicesControllerMethodActions } from './NotificationServicesController-method-action-types.js';\nimport {\n processAndFilterNotifications,\n safeProcessNotification,\n} from './processors/process-notifications.js';\nimport type { ENV } from './services/api-notifications.js';\nimport {\n getAPINotifications,\n getNotificationsApiConfigCached,\n markNotificationsAsRead,\n updateOnChainNotifications,\n} from './services/api-notifications.js';\nimport { getFeatureAnnouncementNotifications } from './services/feature-announcements.js';\nimport { createPerpOrderNotification } from './services/perp-notifications.js';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n} from './types/notification/notification.js';\nimport type { OrderInput } from './types/perps/index.js';\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\nexport const ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS = 1000;\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visited through the\n * account subscription. This allows us to track and add notifications for new accounts and not previous accounts added.\n */\n subscriptionAccountsSeen: string[];\n\n /**\n * Flag that indicates if the metamask notifications feature has been seen\n */\n isMetamaskNotificationsFeatureSeen: boolean;\n\n /**\n * Flag that indicates if the metamask notifications are enabled\n */\n isNotificationServicesEnabled: boolean;\n\n /**\n * Flag that indicates if the feature announcements are enabled\n */\n isFeatureAnnouncementsEnabled: boolean;\n\n /**\n * List of metamask notifications\n */\n metamaskNotificationsList: INotification[];\n\n /**\n * List of read metamask notifications\n */\n metamaskNotificationsReadList: string[];\n /**\n * Flag that indicates that the creating notifications is in progress\n */\n isUpdatingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the fetching notifications is in progress\n * This is used to show a loading spinner in the UI\n * when fetching notifications\n */\n isFetchingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the updating notifications for a specific address is in progress\n */\n isUpdatingMetamaskNotificationsAccount: string[];\n /**\n * Flag that indicates that the checking accounts presence is in progress\n */\n isCheckingAccountsPresence: boolean;\n};\n\nconst metadata: StateMetadata<NotificationServicesControllerState> = {\n subscriptionAccountsSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isNotificationServicesEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFeatureAnnouncementsEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n metamaskNotificationsList: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n metamaskNotificationsReadList: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isUpdatingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFetchingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isUpdatingMetamaskNotificationsAccount: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isCheckingAccountsPresence: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\nexport const defaultState: NotificationServicesControllerState = {\n subscriptionAccountsSeen: [],\n isMetamaskNotificationsFeatureSeen: false,\n isNotificationServicesEnabled: false,\n isFeatureAnnouncementsEnabled: false,\n metamaskNotificationsList: [],\n metamaskNotificationsReadList: [],\n isUpdatingMetamaskNotifications: false,\n isFetchingMetamaskNotifications: false,\n isUpdatingMetamaskNotificationsAccount: [],\n isCheckingAccountsPresence: false,\n};\n\nexport type NotificationServicesControllerEnableNotificationsOptions = {\n /**\n * Whether the user has consented to marketing notifications. Used only when\n * notification preferences are being initialized for the first time to seed\n * marketing push notifications.\n */\n hasMarketingConsent?: boolean;\n /**\n * Whether product announcements are enabled. Used only when notification\n * preferences are being initialized for the first time to seed marketing\n * in-app notifications.\n */\n productAnnouncementEnabled?: boolean;\n /**\n * Whether to attempt FCM/device push registration after notification\n * preferences are initialized or refreshed. This does not request OS push\n * permission.\n *\n * @default true\n */\n registerPushNotifications?: boolean;\n};\n\nexport type NotificationServicesControllerCreateOnChainTriggersOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nexport type NotificationServicesControllerEnableMetamaskNotificationsOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\n/**\n * Hardcoded default Perps notification preferences. Applied when notification\n * preferences are initialized for the first time.\n */\nexport const DEFAULT_PERPS_PREFERENCES: PerpsPreference = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n};\n\n/**\n * Hardcoded default Social AI notification preferences. Applied when\n * notification preferences are initialized for the first time.\n */\nexport const DEFAULT_SOCIAL_AI_PREFERENCES: Required<SocialAIPreference> = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n txAmountLimit: 500,\n mutedTraderProfileIds: [],\n};\n\nexport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\n\n/**\n * Returns the subset of `accounts` that has a wallet-activity subscription in\n * the Trigger API, which is the source of truth for the per-address enabled bit.\n *\n * The address universe is always supplied by the caller from the keyring, so the\n * result cannot contain an address this installation does not hold.\n *\n * @param bearerToken - JWT used to query the Trigger API.\n * @param accounts - The keyring accounts to check.\n * @param env - The environment to use for the Trigger API call.\n * @returns The enabled addresses, as returned by the Trigger API, or `null` if\n * the Trigger API could not be read.\n */\nconst getEnabledAccounts = async (\n bearerToken: string,\n accounts: string[],\n env: ENV,\n): Promise<string[] | null> => {\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n env,\n );\n\n if (triggerConfig === null) {\n return null;\n }\n\n return triggerConfig\n .filter((addressConfig) => Boolean(addressConfig.enabled))\n .map((addressConfig) => addressConfig.address);\n};\n\n/**\n * Builds a fresh `NotificationPreferences` blob using hardcoded defaults for\n * Perps, Social AI, and Agentic CLI and the user's marketing/product-announcement\n * flags.\n *\n * `walletActivity.accounts` is deliberately left empty. Addresses are scoped to a\n * keyring, but this blob is keyed by canonical profile ID, which pairing shares\n * across every SRP belonging to the same user — so storing them here pools the\n * addresses of unrelated SRPs. Subscriptions live in the Trigger API instead.\n *\n * @param hasMarketingConsent - Whether marketing push notifications should be enabled.\n * @param productAnnouncementEnabled - Whether marketing in-app notifications should be enabled.\n * @returns A complete `NotificationPreferences` object.\n */\nconst buildFreshPreferences = (\n hasMarketingConsent: boolean,\n productAnnouncementEnabled: boolean,\n): NotificationPreferences => ({\n walletActivity: {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n accounts: [],\n },\n marketing: {\n inAppNotificationsEnabled: productAnnouncementEnabled,\n pushNotificationsEnabled: hasMarketingConsent,\n },\n perps: { ...DEFAULT_PERPS_PREFERENCES },\n socialAI: { ...DEFAULT_SOCIAL_AI_PREFERENCES },\n agenticCli: { ...DEFAULT_AGENTIC_CLI_PREFERENCES },\n priceAlerts: { ...DEFAULT_PRICE_ALERT_PREFERENCES },\n});\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'init',\n 'enablePushNotifications',\n 'disablePushNotifications',\n 'checkAccountsPresence',\n 'setFeatureAnnouncementsEnabled',\n 'createOnChainTriggers',\n 'enableMetamaskNotifications',\n 'disableNotificationServices',\n 'disableAccounts',\n 'enableAccounts',\n 'fetchAndUpdateMetamaskNotifications',\n 'getNotificationsByType',\n 'deleteNotificationById',\n 'deleteNotificationsById',\n 'markMetamaskNotificationsAsRead',\n 'updateMetamaskNotificationsList',\n 'sendPerpPlaceOrderNotification',\n] as const;\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerMethodActions;\n\n// Allowed Actions\ntype AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerIsSignedInAction\n | AuthenticationController.AuthenticationControllerPerformSignInAction\n // Authenticated User Storage Requests\n | AuthenticatedUserStorageServiceGetNotificationPreferencesAction\n | AuthenticatedUserStorageServicePutNotificationPreferencesAction\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerMethodActions;\n\n// Events\nexport type NotificationServicesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationListUpdatedEvent = {\n type: `${typeof controllerName}:notificationsListUpdated`;\n payload: [INotification[]];\n};\n\nexport type MarkNotificationsAsReadEvent = {\n type: `${typeof controllerName}:markNotificationsAsRead`;\n payload: [INotification[]];\n};\n\n// Events\nexport type Events =\n | NotificationServicesControllerStateChangeEvent\n | NotificationListUpdatedEvent\n | MarkNotificationsAsReadEvent;\n\n// Allowed Events\ntype AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerStateChangeEvent;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n platformVersion?: string;\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n readonly #keyringController = {\n isUnlocked: false,\n\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>): void => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#keyringController.isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', (): void => {\n this.#keyringController.isUnlocked = true;\n // messaging system cannot await promises\n // we don't need to wait for a result on this.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onUnlock();\n });\n\n this.messenger.subscribe('KeyringController:lock', (): void => {\n this.#keyringController.isUnlocked = false;\n });\n },\n };\n\n readonly #auth = {\n getBearerToken: async (): Promise<string | null> => {\n return await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: (): boolean => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async (): Promise<string[]> => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #pushNotifications = {\n // Flag to check is notifications have been setup when the browser/extension is initialized.\n // We want to re-initialize push notifications when the browser/extension is refreshed\n // To ensure we subscribe to the most up-to-date notifications\n isSetup: false,\n\n subscribeToPushNotifications: async (): Promise<void> => {\n await this.messenger.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:enablePushNotifications',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n addPushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:addPushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n disablePushNotifications: async (): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:disablePushNotifications',\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n deletePushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:deletePushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n subscribe: (): void => {\n // Coalesce pushes: at most one fetch in-flight, one queued.\n // Re-fetch after completion because the new row may not be visible yet when the push arrives.\n let pushFetchInFlight = false;\n let pendingPushRefetch = false;\n\n const fetchOnPush = async (): Promise<void> => {\n pushFetchInFlight = true;\n try {\n await this.fetchAndUpdateMetamaskNotifications();\n } finally {\n pushFetchInFlight = false;\n if (pendingPushRefetch) {\n pendingPushRefetch = false;\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n }\n }\n };\n\n this.messenger.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (): void => {\n if (pushFetchInFlight) {\n pendingPushRefetch = true;\n return;\n }\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n },\n );\n },\n initializePushNotifications: async (): Promise<void> => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#pushNotifications.isSetup) {\n return;\n }\n\n // If wallet is unlocked, we can create a fresh push subscription\n // Otherwise we can subscribe to original subscription\n try {\n if (!this.#keyringController.isUnlocked) {\n throw new Error('Keyring is locked');\n }\n await this.enablePushNotifications();\n this.#pushNotifications.isSetup = true;\n } catch {\n await this.#pushNotifications\n .subscribeToPushNotifications()\n .catch(() => {\n // do nothing\n });\n }\n },\n };\n\n readonly #accounts = {\n // Flag to ensure we only setup once\n isNotificationAccountsSetup: false,\n\n getNotificationAccounts: (): string[] | null => {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n const keyringAccounts = [\n ...new Set(\n keyrings\n .flatMap((keyring) => keyring.accounts)\n .map((address) => {\n try {\n return toChecksumHexAddress(address);\n } catch {\n return null;\n }\n })\n .filter(\n (address): address is string =>\n address !== null && isValidHexAddress(address),\n ),\n ),\n ];\n return keyringAccounts.length > 0 ? keyringAccounts : null;\n },\n\n /**\n * Used to get list of addresses from keyring (wallet addresses)\n *\n * @returns addresses removed, added, and latest list of addresses\n */\n listAccounts: (): {\n accountsAdded: string[];\n accountsRemoved: string[];\n accounts: string[];\n } => {\n // Get previous and current account sets\n const nonChecksumAccounts = this.#accounts.getNotificationAccounts();\n if (!nonChecksumAccounts) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n const accounts = nonChecksumAccounts\n .map((address) => toChecksumHexAddress(address))\n .filter((address) => isValidHexAddress(address));\n const currentAccountsSet = new Set(accounts);\n const prevAccountsSet = new Set(this.state.subscriptionAccountsSeen);\n\n // Invalid value you cannot have zero accounts\n // Only occurs when the Accounts controller is initializing.\n if (accounts.length === 0) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n // Calculate added and removed addresses\n const accountsAdded = accounts.filter(\n (account) => !prevAccountsSet.has(account),\n );\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (account) => !currentAccountsSet.has(account),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...currentAccountsSet];\n });\n\n return {\n accountsAdded,\n accountsRemoved,\n accounts,\n };\n },\n\n /**\n * Initializes the cache/previous list. This is handy so we have an accurate in-mem state of the previous list of accounts.\n */\n initialize: (): void => {\n if (\n this.#keyringController.isUnlocked &&\n !this.#accounts.isNotificationAccountsSetup\n ) {\n this.#accounts.listAccounts();\n this.#accounts.isNotificationAccountsSetup = true;\n }\n },\n\n /**\n * Subscription to any state change in the keyring controller (aka wallet accounts).\n * We can call the `listAccounts` defined above to find out about any accounts added, removed\n * And call effects to subscribe/unsubscribe to notifications.\n */\n subscribe: (): void => {\n const debouncedUpdateAccountNotifications = debounce(\n async (\n totalAccounts?: number,\n prevTotalAccounts?: number,\n ): Promise<void> => {\n const hasTotalAccountsChanged = totalAccounts !== prevTotalAccounts;\n if (\n !this.state.isNotificationServicesEnabled ||\n !hasTotalAccountsChanged\n ) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.enableAccounts(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.disableAccounts(accountsRemoved));\n }\n await Promise.allSettled(promises);\n },\n ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS,\n );\n\n this.messenger.subscribe(\n 'KeyringController:stateChange',\n // Using void return for async callback - result is intentionally ignored\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n debouncedUpdateAccountNotifications,\n (state: KeyringControllerState): number => {\n return (\n state?.keyrings?.flatMap?.((keyring) => keyring.accounts)?.length ??\n 0\n );\n },\n );\n },\n };\n\n readonly #locale: () => string;\n\n readonly #featureAnnouncementEnv: FeatureAnnouncementEnv;\n\n readonly #env: ENV;\n\n /**\n * Creates a NotificationServicesController instance.\n *\n * @param args - The arguments to this function.\n * @param args.messenger - Messenger used to communicate with BaseV2 controller.\n * @param args.state - Initial state to set on this controller.\n * @param args.env - environment variables for a given controller.\n * @param args.env.featureAnnouncements - env variables for feature announcements.\n * @param args.env.locale - users locale for better dynamic server notifications\n * @param args.env.env - the environment to use for the controller\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n locale?: () => string;\n env?: ENV;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#locale = env.locale ?? ((): string => 'en');\n this.#env = env.env ?? 'prd';\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.#clearLoadingStates();\n }\n\n init(): void {\n this.#keyringController.setupLockedStateSubscriptions(\n async (): Promise<void> => {\n this.#accounts.initialize();\n await this.#pushNotifications.initializePushNotifications();\n },\n );\n\n this.#accounts.initialize();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#pushNotifications.initializePushNotifications();\n this.#accounts.subscribe();\n this.#pushNotifications.subscribe();\n }\n\n #clearLoadingStates(): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = false;\n state.isCheckingAccountsPresence = false;\n state.isFetchingMetamaskNotifications = false;\n state.isUpdatingMetamaskNotificationsAccount = [];\n });\n }\n\n #assertAuthEnabled(): void {\n if (!this.#auth.isSignedIn()) {\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n });\n throw new Error('User is not signed in.');\n }\n }\n\n async #enableAuth(): Promise<void> {\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n async #getBearerToken(): Promise<{ bearerToken: string }> {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n\n if (!bearerToken) {\n throw new Error('Missing BearerToken');\n }\n\n return { bearerToken };\n }\n\n /**\n * Reads the global wallet-activity push toggle from\n * {@link AuthenticatedUserStorageService}.\n *\n * Only the channel boolean is read. It is a user-level setting that contains\n * no addresses, so sharing it across a paired profile is correct. The address\n * list in the same blob is deliberately ignored — see\n * {@link buildFreshPreferences}.\n *\n * A missing or unreadable blob counts as enabled, matching the API's \"every\n * toggle is on unless stated otherwise\" default, so that a storage outage does\n * not silently stop notifications.\n *\n * @returns Whether wallet-activity push notifications are enabled.\n */\n async #isWalletActivityPushEnabled(): Promise<boolean> {\n const preferences = await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch(() => null);\n\n return preferences?.walletActivity.pushNotificationsEnabled ?? true;\n }\n\n /**\n * Registers this device for push notifications on the given addresses.\n *\n * An empty list cannot be sent: the push API rejects a registration with no\n * addresses, and because that request is what performs the delete-and-reinsert\n * of the device's links, a rejection leaves the previous links in place and\n * push keeps arriving. So \"no addresses\" has to mean unregistering the device.\n *\n * @param addresses - The addresses to receive push notifications for.\n */\n async #registerPushNotifications(addresses: string[]): Promise<void> {\n if (addresses.length === 0) {\n await this.#pushNotifications.disablePushNotifications();\n return;\n }\n\n await this.#pushNotifications.enablePushNotifications(addresses);\n }\n\n /**\n * Sets the state of notification creation process.\n *\n * This method updates the `isUpdatingMetamaskNotifications` state, which can be used to indicate\n * whether the notification creation process is currently active or not. This is useful\n * for UI elements that need to reflect the state of ongoing operations, such as loading\n * indicators or disabled buttons during processing.\n *\n * @param isUpdatingMetamaskNotifications - A boolean value representing the new state of the notification creation process.\n */\n #setIsUpdatingMetamaskNotifications(\n isUpdatingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = isUpdatingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate whether fetching of MetaMask notifications is in progress.\n *\n * This method is used to set the `isFetchingMetamaskNotifications` state, which can be utilized\n * to show or hide loading indicators in the UI when notifications are being fetched.\n *\n * @param isFetchingMetamaskNotifications - A boolean value representing the fetching state.\n */\n #setIsFetchingMetamaskNotifications(\n isFetchingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isFetchingMetamaskNotifications = isFetchingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate that the checking of accounts presence is in progress.\n *\n * This method modifies the `isCheckingAccountsPresence` state, which can be used to manage UI elements\n * that depend on the status of account presence checks, such as displaying loading indicators or disabling\n * buttons while the check is ongoing.\n *\n * @param isCheckingAccountsPresence - A boolean value indicating whether the account presence check is currently active.\n */\n #setIsCheckingAccountsPresence(isCheckingAccountsPresence: boolean): void {\n this.update((state) => {\n state.isCheckingAccountsPresence = isCheckingAccountsPresence;\n });\n }\n\n /**\n * Updates the state to indicate that account updates are in progress.\n * Removes duplicate accounts before updating the state.\n *\n * @param accounts - The accounts being updated.\n */\n #updateUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n const uniqueAccounts = new Set([\n ...state.isUpdatingMetamaskNotificationsAccount,\n ...accounts,\n ]);\n state.isUpdatingMetamaskNotificationsAccount = Array.from(uniqueAccounts);\n });\n }\n\n /**\n * Clears the state indicating that account updates are complete.\n *\n * @param accounts - The accounts that have finished updating.\n */\n #clearUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n /**\n * Public method to expose enabling push notifications\n */\n public async enablePushNotifications(): Promise<void> {\n try {\n if (!(await this.#isWalletActivityPushEnabled())) {\n await this.#pushNotifications.disablePushNotifications();\n return;\n }\n\n const { bearerToken } = await this.#getBearerToken();\n const { accounts } = this.#accounts.listAccounts();\n const enabledAddresses = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (enabledAddresses === null) {\n // \"No addresses\" unregisters the device, so an unreadable subscription\n // list must not be treated as an empty one: leave the existing links\n // alone until we can read the real state.\n return;\n }\n\n await this.#registerPushNotifications(enabledAddresses);\n } catch {\n // Do nothing, failing silently.\n }\n }\n\n /**\n * Public method to expose disabling push notifications\n */\n public async disablePushNotifications(): Promise<void> {\n await this.#pushNotifications.disablePushNotifications();\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n const { bearerToken } = await this.#getBearerToken();\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (triggerConfig === null) {\n // Reporting every account as disabled would misrepresent the user's\n // settings, so surface the failure instead.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n const enabledByAddress = new Map(\n triggerConfig.map((addressConfig) => [\n addressConfig.address.toLowerCase(),\n Boolean(addressConfig.enabled),\n ]),\n );\n\n const result: Record<string, boolean> = {};\n for (const address of accounts) {\n result[address] = enabledByAddress.get(address.toLowerCase()) ?? false;\n }\n return result;\n } catch (error) {\n log.error('Failed to check accounts presence', error);\n throw error;\n } finally {\n this.#setIsCheckingAccountsPresence(false);\n }\n }\n\n /**\n * Sets the enabled state of feature announcements.\n *\n * **Action** - used in the notification settings to enable/disable feature announcements.\n *\n * @param featureAnnouncementsEnabled - A boolean value indicating the desired enabled state of the feature announcements.\n * @async\n * @throws {Error} If fails to update\n */\n public async setFeatureAnnouncementsEnabled(\n featureAnnouncementsEnabled: boolean,\n ): Promise<void> {\n try {\n this.update((state) => {\n state.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (error) {\n log.error('Unable to toggle feature announcements', error);\n throw new Error('Unable to toggle feature announcements');\n }\n }\n\n /**\n * This creates/re-creates on-chain triggers defined in User Storage.\n *\n * **Action** - Used during Sign In / Enabling of notifications.\n *\n * Notification preferences are initialized only when\n * {@link AuthenticatedUserStorageService} has no stored preferences yet.\n * Existing preferences are left as-is.\n *\n * @param opts - optional options to mutate this functionality\n * @param opts.hasMarketingConsent - The user's marketing-consent flag.\n * Used only during initialization to seed marketing push notifications.\n * @param opts.productAnnouncementEnabled - The user's product-announcement flag.\n * Used only during initialization to seed marketing in-app notifications.\n * @param opts.registerPushNotifications - Whether to attempt FCM/device push registration.\n * @returns The updated or newly created user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async createOnChainTriggers(\n opts: NotificationServicesControllerCreateOnChainTriggersOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const { bearerToken } = await this.#getBearerToken();\n\n const { accounts } = this.#accounts.listAccounts();\n\n // 1. Read existing AUS notification preferences. Their absence is what\n // marks a first-time setup, and they are initialized in step 3.\n const preferences = await this.messenger.call(\n 'AuthenticatedUserStorageService:getNotificationPreferences',\n );\n\n const hasMarketingConsent = Boolean(opts?.hasMarketingConsent);\n const productAnnouncementEnabled = Boolean(\n opts?.productAnnouncementEnabled,\n );\n\n const isFirstTimeSetup = preferences === null;\n\n const isPushEnabled =\n preferences?.walletActivity.pushNotificationsEnabled ?? true;\n\n // 2. Subscribe the keyring's accounts on first-time setup only.\n //\n // This method also runs on the daily re-subscribe, so the absence of a\n // preferences blob — not the absence of subscriptions — is what marks a\n // genuine first-time setup. Keying off \"no subscriptions\" would re-enable\n // every account daily for a user who had turned them all off.\n //\n // Even at first-time setup, existing subscriptions win: a user upgrading\n // from a client that never wrote a preferences blob keeps whichever\n // accounts they had already disabled.\n let accountsWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (accountsWithNotifications === null) {\n // An unreadable subscription list is not an empty one. Subscribing\n // every account here would re-enable ones the user had turned off, and\n // registering push for that guessed list would send activity for them,\n // so fail and let the caller retry.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n if (isFirstTimeSetup && accountsWithNotifications.length === 0) {\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n // Match the lower-case form the Trigger API echoes back, which is what\n // every other path feeding the push API uses.\n accountsWithNotifications = accounts.map((address) =>\n address.toLowerCase(),\n );\n }\n\n // 3. Initialize the preferences blob, only once the subscriptions above\n // are in place. Its existence is what makes the next run a re-subscribe\n // rather than a first-time setup, so writing it earlier would let a\n // failed subscribe leave the user enabled with no accounts subscribed\n // and no second chance to seed them.\n if (isFirstTimeSetup) {\n await this.messenger.call(\n 'AuthenticatedUserStorageService:putNotificationPreferences',\n buildFreshPreferences(\n hasMarketingConsent,\n productAnnouncementEnabled,\n ),\n this.#featureAnnouncementEnv.platform,\n );\n }\n\n if (opts.registerPushNotifications ?? true) {\n // Attempt FCM/device registration only; clients must request OS permission separately.\n this.#registerPushNotifications(\n isPushEnabled ? accountsWithNotifications : [],\n ).catch(() => {\n // Do Nothing\n });\n }\n\n // Update the state of the controller\n this.update((state) => {\n // User is re-subscribing (daily resub to get latest notifications)\n if (state.isNotificationServicesEnabled) {\n // Keep their existing preferences on re-subscribe\n // No state updates needed - preserving user's current settings\n } else {\n // User is turning on notifications from a disabled state\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n }\n });\n } catch (error) {\n log.error('Failed to create On Chain triggers', error);\n throw new Error('Failed to create On Chain triggers');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Enables all MetaMask notifications for the user.\n * This is identical flow when initializing notifications for the first time.\n *\n * @param opts - Optional options to mutate this functionality.\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications(\n opts: NotificationServicesControllerEnableMetamaskNotificationsOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n await this.#enableAuth();\n await this.createOnChainTriggers(opts);\n } catch (error) {\n log.error('Unable to enable notifications', error);\n throw new Error('Unable to enable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Disables all MetaMask notifications for the user.\n * This method ensures that the user is authenticated, retrieves all linked accounts,\n * and disables on-chain triggers for each account. It also sets the global notification\n * settings for MetaMask, feature announcements to false.\n *\n * @throws {Error} If the user is not authenticated or if there is an error during the process.\n */\n public async disableNotificationServices(): Promise<void> {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Attempt Disable Push Notifications\n try {\n await this.#pushNotifications.disablePushNotifications();\n } catch {\n // Do nothing\n }\n\n // Update State: remove non-permitted notifications & disable flags\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n state.isFeatureAnnouncementsEnabled = false;\n // reassigning the notifications list with just snaps\n // since the disable shouldn't affect snaps notifications\n state.metamaskNotificationsList = snapNotifications;\n });\n\n // Finish Updating State\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account/s.\n * This method performs several key operations:\n * 1. Validates Auth\n * 2. Deletes accounts\n * (note) We do not need to look through push notifications as we've deleted triggers\n *\n * **Action** - When a user disables notifications for a given account in settings.\n *\n * @param accounts - The account for which on-chain triggers are to be deleted.\n * @returns A promise that resolves to void or an object containing a success message.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async disableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n const { bearerToken } = await this.#getBearerToken();\n\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: false })),\n this.#env,\n );\n\n await this.#pushNotifications.deletePushNotificationLinks(accounts);\n } catch {\n throw new Error('Failed to delete OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Updates/Creates on-chain triggers for a specific account.\n *\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and creates any missing triggers associated with the account\n * 3. Enables any related push notifications\n * 4. Updates Storage to reflect new state.\n *\n * **Action** - When a user enables notifications for an account\n *\n * @param accounts - List of accounts you want to update.\n * @returns A promise that resolves to the updated user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async enableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n\n const { bearerToken } = await this.#getBearerToken();\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n\n await this.#pushNotifications.addPushNotificationLinks(accounts);\n } catch (error) {\n log.error('Failed to update OnChain triggers', error);\n throw new Error('Failed to update OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Fetches the list of metamask notifications.\n * This includes OnChain notifications; Feature Announcements; and Snap Notifications.\n *\n * **Action** - When a user views the notification list page/dropdown\n *\n * @param previewToken - the preview token to use if needed\n * @returns A promise that resolves to the list of notifications.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async fetchAndUpdateMetamaskNotifications(\n previewToken?: string,\n ): Promise<INotification[]> {\n try {\n this.#setIsFetchingMetamaskNotifications(true);\n\n // This is used by Feature Announcement & On Chain\n // Not used by Snaps\n const isGlobalNotifsEnabled = this.state.isNotificationServicesEnabled;\n const notificationPreferences = isGlobalNotifsEnabled\n ? await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch(() => null)\n : null;\n\n // Raw Feature Notifications\n const rawAnnouncements =\n isGlobalNotifsEnabled &&\n notificationPreferences?.marketing.inAppNotificationsEnabled\n ? await getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: NormalisedAPINotification[] = [];\n const isWalletActivityInAppEnabled =\n notificationPreferences?.walletActivity.inAppNotificationsEnabled ??\n true;\n if (isGlobalNotifsEnabled && isWalletActivityInAppEnabled) {\n try {\n const { bearerToken } = await this.#getBearerToken();\n // Addresses come from the keyring, so this installation can only ever\n // ask for activity on accounts it actually holds. The Trigger API\n // narrows that to the ones the user has enabled.\n const { accounts } = this.#accounts.listAccounts();\n const addressesWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n if (addressesWithNotifications !== null) {\n const notifications = await getAPINotifications(\n bearerToken,\n addressesWithNotifications,\n this.#locale(),\n this.#featureAnnouncementEnv.platform,\n this.#env,\n ).catch(() => []);\n rawOnChainNotifications.push(...notifications);\n }\n } catch {\n // Do nothing\n }\n }\n\n // Snap Notifications (original)\n // We do not want to remove them\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n const readIds = this.state.metamaskNotificationsReadList;\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...processAndFilterNotifications(rawAnnouncements, readIds),\n ...processAndFilterNotifications(rawOnChainNotifications, readIds),\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (notificationA, notificationB) =>\n new Date(notificationB.createdAt).getTime() -\n new Date(notificationA.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (error) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', error);\n throw new Error('Failed to fetch notifications');\n }\n }\n\n /**\n * Gets the specified type of notifications from state.\n *\n * @param type - The trigger type.\n * @returns An array of notifications of the passed in type.\n * @throws Throws an error if an invalid trigger type is passed.\n */\n public getNotificationsByType(type: TRIGGER_TYPES): INotification[] {\n assert(\n Object.values(TRIGGER_TYPES).includes(type),\n 'Invalid trigger type.',\n );\n return this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === type,\n );\n }\n\n /**\n * Used to delete a notification by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param id - The id of the notification to delete.\n */\n public async deleteNotificationById(id: string): Promise<void> {\n const fetchedNotification = this.state.metamaskNotificationsList.find(\n (notification) => notification.id === id,\n );\n\n assert(\n fetchedNotification,\n 'The notification to be deleted does not exist.',\n );\n\n assert(\n locallyPersistedNotificationTypes.has(fetchedNotification.type),\n `The notification type of \"${\n // notifications are guaranteed to have type properties which equate to strings\n fetchedNotification.type as string\n }\" is not locally persisted, only the following types can use this function: ${[\n ...locallyPersistedNotificationTypes,\n ].join(', ')}.`,\n );\n\n const newList = this.state.metamaskNotificationsList.filter(\n (notification) => notification.id !== id,\n );\n\n this.update((state) => {\n state.metamaskNotificationsList = newList;\n });\n }\n\n /**\n * Used to batch delete notifications by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param ids - The ids of the notifications to delete.\n */\n public async deleteNotificationsById(ids: string[]): Promise<void> {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Marks specified metamask notifications as read.\n *\n * @param notifications - An array of notifications to be marked as read. Each notification should include its type and read status.\n * @returns A promise that resolves when the operation is complete.\n */\n public async markMetamaskNotificationsAsRead(\n notifications: MarkAsReadNotificationsParam,\n ): Promise<void> {\n let onchainNotificationIds: string[] = [];\n let featureAnnouncementNotificationIds: string[] = [];\n let snapNotificationIds: string[] = [];\n\n try {\n const [\n onChainNotifications,\n featureAnnouncementNotifications,\n snapNotifications,\n ] = notifications.reduce<\n [\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n ]\n >(\n (allNotifications, notification) => {\n if (!notification.isRead) {\n switch (notification.type) {\n case TRIGGER_TYPES.FEATURES_ANNOUNCEMENT:\n allNotifications[1].push(notification);\n break;\n case TRIGGER_TYPES.SNAP:\n allNotifications[2].push(notification);\n break;\n default:\n allNotifications[0].push(notification);\n }\n }\n return allNotifications;\n },\n [[], [], []],\n );\n\n // Mark On-Chain Notifications as Read\n if (onChainNotifications.length > 0) {\n const bearerToken = await this.#auth.getBearerToken();\n\n if (bearerToken) {\n onchainNotificationIds = onChainNotifications.map(\n (notification) => notification.id,\n );\n await markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\n this.#env,\n ).catch(() => {\n onchainNotificationIds = [];\n log.warn('Unable to mark onchain notifications as read');\n });\n }\n }\n\n // Mark Off-Chain notifications as Read\n if (featureAnnouncementNotifications.length > 0) {\n featureAnnouncementNotificationIds =\n featureAnnouncementNotifications.map(\n (notification) => notification.id,\n );\n }\n\n if (snapNotifications.length > 0) {\n snapNotificationIds = snapNotifications.map(\n (notification) => notification.id,\n );\n }\n } catch (error) {\n log.warn('Something failed when marking notifications as read', error);\n }\n\n // Update the state (state is also used on counter & badge)\n this.update((state) => {\n const currentReadList = state.metamaskNotificationsReadList;\n const newReadIds = [\n ...featureAnnouncementNotificationIds,\n ...snapNotificationIds,\n ];\n state.metamaskNotificationsReadList = [\n ...new Set([...currentReadList, ...newReadIds]),\n ];\n\n state.metamaskNotificationsList = state.metamaskNotificationsList.map(\n (notification: INotification) => {\n if (\n newReadIds.includes(notification.id) ||\n onchainNotificationIds.includes(notification.id)\n ) {\n if (notification.type === TRIGGER_TYPES.SNAP) {\n return {\n ...notification,\n isRead: true,\n readDate: new Date().toISOString(),\n };\n }\n return { ...notification, isRead: true };\n }\n return notification;\n },\n );\n });\n\n this.messenger.publish(\n `${controllerName}:markNotificationsAsRead`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Updates the list of MetaMask notifications by adding a new notification at the beginning of the list.\n * This method ensures that the most recent notification is displayed first in the UI.\n *\n * @param notification - The new notification object to be added to the list.\n * @returns A promise that resolves when the notification list has been successfully updated.\n */\n public async updateMetamaskNotificationsList(\n notification: INotification,\n ): Promise<void> {\n if (\n this.state.metamaskNotificationsList.some(\n (existingNotification) => existingNotification.id === notification.id,\n )\n ) {\n return;\n }\n\n const processedNotification = safeProcessNotification(notification);\n\n if (processedNotification) {\n this.update((state) => {\n const existingNotificationIds = new Set(\n state.metamaskNotificationsList.map(\n (existingNotification) => existingNotification.id,\n ),\n );\n // Add the new notification only if its ID is not already present in the list\n if (!existingNotificationIds.has(processedNotification.id)) {\n state.metamaskNotificationsList = [\n processedNotification,\n ...state.metamaskNotificationsList,\n ];\n }\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n\n /**\n * Creates an perp order notification subscription.\n * Requires notifications and auth to be enabled to start receiving this notifications\n *\n * @param input perp input\n */\n public async sendPerpPlaceOrderNotification(\n input: OrderInput,\n ): Promise<void> {\n try {\n const { bearerToken } = await this.#getBearerToken();\n await createPerpOrderNotification(bearerToken, input);\n } catch {\n // Do Nothing\n }\n }\n}\n"]}
1
+ {"version":3,"file":"NotificationServicesController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAOA,OAAO,EACL,+BAA+B,EAC/B,+BAA+B,EAChC,6CAA6C;AAM9C,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACrB,mCAAmC;AAUpC,OAAO,EAAE,MAAM,EAAE,wBAAwB;;;AAEzC,OAAO,IAAG,iBAAiB;;AAO3B,OAAO,EAAE,aAAa,EAAE,4CAA2C;AAGnE,OAAO,EACL,6BAA6B,EAC7B,uBAAuB,EACxB,+CAA8C;AAE/C,OAAO,EACL,mBAAmB,EACnB,+BAA+B,EAC/B,uBAAuB,EACvB,0BAA0B,EAC3B,yCAAwC;AACzC,OAAO,EAAE,mCAAmC,EAAE,6CAA4C;AAC1F,OAAO,EAAE,2BAA2B,EAAE,0CAAyC;AAO/E,iCAAiC;AACjC,MAAM,cAAc,GAAG,gCAAgC,CAAC;AAExD,MAAM,CAAC,MAAM,gCAAgC,GAAG,IAA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K,CAAC,sCAAsC,CAAC,MAAM,CACjD,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,eAAe,CAAC,CACzD,CAAC;IACN,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n AuthenticatedUserStorageServiceGetNotificationPreferencesAction,\n AuthenticatedUserStorageServicePutNotificationPreferencesAction,\n NotificationPreferences,\n PerpsPreference,\n SocialAIPreference,\n} from '@metamask/authenticated-user-storage';\nimport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n isValidHexAddress,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type {\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerState,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport { debounce } from 'lodash';\nimport log from 'loglevel';\n\nimport type {\n NotificationServicesPushControllerStateChangeEvent,\n NotificationServicesPushControllerOnNewNotificationEvent,\n} from '../NotificationServicesPushController/index.js';\nimport type { NotificationServicesPushControllerMethodActions } from '../NotificationServicesPushController/NotificationServicesPushController-method-action-types.js';\nimport { TRIGGER_TYPES } from './constants/notification-schema.js';\nimport type { NormalisedAPINotification } from './index.js';\nimport type { NotificationServicesControllerMethodActions } from './NotificationServicesController-method-action-types.js';\nimport {\n processAndFilterNotifications,\n safeProcessNotification,\n} from './processors/process-notifications.js';\nimport type { ENV } from './services/api-notifications.js';\nimport {\n getAPINotifications,\n getNotificationsApiConfigCached,\n markNotificationsAsRead,\n updateOnChainNotifications,\n} from './services/api-notifications.js';\nimport { getFeatureAnnouncementNotifications } from './services/feature-announcements.js';\nimport { createPerpOrderNotification } from './services/perp-notifications.js';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n} from './types/notification/notification.js';\nimport type { OrderInput } from './types/perps/index.js';\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\nexport const ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS = 1000;\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visited through the\n * account subscription. This allows us to track and add notifications for new accounts and not previous accounts added.\n */\n subscriptionAccountsSeen: string[];\n\n /**\n * Flag that indicates if the metamask notifications feature has been seen\n */\n isMetamaskNotificationsFeatureSeen: boolean;\n\n /**\n * Flag that indicates if the metamask notifications are enabled\n */\n isNotificationServicesEnabled: boolean;\n\n /**\n * Flag that indicates if the feature announcements are enabled\n */\n isFeatureAnnouncementsEnabled: boolean;\n\n /**\n * List of metamask notifications\n */\n metamaskNotificationsList: INotification[];\n\n /**\n * List of read metamask notifications\n */\n metamaskNotificationsReadList: string[];\n /**\n * Flag that indicates that the creating notifications is in progress\n */\n isUpdatingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the fetching notifications is in progress\n * This is used to show a loading spinner in the UI\n * when fetching notifications\n */\n isFetchingMetamaskNotifications: boolean;\n /**\n * Flag that indicates that the updating notifications for a specific address is in progress\n */\n isUpdatingMetamaskNotificationsAccount: string[];\n /**\n * Flag that indicates that the checking accounts presence is in progress\n */\n isCheckingAccountsPresence: boolean;\n};\n\nconst metadata: StateMetadata<NotificationServicesControllerState> = {\n subscriptionAccountsSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isNotificationServicesEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFeatureAnnouncementsEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n metamaskNotificationsList: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n metamaskNotificationsReadList: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isUpdatingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isFetchingMetamaskNotifications: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isUpdatingMetamaskNotificationsAccount: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isCheckingAccountsPresence: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\nexport const defaultState: NotificationServicesControllerState = {\n subscriptionAccountsSeen: [],\n isMetamaskNotificationsFeatureSeen: false,\n isNotificationServicesEnabled: false,\n isFeatureAnnouncementsEnabled: false,\n metamaskNotificationsList: [],\n metamaskNotificationsReadList: [],\n isUpdatingMetamaskNotifications: false,\n isFetchingMetamaskNotifications: false,\n isUpdatingMetamaskNotificationsAccount: [],\n isCheckingAccountsPresence: false,\n};\n\nexport type NotificationServicesControllerEnableNotificationsOptions = {\n /**\n * Whether the user has consented to marketing notifications. Used only when\n * notification preferences are being initialized for the first time to seed\n * marketing push notifications.\n */\n hasMarketingConsent?: boolean;\n /**\n * Whether product announcements are enabled. Used only when notification\n * preferences are being initialized for the first time to seed marketing\n * in-app notifications.\n */\n productAnnouncementEnabled?: boolean;\n /**\n * Whether to attempt FCM/device push registration after notification\n * preferences are initialized or refreshed. This does not request OS push\n * permission.\n *\n * @default true\n */\n registerPushNotifications?: boolean;\n};\n\nexport type NotificationServicesControllerCreateOnChainTriggersOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nexport type NotificationServicesControllerEnableMetamaskNotificationsOptions =\n NotificationServicesControllerEnableNotificationsOptions;\n\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\n/**\n * Hardcoded default Perps notification preferences. Applied when notification\n * preferences are initialized for the first time.\n */\nexport const DEFAULT_PERPS_PREFERENCES: PerpsPreference = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n};\n\n/**\n * Hardcoded default Social AI notification preferences. Applied when\n * notification preferences are initialized for the first time.\n */\nexport const DEFAULT_SOCIAL_AI_PREFERENCES: Required<SocialAIPreference> = {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n txAmountLimit: 500,\n mutedTraderProfileIds: [],\n};\n\nexport {\n DEFAULT_AGENTIC_CLI_PREFERENCES,\n DEFAULT_PRICE_ALERT_PREFERENCES,\n} from '@metamask/authenticated-user-storage';\n\n/**\n * Returns the subset of `accounts` that has a wallet-activity subscription in\n * the Trigger API, which is the source of truth for the per-address enabled bit.\n *\n * The address universe is always supplied by the caller from the keyring, so the\n * result cannot contain an address this installation does not hold.\n *\n * @param bearerToken - JWT used to query the Trigger API.\n * @param accounts - The keyring accounts to check.\n * @param env - The environment to use for the Trigger API call.\n * @returns The enabled addresses, as returned by the Trigger API, or `null` if\n * the Trigger API could not be read.\n */\nconst getEnabledAccounts = async (\n bearerToken: string,\n accounts: string[],\n env: ENV,\n): Promise<string[] | null> => {\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n env,\n );\n\n if (triggerConfig === null) {\n return null;\n }\n\n return triggerConfig\n .filter((addressConfig) => Boolean(addressConfig.enabled))\n .map((addressConfig) => addressConfig.address);\n};\n\n/**\n * Builds a fresh `NotificationPreferences` blob using hardcoded defaults for\n * Perps, Social AI, and Agentic CLI and the user's\n * marketing/product-announcement flags.\n *\n * `walletActivity` is written only because the blob schema requires the field;\n * nothing reads it back. Both channels are always on, and subscriptions are\n * held per address by the Trigger API rather than here — addresses are scoped\n * to a keyring, but this blob is keyed by canonical profile ID, which pairing\n * shares across every SRP belonging to the same user.\n *\n * @param hasMarketingConsent - Whether marketing push notifications should be enabled.\n * @param productAnnouncementEnabled - Whether marketing in-app notifications should be enabled.\n * @returns A complete `NotificationPreferences` object.\n */\nconst buildFreshPreferences = (\n hasMarketingConsent: boolean,\n productAnnouncementEnabled: boolean,\n): NotificationPreferences => ({\n walletActivity: {\n inAppNotificationsEnabled: true,\n pushNotificationsEnabled: true,\n accounts: [],\n },\n marketing: {\n inAppNotificationsEnabled: productAnnouncementEnabled,\n pushNotificationsEnabled: hasMarketingConsent,\n },\n perps: { ...DEFAULT_PERPS_PREFERENCES },\n socialAI: { ...DEFAULT_SOCIAL_AI_PREFERENCES },\n agenticCli: { ...DEFAULT_AGENTIC_CLI_PREFERENCES },\n priceAlerts: { ...DEFAULT_PRICE_ALERT_PREFERENCES },\n});\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'init',\n 'enablePushNotifications',\n 'disablePushNotifications',\n 'checkAccountsPresence',\n 'setFeatureAnnouncementsEnabled',\n 'createOnChainTriggers',\n 'enableMetamaskNotifications',\n 'disableNotificationServices',\n 'disableAccounts',\n 'enableAccounts',\n 'fetchAndUpdateMetamaskNotifications',\n 'getNotificationsByType',\n 'deleteNotificationById',\n 'deleteNotificationsById',\n 'markMetamaskNotificationsAsRead',\n 'updateMetamaskNotificationsList',\n 'sendPerpPlaceOrderNotification',\n] as const;\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerMethodActions;\n\n// Allowed Actions\ntype AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerIsSignedInAction\n | AuthenticationController.AuthenticationControllerPerformSignInAction\n // Authenticated User Storage Requests\n | AuthenticatedUserStorageServiceGetNotificationPreferencesAction\n | AuthenticatedUserStorageServicePutNotificationPreferencesAction\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerMethodActions;\n\n// Events\nexport type NotificationServicesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationListUpdatedEvent = {\n type: `${typeof controllerName}:notificationsListUpdated`;\n payload: [INotification[]];\n};\n\nexport type MarkNotificationsAsReadEvent = {\n type: `${typeof controllerName}:markNotificationsAsRead`;\n payload: [INotification[]];\n};\n\n// Events\nexport type Events =\n | NotificationServicesControllerStateChangeEvent\n | NotificationListUpdatedEvent\n | MarkNotificationsAsReadEvent;\n\n// Allowed Events\ntype AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerStateChangeEvent;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n platformVersion?: string;\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n readonly #keyringController = {\n isUnlocked: false,\n\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>): void => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#keyringController.isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', (): void => {\n this.#keyringController.isUnlocked = true;\n // messaging system cannot await promises\n // we don't need to wait for a result on this.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n onUnlock();\n });\n\n this.messenger.subscribe('KeyringController:lock', (): void => {\n this.#keyringController.isUnlocked = false;\n });\n },\n };\n\n readonly #auth = {\n getBearerToken: async (): Promise<string | null> => {\n return await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: (): boolean => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async (): Promise<string[]> => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #pushNotifications = {\n // Flag to check is notifications have been setup when the browser/extension is initialized.\n // We want to re-initialize push notifications when the browser/extension is refreshed\n // To ensure we subscribe to the most up-to-date notifications\n isSetup: false,\n\n subscribeToPushNotifications: async (): Promise<void> => {\n await this.messenger.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:enablePushNotifications',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n addPushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:addPushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n disablePushNotifications: async (): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:disablePushNotifications',\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n deletePushNotificationLinks: async (addresses: string[]): Promise<void> => {\n try {\n await this.messenger.call(\n 'NotificationServicesPushController:deletePushNotificationLinks',\n addresses,\n );\n } catch {\n // Do nothing, failing silently.\n }\n },\n subscribe: (): void => {\n // Coalesce pushes: at most one fetch in-flight, one queued.\n // Re-fetch after completion because the new row may not be visible yet when the push arrives.\n let pushFetchInFlight = false;\n let pendingPushRefetch = false;\n\n const fetchOnPush = async (): Promise<void> => {\n pushFetchInFlight = true;\n try {\n await this.fetchAndUpdateMetamaskNotifications();\n } finally {\n pushFetchInFlight = false;\n if (pendingPushRefetch) {\n pendingPushRefetch = false;\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n }\n }\n };\n\n this.messenger.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (): void => {\n if (pushFetchInFlight) {\n pendingPushRefetch = true;\n return;\n }\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchOnPush();\n },\n );\n },\n initializePushNotifications: async (): Promise<void> => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#pushNotifications.isSetup) {\n return;\n }\n\n // If wallet is unlocked, we can create a fresh push subscription\n // Otherwise we can subscribe to original subscription\n try {\n if (!this.#keyringController.isUnlocked) {\n throw new Error('Keyring is locked');\n }\n await this.enablePushNotifications();\n this.#pushNotifications.isSetup = true;\n } catch {\n await this.#pushNotifications\n .subscribeToPushNotifications()\n .catch(() => {\n // do nothing\n });\n }\n },\n };\n\n readonly #accounts = {\n // Flag to ensure we only setup once\n isNotificationAccountsSetup: false,\n\n getNotificationAccounts: (): string[] | null => {\n const { keyrings } = this.messenger.call('KeyringController:getState');\n const keyringAccounts = [\n ...new Set(\n keyrings\n .flatMap((keyring) => keyring.accounts)\n .map((address) => {\n try {\n return toChecksumHexAddress(address);\n } catch {\n return null;\n }\n })\n .filter(\n (address): address is string =>\n address !== null && isValidHexAddress(address),\n ),\n ),\n ];\n return keyringAccounts.length > 0 ? keyringAccounts : null;\n },\n\n /**\n * Used to get list of addresses from keyring (wallet addresses)\n *\n * @returns addresses removed, added, and latest list of addresses\n */\n listAccounts: (): {\n accountsAdded: string[];\n accountsRemoved: string[];\n accounts: string[];\n } => {\n // Get previous and current account sets\n const nonChecksumAccounts = this.#accounts.getNotificationAccounts();\n if (!nonChecksumAccounts) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n const accounts = nonChecksumAccounts\n .map((address) => toChecksumHexAddress(address))\n .filter((address) => isValidHexAddress(address));\n const currentAccountsSet = new Set(accounts);\n const prevAccountsSet = new Set(this.state.subscriptionAccountsSeen);\n\n // Invalid value you cannot have zero accounts\n // Only occurs when the Accounts controller is initializing.\n if (accounts.length === 0) {\n return {\n accountsAdded: [],\n accountsRemoved: [],\n accounts: [],\n };\n }\n\n // Calculate added and removed addresses\n const accountsAdded = accounts.filter(\n (account) => !prevAccountsSet.has(account),\n );\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (account) => !currentAccountsSet.has(account),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...currentAccountsSet];\n });\n\n return {\n accountsAdded,\n accountsRemoved,\n accounts,\n };\n },\n\n /**\n * Initializes the cache/previous list. This is handy so we have an accurate in-mem state of the previous list of accounts.\n */\n initialize: (): void => {\n if (\n this.#keyringController.isUnlocked &&\n !this.#accounts.isNotificationAccountsSetup\n ) {\n this.#accounts.listAccounts();\n this.#accounts.isNotificationAccountsSetup = true;\n }\n },\n\n /**\n * Subscription to any state change in the keyring controller (aka wallet accounts).\n * We can call the `listAccounts` defined above to find out about any accounts added, removed\n * And call effects to subscribe/unsubscribe to notifications.\n */\n subscribe: (): void => {\n const debouncedUpdateAccountNotifications = debounce(\n async (\n totalAccounts?: number,\n prevTotalAccounts?: number,\n ): Promise<void> => {\n const hasTotalAccountsChanged = totalAccounts !== prevTotalAccounts;\n if (\n !this.state.isNotificationServicesEnabled ||\n !hasTotalAccountsChanged\n ) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.enableAccounts(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.disableAccounts(accountsRemoved));\n }\n await Promise.allSettled(promises);\n },\n ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS,\n );\n\n this.messenger.subscribe(\n 'KeyringController:stateChange',\n // Using void return for async callback - result is intentionally ignored\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n debouncedUpdateAccountNotifications,\n (state: KeyringControllerState): number => {\n return (\n state?.keyrings?.flatMap?.((keyring) => keyring.accounts)?.length ??\n 0\n );\n },\n );\n },\n };\n\n readonly #locale: () => string;\n\n readonly #featureAnnouncementEnv: FeatureAnnouncementEnv;\n\n readonly #env: ENV;\n\n /**\n * Creates a NotificationServicesController instance.\n *\n * @param args - The arguments to this function.\n * @param args.messenger - Messenger used to communicate with BaseV2 controller.\n * @param args.state - Initial state to set on this controller.\n * @param args.env - environment variables for a given controller.\n * @param args.env.featureAnnouncements - env variables for feature announcements.\n * @param args.env.locale - users locale for better dynamic server notifications\n * @param args.env.env - the environment to use for the controller\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n locale?: () => string;\n env?: ENV;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#locale = env.locale ?? ((): string => 'en');\n this.#env = env.env ?? 'prd';\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.#clearLoadingStates();\n }\n\n init(): void {\n this.#keyringController.setupLockedStateSubscriptions(\n async (): Promise<void> => {\n this.#accounts.initialize();\n await this.#pushNotifications.initializePushNotifications();\n },\n );\n\n this.#accounts.initialize();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#pushNotifications.initializePushNotifications();\n this.#accounts.subscribe();\n this.#pushNotifications.subscribe();\n }\n\n #clearLoadingStates(): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = false;\n state.isCheckingAccountsPresence = false;\n state.isFetchingMetamaskNotifications = false;\n state.isUpdatingMetamaskNotificationsAccount = [];\n });\n }\n\n #assertAuthEnabled(): void {\n if (!this.#auth.isSignedIn()) {\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n });\n throw new Error('User is not signed in.');\n }\n }\n\n async #enableAuth(): Promise<void> {\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n async #getBearerToken(): Promise<{ bearerToken: string }> {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n\n if (!bearerToken) {\n throw new Error('Missing BearerToken');\n }\n\n return { bearerToken };\n }\n\n /**\n * Registers this device for push notifications on the given addresses.\n *\n * An empty list cannot be sent: the push API rejects a registration with no\n * addresses, and because that request is what performs the delete-and-reinsert\n * of the device's links, a rejection leaves the previous links in place and\n * push keeps arriving. So \"no addresses\" has to mean unregistering the device.\n *\n * @param addresses - The addresses to receive push notifications for.\n */\n async #registerPushNotifications(addresses: string[]): Promise<void> {\n if (addresses.length === 0) {\n await this.#pushNotifications.disablePushNotifications();\n return;\n }\n\n await this.#pushNotifications.enablePushNotifications(addresses);\n }\n\n /**\n * Sets the state of notification creation process.\n *\n * This method updates the `isUpdatingMetamaskNotifications` state, which can be used to indicate\n * whether the notification creation process is currently active or not. This is useful\n * for UI elements that need to reflect the state of ongoing operations, such as loading\n * indicators or disabled buttons during processing.\n *\n * @param isUpdatingMetamaskNotifications - A boolean value representing the new state of the notification creation process.\n */\n #setIsUpdatingMetamaskNotifications(\n isUpdatingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotifications = isUpdatingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate whether fetching of MetaMask notifications is in progress.\n *\n * This method is used to set the `isFetchingMetamaskNotifications` state, which can be utilized\n * to show or hide loading indicators in the UI when notifications are being fetched.\n *\n * @param isFetchingMetamaskNotifications - A boolean value representing the fetching state.\n */\n #setIsFetchingMetamaskNotifications(\n isFetchingMetamaskNotifications: boolean,\n ): void {\n this.update((state) => {\n state.isFetchingMetamaskNotifications = isFetchingMetamaskNotifications;\n });\n }\n\n /**\n * Updates the state to indicate that the checking of accounts presence is in progress.\n *\n * This method modifies the `isCheckingAccountsPresence` state, which can be used to manage UI elements\n * that depend on the status of account presence checks, such as displaying loading indicators or disabling\n * buttons while the check is ongoing.\n *\n * @param isCheckingAccountsPresence - A boolean value indicating whether the account presence check is currently active.\n */\n #setIsCheckingAccountsPresence(isCheckingAccountsPresence: boolean): void {\n this.update((state) => {\n state.isCheckingAccountsPresence = isCheckingAccountsPresence;\n });\n }\n\n /**\n * Updates the state to indicate that account updates are in progress.\n * Removes duplicate accounts before updating the state.\n *\n * @param accounts - The accounts being updated.\n */\n #updateUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n const uniqueAccounts = new Set([\n ...state.isUpdatingMetamaskNotificationsAccount,\n ...accounts,\n ]);\n state.isUpdatingMetamaskNotificationsAccount = Array.from(uniqueAccounts);\n });\n }\n\n /**\n * Clears the state indicating that account updates are complete.\n *\n * @param accounts - The accounts that have finished updating.\n */\n #clearUpdatingAccountsState(accounts: string[]): void {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n /**\n * Public method to expose enabling push notifications\n */\n public async enablePushNotifications(): Promise<void> {\n try {\n const { bearerToken } = await this.#getBearerToken();\n const { accounts } = this.#accounts.listAccounts();\n const enabledAddresses = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (enabledAddresses === null) {\n // \"No addresses\" unregisters the device, so an unreadable subscription\n // list must not be treated as an empty one: leave the existing links\n // alone until we can read the real state.\n return;\n }\n\n await this.#registerPushNotifications(enabledAddresses);\n } catch {\n // Do nothing, failing silently.\n }\n }\n\n /**\n * Public method to expose disabling push notifications\n */\n public async disablePushNotifications(): Promise<void> {\n await this.#pushNotifications.disablePushNotifications();\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n const { bearerToken } = await this.#getBearerToken();\n const triggerConfig = await getNotificationsApiConfigCached(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (triggerConfig === null) {\n // Reporting every account as disabled would misrepresent the user's\n // settings, so surface the failure instead.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n const enabledByAddress = new Map(\n triggerConfig.map((addressConfig) => [\n addressConfig.address.toLowerCase(),\n Boolean(addressConfig.enabled),\n ]),\n );\n\n const result: Record<string, boolean> = {};\n for (const address of accounts) {\n result[address] = enabledByAddress.get(address.toLowerCase()) ?? false;\n }\n return result;\n } catch (error) {\n log.error('Failed to check accounts presence', error);\n throw error;\n } finally {\n this.#setIsCheckingAccountsPresence(false);\n }\n }\n\n /**\n * Sets the enabled state of feature announcements.\n *\n * **Action** - used in the notification settings to enable/disable feature announcements.\n *\n * @param featureAnnouncementsEnabled - A boolean value indicating the desired enabled state of the feature announcements.\n * @async\n * @throws {Error} If fails to update\n */\n public async setFeatureAnnouncementsEnabled(\n featureAnnouncementsEnabled: boolean,\n ): Promise<void> {\n try {\n this.update((state) => {\n state.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (error) {\n log.error('Unable to toggle feature announcements', error);\n throw new Error('Unable to toggle feature announcements');\n }\n }\n\n /**\n * This creates/re-creates on-chain triggers defined in User Storage.\n *\n * **Action** - Used during Sign In / Enabling of notifications.\n *\n * Notification preferences are initialized only when\n * {@link AuthenticatedUserStorageService} has no stored preferences yet.\n * Existing preferences are left as-is.\n *\n * @param opts - optional options to mutate this functionality\n * @param opts.hasMarketingConsent - The user's marketing-consent flag.\n * Used only during initialization to seed marketing push notifications.\n * @param opts.productAnnouncementEnabled - The user's product-announcement flag.\n * Used only during initialization to seed marketing in-app notifications.\n * @param opts.registerPushNotifications - Whether to attempt FCM/device push registration.\n * @returns The updated or newly created user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async createOnChainTriggers(\n opts: NotificationServicesControllerCreateOnChainTriggersOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const { bearerToken } = await this.#getBearerToken();\n\n const { accounts } = this.#accounts.listAccounts();\n\n // 1. Read existing AUS notification preferences. Their absence is what\n // marks a first-time setup, and they are initialized in step 3.\n const preferences = await this.messenger.call(\n 'AuthenticatedUserStorageService:getNotificationPreferences',\n );\n\n const hasMarketingConsent = Boolean(opts?.hasMarketingConsent);\n const productAnnouncementEnabled = Boolean(\n opts?.productAnnouncementEnabled,\n );\n\n const isFirstTimeSetup = preferences === null;\n\n // 2. Subscribe the keyring's accounts on first-time setup only.\n //\n // This method also runs on the daily re-subscribe, so the absence of a\n // preferences blob — not the absence of subscriptions — is what marks a\n // genuine first-time setup. Keying off \"no subscriptions\" would re-enable\n // every account daily for a user who had turned them all off.\n //\n // Even at first-time setup, existing subscriptions win: a user upgrading\n // from a client that never wrote a preferences blob keeps whichever\n // accounts they had already disabled.\n let accountsWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n\n if (accountsWithNotifications === null) {\n // An unreadable subscription list is not an empty one. Subscribing\n // every account here would re-enable ones the user had turned off, and\n // registering push for that guessed list would send activity for them,\n // so fail and let the caller retry.\n throw new Error('Failed to read wallet-activity subscriptions');\n }\n\n if (isFirstTimeSetup && accountsWithNotifications.length === 0) {\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n // Match the lower-case form the Trigger API echoes back, which is what\n // every other path feeding the push API uses.\n accountsWithNotifications = accounts.map((address) =>\n address.toLowerCase(),\n );\n }\n\n // 3. Initialize the preferences blob, only once the subscriptions above\n // are in place. Its existence is what makes the next run a re-subscribe\n // rather than a first-time setup, so writing it earlier would let a\n // failed subscribe leave the user enabled with no accounts subscribed\n // and no second chance to seed them.\n if (isFirstTimeSetup) {\n await this.messenger.call(\n 'AuthenticatedUserStorageService:putNotificationPreferences',\n buildFreshPreferences(\n hasMarketingConsent,\n productAnnouncementEnabled,\n ),\n this.#featureAnnouncementEnv.platform,\n );\n }\n\n if (opts.registerPushNotifications ?? true) {\n // Attempt FCM/device registration only; clients must request OS permission separately.\n this.#registerPushNotifications(accountsWithNotifications).catch(() => {\n // Do Nothing\n });\n }\n\n // Update the state of the controller\n this.update((state) => {\n // User is re-subscribing (daily resub to get latest notifications)\n if (state.isNotificationServicesEnabled) {\n // Keep their existing preferences on re-subscribe\n // No state updates needed - preserving user's current settings\n } else {\n // User is turning on notifications from a disabled state\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n }\n });\n } catch (error) {\n log.error('Failed to create On Chain triggers', error);\n throw new Error('Failed to create On Chain triggers');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Enables all MetaMask notifications for the user.\n * This is identical flow when initializing notifications for the first time.\n *\n * @param opts - Optional options to mutate this functionality.\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications(\n opts: NotificationServicesControllerEnableMetamaskNotificationsOptions = {},\n ): Promise<void> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n await this.#enableAuth();\n await this.createOnChainTriggers(opts);\n } catch (error) {\n log.error('Unable to enable notifications', error);\n throw new Error('Unable to enable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Disables all MetaMask notifications for the user.\n * This method ensures that the user is authenticated, retrieves all linked accounts,\n * and disables on-chain triggers for each account. It also sets the global notification\n * settings for MetaMask, feature announcements to false.\n *\n * @throws {Error} If the user is not authenticated or if there is an error during the process.\n */\n public async disableNotificationServices(): Promise<void> {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Attempt Disable Push Notifications\n try {\n await this.#pushNotifications.disablePushNotifications();\n } catch {\n // Do nothing\n }\n\n // Update State: remove non-permitted notifications & disable flags\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n this.update((state) => {\n state.isNotificationServicesEnabled = false;\n state.isFeatureAnnouncementsEnabled = false;\n // reassigning the notifications list with just snaps\n // since the disable shouldn't affect snaps notifications\n state.metamaskNotificationsList = snapNotifications;\n });\n\n // Finish Updating State\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account/s.\n * This method performs several key operations:\n * 1. Validates Auth\n * 2. Deletes accounts\n * (note) We do not need to look through push notifications as we've deleted triggers\n *\n * **Action** - When a user disables notifications for a given account in settings.\n *\n * @param accounts - The account for which on-chain triggers are to be deleted.\n * @returns A promise that resolves to void or an object containing a success message.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async disableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n const { bearerToken } = await this.#getBearerToken();\n\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: false })),\n this.#env,\n );\n\n await this.#pushNotifications.deletePushNotificationLinks(accounts);\n } catch {\n throw new Error('Failed to delete OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Updates/Creates on-chain triggers for a specific account.\n *\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and creates any missing triggers associated with the account\n * 3. Enables any related push notifications\n * 4. Updates Storage to reflect new state.\n *\n * **Action** - When a user enables notifications for an account\n *\n * @param accounts - List of accounts you want to update.\n * @returns A promise that resolves to the updated user storage.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async enableAccounts(accounts: string[]): Promise<void> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n\n const { bearerToken } = await this.#getBearerToken();\n await updateOnChainNotifications(\n bearerToken,\n accounts.map((address) => ({ address, enabled: true })),\n this.#env,\n );\n\n await this.#pushNotifications.addPushNotificationLinks(accounts);\n } catch (error) {\n log.error('Failed to update OnChain triggers', error);\n throw new Error('Failed to update OnChain triggers');\n } finally {\n this.#clearUpdatingAccountsState(accounts);\n }\n }\n\n /**\n * Fetches the list of metamask notifications.\n * This includes OnChain notifications; Feature Announcements; and Snap Notifications.\n *\n * **Action** - When a user views the notification list page/dropdown\n *\n * @param previewToken - the preview token to use if needed\n * @returns A promise that resolves to the list of notifications.\n * @throws {Error} Throws an error if unauthenticated or from other operations.\n */\n public async fetchAndUpdateMetamaskNotifications(\n previewToken?: string,\n ): Promise<INotification[]> {\n try {\n this.#setIsFetchingMetamaskNotifications(true);\n\n // This is used by Feature Announcement & On Chain\n // Not used by Snaps\n const isGlobalNotifsEnabled = this.state.isNotificationServicesEnabled;\n const notificationPreferences = isGlobalNotifsEnabled\n ? await this.messenger\n .call('AuthenticatedUserStorageService:getNotificationPreferences')\n .catch(() => null)\n : null;\n\n // Raw Feature Notifications\n const rawAnnouncements =\n isGlobalNotifsEnabled &&\n notificationPreferences?.marketing.inAppNotificationsEnabled\n ? await getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: NormalisedAPINotification[] = [];\n if (isGlobalNotifsEnabled) {\n try {\n const { bearerToken } = await this.#getBearerToken();\n // Addresses come from the keyring, so this installation can only ever\n // ask for activity on accounts it actually holds. The Trigger API\n // narrows that to the ones the user has enabled.\n const { accounts } = this.#accounts.listAccounts();\n const addressesWithNotifications = await getEnabledAccounts(\n bearerToken,\n accounts,\n this.#env,\n );\n if (addressesWithNotifications !== null) {\n const notifications = await getAPINotifications(\n bearerToken,\n addressesWithNotifications,\n this.#locale(),\n this.#featureAnnouncementEnv.platform,\n this.#env,\n ).catch(() => []);\n rawOnChainNotifications.push(...notifications);\n }\n } catch {\n // Do nothing\n }\n }\n\n // Snap Notifications (original)\n // We do not want to remove them\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n const readIds = this.state.metamaskNotificationsReadList;\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...processAndFilterNotifications(rawAnnouncements, readIds),\n ...processAndFilterNotifications(rawOnChainNotifications, readIds),\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (notificationA, notificationB) =>\n new Date(notificationB.createdAt).getTime() -\n new Date(notificationA.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (error) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', error);\n throw new Error('Failed to fetch notifications');\n }\n }\n\n /**\n * Gets the specified type of notifications from state.\n *\n * @param type - The trigger type.\n * @returns An array of notifications of the passed in type.\n * @throws Throws an error if an invalid trigger type is passed.\n */\n public getNotificationsByType(type: TRIGGER_TYPES): INotification[] {\n assert(\n Object.values(TRIGGER_TYPES).includes(type),\n 'Invalid trigger type.',\n );\n return this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === type,\n );\n }\n\n /**\n * Used to delete a notification by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param id - The id of the notification to delete.\n */\n public async deleteNotificationById(id: string): Promise<void> {\n const fetchedNotification = this.state.metamaskNotificationsList.find(\n (notification) => notification.id === id,\n );\n\n assert(\n fetchedNotification,\n 'The notification to be deleted does not exist.',\n );\n\n assert(\n locallyPersistedNotificationTypes.has(fetchedNotification.type),\n `The notification type of \"${\n // notifications are guaranteed to have type properties which equate to strings\n fetchedNotification.type as string\n }\" is not locally persisted, only the following types can use this function: ${[\n ...locallyPersistedNotificationTypes,\n ].join(', ')}.`,\n );\n\n const newList = this.state.metamaskNotificationsList.filter(\n (notification) => notification.id !== id,\n );\n\n this.update((state) => {\n state.metamaskNotificationsList = newList;\n });\n }\n\n /**\n * Used to batch delete notifications by id.\n *\n * Note: This function should only be used for notifications that are stored\n * in this controller directly, currently only snaps notifications.\n *\n * @param ids - The ids of the notifications to delete.\n */\n public async deleteNotificationsById(ids: string[]): Promise<void> {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Marks specified metamask notifications as read.\n *\n * @param notifications - An array of notifications to be marked as read. Each notification should include its type and read status.\n * @returns A promise that resolves when the operation is complete.\n */\n public async markMetamaskNotificationsAsRead(\n notifications: MarkAsReadNotificationsParam,\n ): Promise<void> {\n let onchainNotificationIds: string[] = [];\n let featureAnnouncementNotificationIds: string[] = [];\n let snapNotificationIds: string[] = [];\n\n try {\n const [\n onChainNotifications,\n featureAnnouncementNotifications,\n snapNotifications,\n ] = notifications.reduce<\n [\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n MarkAsReadNotificationsParam,\n ]\n >(\n (allNotifications, notification) => {\n if (!notification.isRead) {\n switch (notification.type) {\n case TRIGGER_TYPES.FEATURES_ANNOUNCEMENT:\n allNotifications[1].push(notification);\n break;\n case TRIGGER_TYPES.SNAP:\n allNotifications[2].push(notification);\n break;\n default:\n allNotifications[0].push(notification);\n }\n }\n return allNotifications;\n },\n [[], [], []],\n );\n\n // Mark On-Chain Notifications as Read\n if (onChainNotifications.length > 0) {\n const bearerToken = await this.#auth.getBearerToken();\n\n if (bearerToken) {\n onchainNotificationIds = onChainNotifications.map(\n (notification) => notification.id,\n );\n await markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\n this.#env,\n ).catch(() => {\n onchainNotificationIds = [];\n log.warn('Unable to mark onchain notifications as read');\n });\n }\n }\n\n // Mark Off-Chain notifications as Read\n if (featureAnnouncementNotifications.length > 0) {\n featureAnnouncementNotificationIds =\n featureAnnouncementNotifications.map(\n (notification) => notification.id,\n );\n }\n\n if (snapNotifications.length > 0) {\n snapNotificationIds = snapNotifications.map(\n (notification) => notification.id,\n );\n }\n } catch (error) {\n log.warn('Something failed when marking notifications as read', error);\n }\n\n // Update the state (state is also used on counter & badge)\n this.update((state) => {\n const currentReadList = state.metamaskNotificationsReadList;\n const newReadIds = [\n ...featureAnnouncementNotificationIds,\n ...snapNotificationIds,\n ];\n state.metamaskNotificationsReadList = [\n ...new Set([...currentReadList, ...newReadIds]),\n ];\n\n state.metamaskNotificationsList = state.metamaskNotificationsList.map(\n (notification: INotification) => {\n if (\n newReadIds.includes(notification.id) ||\n onchainNotificationIds.includes(notification.id)\n ) {\n if (notification.type === TRIGGER_TYPES.SNAP) {\n return {\n ...notification,\n isRead: true,\n readDate: new Date().toISOString(),\n };\n }\n return { ...notification, isRead: true };\n }\n return notification;\n },\n );\n });\n\n this.messenger.publish(\n `${controllerName}:markNotificationsAsRead`,\n this.state.metamaskNotificationsList,\n );\n }\n\n /**\n * Updates the list of MetaMask notifications by adding a new notification at the beginning of the list.\n * This method ensures that the most recent notification is displayed first in the UI.\n *\n * @param notification - The new notification object to be added to the list.\n * @returns A promise that resolves when the notification list has been successfully updated.\n */\n public async updateMetamaskNotificationsList(\n notification: INotification,\n ): Promise<void> {\n if (\n this.state.metamaskNotificationsList.some(\n (existingNotification) => existingNotification.id === notification.id,\n )\n ) {\n return;\n }\n\n const processedNotification = safeProcessNotification(notification);\n\n if (processedNotification) {\n this.update((state) => {\n const existingNotificationIds = new Set(\n state.metamaskNotificationsList.map(\n (existingNotification) => existingNotification.id,\n ),\n );\n // Add the new notification only if its ID is not already present in the list\n if (!existingNotificationIds.has(processedNotification.id)) {\n state.metamaskNotificationsList = [\n processedNotification,\n ...state.metamaskNotificationsList,\n ];\n }\n });\n\n this.messenger.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n\n /**\n * Creates an perp order notification subscription.\n * Requires notifications and auth to be enabled to start receiving this notifications\n *\n * @param input perp input\n */\n public async sendPerpPlaceOrderNotification(\n input: OrderInput,\n ): Promise<void> {\n try {\n const { bearerToken } = await this.#getBearerToken();\n await createPerpOrderNotification(bearerToken, input);\n } catch {\n // Do Nothing\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/notification-services-controller",
3
- "version": "27.0.0-preview-6fd51644c",
3
+ "version": "27.0.1-preview-d8fceeabc",
4
4
  "description": "Manages New MetaMask decentralized Notification system",
5
5
  "keywords": [
6
6
  "Ethereum",