@metamask-previews/notification-services-controller 10.0.0-preview-7dcef379 → 10.0.0-preview-f9611039

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +0 -16
  2. package/dist/NotificationServicesController/NotificationServicesController.cjs +188 -76
  3. package/dist/NotificationServicesController/NotificationServicesController.cjs.map +1 -1
  4. package/dist/NotificationServicesController/NotificationServicesController.d.cts +16 -10
  5. package/dist/NotificationServicesController/NotificationServicesController.d.cts.map +1 -1
  6. package/dist/NotificationServicesController/NotificationServicesController.d.mts +16 -10
  7. package/dist/NotificationServicesController/NotificationServicesController.d.mts.map +1 -1
  8. package/dist/NotificationServicesController/NotificationServicesController.mjs +189 -77
  9. package/dist/NotificationServicesController/NotificationServicesController.mjs.map +1 -1
  10. package/dist/NotificationServicesController/constants/constants.cjs +7 -0
  11. package/dist/NotificationServicesController/constants/constants.cjs.map +1 -0
  12. package/dist/NotificationServicesController/constants/constants.d.cts +3 -0
  13. package/dist/NotificationServicesController/constants/constants.d.cts.map +1 -0
  14. package/dist/NotificationServicesController/constants/constants.d.mts +3 -0
  15. package/dist/NotificationServicesController/constants/constants.d.mts.map +1 -0
  16. package/dist/NotificationServicesController/constants/constants.mjs +4 -0
  17. package/dist/NotificationServicesController/constants/constants.mjs.map +1 -0
  18. package/dist/NotificationServicesController/constants/index.cjs +1 -0
  19. package/dist/NotificationServicesController/constants/index.cjs.map +1 -1
  20. package/dist/NotificationServicesController/constants/index.d.cts +1 -0
  21. package/dist/NotificationServicesController/constants/index.d.cts.map +1 -1
  22. package/dist/NotificationServicesController/constants/index.d.mts +1 -0
  23. package/dist/NotificationServicesController/constants/index.d.mts.map +1 -1
  24. package/dist/NotificationServicesController/constants/index.mjs +1 -0
  25. package/dist/NotificationServicesController/constants/index.mjs.map +1 -1
  26. package/dist/NotificationServicesController/mocks/index.cjs +2 -0
  27. package/dist/NotificationServicesController/mocks/index.cjs.map +1 -1
  28. package/dist/NotificationServicesController/mocks/index.d.cts +2 -0
  29. package/dist/NotificationServicesController/mocks/index.d.cts.map +1 -1
  30. package/dist/NotificationServicesController/mocks/index.d.mts +2 -0
  31. package/dist/NotificationServicesController/mocks/index.d.mts.map +1 -1
  32. package/dist/NotificationServicesController/mocks/index.mjs +2 -0
  33. package/dist/NotificationServicesController/mocks/index.mjs.map +1 -1
  34. package/dist/NotificationServicesController/mocks/mock-notification-trigger.cjs +22 -0
  35. package/dist/NotificationServicesController/mocks/mock-notification-trigger.cjs.map +1 -0
  36. package/dist/NotificationServicesController/mocks/mock-notification-trigger.d.cts +9 -0
  37. package/dist/NotificationServicesController/mocks/mock-notification-trigger.d.cts.map +1 -0
  38. package/dist/NotificationServicesController/mocks/mock-notification-trigger.d.mts +9 -0
  39. package/dist/NotificationServicesController/mocks/mock-notification-trigger.d.mts.map +1 -0
  40. package/dist/NotificationServicesController/mocks/mock-notification-trigger.mjs +18 -0
  41. package/dist/NotificationServicesController/mocks/mock-notification-trigger.mjs.map +1 -0
  42. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.cjs +82 -0
  43. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.cjs.map +1 -0
  44. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.d.cts +35 -0
  45. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.d.cts.map +1 -0
  46. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.d.mts +35 -0
  47. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.d.mts.map +1 -0
  48. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.mjs +76 -0
  49. package/dist/NotificationServicesController/mocks/mock-notification-user-storage.mjs.map +1 -0
  50. package/dist/NotificationServicesController/mocks/mockResponses.cjs +9 -9
  51. package/dist/NotificationServicesController/mocks/mockResponses.cjs.map +1 -1
  52. package/dist/NotificationServicesController/mocks/mockResponses.d.cts +4 -7
  53. package/dist/NotificationServicesController/mocks/mockResponses.d.cts.map +1 -1
  54. package/dist/NotificationServicesController/mocks/mockResponses.d.mts +4 -7
  55. package/dist/NotificationServicesController/mocks/mockResponses.d.mts.map +1 -1
  56. package/dist/NotificationServicesController/mocks/mockResponses.mjs +7 -7
  57. package/dist/NotificationServicesController/mocks/mockResponses.mjs.map +1 -1
  58. package/dist/NotificationServicesController/processors/process-notifications.cjs +1 -4
  59. package/dist/NotificationServicesController/processors/process-notifications.cjs.map +1 -1
  60. package/dist/NotificationServicesController/processors/process-notifications.d.cts +0 -623
  61. package/dist/NotificationServicesController/processors/process-notifications.d.cts.map +1 -1
  62. package/dist/NotificationServicesController/processors/process-notifications.d.mts +0 -623
  63. package/dist/NotificationServicesController/processors/process-notifications.d.mts.map +1 -1
  64. package/dist/NotificationServicesController/processors/process-notifications.mjs +0 -2
  65. package/dist/NotificationServicesController/processors/process-notifications.mjs.map +1 -1
  66. package/dist/NotificationServicesController/services/onchain-notifications.cjs +140 -67
  67. package/dist/NotificationServicesController/services/onchain-notifications.cjs.map +1 -1
  68. package/dist/NotificationServicesController/services/onchain-notifications.d.cts +31 -25
  69. package/dist/NotificationServicesController/services/onchain-notifications.d.cts.map +1 -1
  70. package/dist/NotificationServicesController/services/onchain-notifications.d.mts +31 -25
  71. package/dist/NotificationServicesController/services/onchain-notifications.d.mts.map +1 -1
  72. package/dist/NotificationServicesController/services/onchain-notifications.mjs +137 -65
  73. package/dist/NotificationServicesController/services/onchain-notifications.mjs.map +1 -1
  74. package/dist/NotificationServicesController/types/index.cjs.map +1 -1
  75. package/dist/NotificationServicesController/types/index.d.cts +1 -0
  76. package/dist/NotificationServicesController/types/index.d.cts.map +1 -1
  77. package/dist/NotificationServicesController/types/index.d.mts +1 -0
  78. package/dist/NotificationServicesController/types/index.d.mts.map +1 -1
  79. package/dist/NotificationServicesController/types/index.mjs.map +1 -1
  80. package/dist/NotificationServicesController/types/user-storage/index.cjs +3 -0
  81. package/dist/NotificationServicesController/types/user-storage/index.cjs.map +1 -0
  82. package/dist/NotificationServicesController/types/user-storage/index.d.cts +2 -0
  83. package/dist/NotificationServicesController/types/user-storage/index.d.cts.map +1 -0
  84. package/dist/NotificationServicesController/types/user-storage/index.d.mts +2 -0
  85. package/dist/NotificationServicesController/types/user-storage/index.d.mts.map +1 -0
  86. package/dist/NotificationServicesController/types/user-storage/index.mjs +2 -0
  87. package/dist/NotificationServicesController/types/user-storage/index.mjs.map +1 -0
  88. package/dist/NotificationServicesController/types/user-storage/user-storage.cjs +3 -0
  89. package/dist/NotificationServicesController/types/user-storage/user-storage.cjs.map +1 -0
  90. package/dist/NotificationServicesController/types/user-storage/user-storage.d.cts +26 -0
  91. package/dist/NotificationServicesController/types/user-storage/user-storage.d.cts.map +1 -0
  92. package/dist/NotificationServicesController/types/user-storage/user-storage.d.mts +26 -0
  93. package/dist/NotificationServicesController/types/user-storage/user-storage.d.mts.map +1 -0
  94. package/dist/NotificationServicesController/types/user-storage/user-storage.mjs +2 -0
  95. package/dist/NotificationServicesController/types/user-storage/user-storage.mjs.map +1 -0
  96. package/dist/NotificationServicesController/utils/utils.cjs +350 -1
  97. package/dist/NotificationServicesController/utils/utils.cjs.map +1 -1
  98. package/dist/NotificationServicesController/utils/utils.d.cts +141 -0
  99. package/dist/NotificationServicesController/utils/utils.d.cts.map +1 -1
  100. package/dist/NotificationServicesController/utils/utils.d.mts +141 -0
  101. package/dist/NotificationServicesController/utils/utils.d.mts.map +1 -1
  102. package/dist/NotificationServicesController/utils/utils.mjs +337 -0
  103. package/dist/NotificationServicesController/utils/utils.mjs.map +1 -1
  104. package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs +15 -22
  105. package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs.map +1 -1
  106. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts +5 -6
  107. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts.map +1 -1
  108. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts +5 -6
  109. package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts.map +1 -1
  110. package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +16 -23
  111. package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs.map +1 -1
  112. package/dist/NotificationServicesPushController/mocks/mockResponse.cjs +16 -1
  113. package/dist/NotificationServicesPushController/mocks/mockResponse.cjs.map +1 -1
  114. package/dist/NotificationServicesPushController/mocks/mockResponse.d.cts +7 -0
  115. package/dist/NotificationServicesPushController/mocks/mockResponse.d.cts.map +1 -1
  116. package/dist/NotificationServicesPushController/mocks/mockResponse.d.mts +7 -0
  117. package/dist/NotificationServicesPushController/mocks/mockResponse.d.mts.map +1 -1
  118. package/dist/NotificationServicesPushController/mocks/mockResponse.mjs +14 -0
  119. package/dist/NotificationServicesPushController/mocks/mockResponse.mjs.map +1 -1
  120. package/dist/NotificationServicesPushController/services/endpoints.cjs +1 -1
  121. package/dist/NotificationServicesPushController/services/endpoints.cjs.map +1 -1
  122. package/dist/NotificationServicesPushController/services/endpoints.d.cts +1 -1
  123. package/dist/NotificationServicesPushController/services/endpoints.d.cts.map +1 -1
  124. package/dist/NotificationServicesPushController/services/endpoints.d.mts +1 -1
  125. package/dist/NotificationServicesPushController/services/endpoints.d.mts.map +1 -1
  126. package/dist/NotificationServicesPushController/services/endpoints.mjs +1 -1
  127. package/dist/NotificationServicesPushController/services/endpoints.mjs.map +1 -1
  128. package/dist/NotificationServicesPushController/services/services.cjs +41 -18
  129. package/dist/NotificationServicesPushController/services/services.cjs.map +1 -1
  130. package/dist/NotificationServicesPushController/services/services.d.cts +33 -19
  131. package/dist/NotificationServicesPushController/services/services.d.cts.map +1 -1
  132. package/dist/NotificationServicesPushController/services/services.d.mts +33 -19
  133. package/dist/NotificationServicesPushController/services/services.d.mts.map +1 -1
  134. package/dist/NotificationServicesPushController/services/services.mjs +39 -17
  135. package/dist/NotificationServicesPushController/services/services.mjs.map +1 -1
  136. package/package.json +1 -1
  137. package/dist/NotificationServicesController/services/notification-config-cache.cjs +0 -72
  138. package/dist/NotificationServicesController/services/notification-config-cache.cjs.map +0 -1
  139. package/dist/NotificationServicesController/services/notification-config-cache.d.cts +0 -19
  140. package/dist/NotificationServicesController/services/notification-config-cache.d.cts.map +0 -1
  141. package/dist/NotificationServicesController/services/notification-config-cache.d.mts +0 -19
  142. package/dist/NotificationServicesController/services/notification-config-cache.d.mts.map +0 -1
  143. package/dist/NotificationServicesController/services/notification-config-cache.mjs +0 -68
  144. package/dist/NotificationServicesController/services/notification-config-cache.mjs.map +0 -1
@@ -4,95 +4,162 @@ function $importDefault(module) {
4
4
  }
5
5
  return module;
6
6
  }
7
+ import { UserStorageController } from "@metamask/profile-sync-controller";
7
8
  import $log from "loglevel";
8
9
  const log = $importDefault($log);
9
- import { notificationsConfigCache } from "./notification-config-cache.mjs";
10
10
  import { toRawOnChainNotification } from "../../shared/to-raw-notification.mjs";
11
- import { makeApiCall } from "../utils/utils.mjs";
11
+ import { cleanUserStorage, makeApiCall, toggleUserStorageTriggerStatus, traverseUserStorageTriggers } from "../utils/utils.mjs";
12
12
  export const TRIGGER_API = 'https://trigger.api.cx.metamask.io';
13
13
  export const NOTIFICATION_API = 'https://notification.api.cx.metamask.io';
14
- // Gets notification settings for each account provided
15
- export const TRIGGER_API_NOTIFICATIONS_QUERY_ENDPOINT = `${TRIGGER_API}/api/v2/notifications/query`;
16
- // Used to create/update account notifications for each account provided
17
- export const TRIGGER_API_NOTIFICATIONS_ENDPOINT = `${TRIGGER_API}/api/v2/notifications`;
18
- // Lists notifications for each account provided
19
- export const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v2/notifications`;
20
- // Makrs notifications as read
21
- export const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v2/notifications/mark-as-read`;
14
+ export const TRIGGER_API_BATCH_ENDPOINT = `${TRIGGER_API}/api/v1/triggers/batch`;
15
+ export const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications`;
16
+ export const NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY = (page) => `${NOTIFICATION_API_LIST_ENDPOINT}?page=${page}&per_page=100`;
17
+ export const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications/mark-as-read`;
22
18
  /**
23
- * fetches notification config (accounts enabled vs disabled)
19
+ * Creates on-chain triggers based on the provided notification triggers.
20
+ * This method generates a unique token for each trigger using the trigger ID and storage key,
21
+ * proving ownership of the trigger being updated. It then makes an API call to create these triggers.
22
+ * Upon successful creation, it updates the userStorage to reflect the new trigger status.
24
23
  *
25
- * @param bearerToken - jwt
26
- * @param addresses - list of addresses to check
27
- * NOTE the API will return addresses config with false if they have not been created before.
28
- * NOTE this is cached for 1s to prevent multiple update calls
29
- * @returns object of notification config, or null if missing
24
+ * @param userStorage - The user's storage object where triggers and their statuses are stored.
25
+ * @param storageKey - A key used along with the trigger ID to generate a unique token for each trigger.
26
+ * @param bearerToken - The JSON Web Token used for authentication in the API call.
27
+ * @param triggers - An array of notification triggers to be created. Each trigger includes an ID, chain ID, kind, and address.
28
+ * @returns A promise that resolves to void. Throws an error if the API call fails or if there's an issue creating the triggers.
30
29
  */
31
- export async function getOnChainNotificationsConfigCached(bearerToken, addresses) {
32
- if (addresses.length === 0) {
33
- return [];
30
+ export async function createOnChainTriggers(userStorage, storageKey, bearerToken, triggers) {
31
+ const triggersToCreate = triggers.map((t) => ({
32
+ id: t.id,
33
+ token: UserStorageController.createSHA256Hash(t.id + storageKey),
34
+ config: {
35
+ kind: t.kind,
36
+ chain_id: Number(t.chainId),
37
+ address: t.address,
38
+ },
39
+ }));
40
+ if (triggersToCreate.length === 0) {
41
+ return;
34
42
  }
35
- addresses = addresses.map((a) => a.toLowerCase());
36
- const cached = notificationsConfigCache.get(addresses);
37
- if (cached) {
38
- return cached;
43
+ const response = await makeApiCall(bearerToken, TRIGGER_API_BATCH_ENDPOINT, 'POST', triggersToCreate);
44
+ if (!response.ok) {
45
+ const errorData = await response.json().catch(() => undefined);
46
+ log.error('Error creating triggers:', errorData);
47
+ throw new Error('OnChain Notifications - unable to create triggers');
39
48
  }
40
- const body = addresses.map((address) => ({ address }));
41
- const data = await makeApiCall(bearerToken, TRIGGER_API_NOTIFICATIONS_QUERY_ENDPOINT, 'POST', body)
42
- .then((r) => (r.ok ? r.json() : null))
43
- .catch(() => null);
44
- const result = data ?? [];
45
- if (result.length > 0) {
46
- notificationsConfigCache.set(result);
49
+ // If the trigger creation was fine
50
+ // then update the userStorage
51
+ for (const trigger of triggersToCreate) {
52
+ toggleUserStorageTriggerStatus(userStorage, trigger.config.address, String(trigger.config.chain_id), trigger.id, true);
47
53
  }
48
- return result;
54
+ cleanUserStorage(userStorage);
49
55
  }
50
56
  /**
51
- * updates notifications for a given addresses
57
+ * Deletes on-chain triggers based on the provided UUIDs.
58
+ * This method generates a unique token for each trigger using the UUID and storage key,
59
+ * proving ownership of the trigger being deleted. It then makes an API call to delete these triggers.
60
+ * Upon successful deletion, it updates the userStorage to remove the deleted trigger statuses.
52
61
  *
53
- * @param bearerToken - jwt
54
- * @param addresses - list of addresses to check
55
- * @returns void
62
+ * @param userStorage - The user's storage object where triggers and their statuses are stored.
63
+ * @param storageKey - A key used along with the UUID to generate a unique token for each trigger.
64
+ * @param bearerToken - The JSON Web Token used for authentication in the API call.
65
+ * @param uuids - An array of UUIDs representing the triggers to be deleted.
66
+ * @returns A promise that resolves to the updated UserStorage object. Throws an error if the API call fails or if there's an issue deleting the triggers.
56
67
  */
57
- export async function updateOnChainNotifications(bearerToken, addresses) {
58
- if (addresses.length === 0) {
59
- return;
68
+ export async function deleteOnChainTriggers(userStorage, storageKey, bearerToken, uuids) {
69
+ const triggersToDelete = uuids.map((uuid) => ({
70
+ id: uuid,
71
+ token: UserStorageController.createSHA256Hash(uuid + storageKey),
72
+ }));
73
+ try {
74
+ const response = await makeApiCall(bearerToken, TRIGGER_API_BATCH_ENDPOINT, 'DELETE', triggersToDelete);
75
+ if (!response.ok) {
76
+ throw new Error(`Failed to delete on-chain notifications for uuids ${uuids.join(', ')}`);
77
+ }
78
+ // Update the state of the deleted trigger to false
79
+ for (const uuid of uuids) {
80
+ for (const address in userStorage) {
81
+ if (address in userStorage) {
82
+ for (const chainId in userStorage[address]) {
83
+ if (userStorage?.[address]?.[chainId]?.[uuid]) {
84
+ delete userStorage[address][chainId][uuid];
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
90
+ // Follow-up cleanup, if an address had no triggers whatsoever, then we can delete the address
91
+ const isEmpty = (obj = {}) => Object.keys(obj).length === 0;
92
+ for (const address in userStorage) {
93
+ if (address in userStorage) {
94
+ for (const chainId in userStorage[address]) {
95
+ // Chain isEmpty Check
96
+ if (isEmpty(userStorage?.[address]?.[chainId])) {
97
+ delete userStorage[address][chainId];
98
+ }
99
+ }
100
+ // Address isEmpty Check
101
+ if (isEmpty(userStorage?.[address])) {
102
+ delete userStorage[address];
103
+ }
104
+ }
105
+ }
60
106
  }
61
- addresses = addresses.map((a) => {
62
- a.address = a.address.toLowerCase();
63
- return a;
64
- });
65
- const body = addresses;
66
- await makeApiCall(bearerToken, TRIGGER_API_NOTIFICATIONS_ENDPOINT, 'POST', body)
67
- .then(() => notificationsConfigCache.replace(addresses))
68
- .catch(() => null);
107
+ catch (err) {
108
+ log.error(`Error deleting on-chain notifications for uuids ${uuids.join(', ')}:`, err);
109
+ throw err;
110
+ }
111
+ return userStorage;
69
112
  }
70
113
  /**
71
- * Fetches on-chain notifications for the given addresses
114
+ * Fetches on-chain notifications for the given user storage and BearerToken.
115
+ * This method iterates through the userStorage to find enabled triggers and fetches notifications for those triggers.
116
+ * It makes paginated API calls to the notifications service, transforming and aggregating the notifications into a single array.
117
+ * The process stops either when all pages have been fetched or when a page has less than 100 notifications, indicating the end of the data.
72
118
  *
119
+ * @param userStorage - The user's storage object containing trigger information.
73
120
  * @param bearerToken - The JSON Web Token used for authentication in the API call.
74
- * @param addresses - List of addresses
75
121
  * @returns A promise that resolves to an array of OnChainRawNotification objects. If no triggers are enabled or an error occurs, it may return an empty array.
76
122
  */
77
- export async function getOnChainNotifications(bearerToken, addresses) {
78
- if (addresses.length === 0) {
123
+ export async function getOnChainNotifications(userStorage, bearerToken) {
124
+ const triggerIds = traverseUserStorageTriggers(userStorage, {
125
+ mapTrigger: (t) => {
126
+ if (!t.enabled) {
127
+ return undefined;
128
+ }
129
+ return t.id;
130
+ },
131
+ });
132
+ if (triggerIds.length === 0) {
79
133
  return [];
80
134
  }
81
- addresses = addresses.map((a) => a.toLowerCase());
82
- const body = addresses.map((address) => ({ address }));
83
- const notifications = await makeApiCall(bearerToken, NOTIFICATION_API_LIST_ENDPOINT, 'POST', body)
84
- .then((r) => r.ok ? r.json() : null)
85
- .catch(() => null);
86
- // Transform and sort notifications
87
- const transformedNotifications = notifications
88
- ?.map((n) => {
89
- if (!n.data?.kind) {
90
- return undefined;
135
+ const onChainNotifications = [];
136
+ const PAGE_LIMIT = 2;
137
+ for (let page = 1; page <= PAGE_LIMIT; page++) {
138
+ try {
139
+ const response = await makeApiCall(bearerToken, NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY(page), 'POST', { trigger_ids: triggerIds });
140
+ const notifications = (await response.json());
141
+ // Transform and sort notifications
142
+ const transformedNotifications = notifications
143
+ .map((n) => {
144
+ if (!n.data?.kind) {
145
+ return undefined;
146
+ }
147
+ return toRawOnChainNotification(n);
148
+ })
149
+ .filter((n) => Boolean(n));
150
+ onChainNotifications.push(...transformedNotifications);
151
+ // if less than 100 notifications on page, then means we reached end
152
+ if (notifications.length < 100) {
153
+ page = PAGE_LIMIT + 1;
154
+ break;
155
+ }
156
+ }
157
+ catch (err) {
158
+ log.error(`Error fetching on-chain notifications for trigger IDs ${triggerIds.join(', ')}:`, err);
159
+ // do nothing
91
160
  }
92
- return toRawOnChainNotification(n);
93
- })
94
- .filter((n) => Boolean(n));
95
- return transformedNotifications ?? [];
161
+ }
162
+ return onChainNotifications;
96
163
  }
97
164
  /**
98
165
  * Marks the specified notifications as read.
@@ -108,10 +175,15 @@ export async function markNotificationsAsRead(bearerToken, notificationIds) {
108
175
  return;
109
176
  }
110
177
  try {
111
- await makeApiCall(bearerToken, NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT, 'POST', { ids: notificationIds });
178
+ const response = await makeApiCall(bearerToken, NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT, 'POST', { ids: notificationIds });
179
+ if (response.status !== 200) {
180
+ const errorData = await response.json().catch(() => undefined);
181
+ throw new Error(`Error marking notifications as read: ${errorData?.message}`);
182
+ }
112
183
  }
113
184
  catch (err) {
114
185
  log.error('Error marking notifications as read:', err);
186
+ throw err;
115
187
  }
116
188
  }
117
189
  //# sourceMappingURL=onchain-notifications.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"onchain-notifications.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/services/onchain-notifications.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EAAE,wBAAwB,EAAE,wCAAoC;AACvE,OAAO,EAAE,wBAAwB,EAAE,6CAAyC;AAK5E,OAAO,EAAE,WAAW,EAAE,2BAAuB;AAS7C,MAAM,CAAC,MAAM,WAAW,GAAG,oCAAoC,CAAC;AAChE,MAAM,CAAC,MAAM,gBAAgB,GAAG,yCAAyC,CAAC;AAE1E,uDAAuD;AACvD,MAAM,CAAC,MAAM,wCAAwC,GAAG,GAAG,WAAW,6BAA6B,CAAC;AAEpG,wEAAwE;AACxE,MAAM,CAAC,MAAM,kCAAkC,GAAG,GAAG,WAAW,uBAAuB,CAAC;AAExF,gDAAgD;AAChD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,gBAAgB,uBAAuB,CAAC;AAEzF,8BAA8B;AAC9B,MAAM,CAAC,MAAM,0CAA0C,GAAG,GAAG,gBAAgB,oCAAoC,CAAC;AAElH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,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AAC,EAA+B,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAE1D,OAAO,wBAAwB,IAAI,EAAE,CAAC;AACxC,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,WAAmB,EACnB,eAAyB;IAEzB,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE;QAChC,OAAO;KACR;IAED,IAAI;QACF,MAAM,WAAW,CACf,WAAW,EACX,0CAA0C,EAC1C,MAAM,EACN,EAAE,GAAG,EAAE,eAAe,EAAE,CACzB,CAAC;KACH;IAAC,OAAO,GAAG,EAAE;QACZ,GAAG,CAAC,KAAK,CAAC,sCAAsC,EAAE,GAAG,CAAC,CAAC;KACxD;AACH,CAAC","sourcesContent":["import log from 'loglevel';\n\nimport { notificationsConfigCache } from './notification-config-cache';\nimport { toRawOnChainNotification } from '../../shared/to-raw-notification';\nimport type {\n OnChainRawNotification,\n UnprocessedOnChainRawNotification,\n} from '../types/on-chain-notification/on-chain-notification';\nimport { makeApiCall } from '../utils/utils';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n};\n\nexport const TRIGGER_API = 'https://trigger.api.cx.metamask.io';\nexport const NOTIFICATION_API = 'https://notification.api.cx.metamask.io';\n\n// Gets notification settings for each account provided\nexport const TRIGGER_API_NOTIFICATIONS_QUERY_ENDPOINT = `${TRIGGER_API}/api/v2/notifications/query`;\n\n// Used to create/update account notifications for each account provided\nexport const TRIGGER_API_NOTIFICATIONS_ENDPOINT = `${TRIGGER_API}/api/v2/notifications`;\n\n// Lists notifications for each account provided\nexport const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v2/notifications`;\n\n// Makrs notifications as read\nexport const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v2/notifications/mark-as-read`;\n\n/**\n * fetches notification config (accounts enabled vs disabled)\n *\n * @param bearerToken - jwt\n * @param addresses - list of addresses to check\n * NOTE the API will return addresses config with false if they have not been created before.\n * NOTE this is cached for 1s to prevent multiple update calls\n * @returns object of notification config, or null if missing\n */\nexport async function getOnChainNotificationsConfigCached(\n bearerToken: string,\n addresses: string[],\n) {\n if (addresses.length === 0) {\n return [];\n }\n\n addresses = addresses.map((a) => a.toLowerCase());\n\n const cached = notificationsConfigCache.get(addresses);\n if (cached) {\n return cached;\n }\n\n type RequestBody = { address: string }[];\n type Response = { address: string; enabled: boolean }[];\n const body: RequestBody = addresses.map((address) => ({ address }));\n const data = await makeApiCall(\n bearerToken,\n TRIGGER_API_NOTIFICATIONS_QUERY_ENDPOINT,\n 'POST',\n body,\n )\n .then<Response | null>((r) => (r.ok ? r.json() : null))\n .catch(() => null);\n\n const result = data ?? [];\n\n if (result.length > 0) {\n notificationsConfigCache.set(result);\n }\n\n return result;\n}\n\n/**\n * updates notifications for a given addresses\n *\n * @param bearerToken - jwt\n * @param addresses - list of addresses to check\n * @returns void\n */\nexport async function updateOnChainNotifications(\n bearerToken: string,\n addresses: { address: string; enabled: boolean }[],\n) {\n if (addresses.length === 0) {\n return;\n }\n\n addresses = addresses.map((a) => {\n a.address = a.address.toLowerCase();\n return a;\n });\n\n type RequestBody = { address: string; enabled: boolean }[];\n const body: RequestBody = addresses;\n await makeApiCall(\n bearerToken,\n TRIGGER_API_NOTIFICATIONS_ENDPOINT,\n 'POST',\n body,\n )\n .then(() => notificationsConfigCache.replace(addresses))\n .catch(() => null);\n}\n\n/**\n * Fetches on-chain notifications for the given addresses\n *\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param addresses - List of addresses\n * @returns A promise that resolves to an array of OnChainRawNotification objects. If no triggers are enabled or an error occurs, it may return an empty array.\n */\nexport async function getOnChainNotifications(\n bearerToken: string,\n addresses: string[],\n): Promise<OnChainRawNotification[]> {\n if (addresses.length === 0) {\n return [];\n }\n\n addresses = addresses.map((a) => a.toLowerCase());\n\n type RequestBody = { address: string }[];\n const body: RequestBody = addresses.map((address) => ({ address }));\n const notifications = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_LIST_ENDPOINT,\n 'POST',\n body,\n )\n .then<UnprocessedOnChainRawNotification[] | null>((r) =>\n r.ok ? r.json() : null,\n )\n .catch(() => null);\n\n // Transform and sort notifications\n const transformedNotifications = notifications\n ?.map((n): OnChainRawNotification | undefined => {\n if (!n.data?.kind) {\n return undefined;\n }\n\n return toRawOnChainNotification(n);\n })\n .filter((n): n is OnChainRawNotification => Boolean(n));\n\n return transformedNotifications ?? [];\n}\n\n/**\n * Marks the specified notifications as read.\n * This method sends a POST request to the notifications service to mark the provided notification IDs as read.\n * If the operation is successful, it completes without error. If the operation fails, it throws an error with details.\n *\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param notificationIds - An array of notification IDs to be marked as read.\n * @returns A promise that resolves to void. The promise will reject if there's an error during the API call or if the response status is not 200.\n */\nexport async function markNotificationsAsRead(\n bearerToken: string,\n notificationIds: string[],\n): Promise<void> {\n if (notificationIds.length === 0) {\n return;\n }\n\n try {\n await makeApiCall(\n bearerToken,\n NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT,\n 'POST',\n { ids: notificationIds },\n );\n } catch (err) {\n log.error('Error marking notifications as read:', err);\n }\n}\n"]}
1
+ {"version":3,"file":"onchain-notifications.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/services/onchain-notifications.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,qBAAqB,EAAE,0CAA0C;AAC1E,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EAAE,wBAAwB,EAAE,6CAAyC;AAM5E,OAAO,EACL,gBAAgB,EAChB,WAAW,EACX,8BAA8B,EAC9B,2BAA2B,EAC5B,2BAAuB;AASxB,MAAM,CAAC,MAAM,WAAW,GAAG,oCAAoC,CAAC;AAChE,MAAM,CAAC,MAAM,gBAAgB,GAAG,yCAAyC,CAAC;AAC1E,MAAM,CAAC,MAAM,0BAA0B,GAAG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IAED,IAAI;QACF,MAAM,QAAQ,GAAG,MAAM,WAAW,CAChC,WAAW,EACX,0CAA0C,EAC1C,MAAM,EACN,EAAE,GAAG,EAAE,eAAe,EAAE,CACzB,CAAC;QAEF,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE;YAC3B,MAAM,SAAS,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC/D,MAAM,IAAI,KAAK,CACb,wCAAwC,SAAS,EAAE,OAAiB,EAAE,CACvE,CAAC;SACH;KACF;IAAC,OAAO,GAAG,EAAE;QACZ,GAAG,CAAC,KAAK,CAAC,sCAAsC,EAAE,GAAG,CAAC,CAAC;QACvD,MAAM,GAAG,CAAC;KACX;AACH,CAAC","sourcesContent":["import { UserStorageController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport { toRawOnChainNotification } from '../../shared/to-raw-notification';\nimport type {\n OnChainRawNotification,\n UnprocessedOnChainRawNotification,\n} from '../types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from '../types/user-storage/user-storage';\nimport {\n cleanUserStorage,\n makeApiCall,\n toggleUserStorageTriggerStatus,\n traverseUserStorageTriggers,\n} from '../utils/utils';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n};\n\nexport const TRIGGER_API = 'https://trigger.api.cx.metamask.io';\nexport const NOTIFICATION_API = 'https://notification.api.cx.metamask.io';\nexport const TRIGGER_API_BATCH_ENDPOINT = `${TRIGGER_API}/api/v1/triggers/batch`;\nexport const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications`;\nexport const NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY = (page: number) =>\n `${NOTIFICATION_API_LIST_ENDPOINT}?page=${page}&per_page=100`;\nexport const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications/mark-as-read`;\n\n/**\n * Creates on-chain triggers based on the provided notification triggers.\n * This method generates a unique token for each trigger using the trigger ID and storage key,\n * proving ownership of the trigger being updated. It then makes an API call to create these triggers.\n * Upon successful creation, it updates the userStorage to reflect the new trigger status.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the trigger ID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param triggers - An array of notification triggers to be created. Each trigger includes an ID, chain ID, kind, and address.\n * @returns A promise that resolves to void. Throws an error if the API call fails or if there's an issue creating the triggers.\n */\nexport async function createOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n triggers: NotificationTrigger[],\n): Promise<void> {\n type RequestPayloadTrigger = {\n id: string;\n // this is the trigger token, generated by using the uuid + storage key. It proves you own the trigger you are updating\n token: string;\n config: {\n kind: string;\n chain_id: number;\n address: string;\n };\n };\n const triggersToCreate: RequestPayloadTrigger[] = triggers.map((t) => ({\n id: t.id,\n token: UserStorageController.createSHA256Hash(t.id + storageKey),\n config: {\n kind: t.kind,\n chain_id: Number(t.chainId),\n address: t.address,\n },\n }));\n\n if (triggersToCreate.length === 0) {\n return;\n }\n\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'POST',\n triggersToCreate,\n );\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => undefined);\n log.error('Error creating triggers:', errorData);\n throw new Error('OnChain Notifications - unable to create triggers');\n }\n\n // If the trigger creation was fine\n // then update the userStorage\n for (const trigger of triggersToCreate) {\n toggleUserStorageTriggerStatus(\n userStorage,\n trigger.config.address,\n String(trigger.config.chain_id),\n trigger.id,\n true,\n );\n }\n\n cleanUserStorage(userStorage);\n}\n\n/**\n * Deletes on-chain triggers based on the provided UUIDs.\n * This method generates a unique token for each trigger using the UUID and storage key,\n * proving ownership of the trigger being deleted. It then makes an API call to delete these triggers.\n * Upon successful deletion, it updates the userStorage to remove the deleted trigger statuses.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the UUID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param uuids - An array of UUIDs representing the triggers to be deleted.\n * @returns A promise that resolves to the updated UserStorage object. Throws an error if the API call fails or if there's an issue deleting the triggers.\n */\nexport async function deleteOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n uuids: string[],\n): Promise<UserStorage> {\n const triggersToDelete = uuids.map((uuid) => ({\n id: uuid,\n token: UserStorageController.createSHA256Hash(uuid + storageKey),\n }));\n\n try {\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'DELETE',\n triggersToDelete,\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to delete on-chain notifications for uuids ${uuids.join(', ')}`,\n );\n }\n\n // Update the state of the deleted trigger to false\n for (const uuid of uuids) {\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n delete userStorage[address][chainId][uuid];\n }\n }\n }\n }\n }\n\n // Follow-up cleanup, if an address had no triggers whatsoever, then we can delete the address\n const isEmpty = (obj = {}) => Object.keys(obj).length === 0;\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n // Chain isEmpty Check\n if (isEmpty(userStorage?.[address]?.[chainId])) {\n delete userStorage[address][chainId];\n }\n }\n\n // Address isEmpty Check\n if (isEmpty(userStorage?.[address])) {\n delete userStorage[address];\n }\n }\n }\n } catch (err) {\n log.error(\n `Error deleting on-chain notifications for uuids ${uuids.join(', ')}:`,\n err,\n );\n throw err;\n }\n\n return userStorage;\n}\n\n/**\n * Fetches on-chain notifications for the given user storage and BearerToken.\n * This method iterates through the userStorage to find enabled triggers and fetches notifications for those triggers.\n * It makes paginated API calls to the notifications service, transforming and aggregating the notifications into a single array.\n * The process stops either when all pages have been fetched or when a page has less than 100 notifications, indicating the end of the data.\n *\n * @param userStorage - The user's storage object containing trigger information.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @returns A promise that resolves to an array of OnChainRawNotification objects. If no triggers are enabled or an error occurs, it may return an empty array.\n */\nexport async function getOnChainNotifications(\n userStorage: UserStorage,\n bearerToken: string,\n): Promise<OnChainRawNotification[]> {\n const triggerIds = traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return undefined;\n }\n return t.id;\n },\n });\n\n if (triggerIds.length === 0) {\n return [];\n }\n\n const onChainNotifications: OnChainRawNotification[] = [];\n const PAGE_LIMIT = 2;\n for (let page = 1; page <= PAGE_LIMIT; page++) {\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY(page),\n 'POST',\n { trigger_ids: triggerIds },\n );\n\n const notifications =\n (await response.json()) as UnprocessedOnChainRawNotification[];\n\n // Transform and sort notifications\n const transformedNotifications = notifications\n .map((n): OnChainRawNotification | undefined => {\n if (!n.data?.kind) {\n return undefined;\n }\n\n return toRawOnChainNotification(n);\n })\n .filter((n): n is OnChainRawNotification => Boolean(n));\n\n onChainNotifications.push(...transformedNotifications);\n\n // if less than 100 notifications on page, then means we reached end\n if (notifications.length < 100) {\n page = PAGE_LIMIT + 1;\n break;\n }\n } catch (err) {\n log.error(\n `Error fetching on-chain notifications for trigger IDs ${triggerIds.join(\n ', ',\n )}:`,\n err,\n );\n // do nothing\n }\n }\n\n return onChainNotifications;\n}\n\n/**\n * Marks the specified notifications as read.\n * This method sends a POST request to the notifications service to mark the provided notification IDs as read.\n * If the operation is successful, it completes without error. If the operation fails, it throws an error with details.\n *\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param notificationIds - An array of notification IDs to be marked as read.\n * @returns A promise that resolves to void. The promise will reject if there's an error during the API call or if the response status is not 200.\n */\nexport async function markNotificationsAsRead(\n bearerToken: string,\n notificationIds: string[],\n): Promise<void> {\n if (notificationIds.length === 0) {\n return;\n }\n\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT,\n 'POST',\n { ids: notificationIds },\n );\n\n if (response.status !== 200) {\n const errorData = await response.json().catch(() => undefined);\n throw new Error(\n `Error marking notifications as read: ${errorData?.message as string}`,\n );\n }\n } catch (err) {\n log.error('Error marking notifications as read:', err);\n throw err;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from './feature-announcement';\nexport type * from './notification';\nexport type * from './on-chain-notification';\nexport type * from './snaps/snaps';\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from './feature-announcement';\nexport type * from './notification';\nexport type * from './on-chain-notification';\nexport type * from './user-storage';\nexport type * from './snaps/snaps';\n"]}
@@ -1,5 +1,6 @@
1
1
  export type * from "./feature-announcement/index.cjs";
2
2
  export type * from "./notification/index.cjs";
3
3
  export type * from "./on-chain-notification/index.cjs";
4
+ export type * from "./user-storage/index.cjs";
4
5
  export type * from "./snaps/snaps.cjs";
5
6
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"AAAA,sDAA4C;AAC5C,8CAAoC;AACpC,uDAA6C;AAC7C,uCAAmC"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"AAAA,sDAA4C;AAC5C,8CAAoC;AACpC,uDAA6C;AAC7C,8CAAoC;AACpC,uCAAmC"}
@@ -1,5 +1,6 @@
1
1
  export type * from "./feature-announcement/index.mjs";
2
2
  export type * from "./notification/index.mjs";
3
3
  export type * from "./on-chain-notification/index.mjs";
4
+ export type * from "./user-storage/index.mjs";
4
5
  export type * from "./snaps/snaps.mjs";
5
6
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"AAAA,sDAA4C;AAC5C,8CAAoC;AACpC,uDAA6C;AAC7C,uCAAmC"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"AAAA,sDAA4C;AAC5C,8CAAoC;AACpC,uDAA6C;AAC7C,8CAAoC;AACpC,uCAAmC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from './feature-announcement';\nexport type * from './notification';\nexport type * from './on-chain-notification';\nexport type * from './snaps/snaps';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesController/types/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from './feature-announcement';\nexport type * from './notification';\nexport type * from './on-chain-notification';\nexport type * from './user-storage';\nexport type * from './snaps/snaps';\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from './user-storage';\n"]}
@@ -0,0 +1,2 @@
1
+ export type * from "./user-storage.cjs";
2
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/index.ts"],"names":[],"mappings":"AAAA,wCAAoC"}
@@ -0,0 +1,2 @@
1
+ export type * from "./user-storage.mjs";
2
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/index.ts"],"names":[],"mappings":"AAAA,wCAAoC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from './user-storage';\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=user-storage.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-storage.cjs","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/user-storage.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n USER_STORAGE_VERSION_KEY,\n USER_STORAGE_VERSION,\n} from '../../constants/constants';\nimport type {\n SUPPORTED_CHAINS,\n TRIGGER_TYPES,\n} from '../../constants/notification-schema';\n\nexport type UserStorage = {\n /**\n * The Version 'v' of the User Storage.\n * NOTE - will allow us to support upgrade/downgrades in the future\n */\n [USER_STORAGE_VERSION_KEY]: typeof USER_STORAGE_VERSION;\n [address: string]: {\n [chain in (typeof SUPPORTED_CHAINS)[number]]: {\n [uuid: string]: {\n /** Trigger Kind 'k' */\n k: TRIGGER_TYPES;\n /**\n * Trigger Enabled 'e'\n * This is mostly an 'acknowledgement' to determine if a trigger has been made\n * For example if we fail to create a trigger, we can set to false & retry (on re-log in, or elsewhere)\n *\n * Most of the time this is 'true', as triggers when deleted are also removed from User Storage\n */\n e: boolean;\n };\n };\n };\n};\n"]}
@@ -0,0 +1,26 @@
1
+ import type { USER_STORAGE_VERSION_KEY, USER_STORAGE_VERSION } from "../../constants/constants.cjs";
2
+ import type { SUPPORTED_CHAINS, TRIGGER_TYPES } from "../../constants/notification-schema.cjs";
3
+ export type UserStorage = {
4
+ /**
5
+ * The Version 'v' of the User Storage.
6
+ * NOTE - will allow us to support upgrade/downgrades in the future
7
+ */
8
+ [USER_STORAGE_VERSION_KEY]: typeof USER_STORAGE_VERSION;
9
+ [address: string]: {
10
+ [chain in (typeof SUPPORTED_CHAINS)[number]]: {
11
+ [uuid: string]: {
12
+ /** Trigger Kind 'k' */
13
+ k: TRIGGER_TYPES;
14
+ /**
15
+ * Trigger Enabled 'e'
16
+ * This is mostly an 'acknowledgement' to determine if a trigger has been made
17
+ * For example if we fail to create a trigger, we can set to false & retry (on re-log in, or elsewhere)
18
+ *
19
+ * Most of the time this is 'true', as triggers when deleted are also removed from User Storage
20
+ */
21
+ e: boolean;
22
+ };
23
+ };
24
+ };
25
+ };
26
+ //# sourceMappingURL=user-storage.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-storage.d.cts","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/user-storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,oBAAoB,EACrB,sCAAkC;AACnC,OAAO,KAAK,EACV,gBAAgB,EAChB,aAAa,EACd,gDAA4C;AAE7C,MAAM,MAAM,WAAW,GAAG;IACxB;;;OAGG;IACH,CAAC,wBAAwB,CAAC,EAAE,OAAO,oBAAoB,CAAC;IACxD,CAAC,OAAO,EAAE,MAAM,GAAG;SAChB,KAAK,IAAI,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,GAAG;YAC5C,CAAC,IAAI,EAAE,MAAM,GAAG;gBACd,uBAAuB;gBACvB,CAAC,EAAE,aAAa,CAAC;gBACjB;;;;;;mBAMG;gBACH,CAAC,EAAE,OAAO,CAAC;aACZ,CAAC;SACH;KACF,CAAC;CACH,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { USER_STORAGE_VERSION_KEY, USER_STORAGE_VERSION } from "../../constants/constants.mjs";
2
+ import type { SUPPORTED_CHAINS, TRIGGER_TYPES } from "../../constants/notification-schema.mjs";
3
+ export type UserStorage = {
4
+ /**
5
+ * The Version 'v' of the User Storage.
6
+ * NOTE - will allow us to support upgrade/downgrades in the future
7
+ */
8
+ [USER_STORAGE_VERSION_KEY]: typeof USER_STORAGE_VERSION;
9
+ [address: string]: {
10
+ [chain in (typeof SUPPORTED_CHAINS)[number]]: {
11
+ [uuid: string]: {
12
+ /** Trigger Kind 'k' */
13
+ k: TRIGGER_TYPES;
14
+ /**
15
+ * Trigger Enabled 'e'
16
+ * This is mostly an 'acknowledgement' to determine if a trigger has been made
17
+ * For example if we fail to create a trigger, we can set to false & retry (on re-log in, or elsewhere)
18
+ *
19
+ * Most of the time this is 'true', as triggers when deleted are also removed from User Storage
20
+ */
21
+ e: boolean;
22
+ };
23
+ };
24
+ };
25
+ };
26
+ //# sourceMappingURL=user-storage.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-storage.d.mts","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/user-storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,oBAAoB,EACrB,sCAAkC;AACnC,OAAO,KAAK,EACV,gBAAgB,EAChB,aAAa,EACd,gDAA4C;AAE7C,MAAM,MAAM,WAAW,GAAG;IACxB;;;OAGG;IACH,CAAC,wBAAwB,CAAC,EAAE,OAAO,oBAAoB,CAAC;IACxD,CAAC,OAAO,EAAE,MAAM,GAAG;SAChB,KAAK,IAAI,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,GAAG;YAC5C,CAAC,IAAI,EAAE,MAAM,GAAG;gBACd,uBAAuB;gBACvB,CAAC,EAAE,aAAa,CAAC;gBACjB;;;;;;mBAMG;gBACH,CAAC,EAAE,OAAO,CAAC;aACZ,CAAC;SACH;KACF,CAAC;CACH,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=user-storage.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-storage.mjs","sourceRoot":"","sources":["../../../../src/NotificationServicesController/types/user-storage/user-storage.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n USER_STORAGE_VERSION_KEY,\n USER_STORAGE_VERSION,\n} from '../../constants/constants';\nimport type {\n SUPPORTED_CHAINS,\n TRIGGER_TYPES,\n} from '../../constants/notification-schema';\n\nexport type UserStorage = {\n /**\n * The Version 'v' of the User Storage.\n * NOTE - will allow us to support upgrade/downgrades in the future\n */\n [USER_STORAGE_VERSION_KEY]: typeof USER_STORAGE_VERSION;\n [address: string]: {\n [chain in (typeof SUPPORTED_CHAINS)[number]]: {\n [uuid: string]: {\n /** Trigger Kind 'k' */\n k: TRIGGER_TYPES;\n /**\n * Trigger Enabled 'e'\n * This is mostly an 'acknowledgement' to determine if a trigger has been made\n * For example if we fail to create a trigger, we can set to false & retry (on re-log in, or elsewhere)\n *\n * Most of the time this is 'true', as triggers when deleted are also removed from User Storage\n */\n e: boolean;\n };\n };\n };\n};\n"]}