@metamask-previews/profile-sync-controller 15.0.0-preview-ef2405f → 15.0.0-preview-e7141654

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 (74) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/controllers/user-storage/UserStorageController.cjs +68 -3
  3. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  4. package/dist/controllers/user-storage/UserStorageController.d.cts +40 -2
  5. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  6. package/dist/controllers/user-storage/UserStorageController.d.mts +40 -2
  7. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  8. package/dist/controllers/user-storage/UserStorageController.mjs +65 -0
  9. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  10. package/dist/controllers/user-storage/constants.cjs +1 -0
  11. package/dist/controllers/user-storage/constants.cjs.map +1 -1
  12. package/dist/controllers/user-storage/constants.d.cts +1 -0
  13. package/dist/controllers/user-storage/constants.d.cts.map +1 -1
  14. package/dist/controllers/user-storage/constants.d.mts +1 -0
  15. package/dist/controllers/user-storage/constants.d.mts.map +1 -1
  16. package/dist/controllers/user-storage/constants.mjs +1 -0
  17. package/dist/controllers/user-storage/constants.mjs.map +1 -1
  18. package/dist/controllers/user-storage/contact-syncing/constants.cjs +12 -0
  19. package/dist/controllers/user-storage/contact-syncing/constants.cjs.map +1 -0
  20. package/dist/controllers/user-storage/contact-syncing/constants.d.cts +9 -0
  21. package/dist/controllers/user-storage/contact-syncing/constants.d.cts.map +1 -0
  22. package/dist/controllers/user-storage/contact-syncing/constants.d.mts +9 -0
  23. package/dist/controllers/user-storage/contact-syncing/constants.d.mts.map +1 -0
  24. package/dist/controllers/user-storage/contact-syncing/constants.mjs +9 -0
  25. package/dist/controllers/user-storage/contact-syncing/constants.mjs.map +1 -0
  26. package/dist/controllers/user-storage/contact-syncing/controller-integration.cjs +376 -0
  27. package/dist/controllers/user-storage/contact-syncing/controller-integration.cjs.map +1 -0
  28. package/dist/controllers/user-storage/contact-syncing/controller-integration.d.cts +45 -0
  29. package/dist/controllers/user-storage/contact-syncing/controller-integration.d.cts.map +1 -0
  30. package/dist/controllers/user-storage/contact-syncing/controller-integration.d.mts +45 -0
  31. package/dist/controllers/user-storage/contact-syncing/controller-integration.d.mts.map +1 -0
  32. package/dist/controllers/user-storage/contact-syncing/controller-integration.mjs +370 -0
  33. package/dist/controllers/user-storage/contact-syncing/controller-integration.mjs.map +1 -0
  34. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.cjs +57 -0
  35. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.cjs.map +1 -0
  36. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.d.cts +8 -0
  37. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.d.cts.map +1 -0
  38. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.d.mts +8 -0
  39. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.d.mts.map +1 -0
  40. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.mjs +53 -0
  41. package/dist/controllers/user-storage/contact-syncing/setup-subscriptions.mjs.map +1 -0
  42. package/dist/controllers/user-storage/contact-syncing/sync-utils.cjs +23 -0
  43. package/dist/controllers/user-storage/contact-syncing/sync-utils.cjs.map +1 -0
  44. package/dist/controllers/user-storage/contact-syncing/sync-utils.d.cts +9 -0
  45. package/dist/controllers/user-storage/contact-syncing/sync-utils.d.cts.map +1 -0
  46. package/dist/controllers/user-storage/contact-syncing/sync-utils.d.mts +9 -0
  47. package/dist/controllers/user-storage/contact-syncing/sync-utils.d.mts.map +1 -0
  48. package/dist/controllers/user-storage/contact-syncing/sync-utils.mjs +19 -0
  49. package/dist/controllers/user-storage/contact-syncing/sync-utils.mjs.map +1 -0
  50. package/dist/controllers/user-storage/contact-syncing/types.cjs +3 -0
  51. package/dist/controllers/user-storage/contact-syncing/types.cjs.map +1 -0
  52. package/dist/controllers/user-storage/contact-syncing/types.d.cts +35 -0
  53. package/dist/controllers/user-storage/contact-syncing/types.d.cts.map +1 -0
  54. package/dist/controllers/user-storage/contact-syncing/types.d.mts +35 -0
  55. package/dist/controllers/user-storage/contact-syncing/types.d.mts.map +1 -0
  56. package/dist/controllers/user-storage/contact-syncing/types.mjs +2 -0
  57. package/dist/controllers/user-storage/contact-syncing/types.mjs.map +1 -0
  58. package/dist/controllers/user-storage/contact-syncing/utils.cjs +68 -0
  59. package/dist/controllers/user-storage/contact-syncing/utils.cjs.map +1 -0
  60. package/dist/controllers/user-storage/contact-syncing/utils.d.cts +29 -0
  61. package/dist/controllers/user-storage/contact-syncing/utils.d.cts.map +1 -0
  62. package/dist/controllers/user-storage/contact-syncing/utils.d.mts +29 -0
  63. package/dist/controllers/user-storage/contact-syncing/utils.d.mts.map +1 -0
  64. package/dist/controllers/user-storage/contact-syncing/utils.mjs +63 -0
  65. package/dist/controllers/user-storage/contact-syncing/utils.mjs.map +1 -0
  66. package/dist/shared/storage-schema.cjs +3 -1
  67. package/dist/shared/storage-schema.cjs.map +1 -1
  68. package/dist/shared/storage-schema.d.cts +2 -0
  69. package/dist/shared/storage-schema.d.cts.map +1 -1
  70. package/dist/shared/storage-schema.d.mts +2 -0
  71. package/dist/shared/storage-schema.d.mts.map +1 -1
  72. package/dist/shared/storage-schema.mjs +3 -1
  73. package/dist/shared/storage-schema.mjs.map +1 -1
  74. package/package.json +1 -1
@@ -0,0 +1,370 @@
1
+ import { canPerformContactSyncing } from "./sync-utils.mjs";
2
+ import { mapAddressBookEntryToUserStorageEntry, mapUserStorageEntryToAddressBookEntry } from "./utils.mjs";
3
+ import { USER_STORAGE_FEATURE_NAMES } from "../../../shared/storage-schema.mjs";
4
+ // Define a constant to use as the key for storing all contacts
5
+ export const ADDRESS_BOOK_CONTACTS_KEY = 'contacts';
6
+ /**
7
+ * Creates a unique key for a contact based on chainId and address
8
+ *
9
+ * @param contact - The contact to create a key for
10
+ * @returns A unique string key
11
+ */
12
+ function createContactKey(contact) {
13
+ return `${contact.chainId}:${contact.address.toLowerCase()}`;
14
+ }
15
+ /**
16
+ * Syncs contacts between local storage and user storage (remote).
17
+ *
18
+ * Handles the following syncing scenarios:
19
+ * 1. First Sync: When local contacts exist but there are no remote contacts, uploads all local contacts.
20
+ * 2. New Device Sync: Downloads remote contacts that don't exist locally (empty local address book).
21
+ * 3. Simple Merge: Ensures both sides (local & remote) have all contacts.
22
+ * 4. Contact Naming Conflicts: When same contact has different names, uses most recent by timestamp.
23
+ * 5. Local Updates: When a contact was updated locally, syncs changes to remote if local is newer.
24
+ * 6. Remote Updates: When a contact was updated remotely, applies changes locally if remote is newer.
25
+ * 7. Local Deletions: When a contact was deleted locally, marks it as deleted in remote storage.
26
+ * 8. Remote Deletions: When a contact was deleted remotely, applies deletion locally.
27
+ * 9. Concurrent Updates: Resolves conflicts using timestamps to determine the winner.
28
+ * 10. Restore After Delete: If a contact is modified after being deleted, restores it.
29
+ * 11. ChainId Differences: Treats same address on different chains as separate contacts.
30
+ *
31
+ * @param config - Parameters used for syncing callbacks
32
+ * @param options - Parameters used for syncing operations
33
+ */
34
+ export async function syncContactsWithUserStorage(config, options) {
35
+ const { getMessenger, getUserStorageControllerInstance } = options;
36
+ const { onContactSyncErroneousSituation, onContactUpdated, onContactDeleted, } = config;
37
+ try {
38
+ if (!canPerformContactSyncing(options)) {
39
+ console.log('🔄 Contacts Sync: Cannot perform sync, conditions not met');
40
+ return;
41
+ }
42
+ console.log('🔄 Contacts Sync: Starting sync process');
43
+ // Activate sync semaphore to prevent event loops
44
+ await getUserStorageControllerInstance().setIsContactSyncingInProgress(true);
45
+ // Get all local contacts from AddressBookController (exclude chain "*" contacts)
46
+ const localVisibleContacts = getMessenger()
47
+ .call('AddressBookController:list')
48
+ .filter((contact) => String(contact.chainId) !== '*') || [];
49
+ console.log('🔄 Contacts Sync: Local contacts', localVisibleContacts);
50
+ // Get remote contacts from user storage API
51
+ const remoteContacts = await getRemoteContacts(options);
52
+ console.log('🔄 Contacts Sync: Remote contacts', remoteContacts);
53
+ // SCENARIO 1: First Sync - No remote contacts but local contacts exist
54
+ if (!remoteContacts || remoteContacts.length === 0) {
55
+ if (localVisibleContacts.length > 0) {
56
+ console.log('🔄 Contacts Sync: First sync - uploading local contacts to remote');
57
+ await saveContactsToUserStorage(localVisibleContacts, options);
58
+ }
59
+ return;
60
+ }
61
+ // Prepare maps for efficient lookup
62
+ const localContactsMap = new Map();
63
+ const remoteContactsMap = new Map();
64
+ localVisibleContacts.forEach((contact) => {
65
+ const key = createContactKey(contact);
66
+ localContactsMap.set(key, contact);
67
+ });
68
+ remoteContacts.forEach((contact) => {
69
+ const key = createContactKey(contact);
70
+ remoteContactsMap.set(key, contact);
71
+ });
72
+ // Lists to track contacts that need to be synced
73
+ const contactsToAddOrUpdateLocally = [];
74
+ const contactsToDeleteLocally = [];
75
+ const contactsToUpdateRemotely = [];
76
+ // SCENARIO 2 & 6: Process remote contacts - handle new device sync and remote updates
77
+ for (const remoteContact of remoteContacts) {
78
+ const key = createContactKey(remoteContact);
79
+ const localContact = localContactsMap.get(key);
80
+ // Handle remote contact based on its status and local existence
81
+ if (remoteContact.deleted) {
82
+ // SCENARIO 8: Remote deletion - should be applied locally if contact exists locally
83
+ if (localContact) {
84
+ console.log('🔄 Contacts Sync: Applying remote deletion locally', remoteContact);
85
+ contactsToDeleteLocally.push(remoteContact);
86
+ // Invoke deletion callback if needed
87
+ if (onContactDeleted) {
88
+ onContactDeleted();
89
+ }
90
+ }
91
+ }
92
+ else if (!localContact) {
93
+ // SCENARIO 2: New contact from remote - import to local
94
+ console.log('🔄 Contacts Sync: Importing new remote contact', remoteContact);
95
+ contactsToAddOrUpdateLocally.push(remoteContact);
96
+ // Invoke update callback if needed
97
+ if (onContactUpdated) {
98
+ onContactUpdated();
99
+ }
100
+ }
101
+ else {
102
+ // SCENARIO 4 & 6: Contact exists on both sides - check for conflicts
103
+ const hasContentDifference = localContact.name !== remoteContact.name ||
104
+ localContact.memo !== remoteContact.memo;
105
+ if (hasContentDifference) {
106
+ // Check timestamps to determine which version to keep
107
+ const localTimestamp = localContact.lastUpdatedAt || 0;
108
+ const remoteTimestamp = remoteContact.lastUpdatedAt || 0;
109
+ if (localTimestamp >= remoteTimestamp) {
110
+ // Local is newer (or same age) - use local version
111
+ console.log('🔄 Contacts Sync: Local wins by timestamp', {
112
+ local: localContact,
113
+ remote: remoteContact,
114
+ localTimestamp,
115
+ remoteTimestamp,
116
+ });
117
+ contactsToUpdateRemotely.push(localContact);
118
+ }
119
+ else {
120
+ // Remote is newer - use remote version
121
+ console.log('🔄 Contacts Sync: Remote wins by timestamp', {
122
+ local: localContact,
123
+ remote: remoteContact,
124
+ localTimestamp,
125
+ remoteTimestamp,
126
+ });
127
+ contactsToAddOrUpdateLocally.push(remoteContact);
128
+ // Invoke update callback if needed
129
+ if (onContactUpdated) {
130
+ onContactUpdated();
131
+ }
132
+ }
133
+ }
134
+ else {
135
+ // Content is identical, no action needed
136
+ console.log('🔄 Contacts Sync: Content identical, no action needed', {
137
+ local: localContact,
138
+ remote: remoteContact,
139
+ });
140
+ }
141
+ }
142
+ }
143
+ // SCENARIO 3 & 5: Process local contacts not in remote
144
+ for (const localContact of localVisibleContacts) {
145
+ const key = createContactKey(localContact);
146
+ const remoteContact = remoteContactsMap.get(key);
147
+ if (!remoteContact) {
148
+ // New local contact - add to remote
149
+ console.log('🔄 Contacts Sync: New local contact - adding to remote', localContact);
150
+ contactsToUpdateRemotely.push(localContact);
151
+ }
152
+ }
153
+ // SCENARIO 7: Detect local deletions
154
+ // Skip for new device scenario (no local contacts but remote has contacts)
155
+ const isNewDeviceScenario = localVisibleContacts.length === 0 && remoteContacts.length > 0;
156
+ if (!isNewDeviceScenario) {
157
+ // Find contacts that exist in remote but not locally (they were deleted locally)
158
+ const contactsToDeleteRemotely = [];
159
+ for (const remoteContact of remoteContacts) {
160
+ if (!remoteContact.deleted) {
161
+ const key = createContactKey(remoteContact);
162
+ if (!localContactsMap.has(key)) {
163
+ console.log('🔄 Contacts Sync: Contact deleted locally, marking as deleted in remote', remoteContact);
164
+ contactsToDeleteRemotely.push(remoteContact);
165
+ // Invoke deletion callback if needed
166
+ if (onContactDeleted) {
167
+ onContactDeleted();
168
+ }
169
+ }
170
+ }
171
+ }
172
+ // Mark contacts as deleted in remote
173
+ if (contactsToDeleteRemotely.length > 0) {
174
+ const remoteContactsWithDeletions = [...remoteContacts];
175
+ for (const contactToDelete of contactsToDeleteRemotely) {
176
+ const key = createContactKey(contactToDelete);
177
+ const indexToDelete = remoteContactsWithDeletions.findIndex((c) => createContactKey(c) === key);
178
+ if (indexToDelete !== -1) {
179
+ const now = Date.now();
180
+ remoteContactsWithDeletions[indexToDelete] = {
181
+ ...remoteContactsWithDeletions[indexToDelete],
182
+ deleted: true,
183
+ deletedAt: now,
184
+ lastUpdatedAt: now,
185
+ };
186
+ }
187
+ }
188
+ // Save updated remote contacts with deletions
189
+ await saveContactsToUserStorage(remoteContactsWithDeletions, options);
190
+ }
191
+ }
192
+ else {
193
+ console.log('🔄 Contacts Sync: Skipping local deletion detection - this is a new device');
194
+ }
195
+ // Apply local deletions
196
+ for (const contact of contactsToDeleteLocally) {
197
+ try {
198
+ console.log('🔄 Contacts Sync: Deleting contact locally', contact);
199
+ await getMessenger().call('AddressBookController:delete', contact.chainId, contact.address);
200
+ }
201
+ catch (error) {
202
+ console.error('Error deleting contact:', error);
203
+ }
204
+ }
205
+ // Apply local additions/updates
206
+ for (const contact of contactsToAddOrUpdateLocally) {
207
+ if (!contact.deleted) {
208
+ try {
209
+ console.log('🔄 Contacts Sync: Adding/updating contact locally', contact);
210
+ await getMessenger().call('AddressBookController:set', contact.address, contact.name || '', contact.chainId, contact.memo || '', contact.addressType);
211
+ }
212
+ catch (error) {
213
+ console.error('Error updating contact:', error);
214
+ }
215
+ }
216
+ }
217
+ // Apply changes to remote storage
218
+ if (contactsToUpdateRemotely.length > 0) {
219
+ console.log('🔄 Contacts Sync: Updating contacts in remote storage', contactsToUpdateRemotely);
220
+ // Update existing remote contacts with new contacts
221
+ const updatedRemoteContacts = [...remoteContacts];
222
+ for (const localContact of contactsToUpdateRemotely) {
223
+ const key = createContactKey(localContact);
224
+ const existingIndex = updatedRemoteContacts.findIndex((c) => createContactKey(c) === key);
225
+ const now = Date.now();
226
+ const updatedEntry = {
227
+ ...localContact,
228
+ lastUpdatedAt: now,
229
+ deleted: false, // Ensure it's not deleted
230
+ };
231
+ if (existingIndex !== -1) {
232
+ // Update existing contact
233
+ updatedRemoteContacts[existingIndex] = updatedEntry;
234
+ }
235
+ else {
236
+ // Add new contact
237
+ updatedRemoteContacts.push(updatedEntry);
238
+ }
239
+ }
240
+ // Save updated contacts to remote storage
241
+ await saveContactsToUserStorage(updatedRemoteContacts, options);
242
+ }
243
+ console.log('🔄 Contacts Sync: Sync completed successfully');
244
+ }
245
+ catch (error) {
246
+ console.error('🔄 Contacts Sync: Error during sync', error);
247
+ if (onContactSyncErroneousSituation) {
248
+ onContactSyncErroneousSituation('Error synchronizing contacts', {
249
+ error,
250
+ });
251
+ }
252
+ }
253
+ finally {
254
+ await getUserStorageControllerInstance().setIsContactSyncingInProgress(false);
255
+ }
256
+ }
257
+ /**
258
+ * Retrieves remote contacts from user storage API
259
+ *
260
+ * @param options - Parameters used for retrieving remote contacts
261
+ * @returns Array of contacts from remote storage, or null if none found
262
+ */
263
+ async function getRemoteContacts(options) {
264
+ const { getUserStorageControllerInstance } = options;
265
+ try {
266
+ const remoteContactsJson = await getUserStorageControllerInstance().performGetStorage(`${USER_STORAGE_FEATURE_NAMES.addressBook}.${ADDRESS_BOOK_CONTACTS_KEY}`);
267
+ if (!remoteContactsJson) {
268
+ return null;
269
+ }
270
+ // Parse the JSON and convert each entry from UserStorageContactEntry to AddressBookEntry
271
+ const remoteStorageEntries = JSON.parse(remoteContactsJson);
272
+ return remoteStorageEntries.map((entry) => mapUserStorageEntryToAddressBookEntry(entry));
273
+ }
274
+ catch {
275
+ return null;
276
+ }
277
+ }
278
+ /**
279
+ * Saves local contacts to user storage
280
+ *
281
+ * @param contacts - The contacts to save to user storage
282
+ * @param options - Parameters used for saving contacts
283
+ */
284
+ async function saveContactsToUserStorage(contacts, options) {
285
+ const { getUserStorageControllerInstance } = options;
286
+ if (!contacts || contacts.length === 0) {
287
+ return;
288
+ }
289
+ // Convert each AddressBookEntry to UserStorageContactEntry format before saving
290
+ const storageEntries = contacts.map((contact) => mapAddressBookEntryToUserStorageEntry(contact));
291
+ await getUserStorageControllerInstance().performSetStorage(`${USER_STORAGE_FEATURE_NAMES.addressBook}.${ADDRESS_BOOK_CONTACTS_KEY}`, JSON.stringify(storageEntries));
292
+ }
293
+ /**
294
+ * Updates a single contact in remote storage without performing a full sync
295
+ * This is used when a contact is updated locally to efficiently push changes to remote
296
+ *
297
+ * @param contact - The contact that was updated locally
298
+ * @param options - Parameters used for syncing operations
299
+ */
300
+ export async function updateContactInRemoteStorage(contact, options) {
301
+ if (!canPerformContactSyncing(options)) {
302
+ return;
303
+ }
304
+ console.log('🔄 Contacts Sync: Updating single contact in remote storage', contact);
305
+ try {
306
+ // Get current remote contacts or initialize empty array
307
+ const remoteContacts = (await getRemoteContacts(options)) || [];
308
+ // Find if this contact already exists in remote
309
+ const key = createContactKey(contact);
310
+ const existingIndex = remoteContacts.findIndex((c) => createContactKey(c) === key);
311
+ const updatedRemoteContacts = [...remoteContacts];
312
+ // Create an updated entry with timestamp
313
+ const updatedEntry = {
314
+ ...contact,
315
+ lastUpdatedAt: contact.lastUpdatedAt || Date.now(),
316
+ deleted: false, // Explicitly set to false in case this was previously deleted
317
+ };
318
+ if (existingIndex !== -1) {
319
+ // Update existing contact
320
+ updatedRemoteContacts[existingIndex] = updatedEntry;
321
+ }
322
+ else {
323
+ // Add as new contact
324
+ updatedRemoteContacts.push(updatedEntry);
325
+ }
326
+ // Save to remote storage
327
+ await saveContactsToUserStorage(updatedRemoteContacts, options);
328
+ }
329
+ catch (error) {
330
+ console.error('🔄 Contacts Sync: Error updating contact in remote storage', error);
331
+ }
332
+ }
333
+ /**
334
+ * Marks a single contact as deleted in remote storage without performing a full sync
335
+ * This is used when a contact is deleted locally to efficiently push the deletion to remote
336
+ *
337
+ * @param contact - The contact that was deleted locally (contains at least address and chainId)
338
+ * @param options - Parameters used for syncing operations
339
+ */
340
+ export async function deleteContactInRemoteStorage(contact, options) {
341
+ if (!canPerformContactSyncing(options)) {
342
+ return;
343
+ }
344
+ console.log('🔄 Contacts Sync: Marking contact as deleted in remote storage', contact);
345
+ try {
346
+ // Get current remote contacts
347
+ const remoteContacts = (await getRemoteContacts(options)) || [];
348
+ // Find the contact in remote storage
349
+ const key = createContactKey(contact);
350
+ const existingIndex = remoteContacts.findIndex((c) => createContactKey(c) === key);
351
+ // If the contact exists in remote storage
352
+ if (existingIndex !== -1) {
353
+ const updatedRemoteContacts = [...remoteContacts];
354
+ const now = Date.now();
355
+ // Mark the contact as deleted
356
+ updatedRemoteContacts[existingIndex] = {
357
+ ...updatedRemoteContacts[existingIndex],
358
+ deleted: true,
359
+ deletedAt: now,
360
+ lastUpdatedAt: now,
361
+ };
362
+ // Save to remote storage
363
+ await saveContactsToUserStorage(updatedRemoteContacts, options);
364
+ }
365
+ }
366
+ catch (error) {
367
+ console.error('🔄 Contacts Sync: Error marking contact as deleted in remote storage', error);
368
+ }
369
+ }
370
+ //# sourceMappingURL=controller-integration.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"controller-integration.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/controller-integration.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,yBAAqB;AAGxD,OAAO,EACL,qCAAqC,EACrC,qCAAqC,EAEtC,oBAAgB;AACjB,OAAO,EAAE,0BAA0B,EAAE,2CAAuC;AAE5E,+DAA+D;AAC/D,MAAM,CAAC,MAAM,yBAAyB,GAAG,UAAU,CAAC;AAWpD;;;;;GAKG;AACH,SAAS,gBAAgB,CAAC,OAAyB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AAO,CAAC,GAAG,CACT,gEAAgE,EAChE,OAAO,CACR,CAAC;IAEF,IAAI;QACF,8BAA8B;QAC9B,MAAM,cAAc,GAAG,CAAC,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;QAEhE,qCAAqC;QACrC,MAAM,GAAG,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACtC,MAAM,aAAa,GAAG,cAAc,CAAC,SAAS,CAC5C,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,GAAG,CACnC,CAAC;QAEF,0CAA0C;QAC1C,IAAI,aAAa,KAAK,CAAC,CAAC,EAAE;YACxB,MAAM,qBAAqB,GAAG,CAAC,GAAG,cAAc,CAAC,CAAC;YAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAEvB,8BAA8B;YAC9B,qBAAqB,CAAC,aAAa,CAAC,GAAG;gBACrC,GAAG,qBAAqB,CAAC,aAAa,CAAC;gBACvC,OAAO,EAAE,IAAI;gBACb,SAAS,EAAE,GAAG;gBACd,aAAa,EAAE,GAAG;aACnB,CAAC;YAEF,yBAAyB;YACzB,MAAM,yBAAyB,CAAC,qBAAqB,EAAE,OAAO,CAAC,CAAC;SACjE;KACF;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CACX,sEAAsE,EACtE,KAAK,CACN,CAAC;KACH;AACH,CAAC","sourcesContent":["import type { AddressBookEntry } from '@metamask/address-book-controller';\n\nimport { canPerformContactSyncing } from './sync-utils';\nimport type { ContactSyncingOptions } from './types';\nimport type { UserStorageContactEntry } from './types';\nimport {\n mapAddressBookEntryToUserStorageEntry,\n mapUserStorageEntryToAddressBookEntry,\n type SyncAddressBookEntry,\n} from './utils';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../../shared/storage-schema';\n\n// Define a constant to use as the key for storing all contacts\nexport const ADDRESS_BOOK_CONTACTS_KEY = 'contacts';\n\nexport type SyncContactsWithUserStorageConfig = {\n onContactSyncErroneousSituation?: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n onContactUpdated?: () => void;\n onContactDeleted?: () => void;\n};\n\n/**\n * Creates a unique key for a contact based on chainId and address\n *\n * @param contact - The contact to create a key for\n * @returns A unique string key\n */\nfunction createContactKey(contact: AddressBookEntry): string {\n return `${contact.chainId}:${contact.address.toLowerCase()}`;\n}\n\n/**\n * Syncs contacts between local storage and user storage (remote).\n *\n * Handles the following syncing scenarios:\n * 1. First Sync: When local contacts exist but there are no remote contacts, uploads all local contacts.\n * 2. New Device Sync: Downloads remote contacts that don't exist locally (empty local address book).\n * 3. Simple Merge: Ensures both sides (local & remote) have all contacts.\n * 4. Contact Naming Conflicts: When same contact has different names, uses most recent by timestamp.\n * 5. Local Updates: When a contact was updated locally, syncs changes to remote if local is newer.\n * 6. Remote Updates: When a contact was updated remotely, applies changes locally if remote is newer.\n * 7. Local Deletions: When a contact was deleted locally, marks it as deleted in remote storage.\n * 8. Remote Deletions: When a contact was deleted remotely, applies deletion locally.\n * 9. Concurrent Updates: Resolves conflicts using timestamps to determine the winner.\n * 10. Restore After Delete: If a contact is modified after being deleted, restores it.\n * 11. ChainId Differences: Treats same address on different chains as separate contacts.\n *\n * @param config - Parameters used for syncing callbacks\n * @param options - Parameters used for syncing operations\n */\nexport async function syncContactsWithUserStorage(\n config: SyncContactsWithUserStorageConfig,\n options: ContactSyncingOptions,\n): Promise<void> {\n const { getMessenger, getUserStorageControllerInstance } = options;\n const {\n onContactSyncErroneousSituation,\n onContactUpdated,\n onContactDeleted,\n } = config;\n\n try {\n if (!canPerformContactSyncing(options)) {\n console.log('🔄 Contacts Sync: Cannot perform sync, conditions not met');\n return;\n }\n\n console.log('🔄 Contacts Sync: Starting sync process');\n\n // Activate sync semaphore to prevent event loops\n await getUserStorageControllerInstance().setIsContactSyncingInProgress(\n true,\n );\n\n // Get all local contacts from AddressBookController (exclude chain \"*\" contacts)\n const localVisibleContacts =\n getMessenger()\n .call('AddressBookController:list')\n .filter((contact) => String(contact.chainId) !== '*') || [];\n\n console.log('🔄 Contacts Sync: Local contacts', localVisibleContacts);\n\n // Get remote contacts from user storage API\n const remoteContacts = await getRemoteContacts(options);\n console.log('🔄 Contacts Sync: Remote contacts', remoteContacts);\n\n // SCENARIO 1: First Sync - No remote contacts but local contacts exist\n if (!remoteContacts || remoteContacts.length === 0) {\n if (localVisibleContacts.length > 0) {\n console.log(\n '🔄 Contacts Sync: First sync - uploading local contacts to remote',\n );\n await saveContactsToUserStorage(localVisibleContacts, options);\n }\n return;\n }\n\n // Prepare maps for efficient lookup\n const localContactsMap = new Map<string, AddressBookEntry>();\n const remoteContactsMap = new Map<string, SyncAddressBookEntry>();\n\n localVisibleContacts.forEach((contact) => {\n const key = createContactKey(contact);\n localContactsMap.set(key, contact);\n });\n\n remoteContacts.forEach((contact) => {\n const key = createContactKey(contact);\n remoteContactsMap.set(key, contact);\n });\n\n // Lists to track contacts that need to be synced\n const contactsToAddOrUpdateLocally: SyncAddressBookEntry[] = [];\n const contactsToDeleteLocally: SyncAddressBookEntry[] = [];\n const contactsToUpdateRemotely: AddressBookEntry[] = [];\n\n // SCENARIO 2 & 6: Process remote contacts - handle new device sync and remote updates\n for (const remoteContact of remoteContacts) {\n const key = createContactKey(remoteContact);\n const localContact = localContactsMap.get(key);\n\n // Handle remote contact based on its status and local existence\n if (remoteContact.deleted) {\n // SCENARIO 8: Remote deletion - should be applied locally if contact exists locally\n if (localContact) {\n console.log(\n '🔄 Contacts Sync: Applying remote deletion locally',\n remoteContact,\n );\n contactsToDeleteLocally.push(remoteContact);\n\n // Invoke deletion callback if needed\n if (onContactDeleted) {\n onContactDeleted();\n }\n }\n } else if (!localContact) {\n // SCENARIO 2: New contact from remote - import to local\n console.log(\n '🔄 Contacts Sync: Importing new remote contact',\n remoteContact,\n );\n contactsToAddOrUpdateLocally.push(remoteContact);\n\n // Invoke update callback if needed\n if (onContactUpdated) {\n onContactUpdated();\n }\n } else {\n // SCENARIO 4 & 6: Contact exists on both sides - check for conflicts\n const hasContentDifference =\n localContact.name !== remoteContact.name ||\n localContact.memo !== remoteContact.memo;\n\n if (hasContentDifference) {\n // Check timestamps to determine which version to keep\n const localTimestamp = localContact.lastUpdatedAt || 0;\n const remoteTimestamp = remoteContact.lastUpdatedAt || 0;\n\n if (localTimestamp >= remoteTimestamp) {\n // Local is newer (or same age) - use local version\n console.log('🔄 Contacts Sync: Local wins by timestamp', {\n local: localContact,\n remote: remoteContact,\n localTimestamp,\n remoteTimestamp,\n });\n contactsToUpdateRemotely.push(localContact);\n } else {\n // Remote is newer - use remote version\n console.log('🔄 Contacts Sync: Remote wins by timestamp', {\n local: localContact,\n remote: remoteContact,\n localTimestamp,\n remoteTimestamp,\n });\n contactsToAddOrUpdateLocally.push(remoteContact);\n\n // Invoke update callback if needed\n if (onContactUpdated) {\n onContactUpdated();\n }\n }\n } else {\n // Content is identical, no action needed\n console.log('🔄 Contacts Sync: Content identical, no action needed', {\n local: localContact,\n remote: remoteContact,\n });\n }\n }\n }\n\n // SCENARIO 3 & 5: Process local contacts not in remote\n for (const localContact of localVisibleContacts) {\n const key = createContactKey(localContact);\n const remoteContact = remoteContactsMap.get(key);\n\n if (!remoteContact) {\n // New local contact - add to remote\n console.log(\n '🔄 Contacts Sync: New local contact - adding to remote',\n localContact,\n );\n contactsToUpdateRemotely.push(localContact);\n }\n }\n\n // SCENARIO 7: Detect local deletions\n // Skip for new device scenario (no local contacts but remote has contacts)\n const isNewDeviceScenario =\n localVisibleContacts.length === 0 && remoteContacts.length > 0;\n\n if (!isNewDeviceScenario) {\n // Find contacts that exist in remote but not locally (they were deleted locally)\n const contactsToDeleteRemotely: SyncAddressBookEntry[] = [];\n\n for (const remoteContact of remoteContacts) {\n if (!remoteContact.deleted) {\n const key = createContactKey(remoteContact);\n if (!localContactsMap.has(key)) {\n console.log(\n '🔄 Contacts Sync: Contact deleted locally, marking as deleted in remote',\n remoteContact,\n );\n contactsToDeleteRemotely.push(remoteContact);\n\n // Invoke deletion callback if needed\n if (onContactDeleted) {\n onContactDeleted();\n }\n }\n }\n }\n\n // Mark contacts as deleted in remote\n if (contactsToDeleteRemotely.length > 0) {\n const remoteContactsWithDeletions = [...remoteContacts];\n\n for (const contactToDelete of contactsToDeleteRemotely) {\n const key = createContactKey(contactToDelete);\n const indexToDelete = remoteContactsWithDeletions.findIndex(\n (c) => createContactKey(c) === key,\n );\n\n if (indexToDelete !== -1) {\n const now = Date.now();\n remoteContactsWithDeletions[indexToDelete] = {\n ...remoteContactsWithDeletions[indexToDelete],\n deleted: true,\n deletedAt: now,\n lastUpdatedAt: now,\n };\n }\n }\n\n // Save updated remote contacts with deletions\n await saveContactsToUserStorage(remoteContactsWithDeletions, options);\n }\n } else {\n console.log(\n '🔄 Contacts Sync: Skipping local deletion detection - this is a new device',\n );\n }\n\n // Apply local deletions\n for (const contact of contactsToDeleteLocally) {\n try {\n console.log('🔄 Contacts Sync: Deleting contact locally', contact);\n await getMessenger().call(\n 'AddressBookController:delete',\n contact.chainId,\n contact.address,\n );\n } catch (error) {\n console.error('Error deleting contact:', error);\n }\n }\n\n // Apply local additions/updates\n for (const contact of contactsToAddOrUpdateLocally) {\n if (!contact.deleted) {\n try {\n console.log(\n '🔄 Contacts Sync: Adding/updating contact locally',\n contact,\n );\n await getMessenger().call(\n 'AddressBookController:set',\n contact.address,\n contact.name || '',\n contact.chainId,\n contact.memo || '',\n contact.addressType,\n );\n } catch (error) {\n console.error('Error updating contact:', error);\n }\n }\n }\n\n // Apply changes to remote storage\n if (contactsToUpdateRemotely.length > 0) {\n console.log(\n '🔄 Contacts Sync: Updating contacts in remote storage',\n contactsToUpdateRemotely,\n );\n\n // Update existing remote contacts with new contacts\n const updatedRemoteContacts = [...remoteContacts];\n\n for (const localContact of contactsToUpdateRemotely) {\n const key = createContactKey(localContact);\n const existingIndex = updatedRemoteContacts.findIndex(\n (c) => createContactKey(c) === key,\n );\n\n const now = Date.now();\n const updatedEntry = {\n ...localContact,\n lastUpdatedAt: now,\n deleted: false, // Ensure it's not deleted\n } as SyncAddressBookEntry;\n\n if (existingIndex !== -1) {\n // Update existing contact\n updatedRemoteContacts[existingIndex] = updatedEntry;\n } else {\n // Add new contact\n updatedRemoteContacts.push(updatedEntry);\n }\n }\n\n // Save updated contacts to remote storage\n await saveContactsToUserStorage(updatedRemoteContacts, options);\n }\n\n console.log('🔄 Contacts Sync: Sync completed successfully');\n } catch (error) {\n console.error('🔄 Contacts Sync: Error during sync', error);\n if (onContactSyncErroneousSituation) {\n onContactSyncErroneousSituation('Error synchronizing contacts', {\n error,\n });\n }\n } finally {\n await getUserStorageControllerInstance().setIsContactSyncingInProgress(\n false,\n );\n }\n}\n\n/**\n * Retrieves remote contacts from user storage API\n *\n * @param options - Parameters used for retrieving remote contacts\n * @returns Array of contacts from remote storage, or null if none found\n */\nasync function getRemoteContacts(\n options: ContactSyncingOptions,\n): Promise<SyncAddressBookEntry[] | null> {\n const { getUserStorageControllerInstance } = options;\n\n try {\n const remoteContactsJson =\n await getUserStorageControllerInstance().performGetStorage(\n `${USER_STORAGE_FEATURE_NAMES.addressBook}.${ADDRESS_BOOK_CONTACTS_KEY}`,\n );\n\n if (!remoteContactsJson) {\n return null;\n }\n\n // Parse the JSON and convert each entry from UserStorageContactEntry to AddressBookEntry\n const remoteStorageEntries = JSON.parse(\n remoteContactsJson,\n ) as UserStorageContactEntry[];\n return remoteStorageEntries.map((entry) =>\n mapUserStorageEntryToAddressBookEntry(entry),\n );\n } catch {\n return null;\n }\n}\n\n/**\n * Saves local contacts to user storage\n *\n * @param contacts - The contacts to save to user storage\n * @param options - Parameters used for saving contacts\n */\nasync function saveContactsToUserStorage(\n contacts: AddressBookEntry[],\n options: ContactSyncingOptions,\n): Promise<void> {\n const { getUserStorageControllerInstance } = options;\n\n if (!contacts || contacts.length === 0) {\n return;\n }\n\n // Convert each AddressBookEntry to UserStorageContactEntry format before saving\n const storageEntries = contacts.map((contact) =>\n mapAddressBookEntryToUserStorageEntry(contact),\n );\n\n await getUserStorageControllerInstance().performSetStorage(\n `${USER_STORAGE_FEATURE_NAMES.addressBook}.${ADDRESS_BOOK_CONTACTS_KEY}`,\n JSON.stringify(storageEntries),\n );\n}\n\n/**\n * Updates a single contact in remote storage without performing a full sync\n * This is used when a contact is updated locally to efficiently push changes to remote\n *\n * @param contact - The contact that was updated locally\n * @param options - Parameters used for syncing operations\n */\nexport async function updateContactInRemoteStorage(\n contact: AddressBookEntry,\n options: ContactSyncingOptions,\n): Promise<void> {\n if (!canPerformContactSyncing(options)) {\n return;\n }\n\n console.log(\n '🔄 Contacts Sync: Updating single contact in remote storage',\n contact,\n );\n\n try {\n // Get current remote contacts or initialize empty array\n const remoteContacts = (await getRemoteContacts(options)) || [];\n\n // Find if this contact already exists in remote\n const key = createContactKey(contact);\n const existingIndex = remoteContacts.findIndex(\n (c) => createContactKey(c) === key,\n );\n\n const updatedRemoteContacts = [...remoteContacts];\n\n // Create an updated entry with timestamp\n const updatedEntry = {\n ...contact,\n lastUpdatedAt: contact.lastUpdatedAt || Date.now(),\n deleted: false, // Explicitly set to false in case this was previously deleted\n } as SyncAddressBookEntry;\n\n if (existingIndex !== -1) {\n // Update existing contact\n updatedRemoteContacts[existingIndex] = updatedEntry;\n } else {\n // Add as new contact\n updatedRemoteContacts.push(updatedEntry);\n }\n\n // Save to remote storage\n await saveContactsToUserStorage(updatedRemoteContacts, options);\n } catch (error) {\n console.error(\n '🔄 Contacts Sync: Error updating contact in remote storage',\n error,\n );\n }\n}\n\n/**\n * Marks a single contact as deleted in remote storage without performing a full sync\n * This is used when a contact is deleted locally to efficiently push the deletion to remote\n *\n * @param contact - The contact that was deleted locally (contains at least address and chainId)\n * @param options - Parameters used for syncing operations\n */\nexport async function deleteContactInRemoteStorage(\n contact: AddressBookEntry,\n options: ContactSyncingOptions,\n): Promise<void> {\n if (!canPerformContactSyncing(options)) {\n return;\n }\n\n console.log(\n '🔄 Contacts Sync: Marking contact as deleted in remote storage',\n contact,\n );\n\n try {\n // Get current remote contacts\n const remoteContacts = (await getRemoteContacts(options)) || [];\n\n // Find the contact in remote storage\n const key = createContactKey(contact);\n const existingIndex = remoteContacts.findIndex(\n (c) => createContactKey(c) === key,\n );\n\n // If the contact exists in remote storage\n if (existingIndex !== -1) {\n const updatedRemoteContacts = [...remoteContacts];\n const now = Date.now();\n\n // Mark the contact as deleted\n updatedRemoteContacts[existingIndex] = {\n ...updatedRemoteContacts[existingIndex],\n deleted: true,\n deletedAt: now,\n lastUpdatedAt: now,\n };\n\n // Save to remote storage\n await saveContactsToUserStorage(updatedRemoteContacts, options);\n }\n } catch (error) {\n console.error(\n '🔄 Contacts Sync: Error marking contact as deleted in remote storage',\n error,\n );\n }\n}\n"]}
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setupContactSyncingSubscriptions = void 0;
4
+ const controller_integration_1 = require("./controller-integration.cjs");
5
+ const sync_utils_1 = require("./sync-utils.cjs");
6
+ /**
7
+ * Initialize and setup events to listen to for contact syncing
8
+ *
9
+ * @param options - parameters used for initializing and enabling contact syncing
10
+ */
11
+ function setupContactSyncingSubscriptions(options) {
12
+ const { getMessenger } = options;
13
+ // Listen for contact updates and immediately sync the individual contact
14
+ getMessenger().subscribe('AddressBookController:contactUpdated', (contactEntry) => {
15
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
16
+ (async () => {
17
+ if (!(0, sync_utils_1.canPerformContactSyncing)(options)) {
18
+ return;
19
+ }
20
+ console.log('AddressBookController:contactUpdated', contactEntry);
21
+ // Skip global accounts with chainId "*" : they are contacts bridged from accounts
22
+ if (String(contactEntry.chainId) === '*') {
23
+ return;
24
+ }
25
+ try {
26
+ // Use the targeted method to update just this contact
27
+ await (0, controller_integration_1.updateContactInRemoteStorage)(contactEntry, options);
28
+ }
29
+ catch (error) {
30
+ console.error('Error updating contact in remote storage:', error);
31
+ }
32
+ })();
33
+ });
34
+ // Listen for contact deletions and immediately sync the individual deletion
35
+ getMessenger().subscribe('AddressBookController:contactDeleted', (contactEntry) => {
36
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
37
+ (async () => {
38
+ if (!(0, sync_utils_1.canPerformContactSyncing)(options)) {
39
+ return;
40
+ }
41
+ console.log('AddressBookController:contactDeleted', contactEntry);
42
+ // Skip global accounts with chainId "*" : they are contacts bridged from accounts
43
+ if (String(contactEntry.chainId) === '*') {
44
+ return;
45
+ }
46
+ try {
47
+ // Use the targeted method to delete just this contact
48
+ await (0, controller_integration_1.deleteContactInRemoteStorage)(contactEntry, options);
49
+ }
50
+ catch (error) {
51
+ console.error('Error deleting contact from remote storage:', error);
52
+ }
53
+ })();
54
+ });
55
+ }
56
+ exports.setupContactSyncingSubscriptions = setupContactSyncingSubscriptions;
57
+ //# sourceMappingURL=setup-subscriptions.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-subscriptions.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/setup-subscriptions.ts"],"names":[],"mappings":";;;AAEA,yEAGkC;AAClC,iDAAwD;AAGxD;;;;GAIG;AACH,SAAgB,gCAAgC,CAC9C,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;IAEjC,yEAAyE;IACzE,YAAY,EAAE,CAAC,SAAS,CACtB,sCAAsC,EACtC,CAAC,YAA8B,EAAE,EAAE;QACjC,mEAAmE;QACnE,CAAC,KAAK,IAAI,EAAE;YACV,IAAI,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC,EAAE;gBACtC,OAAO;aACR;YAED,OAAO,CAAC,GAAG,CAAC,sCAAsC,EAAE,YAAY,CAAC,CAAC;YAElE,kFAAkF;YAClF,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,GAAG,EAAE;gBACxC,OAAO;aACR;YAED,IAAI;gBACF,sDAAsD;gBACtD,MAAM,IAAA,qDAA4B,EAAC,YAAY,EAAE,OAAO,CAAC,CAAC;aAC3D;YAAC,OAAO,KAAK,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;aACnE;QACH,CAAC,CAAC,EAAE,CAAC;IACP,CAAC,CACF,CAAC;IAEF,4EAA4E;IAC5E,YAAY,EAAE,CAAC,SAAS,CACtB,sCAAsC,EACtC,CAAC,YAA8B,EAAE,EAAE;QACjC,mEAAmE;QACnE,CAAC,KAAK,IAAI,EAAE;YACV,IAAI,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC,EAAE;gBACtC,OAAO;aACR;YAED,OAAO,CAAC,GAAG,CAAC,sCAAsC,EAAE,YAAY,CAAC,CAAC;YAElE,kFAAkF;YAClF,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,GAAG,EAAE;gBACxC,OAAO;aACR;YAED,IAAI;gBACF,sDAAsD;gBACtD,MAAM,IAAA,qDAA4B,EAAC,YAAY,EAAE,OAAO,CAAC,CAAC;aAC3D;YAAC,OAAO,KAAK,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;aACrE;QACH,CAAC,CAAC,EAAE,CAAC;IACP,CAAC,CACF,CAAC;AACJ,CAAC;AA1DD,4EA0DC","sourcesContent":["import type { AddressBookEntry } from '@metamask/address-book-controller';\n\nimport {\n updateContactInRemoteStorage,\n deleteContactInRemoteStorage,\n} from './controller-integration';\nimport { canPerformContactSyncing } from './sync-utils';\nimport type { ContactSyncingOptions } from './types';\n\n/**\n * Initialize and setup events to listen to for contact syncing\n *\n * @param options - parameters used for initializing and enabling contact syncing\n */\nexport function setupContactSyncingSubscriptions(\n options: ContactSyncingOptions,\n): void {\n const { getMessenger } = options;\n\n // Listen for contact updates and immediately sync the individual contact\n getMessenger().subscribe(\n 'AddressBookController:contactUpdated',\n (contactEntry: AddressBookEntry) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (async () => {\n if (!canPerformContactSyncing(options)) {\n return;\n }\n\n console.log('AddressBookController:contactUpdated', contactEntry);\n\n // Skip global accounts with chainId \"*\" : they are contacts bridged from accounts\n if (String(contactEntry.chainId) === '*') {\n return;\n }\n\n try {\n // Use the targeted method to update just this contact\n await updateContactInRemoteStorage(contactEntry, options);\n } catch (error) {\n console.error('Error updating contact in remote storage:', error);\n }\n })();\n },\n );\n\n // Listen for contact deletions and immediately sync the individual deletion\n getMessenger().subscribe(\n 'AddressBookController:contactDeleted',\n (contactEntry: AddressBookEntry) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (async () => {\n if (!canPerformContactSyncing(options)) {\n return;\n }\n\n console.log('AddressBookController:contactDeleted', contactEntry);\n\n // Skip global accounts with chainId \"*\" : they are contacts bridged from accounts\n if (String(contactEntry.chainId) === '*') {\n return;\n }\n\n try {\n // Use the targeted method to delete just this contact\n await deleteContactInRemoteStorage(contactEntry, options);\n } catch (error) {\n console.error('Error deleting contact from remote storage:', error);\n }\n })();\n },\n );\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import type { ContactSyncingOptions } from "./types.cjs";
2
+ /**
3
+ * Initialize and setup events to listen to for contact syncing
4
+ *
5
+ * @param options - parameters used for initializing and enabling contact syncing
6
+ */
7
+ export declare function setupContactSyncingSubscriptions(options: ContactSyncingOptions): void;
8
+ //# sourceMappingURL=setup-subscriptions.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-subscriptions.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,qBAAqB,GAC7B,IAAI,CAwDN"}
@@ -0,0 +1,8 @@
1
+ import type { ContactSyncingOptions } from "./types.mjs";
2
+ /**
3
+ * Initialize and setup events to listen to for contact syncing
4
+ *
5
+ * @param options - parameters used for initializing and enabling contact syncing
6
+ */
7
+ export declare function setupContactSyncingSubscriptions(options: ContactSyncingOptions): void;
8
+ //# sourceMappingURL=setup-subscriptions.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-subscriptions.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,qBAAqB,GAC7B,IAAI,CAwDN"}
@@ -0,0 +1,53 @@
1
+ import { updateContactInRemoteStorage, deleteContactInRemoteStorage } from "./controller-integration.mjs";
2
+ import { canPerformContactSyncing } from "./sync-utils.mjs";
3
+ /**
4
+ * Initialize and setup events to listen to for contact syncing
5
+ *
6
+ * @param options - parameters used for initializing and enabling contact syncing
7
+ */
8
+ export function setupContactSyncingSubscriptions(options) {
9
+ const { getMessenger } = options;
10
+ // Listen for contact updates and immediately sync the individual contact
11
+ getMessenger().subscribe('AddressBookController:contactUpdated', (contactEntry) => {
12
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
13
+ (async () => {
14
+ if (!canPerformContactSyncing(options)) {
15
+ return;
16
+ }
17
+ console.log('AddressBookController:contactUpdated', contactEntry);
18
+ // Skip global accounts with chainId "*" : they are contacts bridged from accounts
19
+ if (String(contactEntry.chainId) === '*') {
20
+ return;
21
+ }
22
+ try {
23
+ // Use the targeted method to update just this contact
24
+ await updateContactInRemoteStorage(contactEntry, options);
25
+ }
26
+ catch (error) {
27
+ console.error('Error updating contact in remote storage:', error);
28
+ }
29
+ })();
30
+ });
31
+ // Listen for contact deletions and immediately sync the individual deletion
32
+ getMessenger().subscribe('AddressBookController:contactDeleted', (contactEntry) => {
33
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
34
+ (async () => {
35
+ if (!canPerformContactSyncing(options)) {
36
+ return;
37
+ }
38
+ console.log('AddressBookController:contactDeleted', contactEntry);
39
+ // Skip global accounts with chainId "*" : they are contacts bridged from accounts
40
+ if (String(contactEntry.chainId) === '*') {
41
+ return;
42
+ }
43
+ try {
44
+ // Use the targeted method to delete just this contact
45
+ await deleteContactInRemoteStorage(contactEntry, options);
46
+ }
47
+ catch (error) {
48
+ console.error('Error deleting contact from remote storage:', error);
49
+ }
50
+ })();
51
+ });
52
+ }
53
+ //# sourceMappingURL=setup-subscriptions.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup-subscriptions.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,4BAA4B,EAC5B,4BAA4B,EAC7B,qCAAiC;AAClC,OAAO,EAAE,wBAAwB,EAAE,yBAAqB;AAGxD;;;;GAIG;AACH,MAAM,UAAU,gCAAgC,CAC9C,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC;IAEjC,yEAAyE;IACzE,YAAY,EAAE,CAAC,SAAS,CACtB,sCAAsC,EACtC,CAAC,YAA8B,EAAE,EAAE;QACjC,mEAAmE;QACnE,CAAC,KAAK,IAAI,EAAE;YACV,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,EAAE;gBACtC,OAAO;aACR;YAED,OAAO,CAAC,GAAG,CAAC,sCAAsC,EAAE,YAAY,CAAC,CAAC;YAElE,kFAAkF;YAClF,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,GAAG,EAAE;gBACxC,OAAO;aACR;YAED,IAAI;gBACF,sDAAsD;gBACtD,MAAM,4BAA4B,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;aAC3D;YAAC,OAAO,KAAK,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;aACnE;QACH,CAAC,CAAC,EAAE,CAAC;IACP,CAAC,CACF,CAAC;IAEF,4EAA4E;IAC5E,YAAY,EAAE,CAAC,SAAS,CACtB,sCAAsC,EACtC,CAAC,YAA8B,EAAE,EAAE;QACjC,mEAAmE;QACnE,CAAC,KAAK,IAAI,EAAE;YACV,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,EAAE;gBACtC,OAAO;aACR;YAED,OAAO,CAAC,GAAG,CAAC,sCAAsC,EAAE,YAAY,CAAC,CAAC;YAElE,kFAAkF;YAClF,IAAI,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,GAAG,EAAE;gBACxC,OAAO;aACR;YAED,IAAI;gBACF,sDAAsD;gBACtD,MAAM,4BAA4B,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;aAC3D;YAAC,OAAO,KAAK,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;aACrE;QACH,CAAC,CAAC,EAAE,CAAC;IACP,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AddressBookEntry } from '@metamask/address-book-controller';\n\nimport {\n updateContactInRemoteStorage,\n deleteContactInRemoteStorage,\n} from './controller-integration';\nimport { canPerformContactSyncing } from './sync-utils';\nimport type { ContactSyncingOptions } from './types';\n\n/**\n * Initialize and setup events to listen to for contact syncing\n *\n * @param options - parameters used for initializing and enabling contact syncing\n */\nexport function setupContactSyncingSubscriptions(\n options: ContactSyncingOptions,\n): void {\n const { getMessenger } = options;\n\n // Listen for contact updates and immediately sync the individual contact\n getMessenger().subscribe(\n 'AddressBookController:contactUpdated',\n (contactEntry: AddressBookEntry) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (async () => {\n if (!canPerformContactSyncing(options)) {\n return;\n }\n\n console.log('AddressBookController:contactUpdated', contactEntry);\n\n // Skip global accounts with chainId \"*\" : they are contacts bridged from accounts\n if (String(contactEntry.chainId) === '*') {\n return;\n }\n\n try {\n // Use the targeted method to update just this contact\n await updateContactInRemoteStorage(contactEntry, options);\n } catch (error) {\n console.error('Error updating contact in remote storage:', error);\n }\n })();\n },\n );\n\n // Listen for contact deletions and immediately sync the individual deletion\n getMessenger().subscribe(\n 'AddressBookController:contactDeleted',\n (contactEntry: AddressBookEntry) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (async () => {\n if (!canPerformContactSyncing(options)) {\n return;\n }\n\n console.log('AddressBookController:contactDeleted', contactEntry);\n\n // Skip global accounts with chainId \"*\" : they are contacts bridged from accounts\n if (String(contactEntry.chainId) === '*') {\n return;\n }\n\n try {\n // Use the targeted method to delete just this contact\n await deleteContactInRemoteStorage(contactEntry, options);\n } catch (error) {\n console.error('Error deleting contact from remote storage:', error);\n }\n })();\n },\n );\n}\n"]}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canPerformContactSyncing = void 0;
4
+ /**
5
+ * Check if we can perform contact syncing
6
+ *
7
+ * @param options - parameters used for checking if we can perform contact syncing
8
+ * @returns whether we can perform contact syncing
9
+ */
10
+ function canPerformContactSyncing(options) {
11
+ const { getMessenger, getUserStorageControllerInstance } = options;
12
+ const { isBackupAndSyncEnabled, isContactSyncingEnabled, isContactSyncingInProgress, } = getUserStorageControllerInstance().state;
13
+ const isAuthEnabled = getMessenger().call('AuthenticationController:isSignedIn');
14
+ if (!isBackupAndSyncEnabled ||
15
+ !isContactSyncingEnabled ||
16
+ isContactSyncingInProgress ||
17
+ !isAuthEnabled) {
18
+ return false;
19
+ }
20
+ return true;
21
+ }
22
+ exports.canPerformContactSyncing = canPerformContactSyncing;
23
+ //# sourceMappingURL=sync-utils.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-utils.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/sync-utils.ts"],"names":[],"mappings":";;;AAEA;;;;;GAKG;AACH,SAAgB,wBAAwB,CACtC,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAEnE,MAAM,EACJ,sBAAsB,EACtB,uBAAuB,EACvB,0BAA0B,GAC3B,GAAG,gCAAgC,EAAE,CAAC,KAAK,CAAC;IAC7C,MAAM,aAAa,GAAG,YAAY,EAAE,CAAC,IAAI,CACvC,qCAAqC,CACtC,CAAC;IAEF,IACE,CAAC,sBAAsB;QACvB,CAAC,uBAAuB;QACxB,0BAA0B;QAC1B,CAAC,aAAa,EACd;QACA,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAxBD,4DAwBC","sourcesContent":["import type { ContactSyncingOptions } from './types';\n\n/**\n * Check if we can perform contact syncing\n *\n * @param options - parameters used for checking if we can perform contact syncing\n * @returns whether we can perform contact syncing\n */\nexport function canPerformContactSyncing(\n options: ContactSyncingOptions,\n): boolean {\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n const {\n isBackupAndSyncEnabled,\n isContactSyncingEnabled,\n isContactSyncingInProgress,\n } = getUserStorageControllerInstance().state;\n const isAuthEnabled = getMessenger().call(\n 'AuthenticationController:isSignedIn',\n );\n\n if (\n !isBackupAndSyncEnabled ||\n !isContactSyncingEnabled ||\n isContactSyncingInProgress ||\n !isAuthEnabled\n ) {\n return false;\n }\n\n return true;\n}\n"]}
@@ -0,0 +1,9 @@
1
+ import type { ContactSyncingOptions } from "./types.cjs";
2
+ /**
3
+ * Check if we can perform contact syncing
4
+ *
5
+ * @param options - parameters used for checking if we can perform contact syncing
6
+ * @returns whether we can perform contact syncing
7
+ */
8
+ export declare function canPerformContactSyncing(options: ContactSyncingOptions): boolean;
9
+ //# sourceMappingURL=sync-utils.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-utils.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/contact-syncing/sync-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAsBT"}