@metamask-previews/notification-services-controller 0.18.0-preview-0d0d258d → 0.18.0-preview-aec8dc46
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/dist/NotificationServicesController/NotificationServicesController.cjs +12 -19
- package/dist/NotificationServicesController/NotificationServicesController.cjs.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.cts +2 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.cts.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.mts +2 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.mts.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.mjs +12 -19
- package/dist/NotificationServicesController/NotificationServicesController.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -36,7 +36,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
36
36
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
37
37
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
38
38
|
};
|
|
39
|
-
var _NotificationServicesController_instances, _NotificationServicesController_isPushIntegrated, _NotificationServicesController_isPushNotificationsSetup, _NotificationServicesController_isUnlocked, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_storage, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_registerMessageHandlers, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_getValidStorageKeyAndBearerToken,
|
|
39
|
+
var _NotificationServicesController_instances, _NotificationServicesController_isPushIntegrated, _NotificationServicesController_isPushNotificationsSetup, _NotificationServicesController_isUnlocked, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_storage, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_registerMessageHandlers, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_getValidStorageKeyAndBearerToken, _NotificationServicesController_assertUserStorage, _NotificationServicesController_getUserStorage, _NotificationServicesController_setIsUpdatingMetamaskNotifications, _NotificationServicesController_setIsFetchingMetamaskNotifications, _NotificationServicesController_setIsCheckingAccountsPresence, _NotificationServicesController_updateUpdatingAccountsState, _NotificationServicesController_clearUpdatingAccountsState;
|
|
40
40
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
41
41
|
exports.defaultState = void 0;
|
|
42
42
|
const base_controller_1 = require("@metamask/base-controller");
|
|
@@ -160,11 +160,11 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
160
160
|
isSignedIn: () => {
|
|
161
161
|
return this.messagingSystem.call('AuthenticationController:isSignedIn');
|
|
162
162
|
},
|
|
163
|
+
signIn: async () => {
|
|
164
|
+
return await this.messagingSystem.call('AuthenticationController:performSignIn');
|
|
165
|
+
},
|
|
163
166
|
});
|
|
164
167
|
_NotificationServicesController_storage.set(this, {
|
|
165
|
-
enableProfileSyncing: async () => {
|
|
166
|
-
return await this.messagingSystem.call('UserStorageController:enableProfileSyncing');
|
|
167
|
-
},
|
|
168
168
|
getStorageKey: () => {
|
|
169
169
|
return this.messagingSystem.call('UserStorageController:getStorageKey');
|
|
170
170
|
},
|
|
@@ -295,9 +295,7 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
295
295
|
* And call effects to subscribe/unsubscribe to notifications.
|
|
296
296
|
*/
|
|
297
297
|
subscribe: () => {
|
|
298
|
-
this.messagingSystem.subscribe('KeyringController:stateChange',
|
|
299
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
300
|
-
async () => {
|
|
298
|
+
this.messagingSystem.subscribe('KeyringController:stateChange', async () => {
|
|
301
299
|
if (!this.state.isNotificationServicesEnabled) {
|
|
302
300
|
return;
|
|
303
301
|
}
|
|
@@ -314,15 +312,6 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
314
312
|
},
|
|
315
313
|
});
|
|
316
314
|
_NotificationServicesController_featureAnnouncementEnv.set(this, void 0);
|
|
317
|
-
_NotificationServicesController_performEnableProfileSyncing.set(this, async () => {
|
|
318
|
-
try {
|
|
319
|
-
await __classPrivateFieldGet(this, _NotificationServicesController_storage, "f").enableProfileSyncing();
|
|
320
|
-
}
|
|
321
|
-
catch (e) {
|
|
322
|
-
loglevel_1.default.error('Failed to enable profile syncing', e);
|
|
323
|
-
throw new Error('Failed to enable profile syncing');
|
|
324
|
-
}
|
|
325
|
-
});
|
|
326
315
|
__classPrivateFieldSet(this, _NotificationServicesController_isPushIntegrated, env.isPushIntegrated ?? true, "f");
|
|
327
316
|
__classPrivateFieldSet(this, _NotificationServicesController_featureAnnouncementEnv, env.featureAnnouncements, "f");
|
|
328
317
|
__classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_registerMessageHandlers).call(this);
|
|
@@ -397,7 +386,6 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
397
386
|
async createOnChainTriggers(opts) {
|
|
398
387
|
try {
|
|
399
388
|
__classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_setIsUpdatingMetamaskNotifications).call(this, true);
|
|
400
|
-
await __classPrivateFieldGet(this, _NotificationServicesController_performEnableProfileSyncing, "f").call(this);
|
|
401
389
|
const { bearerToken, storageKey } = await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_getValidStorageKeyAndBearerToken).call(this);
|
|
402
390
|
const { accounts } = await __classPrivateFieldGet(this, _NotificationServicesController_accounts, "f").listAccounts();
|
|
403
391
|
// Attempt Get User Storage
|
|
@@ -451,6 +439,10 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
451
439
|
async enableMetamaskNotifications() {
|
|
452
440
|
try {
|
|
453
441
|
__classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_setIsUpdatingMetamaskNotifications).call(this, true);
|
|
442
|
+
const isSignedIn = __classPrivateFieldGet(this, _NotificationServicesController_auth, "f").isSignedIn();
|
|
443
|
+
if (!isSignedIn) {
|
|
444
|
+
await __classPrivateFieldGet(this, _NotificationServicesController_auth, "f").signIn();
|
|
445
|
+
}
|
|
454
446
|
await this.createOnChainTriggers();
|
|
455
447
|
}
|
|
456
448
|
catch (e) {
|
|
@@ -610,6 +602,7 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
610
602
|
* **Action** - When a user views the notification list page/dropdown
|
|
611
603
|
*
|
|
612
604
|
* @param previewToken - the preview token to use if needed
|
|
605
|
+
* @returns A promise that resolves to the list of notifications.
|
|
613
606
|
* @throws {Error} Throws an error if unauthenticated or from other operations.
|
|
614
607
|
*/
|
|
615
608
|
async fetchAndUpdateMetamaskNotifications(previewToken) {
|
|
@@ -817,7 +810,7 @@ class NotificationServicesController extends base_controller_1.BaseController {
|
|
|
817
810
|
}
|
|
818
811
|
}
|
|
819
812
|
}
|
|
820
|
-
_NotificationServicesController_isPushIntegrated = new WeakMap(), _NotificationServicesController_isPushNotificationsSetup = new WeakMap(), _NotificationServicesController_isUnlocked = new WeakMap(), _NotificationServicesController_keyringController = new WeakMap(), _NotificationServicesController_auth = new WeakMap(), _NotificationServicesController_storage = new WeakMap(), _NotificationServicesController_pushNotifications = new WeakMap(), _NotificationServicesController_accounts = new WeakMap(), _NotificationServicesController_featureAnnouncementEnv = new WeakMap(),
|
|
813
|
+
_NotificationServicesController_isPushIntegrated = new WeakMap(), _NotificationServicesController_isPushNotificationsSetup = new WeakMap(), _NotificationServicesController_isUnlocked = new WeakMap(), _NotificationServicesController_keyringController = new WeakMap(), _NotificationServicesController_auth = new WeakMap(), _NotificationServicesController_storage = new WeakMap(), _NotificationServicesController_pushNotifications = new WeakMap(), _NotificationServicesController_accounts = new WeakMap(), _NotificationServicesController_featureAnnouncementEnv = new WeakMap(), _NotificationServicesController_instances = new WeakSet(), _NotificationServicesController_registerMessageHandlers = function _NotificationServicesController_registerMessageHandlers() {
|
|
821
814
|
this.messagingSystem.registerActionHandler(`${controllerName}:updateMetamaskNotificationsList`, this.updateMetamaskNotificationsList.bind(this));
|
|
822
815
|
this.messagingSystem.registerActionHandler(`${controllerName}:disableNotificationServices`, this.disableNotificationServices.bind(this));
|
|
823
816
|
this.messagingSystem.registerActionHandler(`${controllerName}:selectIsNotificationServicesEnabled`, this.selectIsNotificationServicesEnabled.bind(this));
|
|
@@ -868,7 +861,7 @@ async function _NotificationServicesController_getUserStorage() {
|
|
|
868
861
|
const userStorage = JSON.parse(userStorageString);
|
|
869
862
|
return userStorage;
|
|
870
863
|
}
|
|
871
|
-
catch
|
|
864
|
+
catch {
|
|
872
865
|
loglevel_1.default.error('Unable to parse User Storage');
|
|
873
866
|
return null;
|
|
874
867
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationServicesController.cjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,+DAA2D;AAC3D,iEAAkE;AAYlE,2CAAyC;AACzC,wDAA2B;AAE3B,yDAAiE;AACjE,6EAAgE;AAChE,kFAA6E;AAC7E,2FAAyE;AACzE,2FAAyE;AAQzE,yDAAuC;AA6BvC,iCAAiC;AACjC,MAAM,cAAc,GAAG,gCAAgC,CAAC;AAwDxD,MAAM,QAAQ,GAAuD;IACnE,wBAAwB,EAAE;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IAED,kCAAkC,EAAE;QAClC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,yBAAyB,EAAE;QACzB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,I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AsC;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;kBA3dkB,8BAA8B","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { toChecksumHexAddress } from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetAccountsAction,\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n AuthenticationController,\n UserStorageController,\n} from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport log from 'loglevel';\n\nimport { USER_STORAGE_VERSION_KEY } from './constants/constants';\nimport { TRIGGER_TYPES } from './constants/notification-schema';\nimport { safeProcessNotification } from './processors/process-notifications';\nimport * as FeatureNotifications from './services/feature-announcements';\nimport * as OnChainNotifications from './services/onchain-notifications';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n RawNotificationUnion,\n} from './types/notification/notification';\nimport type { OnChainRawNotification } from './types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from './types/user-storage/user-storage';\nimport * as Utils from './utils/utils';\n\n// TODO: Fix Circular Type Dependencies\n// This indicates that control flow of messages is everywhere, lets orchestrate these better\nexport type NotificationServicesPushControllerEnablePushNotifications = {\n type: `NotificationServicesPushController:enablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerDisablePushNotifications = {\n type: `NotificationServicesPushController:disablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerUpdateTriggerPushNotifications = {\n type: `NotificationServicesPushController:updateTriggerPushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerSubscribeToNotifications = {\n type: `NotificationServicesPushController:subscribeToPushNotifications`;\n handler: () => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerOnNewNotification = {\n type: `NotificationServicesPushController:onNewNotifications`;\n payload: [INotification];\n};\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visted 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 persist: true,\n anonymous: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n persist: true,\n anonymous: false,\n },\n isNotificationServicesEnabled: {\n persist: true,\n anonymous: false,\n },\n isFeatureAnnouncementsEnabled: {\n persist: true,\n anonymous: false,\n },\n metamaskNotificationsList: {\n persist: true,\n anonymous: true,\n },\n metamaskNotificationsReadList: {\n persist: true,\n anonymous: true,\n },\n isUpdatingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isFetchingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isUpdatingMetamaskNotificationsAccount: {\n persist: false,\n anonymous: false,\n },\n isCheckingAccountsPresence: {\n persist: false,\n anonymous: false,\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\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationServicesControllerUpdateMetamaskNotificationsList = {\n type: `${typeof controllerName}:updateMetamaskNotificationsList`;\n handler: NotificationServicesController['updateMetamaskNotificationsList'];\n};\n\nexport type NotificationServicesControllerDisableNotificationServices = {\n type: `${typeof controllerName}:disableNotificationServices`;\n handler: NotificationServicesController['disableNotificationServices'];\n};\n\nexport type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `${typeof controllerName}:selectIsNotificationServicesEnabled`;\n handler: NotificationServicesController['selectIsNotificationServicesEnabled'];\n };\n\nexport type NotificationServicesControllerGetNotificationsByType = {\n type: `${typeof controllerName}:getNotificationsByType`;\n handler: NotificationServicesController['getNotificationsByType'];\n};\n\nexport type NotificationServicesControllerDeleteNotificationsById = {\n type: `${typeof controllerName}:deleteNotificationsById`;\n handler: NotificationServicesController['deleteNotificationsById'];\n};\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerUpdateMetamaskNotificationsList\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n | NotificationServicesControllerGetNotificationsByType\n | NotificationServicesControllerDeleteNotificationsById;\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerIsSignedIn\n // User Storage Controller Requests\n | UserStorageController.UserStorageControllerEnableProfileSyncing\n | UserStorageController.UserStorageControllerGetStorageKey\n | UserStorageController.UserStorageControllerPerformGetStorage\n | UserStorageController.UserStorageControllerPerformSetStorage\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerEnablePushNotifications\n | NotificationServicesPushControllerDisablePushNotifications\n | NotificationServicesPushControllerUpdateTriggerPushNotifications\n | NotificationServicesPushControllerSubscribeToNotifications;\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\nexport type AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotification;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport default class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n // Temporary boolean as push notifications are not yet enabled on mobile\n #isPushIntegrated = true;\n\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 #isPushNotificationsSetup = false;\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>) => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#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.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n };\n\n #storage = {\n enableProfileSyncing: async () => {\n return await this.messagingSystem.call(\n 'UserStorageController:enableProfileSyncing',\n );\n },\n getStorageKey: () => {\n return this.messagingSystem.call('UserStorageController:getStorageKey');\n },\n getNotificationStorage: async () => {\n return await this.messagingSystem.call(\n 'UserStorageController:performGetStorage',\n 'notifications.notification_settings',\n );\n },\n setNotificationStorage: async (state: string) => {\n return await this.messagingSystem.call(\n 'UserStorageController:performSetStorage',\n 'notifications.notification_settings',\n state,\n );\n },\n };\n\n #pushNotifications = {\n subscribeToPushNotifications: async () => {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:enablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to enable push notifications', e);\n }\n },\n disablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:disablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to disable push notifications', e);\n }\n },\n updatePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to update push notifications', e);\n }\n },\n subscribe: () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n this.messagingSystem.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (notification) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateMetamaskNotificationsList(notification);\n },\n );\n },\n initializePushNotifications: async () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#isPushNotificationsSetup) {\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 if (this.#isUnlocked) {\n const storage = await this.#getUserStorage();\n if (!storage) {\n return;\n }\n\n const uuids = Utils.getAllUUIDs(storage);\n await this.#pushNotifications.enablePushNotifications(uuids);\n this.#isPushNotificationsSetup = true;\n } else {\n await this.#pushNotifications.subscribeToPushNotifications();\n }\n },\n };\n\n #accounts = {\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: async () => {\n // Get previous and current account sets\n const nonChecksumAccounts = await this.messagingSystem.call(\n 'KeyringController:getAccounts',\n );\n const accounts = nonChecksumAccounts.map((a) => toChecksumHexAddress(a));\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((a) => !prevAccountsSet.has(a));\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (a) => !currentAccountsSet.has(a),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...prevAccountsSet, ...accountsAdded];\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 * @returns result from list accounts\n */\n initialize: () => {\n return this.#accounts.listAccounts();\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: () => {\n this.messagingSystem.subscribe(\n 'KeyringController:stateChange',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n await this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.updateOnChainTriggersByAccount(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.deleteOnChainTriggersByAccount(accountsRemoved));\n }\n await Promise.all(promises);\n },\n );\n },\n };\n\n #featureAnnouncementEnv: FeatureAnnouncementEnv;\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.isPushIntegrated - toggle push notifications on/off if client has integrated them.\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n isPushIntegrated?: boolean;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#isPushIntegrated = env.isPushIntegrated ?? true;\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#registerMessageHandlers();\n this.#clearLoadingStates();\n\n this.#keyringController.setupLockedStateSubscriptions(\n this.#pushNotifications.initializePushNotifications,\n );\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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 #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateMetamaskNotificationsList`,\n this.updateMetamaskNotificationsList.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disableNotificationServices`,\n this.disableNotificationServices.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:selectIsNotificationServicesEnabled`,\n this.selectIsNotificationServicesEnabled.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getNotificationsByType`,\n this.getNotificationsByType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteNotificationsById`,\n this.deleteNotificationsById.bind(this),\n );\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() {\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 #getValidStorageKeyAndBearerToken() {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n const storageKey = await this.#storage.getStorageKey();\n\n if (!bearerToken || !storageKey) {\n throw new Error('Missing BearerToken or storage key');\n }\n\n return { bearerToken, storageKey };\n }\n\n #performEnableProfileSyncing = async () => {\n try {\n await this.#storage.enableProfileSyncing();\n } catch (e) {\n log.error('Failed to enable profile syncing', e);\n throw new Error('Failed to enable profile syncing');\n }\n };\n\n #assertUserStorage(\n storage: UserStorage | null,\n ): asserts storage is UserStorage {\n if (!storage) {\n throw new Error('User Storage does not exist');\n }\n }\n\n /**\n * Retrieves and parses the user storage from the storage key.\n *\n * This method attempts to retrieve the user storage using the specified storage key,\n * then parses the JSON string to an object. If the storage is not found or cannot be parsed,\n * it throws an error.\n *\n * @returns The parsed user storage object or null\n */\n async #getUserStorage(): Promise<UserStorage | null> {\n const userStorageString: string | null =\n await this.#storage.getNotificationStorage();\n\n if (!userStorageString) {\n return null;\n }\n\n try {\n const userStorage: UserStorage = JSON.parse(userStorageString);\n return userStorage;\n } catch (error) {\n log.error('Unable to parse User Storage');\n return null;\n }\n }\n\n /**\n * Retrieves the current enabled state of MetaMask notifications.\n *\n * This method directly returns the boolean value of `isMetamaskNotificationsEnabled`\n * from the controller's state, indicating whether MetaMask notifications are currently enabled.\n *\n * @returns The enabled state of MetaMask notifications.\n */\n public selectIsNotificationServicesEnabled(): boolean {\n return this.state.isNotificationServicesEnabled;\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 ) {\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 ) {\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) {\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[]) {\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[]) {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n // Retrieve user storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n const presence = Utils.checkAccountsPresence(userStorage, accounts);\n return presence;\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 ) {\n try {\n this.update((s) => {\n s.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (e) {\n log.error('Unable to toggle feature announcements', e);\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 * @param opts - optional options to mutate this functionality\n * @param opts.resetNotifications - this will not use the users stored preferences, and instead re-create notification triggers\n * It will help in case uses get into a corrupted state or wants to wipe their notifications.\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(opts?: {\n resetNotifications?: boolean;\n }): Promise<UserStorage> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n await this.#performEnableProfileSyncing();\n\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n const { accounts } = await this.#accounts.listAccounts();\n\n // Attempt Get User Storage\n // Will be null if entry does not exist, or a user is resetting their notifications\n // Will be defined if entry exists\n // Will throw if fails to get the user storage entry\n let userStorage = opts?.resetNotifications\n ? null\n : await this.#getUserStorage();\n\n // If userStorage does not exist, create a new one\n // All the triggers created are set as: \"disabled\"\n if (userStorage?.[USER_STORAGE_VERSION_KEY] === undefined) {\n userStorage = Utils.initializeUserStorage(\n accounts.map((account) => ({ address: account })),\n false,\n );\n\n // Write the userStorage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n }\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage);\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n\n // Create push notifications triggers\n const allUUIDS = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.enablePushNotifications(allUUIDS);\n\n // Write the new userStorage (triggers are now \"enabled\")\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Update the state of the controller\n this.update((state) => {\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n });\n\n return userStorage;\n } catch (err) {\n log.error('Failed to create On Chain triggers', err);\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 * 1. Enable Profile Syncing\n * 2. Get or Create Notification User Storage\n * 3. Upsert Triggers\n * 4. Update Push notifications\n *\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n await this.createOnChainTriggers();\n } catch (e) {\n log.error('Unable to enable notifications', e);\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() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Disable Push Notifications\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n // Clear Notification States (toggles and list)\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 } catch (e) {\n log.error('Unable to disable notifications', e);\n throw new Error('Unable to disable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account.\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and deletes all triggers associated with the account\n * 3. Disables any related push notifications\n * 4. Updates Storage to reflect new state.\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 deleteOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Get the UUIDs to delete\n const UUIDs = accounts\n .map((a) => Utils.getUUIDsForAccount(userStorage, a.toLowerCase()))\n .flat();\n\n if (UUIDs.length === 0) {\n return userStorage;\n }\n\n // Delete these UUIDs (Mutates User Storage)\n await OnChainNotifications.deleteOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n UUIDs,\n );\n\n // Delete these UUIDs from the push notifications\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n // Update User Storage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to delete OnChain triggers', err);\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 updateOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Add any missing triggers\n accounts.forEach((a) => Utils.upsertAddressTriggers(a, userStorage));\n\n const newTriggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return t;\n }\n return undefined;\n },\n });\n\n // Create any missing triggers.\n if (newTriggers.length > 0) {\n // Write te updated userStorage (where triggers are disabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (\n accounts.some((a) => a.toLowerCase() === t.address.toLowerCase())\n ) {\n return t;\n }\n return undefined;\n },\n });\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n }\n\n // Update Push Notifications Triggers\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.updatePushNotifications(UUIDs);\n\n // Update the userStorage (where triggers are enabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to update OnChain triggers', err);\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 * @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\n // Raw Feature Notifications\n const rawFeatureAnnouncementNotifications =\n isGlobalNotifsEnabled && this.state.isFeatureAnnouncementsEnabled\n ? await FeatureNotifications.getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: OnChainRawNotification[] = [];\n if (isGlobalNotifsEnabled) {\n const userStorage = await this.#storage\n .getNotificationStorage()\n .then((s) => s && (JSON.parse(s) as UserStorage))\n .catch(() => null);\n const bearerToken = await this.#auth.getBearerToken().catch(() => null);\n if (userStorage && bearerToken) {\n const notifications =\n await OnChainNotifications.getOnChainNotifications(\n userStorage,\n bearerToken,\n ).catch(() => []);\n\n rawOnChainNotifications.push(...notifications);\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 // Process Notifications\n const readIds = this.state.metamaskNotificationsReadList;\n const isNotUndefined = <Item>(t?: Item): t is Item => Boolean(t);\n const processAndFilter = (ns: RawNotificationUnion[]) =>\n ns\n .map((n) => safeProcessNotification(n, readIds))\n .filter(isNotUndefined);\n\n const featureAnnouncementNotifications = processAndFilter(\n rawFeatureAnnouncementNotifications,\n );\n const onChainNotifications = processAndFilter(rawOnChainNotifications);\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...featureAnnouncementNotifications,\n ...onChainNotifications,\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (err) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', err);\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) {\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) {\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[]) {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messagingSystem.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 OnChainNotifications.markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\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 (err) {\n log.warn('Something failed when marking notifications as read', err);\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.messagingSystem.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) => n.id === notification.id)\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) => n.id),\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.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NotificationServicesController.cjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,+DAA2D;AAC3D,iEAAkE;AAYlE,2CA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BAA+B,CAAC;IAC1E,CAAC,CAAC,CAAC;AACL,CAAC,yIAW8B,0BAAmC;IAChE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,0BAA0B,GAAG,0BAA0B,CAAC;IAChE,CAAC,CAAC,CAAC;AACL,CAAC,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;kBAldkB,8BAA8B","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { toChecksumHexAddress } from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetAccountsAction,\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n AuthenticationController,\n UserStorageController,\n} from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport log from 'loglevel';\n\nimport { USER_STORAGE_VERSION_KEY } from './constants/constants';\nimport { TRIGGER_TYPES } from './constants/notification-schema';\nimport { safeProcessNotification } from './processors/process-notifications';\nimport * as FeatureNotifications from './services/feature-announcements';\nimport * as OnChainNotifications from './services/onchain-notifications';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n RawNotificationUnion,\n} from './types/notification/notification';\nimport type { OnChainRawNotification } from './types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from './types/user-storage/user-storage';\nimport * as Utils from './utils/utils';\n\n// TODO: Fix Circular Type Dependencies\n// This indicates that control flow of messages is everywhere, lets orchestrate these better\nexport type NotificationServicesPushControllerEnablePushNotifications = {\n type: `NotificationServicesPushController:enablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerDisablePushNotifications = {\n type: `NotificationServicesPushController:disablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerUpdateTriggerPushNotifications = {\n type: `NotificationServicesPushController:updateTriggerPushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerSubscribeToNotifications = {\n type: `NotificationServicesPushController:subscribeToPushNotifications`;\n handler: () => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerOnNewNotification = {\n type: `NotificationServicesPushController:onNewNotifications`;\n payload: [INotification];\n};\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visted 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 persist: true,\n anonymous: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n persist: true,\n anonymous: false,\n },\n isNotificationServicesEnabled: {\n persist: true,\n anonymous: false,\n },\n isFeatureAnnouncementsEnabled: {\n persist: true,\n anonymous: false,\n },\n metamaskNotificationsList: {\n persist: true,\n anonymous: true,\n },\n metamaskNotificationsReadList: {\n persist: true,\n anonymous: true,\n },\n isUpdatingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isFetchingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isUpdatingMetamaskNotificationsAccount: {\n persist: false,\n anonymous: false,\n },\n isCheckingAccountsPresence: {\n persist: false,\n anonymous: false,\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\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationServicesControllerUpdateMetamaskNotificationsList = {\n type: `${typeof controllerName}:updateMetamaskNotificationsList`;\n handler: NotificationServicesController['updateMetamaskNotificationsList'];\n};\n\nexport type NotificationServicesControllerDisableNotificationServices = {\n type: `${typeof controllerName}:disableNotificationServices`;\n handler: NotificationServicesController['disableNotificationServices'];\n};\n\nexport type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `${typeof controllerName}:selectIsNotificationServicesEnabled`;\n handler: NotificationServicesController['selectIsNotificationServicesEnabled'];\n };\n\nexport type NotificationServicesControllerGetNotificationsByType = {\n type: `${typeof controllerName}:getNotificationsByType`;\n handler: NotificationServicesController['getNotificationsByType'];\n};\n\nexport type NotificationServicesControllerDeleteNotificationsById = {\n type: `${typeof controllerName}:deleteNotificationsById`;\n handler: NotificationServicesController['deleteNotificationsById'];\n};\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerUpdateMetamaskNotificationsList\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n | NotificationServicesControllerGetNotificationsByType\n | NotificationServicesControllerDeleteNotificationsById;\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerIsSignedIn\n | AuthenticationController.AuthenticationControllerPerformSignIn\n // User Storage Controller Requests\n | UserStorageController.UserStorageControllerGetStorageKey\n | UserStorageController.UserStorageControllerPerformGetStorage\n | UserStorageController.UserStorageControllerPerformSetStorage\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerEnablePushNotifications\n | NotificationServicesPushControllerDisablePushNotifications\n | NotificationServicesPushControllerUpdateTriggerPushNotifications\n | NotificationServicesPushControllerSubscribeToNotifications;\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\nexport type AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotification;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport default class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n // Temporary boolean as push notifications are not yet enabled on mobile\n readonly #isPushIntegrated: boolean = true;\n\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 #isPushNotificationsSetup = false;\n\n #isUnlocked = false;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>) => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#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.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #storage = {\n getStorageKey: () => {\n return this.messagingSystem.call('UserStorageController:getStorageKey');\n },\n getNotificationStorage: async () => {\n return await this.messagingSystem.call(\n 'UserStorageController:performGetStorage',\n 'notifications.notification_settings',\n );\n },\n setNotificationStorage: async (state: string) => {\n return await this.messagingSystem.call(\n 'UserStorageController:performSetStorage',\n 'notifications.notification_settings',\n state,\n );\n },\n };\n\n readonly #pushNotifications = {\n subscribeToPushNotifications: async () => {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:enablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to enable push notifications', e);\n }\n },\n disablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:disablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to disable push notifications', e);\n }\n },\n updatePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to update push notifications', e);\n }\n },\n subscribe: () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n this.messagingSystem.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (notification) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateMetamaskNotificationsList(notification);\n },\n );\n },\n initializePushNotifications: async () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#isPushNotificationsSetup) {\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 if (this.#isUnlocked) {\n const storage = await this.#getUserStorage();\n if (!storage) {\n return;\n }\n\n const uuids = Utils.getAllUUIDs(storage);\n await this.#pushNotifications.enablePushNotifications(uuids);\n this.#isPushNotificationsSetup = true;\n } else {\n await this.#pushNotifications.subscribeToPushNotifications();\n }\n },\n };\n\n readonly #accounts = {\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: async () => {\n // Get previous and current account sets\n const nonChecksumAccounts = await this.messagingSystem.call(\n 'KeyringController:getAccounts',\n );\n const accounts = nonChecksumAccounts.map((a) => toChecksumHexAddress(a));\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((a) => !prevAccountsSet.has(a));\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (a) => !currentAccountsSet.has(a),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...prevAccountsSet, ...accountsAdded];\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 * @returns result from list accounts\n */\n initialize: () => {\n return this.#accounts.listAccounts();\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: () => {\n this.messagingSystem.subscribe(\n 'KeyringController:stateChange',\n\n async () => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n await this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.updateOnChainTriggersByAccount(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.deleteOnChainTriggersByAccount(accountsRemoved));\n }\n await Promise.all(promises);\n },\n );\n },\n };\n\n readonly #featureAnnouncementEnv: FeatureAnnouncementEnv;\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.isPushIntegrated - toggle push notifications on/off if client has integrated them.\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n isPushIntegrated?: boolean;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#isPushIntegrated = env.isPushIntegrated ?? true;\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#registerMessageHandlers();\n this.#clearLoadingStates();\n\n this.#keyringController.setupLockedStateSubscriptions(\n this.#pushNotifications.initializePushNotifications,\n );\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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 #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateMetamaskNotificationsList`,\n this.updateMetamaskNotificationsList.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disableNotificationServices`,\n this.disableNotificationServices.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:selectIsNotificationServicesEnabled`,\n this.selectIsNotificationServicesEnabled.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getNotificationsByType`,\n this.getNotificationsByType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteNotificationsById`,\n this.deleteNotificationsById.bind(this),\n );\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() {\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 #getValidStorageKeyAndBearerToken() {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n const storageKey = await this.#storage.getStorageKey();\n\n if (!bearerToken || !storageKey) {\n throw new Error('Missing BearerToken or storage key');\n }\n\n return { bearerToken, storageKey };\n }\n\n #assertUserStorage(\n storage: UserStorage | null,\n ): asserts storage is UserStorage {\n if (!storage) {\n throw new Error('User Storage does not exist');\n }\n }\n\n /**\n * Retrieves and parses the user storage from the storage key.\n *\n * This method attempts to retrieve the user storage using the specified storage key,\n * then parses the JSON string to an object. If the storage is not found or cannot be parsed,\n * it throws an error.\n *\n * @returns The parsed user storage object or null\n */\n async #getUserStorage(): Promise<UserStorage | null> {\n const userStorageString: string | null =\n await this.#storage.getNotificationStorage();\n\n if (!userStorageString) {\n return null;\n }\n\n try {\n const userStorage: UserStorage = JSON.parse(userStorageString);\n return userStorage;\n } catch {\n log.error('Unable to parse User Storage');\n return null;\n }\n }\n\n /**\n * Retrieves the current enabled state of MetaMask notifications.\n *\n * This method directly returns the boolean value of `isMetamaskNotificationsEnabled`\n * from the controller's state, indicating whether MetaMask notifications are currently enabled.\n *\n * @returns The enabled state of MetaMask notifications.\n */\n public selectIsNotificationServicesEnabled(): boolean {\n return this.state.isNotificationServicesEnabled;\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 ) {\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 ) {\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) {\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[]) {\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[]) {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n // Retrieve user storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n const presence = Utils.checkAccountsPresence(userStorage, accounts);\n return presence;\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 ) {\n try {\n this.update((s) => {\n s.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (e) {\n log.error('Unable to toggle feature announcements', e);\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 * @param opts - optional options to mutate this functionality\n * @param opts.resetNotifications - this will not use the users stored preferences, and instead re-create notification triggers\n * It will help in case uses get into a corrupted state or wants to wipe their notifications.\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(opts?: {\n resetNotifications?: boolean;\n }): Promise<UserStorage> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n const { accounts } = await this.#accounts.listAccounts();\n\n // Attempt Get User Storage\n // Will be null if entry does not exist, or a user is resetting their notifications\n // Will be defined if entry exists\n // Will throw if fails to get the user storage entry\n let userStorage = opts?.resetNotifications\n ? null\n : await this.#getUserStorage();\n\n // If userStorage does not exist, create a new one\n // All the triggers created are set as: \"disabled\"\n if (userStorage?.[USER_STORAGE_VERSION_KEY] === undefined) {\n userStorage = Utils.initializeUserStorage(\n accounts.map((account) => ({ address: account })),\n false,\n );\n\n // Write the userStorage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n }\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage);\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n\n // Create push notifications triggers\n const allUUIDS = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.enablePushNotifications(allUUIDS);\n\n // Write the new userStorage (triggers are now \"enabled\")\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Update the state of the controller\n this.update((state) => {\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n });\n\n return userStorage;\n } catch (err) {\n log.error('Failed to create On Chain triggers', err);\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 * 1. Enable Profile Syncing\n * 2. Get or Create Notification User Storage\n * 3. Upsert Triggers\n * 4. Update Push notifications\n *\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n\n await this.createOnChainTriggers();\n } catch (e) {\n log.error('Unable to enable notifications', e);\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() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Disable Push Notifications\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n // Clear Notification States (toggles and list)\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 } catch (e) {\n log.error('Unable to disable notifications', e);\n throw new Error('Unable to disable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account.\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and deletes all triggers associated with the account\n * 3. Disables any related push notifications\n * 4. Updates Storage to reflect new state.\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 deleteOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Get the UUIDs to delete\n const UUIDs = accounts\n .map((a) => Utils.getUUIDsForAccount(userStorage, a.toLowerCase()))\n .flat();\n\n if (UUIDs.length === 0) {\n return userStorage;\n }\n\n // Delete these UUIDs (Mutates User Storage)\n await OnChainNotifications.deleteOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n UUIDs,\n );\n\n // Delete these UUIDs from the push notifications\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n // Update User Storage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to delete OnChain triggers', err);\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 updateOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Add any missing triggers\n accounts.forEach((a) => Utils.upsertAddressTriggers(a, userStorage));\n\n const newTriggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return t;\n }\n return undefined;\n },\n });\n\n // Create any missing triggers.\n if (newTriggers.length > 0) {\n // Write te updated userStorage (where triggers are disabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (\n accounts.some((a) => a.toLowerCase() === t.address.toLowerCase())\n ) {\n return t;\n }\n return undefined;\n },\n });\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n }\n\n // Update Push Notifications Triggers\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.updatePushNotifications(UUIDs);\n\n // Update the userStorage (where triggers are enabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to update OnChain triggers', err);\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\n // Raw Feature Notifications\n const rawFeatureAnnouncementNotifications =\n isGlobalNotifsEnabled && this.state.isFeatureAnnouncementsEnabled\n ? await FeatureNotifications.getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: OnChainRawNotification[] = [];\n if (isGlobalNotifsEnabled) {\n const userStorage = await this.#storage\n .getNotificationStorage()\n .then((s) => s && (JSON.parse(s) as UserStorage))\n .catch(() => null);\n const bearerToken = await this.#auth.getBearerToken().catch(() => null);\n if (userStorage && bearerToken) {\n const notifications =\n await OnChainNotifications.getOnChainNotifications(\n userStorage,\n bearerToken,\n ).catch(() => []);\n\n rawOnChainNotifications.push(...notifications);\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 // Process Notifications\n const readIds = this.state.metamaskNotificationsReadList;\n const isNotUndefined = <Item>(t?: Item): t is Item => Boolean(t);\n const processAndFilter = (ns: RawNotificationUnion[]) =>\n ns\n .map((n) => safeProcessNotification(n, readIds))\n .filter(isNotUndefined);\n\n const featureAnnouncementNotifications = processAndFilter(\n rawFeatureAnnouncementNotifications,\n );\n const onChainNotifications = processAndFilter(rawOnChainNotifications);\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...featureAnnouncementNotifications,\n ...onChainNotifications,\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (err) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', err);\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) {\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) {\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[]) {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messagingSystem.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 OnChainNotifications.markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\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 (err) {\n log.warn('Something failed when marking notifications as read', err);\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.messagingSystem.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) => n.id === notification.id)\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) => n.id),\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.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n}\n"]}
|
|
@@ -97,7 +97,7 @@ export type NotificationServicesControllerDeleteNotificationsById = {
|
|
|
97
97
|
handler: NotificationServicesController['deleteNotificationsById'];
|
|
98
98
|
};
|
|
99
99
|
export type Actions = NotificationServicesControllerGetStateAction | NotificationServicesControllerUpdateMetamaskNotificationsList | NotificationServicesControllerDisableNotificationServices | NotificationServicesControllerSelectIsNotificationServicesEnabled | NotificationServicesControllerGetNotificationsByType | NotificationServicesControllerDeleteNotificationsById;
|
|
100
|
-
export type AllowedActions = KeyringControllerGetAccountsAction | KeyringControllerGetStateAction | AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerIsSignedIn |
|
|
100
|
+
export type AllowedActions = KeyringControllerGetAccountsAction | KeyringControllerGetStateAction | AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerIsSignedIn | AuthenticationController.AuthenticationControllerPerformSignIn | UserStorageController.UserStorageControllerGetStorageKey | UserStorageController.UserStorageControllerPerformGetStorage | UserStorageController.UserStorageControllerPerformSetStorage | NotificationServicesPushControllerEnablePushNotifications | NotificationServicesPushControllerDisablePushNotifications | NotificationServicesPushControllerUpdateTriggerPushNotifications | NotificationServicesPushControllerSubscribeToNotifications;
|
|
101
101
|
export type NotificationServicesControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, NotificationServicesControllerState>;
|
|
102
102
|
export type NotificationListUpdatedEvent = {
|
|
103
103
|
type: `${typeof controllerName}:notificationsListUpdated`;
|
|
@@ -230,6 +230,7 @@ export default class NotificationServicesController extends BaseController<typeo
|
|
|
230
230
|
* **Action** - When a user views the notification list page/dropdown
|
|
231
231
|
*
|
|
232
232
|
* @param previewToken - the preview token to use if needed
|
|
233
|
+
* @returns A promise that resolves to the list of notifications.
|
|
233
234
|
* @throws {Error} Throws an error if unauthenticated or from other operations.
|
|
234
235
|
*/
|
|
235
236
|
fetchAndUpdateMetamaskNotifications(previewToken?: string): Promise<INotification[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationServicesController.d.cts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,KAAK,EACV,kCAAkC,EAClC,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EACV,wBAAwB,EACxB,qBAAqB,EACtB,0CAA0C;AAK3C,OAAO,EAAE,aAAa,EAAE,4CAAwC;AAIhE,OAAO,KAAK,EACV,aAAa,EACb,4BAA4B,EAE7B,8CAA0C;AAE3C,OAAO,KAAK,EAAE,WAAW,EAAE,8CAA0C;AAKrE,MAAM,MAAM,yDAAyD,GAAG;IACtE,IAAI,EAAE,4DAA4D,CAAC;IACnE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,0DAA0D,GAAG;IACvE,IAAI,EAAE,6DAA6D,CAAC;IACpE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,gEAAgE,GAAG;IAC7E,IAAI,EAAE,mEAAmE,CAAC;IAC1E,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,0DAA0D,GAAG;IACvE,IAAI,EAAE,iEAAiE,CAAC;IACxE,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B,CA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8BAA8B,CAAC,qCAAqC,CAAC,CAAC;CAChF,CAAC;AAEJ,MAAM,MAAM,oDAAoD,GAAG;IACjE,IAAI,EAAE,GAAG,OAAO,cAAc,yBAAyB,CAAC;IACxD,OAAO,EAAE,8BAA8B,CAAC,wBAAwB,CAAC,CAAC;CACnE,CAAC;AAEF,MAAM,MAAM,qDAAqD,GAAG;IAClE,IAAI,EAAE,GAAG,OAAO,cAAc,0BAA0B,CAAC;IACzD,OAAO,EAAE,8BAA8B,CAAC,yBAAyB,CAAC,CAAC;CACpE,CAAC;AAGF,MAAM,MAAM,OAAO,GACf,4CAA4C,GAC5C,6DAA6D,GAC7D,yDAAyD,GACzD,iEAAiE,GACjE,oDAAoD,GACpD,qDAAqD,CAAC;AAG1D,MAAM,MAAM,cAAc,GAEtB,kCAAkC,GAClC,+BAA+B,GAE/B,wBAAwB,CAAC,sCAAsC,GAC/D,wBAAwB,CAAC,kCAAkC,
|
|
1
|
+
{"version":3,"file":"NotificationServicesController.d.cts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,KAAK,EACV,kCAAkC,EAClC,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EACV,wBAAwB,EACxB,qBAAqB,EACtB,0CAA0C;AAK3C,OAAO,EAAE,aAAa,EAAE,4CAAwC;AAIhE,OAAO,KAAK,EACV,aAAa,EACb,4BAA4B,EAE7B,8CAA0C;AAE3C,OAAO,KAAK,EAAE,WAAW,EAAE,8CAA0C;AAKrE,MAAM,MAAM,yDAAyD,GAAG;IACtE,IAAI,EAAE,4DAA4D,CAAC;IACnE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO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ificationServicesController['deleteNotificationsById'];
|
|
98
98
|
};
|
|
99
99
|
export type Actions = NotificationServicesControllerGetStateAction | NotificationServicesControllerUpdateMetamaskNotificationsList | NotificationServicesControllerDisableNotificationServices | NotificationServicesControllerSelectIsNotificationServicesEnabled | NotificationServicesControllerGetNotificationsByType | NotificationServicesControllerDeleteNotificationsById;
|
|
100
|
-
export type AllowedActions = KeyringControllerGetAccountsAction | KeyringControllerGetStateAction | AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerIsSignedIn |
|
|
100
|
+
export type AllowedActions = KeyringControllerGetAccountsAction | KeyringControllerGetStateAction | AuthenticationController.AuthenticationControllerGetBearerToken | AuthenticationController.AuthenticationControllerIsSignedIn | AuthenticationController.AuthenticationControllerPerformSignIn | UserStorageController.UserStorageControllerGetStorageKey | UserStorageController.UserStorageControllerPerformGetStorage | UserStorageController.UserStorageControllerPerformSetStorage | NotificationServicesPushControllerEnablePushNotifications | NotificationServicesPushControllerDisablePushNotifications | NotificationServicesPushControllerUpdateTriggerPushNotifications | NotificationServicesPushControllerSubscribeToNotifications;
|
|
101
101
|
export type NotificationServicesControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, NotificationServicesControllerState>;
|
|
102
102
|
export type NotificationListUpdatedEvent = {
|
|
103
103
|
type: `${typeof controllerName}:notificationsListUpdated`;
|
|
@@ -230,6 +230,7 @@ export default class NotificationServicesController extends BaseController<typeo
|
|
|
230
230
|
* **Action** - When a user views the notification list page/dropdown
|
|
231
231
|
*
|
|
232
232
|
* @param previewToken - the preview token to use if needed
|
|
233
|
+
* @returns A promise that resolves to the list of notifications.
|
|
233
234
|
* @throws {Error} Throws an error if unauthenticated or from other operations.
|
|
234
235
|
*/
|
|
235
236
|
fetchAndUpdateMetamaskNotifications(previewToken?: string): Promise<INotification[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationServicesController.d.mts","sourceRoot":"","sources":["../../src/NotificationServicesController/Notification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C,wBAAwB,CAAC,CAAC;CACnE,CAAC;AAEF,MAAM,MAAM,qDAAqD,GAAG;IAClE,IAAI,EAAE,GAAG,OAAO,cAAc,0BAA0B,CAAC;IACzD,OAAO,EAAE,8BAA8B,CAAC,yBAAyB,CAAC,CAAC;CACpE,CAAC;AAGF,MAAM,MAAM,OAAO,GACf,4CAA4C,GAC5C,6DAA6D,GAC7D,yDAAyD,GACzD,iEAAiE,GACjE,oDAAoD,GACpD,qDAAqD,CAAC;AAG1D,MAAM,MAAM,cAAc,GAEtB,kCAAkC,GAClC,+BAA+B,GAE/B,wBAAwB,CAAC,sCAAsC,GAC/D,wBAAwB,CAAC,kCAAkC,
|
|
1
|
+
{"version":3,"file":"NotificationServicesController.d.mts","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,KAAK,EACV,kCAAkC,EAClC,iCAAiC,EACjC,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EACV,wBAAwB,EACxB,qBAAqB,EACtB,0CAA0C;AAK3C,OAAO,EAAE,aAAa,EAAE,4CAAwC;AAIhE,OAAO,KAAK,EACV,aAAa,EACb,4BAA4B,EAE7B,8CAA0C;AAE3C,OAAO,KAAK,EAAE,WAAW,EAAE,8CAA0C;AAKrE,MAAM,MAAM,yDAAyD,GAAG;IACtE,IAAI,EAAE,4DAA4D,CAAC;IACnE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,0DAA0D,GAAG;IACvE,IAAI,EAAE,6DAA6D,CAAC;IACpE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,OAA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MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAkBnC;;;;;;;;OAQG;IACU,8BAA8B,CACzC,2BAA2B,EAAE,OAAO;IAYtC;;;;;;;;;;OAUG;IACU,qBAAqB,CAAC,IAAI,CAAC,EAAE;QACxC,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B,GAAG,OAAO,CAAC,WAAW,CAAC;IA6DxB;;;;;;;;;OASG;IACU,2BAA2B;IAkBxC;;;;;;;OAOG;IACU,2BAA2B;IA8BxC;;;;;;;;;;;;;OAaG;IACU,8BAA8B,CACzC,QAAQ,EAAE,MAAM,EAAE,GACjB,OAAO,CAAC,WAAW,CAAC;IA0CvB;;;;;;;;;;;;;;OAcG;IACU,8BAA8B,CACzC,QAAQ,EAAE,MAAM,EAAE,GACjB,OAAO,CAAC,WAAW,CAAC;IA8DvB;;;;;;;;;OASG;IACU,mCAAmC,CAC9C,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,EAAE,CAAC;IAuF3B;;;;;;OAMG;IACI,sBAAsB,CAAC,IAAI,EAAE,aAAa;IAUjD;;;;;;;OAOG;IACU,sBAAsB,CAAC,EAAE,EAAE,MAAM;IA6B9C;;;;;;;OAOG;IACU,uBAAuB,CAAC,GAAG,EAAE,MAAM,EAAE;IAWlD;;;;;OAKG;IACU,+BAA+B,CAC1C,aAAa,EAAE,4BAA4B,GAC1C,OAAO,CAAC,IAAI,CAAC;IA2GhB;;;;;;OAMG;IACU,+BAA+B,CAC1C,YAAY,EAAE,aAAa,GAC1B,OAAO,CAAC,IAAI,CAAC;CA6BjB"}
|
|
@@ -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_isPushIntegrated, _NotificationServicesController_isPushNotificationsSetup, _NotificationServicesController_isUnlocked, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_storage, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_registerMessageHandlers, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_getValidStorageKeyAndBearerToken,
|
|
12
|
+
var _NotificationServicesController_instances, _NotificationServicesController_isPushIntegrated, _NotificationServicesController_isPushNotificationsSetup, _NotificationServicesController_isUnlocked, _NotificationServicesController_keyringController, _NotificationServicesController_auth, _NotificationServicesController_storage, _NotificationServicesController_pushNotifications, _NotificationServicesController_accounts, _NotificationServicesController_featureAnnouncementEnv, _NotificationServicesController_registerMessageHandlers, _NotificationServicesController_clearLoadingStates, _NotificationServicesController_assertAuthEnabled, _NotificationServicesController_getValidStorageKeyAndBearerToken, _NotificationServicesController_assertUserStorage, _NotificationServicesController_getUserStorage, _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;
|
|
@@ -138,11 +138,11 @@ class NotificationServicesController extends BaseController {
|
|
|
138
138
|
isSignedIn: () => {
|
|
139
139
|
return this.messagingSystem.call('AuthenticationController:isSignedIn');
|
|
140
140
|
},
|
|
141
|
+
signIn: async () => {
|
|
142
|
+
return await this.messagingSystem.call('AuthenticationController:performSignIn');
|
|
143
|
+
},
|
|
141
144
|
});
|
|
142
145
|
_NotificationServicesController_storage.set(this, {
|
|
143
|
-
enableProfileSyncing: async () => {
|
|
144
|
-
return await this.messagingSystem.call('UserStorageController:enableProfileSyncing');
|
|
145
|
-
},
|
|
146
146
|
getStorageKey: () => {
|
|
147
147
|
return this.messagingSystem.call('UserStorageController:getStorageKey');
|
|
148
148
|
},
|
|
@@ -273,9 +273,7 @@ class NotificationServicesController extends BaseController {
|
|
|
273
273
|
* And call effects to subscribe/unsubscribe to notifications.
|
|
274
274
|
*/
|
|
275
275
|
subscribe: () => {
|
|
276
|
-
this.messagingSystem.subscribe('KeyringController:stateChange',
|
|
277
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
278
|
-
async () => {
|
|
276
|
+
this.messagingSystem.subscribe('KeyringController:stateChange', async () => {
|
|
279
277
|
if (!this.state.isNotificationServicesEnabled) {
|
|
280
278
|
return;
|
|
281
279
|
}
|
|
@@ -292,15 +290,6 @@ class NotificationServicesController extends BaseController {
|
|
|
292
290
|
},
|
|
293
291
|
});
|
|
294
292
|
_NotificationServicesController_featureAnnouncementEnv.set(this, void 0);
|
|
295
|
-
_NotificationServicesController_performEnableProfileSyncing.set(this, async () => {
|
|
296
|
-
try {
|
|
297
|
-
await __classPrivateFieldGet(this, _NotificationServicesController_storage, "f").enableProfileSyncing();
|
|
298
|
-
}
|
|
299
|
-
catch (e) {
|
|
300
|
-
log.error('Failed to enable profile syncing', e);
|
|
301
|
-
throw new Error('Failed to enable profile syncing');
|
|
302
|
-
}
|
|
303
|
-
});
|
|
304
293
|
__classPrivateFieldSet(this, _NotificationServicesController_isPushIntegrated, env.isPushIntegrated ?? true, "f");
|
|
305
294
|
__classPrivateFieldSet(this, _NotificationServicesController_featureAnnouncementEnv, env.featureAnnouncements, "f");
|
|
306
295
|
__classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_registerMessageHandlers).call(this);
|
|
@@ -375,7 +364,6 @@ class NotificationServicesController extends BaseController {
|
|
|
375
364
|
async createOnChainTriggers(opts) {
|
|
376
365
|
try {
|
|
377
366
|
__classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_setIsUpdatingMetamaskNotifications).call(this, true);
|
|
378
|
-
await __classPrivateFieldGet(this, _NotificationServicesController_performEnableProfileSyncing, "f").call(this);
|
|
379
367
|
const { bearerToken, storageKey } = await __classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_getValidStorageKeyAndBearerToken).call(this);
|
|
380
368
|
const { accounts } = await __classPrivateFieldGet(this, _NotificationServicesController_accounts, "f").listAccounts();
|
|
381
369
|
// Attempt Get User Storage
|
|
@@ -429,6 +417,10 @@ class NotificationServicesController extends BaseController {
|
|
|
429
417
|
async enableMetamaskNotifications() {
|
|
430
418
|
try {
|
|
431
419
|
__classPrivateFieldGet(this, _NotificationServicesController_instances, "m", _NotificationServicesController_setIsUpdatingMetamaskNotifications).call(this, true);
|
|
420
|
+
const isSignedIn = __classPrivateFieldGet(this, _NotificationServicesController_auth, "f").isSignedIn();
|
|
421
|
+
if (!isSignedIn) {
|
|
422
|
+
await __classPrivateFieldGet(this, _NotificationServicesController_auth, "f").signIn();
|
|
423
|
+
}
|
|
432
424
|
await this.createOnChainTriggers();
|
|
433
425
|
}
|
|
434
426
|
catch (e) {
|
|
@@ -588,6 +580,7 @@ class NotificationServicesController extends BaseController {
|
|
|
588
580
|
* **Action** - When a user views the notification list page/dropdown
|
|
589
581
|
*
|
|
590
582
|
* @param previewToken - the preview token to use if needed
|
|
583
|
+
* @returns A promise that resolves to the list of notifications.
|
|
591
584
|
* @throws {Error} Throws an error if unauthenticated or from other operations.
|
|
592
585
|
*/
|
|
593
586
|
async fetchAndUpdateMetamaskNotifications(previewToken) {
|
|
@@ -795,7 +788,7 @@ class NotificationServicesController extends BaseController {
|
|
|
795
788
|
}
|
|
796
789
|
}
|
|
797
790
|
}
|
|
798
|
-
_NotificationServicesController_isPushIntegrated = new WeakMap(), _NotificationServicesController_isPushNotificationsSetup = new WeakMap(), _NotificationServicesController_isUnlocked = new WeakMap(), _NotificationServicesController_keyringController = new WeakMap(), _NotificationServicesController_auth = new WeakMap(), _NotificationServicesController_storage = new WeakMap(), _NotificationServicesController_pushNotifications = new WeakMap(), _NotificationServicesController_accounts = new WeakMap(), _NotificationServicesController_featureAnnouncementEnv = new WeakMap(),
|
|
791
|
+
_NotificationServicesController_isPushIntegrated = new WeakMap(), _NotificationServicesController_isPushNotificationsSetup = new WeakMap(), _NotificationServicesController_isUnlocked = new WeakMap(), _NotificationServicesController_keyringController = new WeakMap(), _NotificationServicesController_auth = new WeakMap(), _NotificationServicesController_storage = new WeakMap(), _NotificationServicesController_pushNotifications = new WeakMap(), _NotificationServicesController_accounts = new WeakMap(), _NotificationServicesController_featureAnnouncementEnv = new WeakMap(), _NotificationServicesController_instances = new WeakSet(), _NotificationServicesController_registerMessageHandlers = function _NotificationServicesController_registerMessageHandlers() {
|
|
799
792
|
this.messagingSystem.registerActionHandler(`${controllerName}:updateMetamaskNotificationsList`, this.updateMetamaskNotificationsList.bind(this));
|
|
800
793
|
this.messagingSystem.registerActionHandler(`${controllerName}:disableNotificationServices`, this.disableNotificationServices.bind(this));
|
|
801
794
|
this.messagingSystem.registerActionHandler(`${controllerName}:selectIsNotificationServicesEnabled`, this.selectIsNotificationServicesEnabled.bind(this));
|
|
@@ -846,7 +839,7 @@ async function _NotificationServicesController_getUserStorage() {
|
|
|
846
839
|
const userStorage = JSON.parse(userStorageString);
|
|
847
840
|
return userStorage;
|
|
848
841
|
}
|
|
849
|
-
catch
|
|
842
|
+
catch {
|
|
850
843
|
log.error('Unable to parse User Storage');
|
|
851
844
|
return null;
|
|
852
845
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationServicesController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,mCAAmC;AAYlE,OAAO,EAAE,MAAM,EAAE,wBAAwB;AACzC,OAAO,IAAG,iBAAiB;;AAE3B,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,mJAyBC,+BAAwC;IAExC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,+BAA+B,GAAG,+BAA+B,CAAC;IAC1E,CAAC,CAAC,CAAC;AACL,CAAC,mJAWC,+BAAwC;IAExC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,+BAA+B,GAAG,+BAA+B,CAAC;IAC1E,CAAC,CAAC,CAAC;AACL,CAAC,yIAW8B,0BAAmC;IAChE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,0BAA0B,GAAG,0BAA0B,CAAC;IAChE,CAAC,CAAC,CAAC;AACL,CAAC,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;eA3dkB,8BAA8B","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { toChecksumHexAddress } from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetAccountsAction,\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n AuthenticationController,\n UserStorageController,\n} from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport log from 'loglevel';\n\nimport { USER_STORAGE_VERSION_KEY } from './constants/constants';\nimport { TRIGGER_TYPES } from './constants/notification-schema';\nimport { safeProcessNotification } from './processors/process-notifications';\nimport * as FeatureNotifications from './services/feature-announcements';\nimport * as OnChainNotifications from './services/onchain-notifications';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n RawNotificationUnion,\n} from './types/notification/notification';\nimport type { OnChainRawNotification } from './types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from './types/user-storage/user-storage';\nimport * as Utils from './utils/utils';\n\n// TODO: Fix Circular Type Dependencies\n// This indicates that control flow of messages is everywhere, lets orchestrate these better\nexport type NotificationServicesPushControllerEnablePushNotifications = {\n type: `NotificationServicesPushController:enablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerDisablePushNotifications = {\n type: `NotificationServicesPushController:disablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerUpdateTriggerPushNotifications = {\n type: `NotificationServicesPushController:updateTriggerPushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerSubscribeToNotifications = {\n type: `NotificationServicesPushController:subscribeToPushNotifications`;\n handler: () => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerOnNewNotification = {\n type: `NotificationServicesPushController:onNewNotifications`;\n payload: [INotification];\n};\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visted 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 persist: true,\n anonymous: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n persist: true,\n anonymous: false,\n },\n isNotificationServicesEnabled: {\n persist: true,\n anonymous: false,\n },\n isFeatureAnnouncementsEnabled: {\n persist: true,\n anonymous: false,\n },\n metamaskNotificationsList: {\n persist: true,\n anonymous: true,\n },\n metamaskNotificationsReadList: {\n persist: true,\n anonymous: true,\n },\n isUpdatingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isFetchingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isUpdatingMetamaskNotificationsAccount: {\n persist: false,\n anonymous: false,\n },\n isCheckingAccountsPresence: {\n persist: false,\n anonymous: false,\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\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationServicesControllerUpdateMetamaskNotificationsList = {\n type: `${typeof controllerName}:updateMetamaskNotificationsList`;\n handler: NotificationServicesController['updateMetamaskNotificationsList'];\n};\n\nexport type NotificationServicesControllerDisableNotificationServices = {\n type: `${typeof controllerName}:disableNotificationServices`;\n handler: NotificationServicesController['disableNotificationServices'];\n};\n\nexport type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `${typeof controllerName}:selectIsNotificationServicesEnabled`;\n handler: NotificationServicesController['selectIsNotificationServicesEnabled'];\n };\n\nexport type NotificationServicesControllerGetNotificationsByType = {\n type: `${typeof controllerName}:getNotificationsByType`;\n handler: NotificationServicesController['getNotificationsByType'];\n};\n\nexport type NotificationServicesControllerDeleteNotificationsById = {\n type: `${typeof controllerName}:deleteNotificationsById`;\n handler: NotificationServicesController['deleteNotificationsById'];\n};\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerUpdateMetamaskNotificationsList\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n | NotificationServicesControllerGetNotificationsByType\n | NotificationServicesControllerDeleteNotificationsById;\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerIsSignedIn\n // User Storage Controller Requests\n | UserStorageController.UserStorageControllerEnableProfileSyncing\n | UserStorageController.UserStorageControllerGetStorageKey\n | UserStorageController.UserStorageControllerPerformGetStorage\n | UserStorageController.UserStorageControllerPerformSetStorage\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerEnablePushNotifications\n | NotificationServicesPushControllerDisablePushNotifications\n | NotificationServicesPushControllerUpdateTriggerPushNotifications\n | NotificationServicesPushControllerSubscribeToNotifications;\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\nexport type AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotification;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport default class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n // Temporary boolean as push notifications are not yet enabled on mobile\n #isPushIntegrated = true;\n\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 #isPushNotificationsSetup = false;\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>) => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#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.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n };\n\n #storage = {\n enableProfileSyncing: async () => {\n return await this.messagingSystem.call(\n 'UserStorageController:enableProfileSyncing',\n );\n },\n getStorageKey: () => {\n return this.messagingSystem.call('UserStorageController:getStorageKey');\n },\n getNotificationStorage: async () => {\n return await this.messagingSystem.call(\n 'UserStorageController:performGetStorage',\n 'notifications.notification_settings',\n );\n },\n setNotificationStorage: async (state: string) => {\n return await this.messagingSystem.call(\n 'UserStorageController:performSetStorage',\n 'notifications.notification_settings',\n state,\n );\n },\n };\n\n #pushNotifications = {\n subscribeToPushNotifications: async () => {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:enablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to enable push notifications', e);\n }\n },\n disablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:disablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to disable push notifications', e);\n }\n },\n updatePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to update push notifications', e);\n }\n },\n subscribe: () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n this.messagingSystem.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (notification) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateMetamaskNotificationsList(notification);\n },\n );\n },\n initializePushNotifications: async () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#isPushNotificationsSetup) {\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 if (this.#isUnlocked) {\n const storage = await this.#getUserStorage();\n if (!storage) {\n return;\n }\n\n const uuids = Utils.getAllUUIDs(storage);\n await this.#pushNotifications.enablePushNotifications(uuids);\n this.#isPushNotificationsSetup = true;\n } else {\n await this.#pushNotifications.subscribeToPushNotifications();\n }\n },\n };\n\n #accounts = {\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: async () => {\n // Get previous and current account sets\n const nonChecksumAccounts = await this.messagingSystem.call(\n 'KeyringController:getAccounts',\n );\n const accounts = nonChecksumAccounts.map((a) => toChecksumHexAddress(a));\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((a) => !prevAccountsSet.has(a));\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (a) => !currentAccountsSet.has(a),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...prevAccountsSet, ...accountsAdded];\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 * @returns result from list accounts\n */\n initialize: () => {\n return this.#accounts.listAccounts();\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: () => {\n this.messagingSystem.subscribe(\n 'KeyringController:stateChange',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n await this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.updateOnChainTriggersByAccount(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.deleteOnChainTriggersByAccount(accountsRemoved));\n }\n await Promise.all(promises);\n },\n );\n },\n };\n\n #featureAnnouncementEnv: FeatureAnnouncementEnv;\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.isPushIntegrated - toggle push notifications on/off if client has integrated them.\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n isPushIntegrated?: boolean;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#isPushIntegrated = env.isPushIntegrated ?? true;\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#registerMessageHandlers();\n this.#clearLoadingStates();\n\n this.#keyringController.setupLockedStateSubscriptions(\n this.#pushNotifications.initializePushNotifications,\n );\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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 #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateMetamaskNotificationsList`,\n this.updateMetamaskNotificationsList.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disableNotificationServices`,\n this.disableNotificationServices.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:selectIsNotificationServicesEnabled`,\n this.selectIsNotificationServicesEnabled.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getNotificationsByType`,\n this.getNotificationsByType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteNotificationsById`,\n this.deleteNotificationsById.bind(this),\n );\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() {\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 #getValidStorageKeyAndBearerToken() {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n const storageKey = await this.#storage.getStorageKey();\n\n if (!bearerToken || !storageKey) {\n throw new Error('Missing BearerToken or storage key');\n }\n\n return { bearerToken, storageKey };\n }\n\n #performEnableProfileSyncing = async () => {\n try {\n await this.#storage.enableProfileSyncing();\n } catch (e) {\n log.error('Failed to enable profile syncing', e);\n throw new Error('Failed to enable profile syncing');\n }\n };\n\n #assertUserStorage(\n storage: UserStorage | null,\n ): asserts storage is UserStorage {\n if (!storage) {\n throw new Error('User Storage does not exist');\n }\n }\n\n /**\n * Retrieves and parses the user storage from the storage key.\n *\n * This method attempts to retrieve the user storage using the specified storage key,\n * then parses the JSON string to an object. If the storage is not found or cannot be parsed,\n * it throws an error.\n *\n * @returns The parsed user storage object or null\n */\n async #getUserStorage(): Promise<UserStorage | null> {\n const userStorageString: string | null =\n await this.#storage.getNotificationStorage();\n\n if (!userStorageString) {\n return null;\n }\n\n try {\n const userStorage: UserStorage = JSON.parse(userStorageString);\n return userStorage;\n } catch (error) {\n log.error('Unable to parse User Storage');\n return null;\n }\n }\n\n /**\n * Retrieves the current enabled state of MetaMask notifications.\n *\n * This method directly returns the boolean value of `isMetamaskNotificationsEnabled`\n * from the controller's state, indicating whether MetaMask notifications are currently enabled.\n *\n * @returns The enabled state of MetaMask notifications.\n */\n public selectIsNotificationServicesEnabled(): boolean {\n return this.state.isNotificationServicesEnabled;\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 ) {\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 ) {\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) {\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[]) {\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[]) {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n // Retrieve user storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n const presence = Utils.checkAccountsPresence(userStorage, accounts);\n return presence;\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 ) {\n try {\n this.update((s) => {\n s.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (e) {\n log.error('Unable to toggle feature announcements', e);\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 * @param opts - optional options to mutate this functionality\n * @param opts.resetNotifications - this will not use the users stored preferences, and instead re-create notification triggers\n * It will help in case uses get into a corrupted state or wants to wipe their notifications.\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(opts?: {\n resetNotifications?: boolean;\n }): Promise<UserStorage> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n await this.#performEnableProfileSyncing();\n\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n const { accounts } = await this.#accounts.listAccounts();\n\n // Attempt Get User Storage\n // Will be null if entry does not exist, or a user is resetting their notifications\n // Will be defined if entry exists\n // Will throw if fails to get the user storage entry\n let userStorage = opts?.resetNotifications\n ? null\n : await this.#getUserStorage();\n\n // If userStorage does not exist, create a new one\n // All the triggers created are set as: \"disabled\"\n if (userStorage?.[USER_STORAGE_VERSION_KEY] === undefined) {\n userStorage = Utils.initializeUserStorage(\n accounts.map((account) => ({ address: account })),\n false,\n );\n\n // Write the userStorage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n }\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage);\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n\n // Create push notifications triggers\n const allUUIDS = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.enablePushNotifications(allUUIDS);\n\n // Write the new userStorage (triggers are now \"enabled\")\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Update the state of the controller\n this.update((state) => {\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n });\n\n return userStorage;\n } catch (err) {\n log.error('Failed to create On Chain triggers', err);\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 * 1. Enable Profile Syncing\n * 2. Get or Create Notification User Storage\n * 3. Upsert Triggers\n * 4. Update Push notifications\n *\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n await this.createOnChainTriggers();\n } catch (e) {\n log.error('Unable to enable notifications', e);\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() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Disable Push Notifications\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n // Clear Notification States (toggles and list)\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 } catch (e) {\n log.error('Unable to disable notifications', e);\n throw new Error('Unable to disable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account.\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and deletes all triggers associated with the account\n * 3. Disables any related push notifications\n * 4. Updates Storage to reflect new state.\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 deleteOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Get the UUIDs to delete\n const UUIDs = accounts\n .map((a) => Utils.getUUIDsForAccount(userStorage, a.toLowerCase()))\n .flat();\n\n if (UUIDs.length === 0) {\n return userStorage;\n }\n\n // Delete these UUIDs (Mutates User Storage)\n await OnChainNotifications.deleteOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n UUIDs,\n );\n\n // Delete these UUIDs from the push notifications\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n // Update User Storage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to delete OnChain triggers', err);\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 updateOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Add any missing triggers\n accounts.forEach((a) => Utils.upsertAddressTriggers(a, userStorage));\n\n const newTriggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return t;\n }\n return undefined;\n },\n });\n\n // Create any missing triggers.\n if (newTriggers.length > 0) {\n // Write te updated userStorage (where triggers are disabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (\n accounts.some((a) => a.toLowerCase() === t.address.toLowerCase())\n ) {\n return t;\n }\n return undefined;\n },\n });\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n }\n\n // Update Push Notifications Triggers\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.updatePushNotifications(UUIDs);\n\n // Update the userStorage (where triggers are enabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to update OnChain triggers', err);\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 * @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\n // Raw Feature Notifications\n const rawFeatureAnnouncementNotifications =\n isGlobalNotifsEnabled && this.state.isFeatureAnnouncementsEnabled\n ? await FeatureNotifications.getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: OnChainRawNotification[] = [];\n if (isGlobalNotifsEnabled) {\n const userStorage = await this.#storage\n .getNotificationStorage()\n .then((s) => s && (JSON.parse(s) as UserStorage))\n .catch(() => null);\n const bearerToken = await this.#auth.getBearerToken().catch(() => null);\n if (userStorage && bearerToken) {\n const notifications =\n await OnChainNotifications.getOnChainNotifications(\n userStorage,\n bearerToken,\n ).catch(() => []);\n\n rawOnChainNotifications.push(...notifications);\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 // Process Notifications\n const readIds = this.state.metamaskNotificationsReadList;\n const isNotUndefined = <Item>(t?: Item): t is Item => Boolean(t);\n const processAndFilter = (ns: RawNotificationUnion[]) =>\n ns\n .map((n) => safeProcessNotification(n, readIds))\n .filter(isNotUndefined);\n\n const featureAnnouncementNotifications = processAndFilter(\n rawFeatureAnnouncementNotifications,\n );\n const onChainNotifications = processAndFilter(rawOnChainNotifications);\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...featureAnnouncementNotifications,\n ...onChainNotifications,\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (err) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', err);\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) {\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) {\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[]) {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messagingSystem.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 OnChainNotifications.markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\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 (err) {\n log.warn('Something failed when marking notifications as read', err);\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.messagingSystem.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) => n.id === notification.id)\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) => n.id),\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.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NotificationServicesController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesController/NotificationServicesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,mCAAmC;AAYlE,OAAO,EAAE,MAAM,EAAE,wBAAwB;AACzC,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EAAE,wBAAwB,EAAE,kCAA8B;AACjE,OAAO,EAAE,aAAa,EAAE,4CAAwC;AAChE,OAAO,EAAE,uBAAuB,EAAE,+CAA2C;AAC7E,OAAO,KAAK,oBAAoB,6CAAyC;AACzE,OAAO,KAAK,oBAAoB,6CAAyC;AAQzE,OAAO,KAAK,KAAK,0BAAsB;AA6BvC,iCAAiC;AACjC,MAAM,cAAc,GAAG,gCAAgC,CAAC;AAwDxD,MAAM,QAAQ,GAAuD;IACnE,wBAAwB,EAAE;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IAED,kCAAkC,EAAE;QAClC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,6BAA6B,EAAE;Q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C;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;eAldkB,8BAA8B","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { toChecksumHexAddress } from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetAccountsAction,\n KeyringControllerStateChangeEvent,\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n AuthenticationController,\n UserStorageController,\n} from '@metamask/profile-sync-controller';\nimport { assert } from '@metamask/utils';\nimport log from 'loglevel';\n\nimport { USER_STORAGE_VERSION_KEY } from './constants/constants';\nimport { TRIGGER_TYPES } from './constants/notification-schema';\nimport { safeProcessNotification } from './processors/process-notifications';\nimport * as FeatureNotifications from './services/feature-announcements';\nimport * as OnChainNotifications from './services/onchain-notifications';\nimport type {\n INotification,\n MarkAsReadNotificationsParam,\n RawNotificationUnion,\n} from './types/notification/notification';\nimport type { OnChainRawNotification } from './types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from './types/user-storage/user-storage';\nimport * as Utils from './utils/utils';\n\n// TODO: Fix Circular Type Dependencies\n// This indicates that control flow of messages is everywhere, lets orchestrate these better\nexport type NotificationServicesPushControllerEnablePushNotifications = {\n type: `NotificationServicesPushController:enablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerDisablePushNotifications = {\n type: `NotificationServicesPushController:disablePushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerUpdateTriggerPushNotifications = {\n type: `NotificationServicesPushController:updateTriggerPushNotifications`;\n handler: (UUIDs: string[]) => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerSubscribeToNotifications = {\n type: `NotificationServicesPushController:subscribeToPushNotifications`;\n handler: () => Promise<void>;\n};\n\nexport type NotificationServicesPushControllerOnNewNotification = {\n type: `NotificationServicesPushController:onNewNotifications`;\n payload: [INotification];\n};\n\n// Unique name for the controller\nconst controllerName = 'NotificationServicesController';\n\n/**\n * State shape for NotificationServicesController\n */\nexport type NotificationServicesControllerState = {\n /**\n * We store and manage accounts that have been seen/visted 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 persist: true,\n anonymous: true,\n },\n\n isMetamaskNotificationsFeatureSeen: {\n persist: true,\n anonymous: false,\n },\n isNotificationServicesEnabled: {\n persist: true,\n anonymous: false,\n },\n isFeatureAnnouncementsEnabled: {\n persist: true,\n anonymous: false,\n },\n metamaskNotificationsList: {\n persist: true,\n anonymous: true,\n },\n metamaskNotificationsReadList: {\n persist: true,\n anonymous: true,\n },\n isUpdatingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isFetchingMetamaskNotifications: {\n persist: false,\n anonymous: false,\n },\n isUpdatingMetamaskNotificationsAccount: {\n persist: false,\n anonymous: false,\n },\n isCheckingAccountsPresence: {\n persist: false,\n anonymous: false,\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\nconst locallyPersistedNotificationTypes = new Set<TRIGGER_TYPES>([\n TRIGGER_TYPES.SNAP,\n]);\n\nexport type NotificationServicesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesControllerState\n >;\n\nexport type NotificationServicesControllerUpdateMetamaskNotificationsList = {\n type: `${typeof controllerName}:updateMetamaskNotificationsList`;\n handler: NotificationServicesController['updateMetamaskNotificationsList'];\n};\n\nexport type NotificationServicesControllerDisableNotificationServices = {\n type: `${typeof controllerName}:disableNotificationServices`;\n handler: NotificationServicesController['disableNotificationServices'];\n};\n\nexport type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `${typeof controllerName}:selectIsNotificationServicesEnabled`;\n handler: NotificationServicesController['selectIsNotificationServicesEnabled'];\n };\n\nexport type NotificationServicesControllerGetNotificationsByType = {\n type: `${typeof controllerName}:getNotificationsByType`;\n handler: NotificationServicesController['getNotificationsByType'];\n};\n\nexport type NotificationServicesControllerDeleteNotificationsById = {\n type: `${typeof controllerName}:deleteNotificationsById`;\n handler: NotificationServicesController['deleteNotificationsById'];\n};\n\n// Messenger Actions\nexport type Actions =\n | NotificationServicesControllerGetStateAction\n | NotificationServicesControllerUpdateMetamaskNotificationsList\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n | NotificationServicesControllerGetNotificationsByType\n | NotificationServicesControllerDeleteNotificationsById;\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Controller Requests\n | KeyringControllerGetAccountsAction\n | KeyringControllerGetStateAction\n // Auth Controller Requests\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerIsSignedIn\n | AuthenticationController.AuthenticationControllerPerformSignIn\n // User Storage Controller Requests\n | UserStorageController.UserStorageControllerGetStorageKey\n | UserStorageController.UserStorageControllerPerformGetStorage\n | UserStorageController.UserStorageControllerPerformSetStorage\n // Push Notifications Controller Requests\n | NotificationServicesPushControllerEnablePushNotifications\n | NotificationServicesPushControllerDisablePushNotifications\n | NotificationServicesPushControllerUpdateTriggerPushNotifications\n | NotificationServicesPushControllerSubscribeToNotifications;\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\nexport type AllowedEvents =\n // Keyring Events\n | KeyringControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Push Notification Events\n | NotificationServicesPushControllerOnNewNotification;\n\n// Type for the messenger of NotificationServicesController\nexport type NotificationServicesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\ntype FeatureAnnouncementEnv = {\n spaceId: string;\n accessToken: string;\n platform: 'extension' | 'mobile';\n};\n\n/**\n * Controller that enables wallet notifications and feature announcements\n */\nexport default class NotificationServicesController extends BaseController<\n typeof controllerName,\n NotificationServicesControllerState,\n NotificationServicesControllerMessenger\n> {\n // Temporary boolean as push notifications are not yet enabled on mobile\n readonly #isPushIntegrated: boolean = true;\n\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 #isPushNotificationsSetup = false;\n\n #isUnlocked = false;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: (onUnlock: () => Promise<void>) => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#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.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #storage = {\n getStorageKey: () => {\n return this.messagingSystem.call('UserStorageController:getStorageKey');\n },\n getNotificationStorage: async () => {\n return await this.messagingSystem.call(\n 'UserStorageController:performGetStorage',\n 'notifications.notification_settings',\n );\n },\n setNotificationStorage: async (state: string) => {\n return await this.messagingSystem.call(\n 'UserStorageController:performSetStorage',\n 'notifications.notification_settings',\n state,\n );\n },\n };\n\n readonly #pushNotifications = {\n subscribeToPushNotifications: async () => {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n );\n },\n enablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:enablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to enable push notifications', e);\n }\n },\n disablePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:disablePushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to disable push notifications', e);\n }\n },\n updatePushNotifications: async (UUIDs: string[]) => {\n if (!this.#isPushIntegrated) {\n return;\n }\n try {\n await this.messagingSystem.call(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n UUIDs,\n );\n } catch (e) {\n log.error('Silently failed to update push notifications', e);\n }\n },\n subscribe: () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n this.messagingSystem.subscribe(\n 'NotificationServicesPushController:onNewNotifications',\n (notification) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateMetamaskNotificationsList(notification);\n },\n );\n },\n initializePushNotifications: async () => {\n if (!this.#isPushIntegrated) {\n return;\n }\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n if (this.#isPushNotificationsSetup) {\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 if (this.#isUnlocked) {\n const storage = await this.#getUserStorage();\n if (!storage) {\n return;\n }\n\n const uuids = Utils.getAllUUIDs(storage);\n await this.#pushNotifications.enablePushNotifications(uuids);\n this.#isPushNotificationsSetup = true;\n } else {\n await this.#pushNotifications.subscribeToPushNotifications();\n }\n },\n };\n\n readonly #accounts = {\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: async () => {\n // Get previous and current account sets\n const nonChecksumAccounts = await this.messagingSystem.call(\n 'KeyringController:getAccounts',\n );\n const accounts = nonChecksumAccounts.map((a) => toChecksumHexAddress(a));\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((a) => !prevAccountsSet.has(a));\n const accountsRemoved = [...prevAccountsSet.values()].filter(\n (a) => !currentAccountsSet.has(a),\n );\n\n // Update accounts seen\n this.update((state) => {\n state.subscriptionAccountsSeen = [...prevAccountsSet, ...accountsAdded];\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 * @returns result from list accounts\n */\n initialize: () => {\n return this.#accounts.listAccounts();\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: () => {\n this.messagingSystem.subscribe(\n 'KeyringController:stateChange',\n\n async () => {\n if (!this.state.isNotificationServicesEnabled) {\n return;\n }\n\n const { accountsAdded, accountsRemoved } =\n await this.#accounts.listAccounts();\n\n const promises: Promise<unknown>[] = [];\n if (accountsAdded.length > 0) {\n promises.push(this.updateOnChainTriggersByAccount(accountsAdded));\n }\n if (accountsRemoved.length > 0) {\n promises.push(this.deleteOnChainTriggersByAccount(accountsRemoved));\n }\n await Promise.all(promises);\n },\n );\n },\n };\n\n readonly #featureAnnouncementEnv: FeatureAnnouncementEnv;\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.isPushIntegrated - toggle push notifications on/off if client has integrated them.\n */\n constructor({\n messenger,\n state,\n env,\n }: {\n messenger: NotificationServicesControllerMessenger;\n state?: Partial<NotificationServicesControllerState>;\n env: {\n featureAnnouncements: FeatureAnnouncementEnv;\n isPushIntegrated?: boolean;\n };\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#isPushIntegrated = env.isPushIntegrated ?? true;\n this.#featureAnnouncementEnv = env.featureAnnouncements;\n this.#registerMessageHandlers();\n this.#clearLoadingStates();\n\n this.#keyringController.setupLockedStateSubscriptions(\n this.#pushNotifications.initializePushNotifications,\n );\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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 #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateMetamaskNotificationsList`,\n this.updateMetamaskNotificationsList.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disableNotificationServices`,\n this.disableNotificationServices.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:selectIsNotificationServicesEnabled`,\n this.selectIsNotificationServicesEnabled.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getNotificationsByType`,\n this.getNotificationsByType.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteNotificationsById`,\n this.deleteNotificationsById.bind(this),\n );\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() {\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 #getValidStorageKeyAndBearerToken() {\n this.#assertAuthEnabled();\n\n const bearerToken = await this.#auth.getBearerToken();\n const storageKey = await this.#storage.getStorageKey();\n\n if (!bearerToken || !storageKey) {\n throw new Error('Missing BearerToken or storage key');\n }\n\n return { bearerToken, storageKey };\n }\n\n #assertUserStorage(\n storage: UserStorage | null,\n ): asserts storage is UserStorage {\n if (!storage) {\n throw new Error('User Storage does not exist');\n }\n }\n\n /**\n * Retrieves and parses the user storage from the storage key.\n *\n * This method attempts to retrieve the user storage using the specified storage key,\n * then parses the JSON string to an object. If the storage is not found or cannot be parsed,\n * it throws an error.\n *\n * @returns The parsed user storage object or null\n */\n async #getUserStorage(): Promise<UserStorage | null> {\n const userStorageString: string | null =\n await this.#storage.getNotificationStorage();\n\n if (!userStorageString) {\n return null;\n }\n\n try {\n const userStorage: UserStorage = JSON.parse(userStorageString);\n return userStorage;\n } catch {\n log.error('Unable to parse User Storage');\n return null;\n }\n }\n\n /**\n * Retrieves the current enabled state of MetaMask notifications.\n *\n * This method directly returns the boolean value of `isMetamaskNotificationsEnabled`\n * from the controller's state, indicating whether MetaMask notifications are currently enabled.\n *\n * @returns The enabled state of MetaMask notifications.\n */\n public selectIsNotificationServicesEnabled(): boolean {\n return this.state.isNotificationServicesEnabled;\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 ) {\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 ) {\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) {\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[]) {\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[]) {\n this.update((state) => {\n state.isUpdatingMetamaskNotificationsAccount =\n state.isUpdatingMetamaskNotificationsAccount.filter(\n (existingAccount) => !accounts.includes(existingAccount),\n );\n });\n }\n\n public async checkAccountsPresence(\n accounts: string[],\n ): Promise<Record<string, boolean>> {\n try {\n this.#setIsCheckingAccountsPresence(true);\n\n // Retrieve user storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n const presence = Utils.checkAccountsPresence(userStorage, accounts);\n return presence;\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 ) {\n try {\n this.update((s) => {\n s.isFeatureAnnouncementsEnabled = featureAnnouncementsEnabled;\n });\n } catch (e) {\n log.error('Unable to toggle feature announcements', e);\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 * @param opts - optional options to mutate this functionality\n * @param opts.resetNotifications - this will not use the users stored preferences, and instead re-create notification triggers\n * It will help in case uses get into a corrupted state or wants to wipe their notifications.\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(opts?: {\n resetNotifications?: boolean;\n }): Promise<UserStorage> {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n const { accounts } = await this.#accounts.listAccounts();\n\n // Attempt Get User Storage\n // Will be null if entry does not exist, or a user is resetting their notifications\n // Will be defined if entry exists\n // Will throw if fails to get the user storage entry\n let userStorage = opts?.resetNotifications\n ? null\n : await this.#getUserStorage();\n\n // If userStorage does not exist, create a new one\n // All the triggers created are set as: \"disabled\"\n if (userStorage?.[USER_STORAGE_VERSION_KEY] === undefined) {\n userStorage = Utils.initializeUserStorage(\n accounts.map((account) => ({ address: account })),\n false,\n );\n\n // Write the userStorage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n }\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage);\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n\n // Create push notifications triggers\n const allUUIDS = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.enablePushNotifications(allUUIDS);\n\n // Write the new userStorage (triggers are now \"enabled\")\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Update the state of the controller\n this.update((state) => {\n state.isNotificationServicesEnabled = true;\n state.isFeatureAnnouncementsEnabled = true;\n state.isMetamaskNotificationsFeatureSeen = true;\n });\n\n return userStorage;\n } catch (err) {\n log.error('Failed to create On Chain triggers', err);\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 * 1. Enable Profile Syncing\n * 2. Get or Create Notification User Storage\n * 3. Upsert Triggers\n * 4. Update Push notifications\n *\n * @throws {Error} If there is an error during the process of enabling notifications.\n */\n public async enableMetamaskNotifications() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n\n await this.createOnChainTriggers();\n } catch (e) {\n log.error('Unable to enable notifications', e);\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() {\n try {\n this.#setIsUpdatingMetamaskNotifications(true);\n\n // Disable Push Notifications\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n const snapNotifications = this.state.metamaskNotificationsList.filter(\n (notification) => notification.type === TRIGGER_TYPES.SNAP,\n );\n\n // Clear Notification States (toggles and list)\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 } catch (e) {\n log.error('Unable to disable notifications', e);\n throw new Error('Unable to disable notifications');\n } finally {\n this.#setIsUpdatingMetamaskNotifications(false);\n }\n }\n\n /**\n * Deletes on-chain triggers associated with a specific account.\n * This method performs several key operations:\n * 1. Validates Auth & Storage\n * 2. Finds and deletes all triggers associated with the account\n * 3. Disables any related push notifications\n * 4. Updates Storage to reflect new state.\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 deleteOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Get the UUIDs to delete\n const UUIDs = accounts\n .map((a) => Utils.getUUIDsForAccount(userStorage, a.toLowerCase()))\n .flat();\n\n if (UUIDs.length === 0) {\n return userStorage;\n }\n\n // Delete these UUIDs (Mutates User Storage)\n await OnChainNotifications.deleteOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n UUIDs,\n );\n\n // Delete these UUIDs from the push notifications\n await this.#pushNotifications.disablePushNotifications(UUIDs);\n\n // Update User Storage\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to delete OnChain triggers', err);\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 updateOnChainTriggersByAccount(\n accounts: string[],\n ): Promise<UserStorage> {\n try {\n this.#updateUpdatingAccountsState(accounts);\n // Get and Validate BearerToken and User Storage Key\n const { bearerToken, storageKey } =\n await this.#getValidStorageKeyAndBearerToken();\n\n // Get & Validate User Storage\n const userStorage = await this.#getUserStorage();\n this.#assertUserStorage(userStorage);\n\n // Add any missing triggers\n accounts.forEach((a) => Utils.upsertAddressTriggers(a, userStorage));\n\n const newTriggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return t;\n }\n return undefined;\n },\n });\n\n // Create any missing triggers.\n if (newTriggers.length > 0) {\n // Write te updated userStorage (where triggers are disabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n\n // Create the triggers\n const triggers = Utils.traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (\n accounts.some((a) => a.toLowerCase() === t.address.toLowerCase())\n ) {\n return t;\n }\n return undefined;\n },\n });\n await OnChainNotifications.createOnChainTriggers(\n userStorage,\n storageKey,\n bearerToken,\n triggers,\n );\n }\n\n // Update Push Notifications Triggers\n const UUIDs = Utils.getAllUUIDs(userStorage);\n await this.#pushNotifications.updatePushNotifications(UUIDs);\n\n // Update the userStorage (where triggers are enabled)\n await this.#storage.setNotificationStorage(JSON.stringify(userStorage));\n return userStorage;\n } catch (err) {\n log.error('Failed to update OnChain triggers', err);\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\n // Raw Feature Notifications\n const rawFeatureAnnouncementNotifications =\n isGlobalNotifsEnabled && this.state.isFeatureAnnouncementsEnabled\n ? await FeatureNotifications.getFeatureAnnouncementNotifications(\n this.#featureAnnouncementEnv,\n previewToken,\n ).catch(() => [])\n : [];\n\n // Raw On Chain Notifications\n const rawOnChainNotifications: OnChainRawNotification[] = [];\n if (isGlobalNotifsEnabled) {\n const userStorage = await this.#storage\n .getNotificationStorage()\n .then((s) => s && (JSON.parse(s) as UserStorage))\n .catch(() => null);\n const bearerToken = await this.#auth.getBearerToken().catch(() => null);\n if (userStorage && bearerToken) {\n const notifications =\n await OnChainNotifications.getOnChainNotifications(\n userStorage,\n bearerToken,\n ).catch(() => []);\n\n rawOnChainNotifications.push(...notifications);\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 // Process Notifications\n const readIds = this.state.metamaskNotificationsReadList;\n const isNotUndefined = <Item>(t?: Item): t is Item => Boolean(t);\n const processAndFilter = (ns: RawNotificationUnion[]) =>\n ns\n .map((n) => safeProcessNotification(n, readIds))\n .filter(isNotUndefined);\n\n const featureAnnouncementNotifications = processAndFilter(\n rawFeatureAnnouncementNotifications,\n );\n const onChainNotifications = processAndFilter(rawOnChainNotifications);\n\n // Combine Notifications\n const metamaskNotifications: INotification[] = [\n ...featureAnnouncementNotifications,\n ...onChainNotifications,\n ...snapNotifications,\n ];\n\n // Sort Notifications\n metamaskNotifications.sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n );\n\n // Update State\n this.update((state) => {\n state.metamaskNotificationsList = metamaskNotifications;\n });\n\n this.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n\n this.#setIsFetchingMetamaskNotifications(false);\n return metamaskNotifications;\n } catch (err) {\n this.#setIsFetchingMetamaskNotifications(false);\n log.error('Failed to fetch notifications', err);\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) {\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) {\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[]) {\n for (const id of ids) {\n await this.deleteNotificationById(id);\n }\n\n this.messagingSystem.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 OnChainNotifications.markNotificationsAsRead(\n bearerToken,\n onchainNotificationIds,\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 (err) {\n log.warn('Something failed when marking notifications as read', err);\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.messagingSystem.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) => n.id === notification.id)\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) => n.id),\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.messagingSystem.publish(\n `${controllerName}:notificationsListUpdated`,\n this.state.metamaskNotificationsList,\n );\n }\n }\n}\n"]}
|
package/package.json
CHANGED