@metamask/profile-sync-controller 23.0.0 → 25.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/dist/controllers/authentication/AuthenticationController.cjs +4 -0
  3. package/dist/controllers/authentication/AuthenticationController.cjs.map +1 -1
  4. package/dist/controllers/authentication/AuthenticationController.d.cts.map +1 -1
  5. package/dist/controllers/authentication/AuthenticationController.d.mts.map +1 -1
  6. package/dist/controllers/authentication/AuthenticationController.mjs +4 -0
  7. package/dist/controllers/authentication/AuthenticationController.mjs.map +1 -1
  8. package/dist/controllers/user-storage/UserStorageController.cjs +14 -87
  9. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  10. package/dist/controllers/user-storage/UserStorageController.d.cts +3 -52
  11. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  12. package/dist/controllers/user-storage/UserStorageController.d.mts +3 -52
  13. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  14. package/dist/controllers/user-storage/UserStorageController.mjs +10 -83
  15. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  16. package/dist/controllers/user-storage/constants.cjs +0 -3
  17. package/dist/controllers/user-storage/constants.cjs.map +1 -1
  18. package/dist/controllers/user-storage/constants.d.cts +0 -2
  19. package/dist/controllers/user-storage/constants.d.cts.map +1 -1
  20. package/dist/controllers/user-storage/constants.d.mts +0 -2
  21. package/dist/controllers/user-storage/constants.d.mts.map +1 -1
  22. package/dist/controllers/user-storage/constants.mjs +0 -3
  23. package/dist/controllers/user-storage/constants.mjs.map +1 -1
  24. package/dist/sdk/authentication-jwt-bearer/flow-srp.cjs +28 -2
  25. package/dist/sdk/authentication-jwt-bearer/flow-srp.cjs.map +1 -1
  26. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.cts.map +1 -1
  27. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.mts.map +1 -1
  28. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +28 -2
  29. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs.map +1 -1
  30. package/package.json +10 -10
  31. package/dist/controllers/user-storage/account-syncing/constants.cjs +0 -51
  32. package/dist/controllers/user-storage/account-syncing/constants.cjs.map +0 -1
  33. package/dist/controllers/user-storage/account-syncing/constants.d.cts +0 -4
  34. package/dist/controllers/user-storage/account-syncing/constants.d.cts.map +0 -1
  35. package/dist/controllers/user-storage/account-syncing/constants.d.mts +0 -4
  36. package/dist/controllers/user-storage/account-syncing/constants.d.mts.map +0 -1
  37. package/dist/controllers/user-storage/account-syncing/constants.mjs +0 -48
  38. package/dist/controllers/user-storage/account-syncing/constants.mjs.map +0 -1
  39. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs +0 -253
  40. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs.map +0 -1
  41. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts +0 -38
  42. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts.map +0 -1
  43. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts +0 -38
  44. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts.map +0 -1
  45. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs +0 -247
  46. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs.map +0 -1
  47. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs +0 -35
  48. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs.map +0 -1
  49. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts +0 -8
  50. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts.map +0 -1
  51. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts +0 -8
  52. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts.map +0 -1
  53. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs +0 -31
  54. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs.map +0 -1
  55. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs +0 -61
  56. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs.map +0 -1
  57. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts +0 -30
  58. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts.map +0 -1
  59. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts +0 -30
  60. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts.map +0 -1
  61. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs +0 -55
  62. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs.map +0 -1
  63. package/dist/controllers/user-storage/account-syncing/types.cjs +0 -3
  64. package/dist/controllers/user-storage/account-syncing/types.cjs.map +0 -1
  65. package/dist/controllers/user-storage/account-syncing/types.d.cts +0 -25
  66. package/dist/controllers/user-storage/account-syncing/types.d.cts.map +0 -1
  67. package/dist/controllers/user-storage/account-syncing/types.d.mts +0 -25
  68. package/dist/controllers/user-storage/account-syncing/types.d.mts.map +0 -1
  69. package/dist/controllers/user-storage/account-syncing/types.mjs +0 -2
  70. package/dist/controllers/user-storage/account-syncing/types.mjs.map +0 -1
  71. package/dist/controllers/user-storage/account-syncing/utils.cjs +0 -36
  72. package/dist/controllers/user-storage/account-syncing/utils.cjs.map +0 -1
  73. package/dist/controllers/user-storage/account-syncing/utils.d.cts +0 -18
  74. package/dist/controllers/user-storage/account-syncing/utils.d.cts.map +0 -1
  75. package/dist/controllers/user-storage/account-syncing/utils.d.mts +0 -18
  76. package/dist/controllers/user-storage/account-syncing/utils.d.mts.map +0 -1
  77. package/dist/controllers/user-storage/account-syncing/utils.mjs +0 -31
  78. package/dist/controllers/user-storage/account-syncing/utils.mjs.map +0 -1
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOCALIZED_DEFAULT_ACCOUNT_NAMES = exports.USER_STORAGE_VERSION_KEY = exports.USER_STORAGE_VERSION = void 0;
4
- exports.USER_STORAGE_VERSION = '1';
5
- // Force cast. We don't really care about the type here since we treat it as a unique symbol
6
- exports.USER_STORAGE_VERSION_KEY = 'v';
7
- // We need this in order to know if an account is a default account or not when we do account syncing
8
- exports.LOCALIZED_DEFAULT_ACCOUNT_NAMES = [
9
- 'Account',
10
- 'መለያ',
11
- 'الحساب',
12
- 'Профил',
13
- 'অ্যাকাউন্ট',
14
- 'Compte',
15
- 'Účet',
16
- 'Konto',
17
- 'Λογαριασμός',
18
- 'Cuenta',
19
- 'حساب',
20
- 'Tili',
21
- 'એકાઉન્ટ',
22
- 'חשבון',
23
- 'अकाउंट',
24
- 'खाता',
25
- 'Račun',
26
- 'Kont',
27
- 'Fiók',
28
- 'Akun',
29
- 'アカウント',
30
- 'ಖಾತೆ',
31
- '계정',
32
- 'Paskyra',
33
- 'Konts',
34
- 'അക്കൗണ്ട്',
35
- 'खाते',
36
- 'Akaun',
37
- 'Conta',
38
- 'Cont',
39
- 'Счет',
40
- 'налог',
41
- 'Akaunti',
42
- 'கணக்கு',
43
- 'ఖాతా',
44
- 'บัญชี',
45
- 'Hesap',
46
- 'Обліковий запис',
47
- 'Tài khoản',
48
- '账户',
49
- '帳戶',
50
- ];
51
- //# sourceMappingURL=constants.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,oBAAoB,GAAG,GAAG,CAAC;AAExC,4FAA4F;AAC/E,QAAA,wBAAwB,GAAkB,GAAY,CAAC;AAEpE,qGAAqG;AACxF,QAAA,+BAA+B,GAAG;IAC7C,SAAS;IACT,KAAK;IACL,QAAQ;IACR,QAAQ;IACR,YAAY;IACZ,QAAQ;IACR,MAAM;IACN,OAAO;IACP,aAAa;IACb,QAAQ;IACR,MAAM;IACN,MAAM;IACN,SAAS;IACT,OAAO;IACP,QAAQ;IACR,MAAM;IACN,OAAO;IACP,MAAM;IACN,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,IAAI;IACJ,SAAS;IACT,OAAO;IACP,WAAW;IACX,MAAM;IACN,OAAO;IACP,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;IACP,OAAO;IACP,iBAAiB;IACjB,WAAW;IACX,IAAI;IACJ,IAAI;CACI,CAAC","sourcesContent":["export const USER_STORAGE_VERSION = '1';\n\n// Force cast. We don't really care about the type here since we treat it as a unique symbol\nexport const USER_STORAGE_VERSION_KEY: unique symbol = 'v' as never;\n\n// We need this in order to know if an account is a default account or not when we do account syncing\nexport const LOCALIZED_DEFAULT_ACCOUNT_NAMES = [\n 'Account',\n 'መለያ',\n 'الحساب',\n 'Профил',\n 'অ্যাকাউন্ট',\n 'Compte',\n 'Účet',\n 'Konto',\n 'Λογαριασμός',\n 'Cuenta',\n 'حساب',\n 'Tili',\n 'એકાઉન્ટ',\n 'חשבון',\n 'अकाउंट',\n 'खाता',\n 'Račun',\n 'Kont',\n 'Fiók',\n 'Akun',\n 'アカウント',\n 'ಖಾತೆ',\n '계정',\n 'Paskyra',\n 'Konts',\n 'അക്കൗണ്ട്',\n 'खाते',\n 'Akaun',\n 'Conta',\n 'Cont',\n 'Счет',\n 'налог',\n 'Akaunti',\n 'கணக்கு',\n 'ఖాతా',\n 'บัญชี',\n 'Hesap',\n 'Обліковий запис',\n 'Tài khoản',\n '账户',\n '帳戶',\n] as const;\n"]}
@@ -1,4 +0,0 @@
1
- export declare const USER_STORAGE_VERSION = "1";
2
- export declare const USER_STORAGE_VERSION_KEY: unique symbol;
3
- export declare const LOCALIZED_DEFAULT_ACCOUNT_NAMES: readonly ["Account", "መለያ", "الحساب", "Профил", "অ্যাকাউন্ট", "Compte", "Účet", "Konto", "Λογαριασμός", "Cuenta", "حساب", "Tili", "એકાઉન્ટ", "חשבון", "अकाउंट", "खाता", "Račun", "Kont", "Fiók", "Akun", "アカウント", "ಖಾತೆ", "계정", "Paskyra", "Konts", "അക്കൗണ്ട്", "खाते", "Akaun", "Conta", "Cont", "Счет", "налог", "Akaunti", "கணக்கு", "ఖాతా", "บัญชี", "Hesap", "Обліковий запис", "Tài khoản", "账户", "帳戶"];
4
- //# sourceMappingURL=constants.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAGxC,eAAO,MAAM,wBAAwB,EAAE,OAAO,MAAqB,CAAC;AAGpE,eAAO,MAAM,+BAA+B,gZA0ClC,CAAC"}
@@ -1,4 +0,0 @@
1
- export declare const USER_STORAGE_VERSION = "1";
2
- export declare const USER_STORAGE_VERSION_KEY: unique symbol;
3
- export declare const LOCALIZED_DEFAULT_ACCOUNT_NAMES: readonly ["Account", "መለያ", "الحساب", "Профил", "অ্যাকাউন্ট", "Compte", "Účet", "Konto", "Λογαριασμός", "Cuenta", "حساب", "Tili", "એકાઉન્ટ", "חשבון", "अकाउंट", "खाता", "Račun", "Kont", "Fiók", "Akun", "アカウント", "ಖಾತೆ", "계정", "Paskyra", "Konts", "അക്കൗണ്ട്", "खाते", "Akaun", "Conta", "Cont", "Счет", "налог", "Akaunti", "கணக்கு", "ఖాతా", "บัญชี", "Hesap", "Обліковий запис", "Tài khoản", "账户", "帳戶"];
4
- //# sourceMappingURL=constants.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAGxC,eAAO,MAAM,wBAAwB,EAAE,OAAO,MAAqB,CAAC;AAGpE,eAAO,MAAM,+BAA+B,gZA0ClC,CAAC"}
@@ -1,48 +0,0 @@
1
- export const USER_STORAGE_VERSION = '1';
2
- // Force cast. We don't really care about the type here since we treat it as a unique symbol
3
- export const USER_STORAGE_VERSION_KEY = 'v';
4
- // We need this in order to know if an account is a default account or not when we do account syncing
5
- export const LOCALIZED_DEFAULT_ACCOUNT_NAMES = [
6
- 'Account',
7
- 'መለያ',
8
- 'الحساب',
9
- 'Профил',
10
- 'অ্যাকাউন্ট',
11
- 'Compte',
12
- 'Účet',
13
- 'Konto',
14
- 'Λογαριασμός',
15
- 'Cuenta',
16
- 'حساب',
17
- 'Tili',
18
- 'એકાઉન્ટ',
19
- 'חשבון',
20
- 'अकाउंट',
21
- 'खाता',
22
- 'Račun',
23
- 'Kont',
24
- 'Fiók',
25
- 'Akun',
26
- 'アカウント',
27
- 'ಖಾತೆ',
28
- '계정',
29
- 'Paskyra',
30
- 'Konts',
31
- 'അക്കൗണ്ട്',
32
- 'खाते',
33
- 'Akaun',
34
- 'Conta',
35
- 'Cont',
36
- 'Счет',
37
- 'налог',
38
- 'Akaunti',
39
- 'கணக்கு',
40
- 'ఖాతా',
41
- 'บัญชี',
42
- 'Hesap',
43
- 'Обліковий запис',
44
- 'Tài khoản',
45
- '账户',
46
- '帳戶',
47
- ];
48
- //# sourceMappingURL=constants.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAExC,4FAA4F;AAC5F,MAAM,CAAC,MAAM,wBAAwB,GAAkB,GAAY,CAAC;AAEpE,qGAAqG;AACrG,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC7C,SAAS;IACT,KAAK;IACL,QAAQ;IACR,QAAQ;IACR,YAAY;IACZ,QAAQ;IACR,MAAM;IACN,OAAO;IACP,aAAa;IACb,QAAQ;IACR,MAAM;IACN,MAAM;IACN,SAAS;IACT,OAAO;IACP,QAAQ;IACR,MAAM;IACN,OAAO;IACP,MAAM;IACN,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,IAAI;IACJ,SAAS;IACT,OAAO;IACP,WAAW;IACX,MAAM;IACN,OAAO;IACP,OAAO;IACP,MAAM;IACN,MAAM;IACN,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;IACP,OAAO;IACP,iBAAiB;IACjB,WAAW;IACX,IAAI;IACJ,IAAI;CACI,CAAC","sourcesContent":["export const USER_STORAGE_VERSION = '1';\n\n// Force cast. We don't really care about the type here since we treat it as a unique symbol\nexport const USER_STORAGE_VERSION_KEY: unique symbol = 'v' as never;\n\n// We need this in order to know if an account is a default account or not when we do account syncing\nexport const LOCALIZED_DEFAULT_ACCOUNT_NAMES = [\n 'Account',\n 'መለያ',\n 'الحساب',\n 'Профил',\n 'অ্যাকাউন্ট',\n 'Compte',\n 'Účet',\n 'Konto',\n 'Λογαριασμός',\n 'Cuenta',\n 'حساب',\n 'Tili',\n 'એકાઉન્ટ',\n 'חשבון',\n 'अकाउंट',\n 'खाता',\n 'Račun',\n 'Kont',\n 'Fiók',\n 'Akun',\n 'アカウント',\n 'ಖಾತೆ',\n '계정',\n 'Paskyra',\n 'Konts',\n 'അക്കൗണ്ട്',\n 'खाते',\n 'Akaun',\n 'Conta',\n 'Cont',\n 'Счет',\n 'налог',\n 'Akaunti',\n 'கணக்கு',\n 'ఖాతా',\n 'บัญชี',\n 'Hesap',\n 'Обліковий запис',\n 'Tài khoản',\n '账户',\n '帳戶',\n] as const;\n"]}
@@ -1,253 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.syncInternalAccountsWithUserStorage = exports.saveInternalAccountsListToUserStorage = exports.saveInternalAccountToUserStorage = void 0;
4
- const keyring_controller_1 = require("@metamask/keyring-controller");
5
- const sync_utils_1 = require("./sync-utils.cjs");
6
- const utils_1 = require("./utils.cjs");
7
- const storage_schema_1 = require("../../../shared/storage-schema.cjs");
8
- const constants_1 = require("../constants.cjs");
9
- /**
10
- * Saves an individual internal account to the user storage.
11
- *
12
- * @param internalAccount - The internal account to save
13
- * @param options - parameters used for saving the internal account
14
- * @returns Promise that resolves when the account is saved
15
- */
16
- async function saveInternalAccountToUserStorage(internalAccount, options) {
17
- const { trace } = options;
18
- const saveAccount = async () => {
19
- const { getUserStorageControllerInstance } = options;
20
- if (!(0, sync_utils_1.canPerformAccountSyncing)(options) ||
21
- internalAccount.metadata.keyring.type !== String(keyring_controller_1.KeyringTypes.hd) // sync only EVM accounts until we support multichain accounts
22
- ) {
23
- return;
24
- }
25
- // properties of `options` are (wrongly?) typed as `Json` and eslint crashes if we try to interpret it as such and call a `?.toString()` on it.
26
- // but we know this is a string?, so we can safely cast it
27
- const entropySourceId = internalAccount.options?.entropySource;
28
- try {
29
- // Map the internal account to the user storage account schema
30
- const mappedAccount = (0, utils_1.mapInternalAccountToUserStorageAccount)(internalAccount);
31
- await getUserStorageControllerInstance().performSetStorage(`${storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`, JSON.stringify(mappedAccount), entropySourceId);
32
- }
33
- catch (e) {
34
- // istanbul ignore next
35
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
36
- throw new Error(`UserStorageController - failed to save account to user storage - ${errorMessage}`);
37
- }
38
- };
39
- if (trace) {
40
- return await trace({ name: constants_1.TraceName.AccountSyncSaveIndividual }, saveAccount);
41
- }
42
- return await saveAccount();
43
- }
44
- exports.saveInternalAccountToUserStorage = saveInternalAccountToUserStorage;
45
- /**
46
- * Saves the list of internal accounts to the user storage.
47
- *
48
- * @param options - parameters used for saving the list of internal accounts
49
- * @param entropySourceId - The entropy source ID used to derive the key,
50
- * when multiple sources are available (Multi-SRP).
51
- * @returns Promise that resolves when all accounts are saved
52
- */
53
- async function saveInternalAccountsListToUserStorage(options, entropySourceId) {
54
- const { getUserStorageControllerInstance } = options;
55
- const internalAccountsList = await (0, sync_utils_1.getInternalAccountsList)(options, entropySourceId);
56
- if (!internalAccountsList?.length) {
57
- return;
58
- }
59
- const internalAccountsListFormattedForUserStorage = internalAccountsList.map(utils_1.mapInternalAccountToUserStorageAccount);
60
- await getUserStorageControllerInstance().performBatchSetStorage(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts, internalAccountsListFormattedForUserStorage.map((account) => [
61
- account.a,
62
- JSON.stringify(account),
63
- ]), entropySourceId);
64
- }
65
- exports.saveInternalAccountsListToUserStorage = saveInternalAccountsListToUserStorage;
66
- /**
67
- * Syncs the internal accounts list with the user storage accounts list.
68
- * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.
69
- * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.
70
- *
71
- * @param config - parameters used for syncing the internal accounts list with the user storage accounts list
72
- * @param options - parameters used for syncing the internal accounts list with the user storage accounts list
73
- * @param entropySourceId - The entropy source ID used to derive the key,
74
- * @returns Promise that resolves when synchronization is complete
75
- */
76
- async function syncInternalAccountsWithUserStorage(config, options, entropySourceId) {
77
- const { trace } = options;
78
- const performAccountSync = async () => {
79
- if (!(0, sync_utils_1.canPerformAccountSyncing)(options)) {
80
- return;
81
- }
82
- const { maxNumberOfAccountsToAdd = Infinity, onAccountAdded, onAccountNameUpdated, onAccountSyncErroneousSituation, } = config;
83
- const { getMessenger, getUserStorageControllerInstance } = options;
84
- try {
85
- await getUserStorageControllerInstance().setIsAccountSyncingInProgress(true);
86
- const userStorageAccountsList = await (0, sync_utils_1.getUserStorageAccountsList)(options, entropySourceId);
87
- if (!userStorageAccountsList || !userStorageAccountsList.length) {
88
- await saveInternalAccountsListToUserStorage(options, entropySourceId);
89
- return;
90
- }
91
- // Keep a record if erroneous situations are found during the sync
92
- // This is done so we can send the context to Sentry in case of an erroneous situation
93
- let erroneousSituationsFound = false;
94
- // Prepare an array of internal accounts to be saved to the user storage
95
- const internalAccountsToBeSavedToUserStorage = [];
96
- // Compare internal accounts list with user storage accounts list
97
- // First step: compare lengths
98
- const internalAccountsList = await (0, sync_utils_1.getInternalAccountsList)(options, entropySourceId);
99
- if (!internalAccountsList || !internalAccountsList.length) {
100
- throw new Error(`Failed to get internal accounts list`);
101
- }
102
- const hasMoreUserStorageAccountsThanInternalAccounts = userStorageAccountsList.length > internalAccountsList.length;
103
- // We don't want to remove existing accounts for a user
104
- // so we only add new accounts if the user has more accounts in user storage than internal accounts
105
- if (hasMoreUserStorageAccountsThanInternalAccounts) {
106
- const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -
107
- internalAccountsList.length;
108
- // Create new accounts to match the user storage accounts list
109
- await getMessenger().call('KeyringController:withKeyring', {
110
- id: entropySourceId,
111
- }, async ({ keyring }) => {
112
- await keyring.addAccounts(numberOfAccountsToAdd);
113
- });
114
- // TODO: below code is kept for analytics but should probably be re-thought
115
- for (let i = 0; i < numberOfAccountsToAdd; i++) {
116
- onAccountAdded?.();
117
- }
118
- }
119
- // Second step: compare account names
120
- // Get the internal accounts list again since new accounts might have been added in the previous step
121
- const refreshedInternalAccountsList = await (0, sync_utils_1.getInternalAccountsList)(options, entropySourceId);
122
- const newlyAddedAccounts = refreshedInternalAccountsList.filter((account) => !internalAccountsList.find((a) => a.address === account.address));
123
- for (const internalAccount of refreshedInternalAccountsList) {
124
- const userStorageAccount = userStorageAccountsList.find((account) => account.a === internalAccount.address);
125
- // If the account is not present in user storage
126
- // istanbul ignore next
127
- if (!userStorageAccount) {
128
- // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account
129
- if (newlyAddedAccounts.includes(internalAccount)) {
130
- erroneousSituationsFound = true;
131
- onAccountSyncErroneousSituation?.('An account was added to the internal accounts list but was not present in the user storage accounts list', {
132
- internalAccount,
133
- userStorageAccount,
134
- newlyAddedAccounts,
135
- userStorageAccountsList,
136
- internalAccountsList,
137
- refreshedInternalAccountsList,
138
- internalAccountsToBeSavedToUserStorage,
139
- });
140
- continue;
141
- }
142
- // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage
143
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
144
- continue;
145
- }
146
- // From this point on, we know that the account is present in
147
- // both the internal accounts list and the user storage accounts list
148
- // One or both accounts have default names
149
- const isInternalAccountNameDefault = (0, utils_1.isNameDefaultAccountName)(internalAccount.metadata.name);
150
- const isUserStorageAccountNameDefault = (0, utils_1.isNameDefaultAccountName)(userStorageAccount.n);
151
- // Internal account has default name
152
- if (isInternalAccountNameDefault) {
153
- if (!isUserStorageAccountNameDefault) {
154
- getMessenger().call('AccountsController:updateAccountMetadata', internalAccount.id, {
155
- name: userStorageAccount.n,
156
- });
157
- onAccountNameUpdated?.();
158
- }
159
- continue;
160
- }
161
- // Internal account has custom name but user storage account has default name
162
- if (isUserStorageAccountNameDefault) {
163
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
164
- continue;
165
- }
166
- // Both accounts have custom names
167
- // User storage account has a nameLastUpdatedAt timestamp
168
- // Note: not storing the undefined checks in constants to act as a type guard
169
- if (userStorageAccount.nlu !== undefined) {
170
- if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {
171
- const isInternalAccountNameNewer = internalAccount.metadata.nameLastUpdatedAt >
172
- userStorageAccount.nlu;
173
- if (isInternalAccountNameNewer) {
174
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
175
- continue;
176
- }
177
- }
178
- getMessenger().call('AccountsController:updateAccountMetadata', internalAccount.id, {
179
- name: userStorageAccount.n,
180
- nameLastUpdatedAt: userStorageAccount.nlu,
181
- });
182
- const areInternalAndUserStorageAccountNamesEqual = internalAccount.metadata.name === userStorageAccount.n;
183
- if (!areInternalAndUserStorageAccountNamesEqual) {
184
- onAccountNameUpdated?.();
185
- }
186
- continue;
187
- }
188
- else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {
189
- internalAccountsToBeSavedToUserStorage.push(internalAccount);
190
- continue;
191
- }
192
- }
193
- // Save the internal accounts list to the user storage
194
- if (internalAccountsToBeSavedToUserStorage.length) {
195
- await getUserStorageControllerInstance().performBatchSetStorage(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts, internalAccountsToBeSavedToUserStorage.map((account) => [
196
- account.address,
197
- JSON.stringify((0, utils_1.mapInternalAccountToUserStorageAccount)(account)),
198
- ]), entropySourceId);
199
- }
200
- // In case we have corrupted user storage with accounts that don't exist in the internal accounts list
201
- // Delete those accounts from the user storage
202
- const userStorageAccountsToBeDeleted = userStorageAccountsList.filter((account) => !refreshedInternalAccountsList.find((a) => a.address === account.a));
203
- if (userStorageAccountsToBeDeleted.length) {
204
- await getUserStorageControllerInstance().performBatchDeleteStorage(storage_schema_1.USER_STORAGE_FEATURE_NAMES.accounts, userStorageAccountsToBeDeleted.map((account) => account.a), entropySourceId);
205
- erroneousSituationsFound = true;
206
- onAccountSyncErroneousSituation?.('An account was present in the user storage accounts list but was not found in the internal accounts list after the sync', {
207
- userStorageAccountsToBeDeleted,
208
- internalAccountsList,
209
- refreshedInternalAccountsList,
210
- internalAccountsToBeSavedToUserStorage,
211
- userStorageAccountsList,
212
- });
213
- }
214
- if (erroneousSituationsFound) {
215
- const [finalUserStorageAccountsList, finalInternalAccountsList] = await Promise.all([
216
- (0, sync_utils_1.getUserStorageAccountsList)(options, entropySourceId),
217
- (0, sync_utils_1.getInternalAccountsList)(options, entropySourceId),
218
- ]);
219
- const doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList = finalInternalAccountsList.every((account) => finalUserStorageAccountsList?.some((userStorageAccount) => userStorageAccount.a === account.address));
220
- // istanbul ignore next
221
- const doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList = (finalUserStorageAccountsList?.length || 0) > maxNumberOfAccountsToAdd
222
- ? true
223
- : finalUserStorageAccountsList?.every((account) => finalInternalAccountsList.some((internalAccount) => internalAccount.address === account.a));
224
- const doFinalListsMatch = doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList &&
225
- doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList;
226
- const context = {
227
- finalUserStorageAccountsList,
228
- finalInternalAccountsList,
229
- };
230
- if (doFinalListsMatch) {
231
- onAccountSyncErroneousSituation?.('Erroneous situations were found during the sync, but final state matches the expected state', context);
232
- }
233
- else {
234
- onAccountSyncErroneousSituation?.('Erroneous situations were found during the sync, and final state does not match the expected state', context);
235
- }
236
- }
237
- }
238
- catch (e) {
239
- // istanbul ignore next
240
- const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
241
- throw new Error(`UserStorageController - failed to sync user storage accounts list - ${errorMessage}`);
242
- }
243
- finally {
244
- await getUserStorageControllerInstance().setIsAccountSyncingInProgress(false);
245
- }
246
- };
247
- if (trace) {
248
- return await trace({ name: constants_1.TraceName.AccountSyncFull }, performAccountSync);
249
- }
250
- return await performAccountSync();
251
- }
252
- exports.syncInternalAccountsWithUserStorage = syncInternalAccountsWithUserStorage;
253
- //# sourceMappingURL=controller-integration.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":";;;AAAA,qEAA4D;AAG5D,iDAIsB;AAEtB,uCAGiB;AACjB,uEAA4E;AAC5E,gDAAyC;AAEzC;;;;;;GAMG;AACI,KAAK,UAAU,gCAAgC,CACpD,eAAgC,EAChC,OAA8B;IAE9B,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IAE1B,MAAM,WAAW,GAAG,KAAK,IAAI,EAAE;QAC7B,MAAM,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;QAErD,IACE,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC;YAClC,eAAe,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,iCAAY,CAAC,EAAE,CAAC,CAAC,8DAA8D;UAChI;YACA,OAAO;SACR;QAED,+IAA+I;QAC/I,0DAA0D;QAC1D,MAAM,eAAe,GAAG,eAAe,CAAC,OAAO,EAAE,aAEpC,CAAC;QAEd,IAAI;YACF,8DAA8D;YAC9D,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+BAA+B,EAAE,CAC/B,oGAAoG,EACpG,OAAO,CACR,CAAC;iBACH;aACF;SACF;QAAC,OAAO,CAAC,EAAE;YACV,uBAAuB;YACvB,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;YACxE,MAAM,IAAI,KAAK,CACb,uEAAuE,YAAY,EAAE,CACtF,CAAC;SACH;gBAAS;YACR,MAAM,gCAAgC,EAAE,CAAC,6BAA6B,CACpE,KAAK,CACN,CAAC;SACH;IACH,CAAC,CAAC;IAEF,IAAI,KAAK,EAAE;QACT,OAAO,MAAM,KAAK,CAAC,EAAE,IAAI,EAAE,qBAAS,CAAC,eAAe,EAAE,EAAE,kBAAkB,CAAC,CAAC;KAC7E;IAED,OAAO,MAAM,kBAAkB,EAAE,CAAC;AACpC,CAAC;AArSD,kFAqSC","sourcesContent":["import { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport {\n canPerformAccountSyncing,\n getInternalAccountsList,\n getUserStorageAccountsList,\n} from './sync-utils';\nimport type { AccountSyncingOptions } from './types';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './utils';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../../shared/storage-schema';\nimport { TraceName } from '../constants';\n\n/**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n * @param options - parameters used for saving the internal account\n * @returns Promise that resolves when the account is saved\n */\nexport async function saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n options: AccountSyncingOptions,\n): Promise<void> {\n const { trace } = options;\n\n const saveAccount = async () => {\n const { getUserStorageControllerInstance } = options;\n\n if (\n !canPerformAccountSyncing(options) ||\n internalAccount.metadata.keyring.type !== String(KeyringTypes.hd) // sync only EVM accounts until we support multichain accounts\n ) {\n return;\n }\n\n // properties of `options` are (wrongly?) typed as `Json` and eslint crashes if we try to interpret it as such and call a `?.toString()` on it.\n // but we know this is a string?, so we can safely cast it\n const entropySourceId = internalAccount.options?.entropySource as\n | string\n | undefined;\n\n try {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await getUserStorageControllerInstance().performSetStorage(\n `${USER_STORAGE_FEATURE_NAMES.accounts}.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n entropySourceId,\n );\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to save account to user storage - ${errorMessage}`,\n );\n }\n };\n\n if (trace) {\n return await trace(\n { name: TraceName.AccountSyncSaveIndividual },\n saveAccount,\n );\n }\n\n return await saveAccount();\n}\n\n/**\n * Saves the list of internal accounts to the user storage.\n *\n * @param options - parameters used for saving the list of internal accounts\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns Promise that resolves when all accounts are saved\n */\nexport async function saveInternalAccountsListToUserStorage(\n options: AccountSyncingOptions,\n entropySourceId: string,\n): Promise<void> {\n const { getUserStorageControllerInstance } = options;\n\n const internalAccountsList = await getInternalAccountsList(\n options,\n entropySourceId,\n );\n\n if (!internalAccountsList?.length) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n entropySourceId,\n );\n}\n\ntype SyncInternalAccountsWithUserStorageConfig = {\n maxNumberOfAccountsToAdd?: number;\n onAccountAdded?: () => void;\n onAccountNameUpdated?: () => void;\n onAccountSyncErroneousSituation?: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n};\n\n/**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n *\n * @param config - parameters used for syncing the internal accounts list with the user storage accounts list\n * @param options - parameters used for syncing the internal accounts list with the user storage accounts list\n * @param entropySourceId - The entropy source ID used to derive the key,\n * @returns Promise that resolves when synchronization is complete\n */\nexport async function syncInternalAccountsWithUserStorage(\n config: SyncInternalAccountsWithUserStorageConfig,\n options: AccountSyncingOptions,\n entropySourceId: string,\n): Promise<void> {\n const { trace } = options;\n\n const performAccountSync = async () => {\n if (!canPerformAccountSyncing(options)) {\n return;\n }\n\n const {\n maxNumberOfAccountsToAdd = Infinity,\n onAccountAdded,\n onAccountNameUpdated,\n onAccountSyncErroneousSituation,\n } = config;\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n try {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n true,\n );\n\n const userStorageAccountsList = await getUserStorageAccountsList(\n options,\n entropySourceId,\n );\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await saveInternalAccountsListToUserStorage(options, entropySourceId);\n return;\n }\n // Keep a record if erroneous situations are found during the sync\n // This is done so we can send the context to Sentry in case of an erroneous situation\n let erroneousSituationsFound = false;\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n const internalAccountsList = await getInternalAccountsList(\n options,\n entropySourceId,\n );\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreUserStorageAccountsThanInternalAccounts =\n userStorageAccountsList.length > internalAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts in user storage than internal accounts\n if (hasMoreUserStorageAccountsThanInternalAccounts) {\n const numberOfAccountsToAdd =\n Math.min(userStorageAccountsList.length, maxNumberOfAccountsToAdd) -\n internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n await getMessenger().call(\n 'KeyringController:withKeyring',\n {\n id: entropySourceId,\n },\n async ({ keyring }) => {\n await keyring.addAccounts(numberOfAccountsToAdd);\n },\n );\n\n // TODO: below code is kept for analytics but should probably be re-thought\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n onAccountAdded?.();\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n const refreshedInternalAccountsList = await getInternalAccountsList(\n options,\n entropySourceId,\n );\n\n const newlyAddedAccounts = refreshedInternalAccountsList.filter(\n (account) =>\n !internalAccountsList.find((a) => a.address === account.address),\n );\n\n for (const internalAccount of refreshedInternalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n // If the account is not present in user storage\n // istanbul ignore next\n if (!userStorageAccount) {\n // If the account was just added in the previous step, skip saving it, it's likely to be a bogus account\n if (newlyAddedAccounts.includes(internalAccount)) {\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was added to the internal accounts list but was not present in the user storage accounts list',\n {\n internalAccount,\n userStorageAccount,\n newlyAddedAccounts,\n userStorageAccountsList,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n },\n );\n continue;\n }\n // Otherwise, it means that this internal account was present before the sync, and needs to be saved to the user storage\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // From this point on, we know that the account is present in\n // both the internal accounts list and the user storage accounts list\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n onAccountNameUpdated?.();\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n getMessenger().call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n onAccountNameUpdated?.();\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n if (internalAccountsToBeSavedToUserStorage.length) {\n await getUserStorageControllerInstance().performBatchSetStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n entropySourceId,\n );\n }\n\n // In case we have corrupted user storage with accounts that don't exist in the internal accounts list\n // Delete those accounts from the user storage\n const userStorageAccountsToBeDeleted = userStorageAccountsList.filter(\n (account) =>\n !refreshedInternalAccountsList.find((a) => a.address === account.a),\n );\n\n if (userStorageAccountsToBeDeleted.length) {\n await getUserStorageControllerInstance().performBatchDeleteStorage(\n USER_STORAGE_FEATURE_NAMES.accounts,\n userStorageAccountsToBeDeleted.map((account) => account.a),\n entropySourceId,\n );\n erroneousSituationsFound = true;\n onAccountSyncErroneousSituation?.(\n 'An account was present in the user storage accounts list but was not found in the internal accounts list after the sync',\n {\n userStorageAccountsToBeDeleted,\n internalAccountsList,\n refreshedInternalAccountsList,\n internalAccountsToBeSavedToUserStorage,\n userStorageAccountsList,\n },\n );\n }\n\n if (erroneousSituationsFound) {\n const [finalUserStorageAccountsList, finalInternalAccountsList] =\n await Promise.all([\n getUserStorageAccountsList(options, entropySourceId),\n getInternalAccountsList(options, entropySourceId),\n ]);\n\n const doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList =\n finalInternalAccountsList.every((account) =>\n finalUserStorageAccountsList?.some(\n (userStorageAccount) => userStorageAccount.a === account.address,\n ),\n );\n\n // istanbul ignore next\n const doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList =\n (finalUserStorageAccountsList?.length || 0) > maxNumberOfAccountsToAdd\n ? true\n : finalUserStorageAccountsList?.every((account) =>\n finalInternalAccountsList.some(\n (internalAccount) => internalAccount.address === account.a,\n ),\n );\n\n const doFinalListsMatch =\n doesEveryAccountInInternalAccountsListExistInUserStorageAccountsList &&\n doesEveryAccountInUserStorageAccountsListExistInInternalAccountsList;\n\n const context = {\n finalUserStorageAccountsList,\n finalInternalAccountsList,\n };\n if (doFinalListsMatch) {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, but final state matches the expected state',\n context,\n );\n } else {\n onAccountSyncErroneousSituation?.(\n 'Erroneous situations were found during the sync, and final state does not match the expected state',\n context,\n );\n }\n }\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `UserStorageController - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n await getUserStorageControllerInstance().setIsAccountSyncingInProgress(\n false,\n );\n }\n };\n\n if (trace) {\n return await trace({ name: TraceName.AccountSyncFull }, performAccountSync);\n }\n\n return await performAccountSync();\n}\n"]}
@@ -1,38 +0,0 @@
1
- import type { InternalAccount } from "@metamask/keyring-internal-api";
2
- import type { AccountSyncingOptions } from "./types.cjs";
3
- /**
4
- * Saves an individual internal account to the user storage.
5
- *
6
- * @param internalAccount - The internal account to save
7
- * @param options - parameters used for saving the internal account
8
- * @returns Promise that resolves when the account is saved
9
- */
10
- export declare function saveInternalAccountToUserStorage(internalAccount: InternalAccount, options: AccountSyncingOptions): Promise<void>;
11
- /**
12
- * Saves the list of internal accounts to the user storage.
13
- *
14
- * @param options - parameters used for saving the list of internal accounts
15
- * @param entropySourceId - The entropy source ID used to derive the key,
16
- * when multiple sources are available (Multi-SRP).
17
- * @returns Promise that resolves when all accounts are saved
18
- */
19
- export declare function saveInternalAccountsListToUserStorage(options: AccountSyncingOptions, entropySourceId: string): Promise<void>;
20
- type SyncInternalAccountsWithUserStorageConfig = {
21
- maxNumberOfAccountsToAdd?: number;
22
- onAccountAdded?: () => void;
23
- onAccountNameUpdated?: () => void;
24
- onAccountSyncErroneousSituation?: (errorMessage: string, sentryContext?: Record<string, unknown>) => void;
25
- };
26
- /**
27
- * Syncs the internal accounts list with the user storage accounts list.
28
- * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.
29
- * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.
30
- *
31
- * @param config - parameters used for syncing the internal accounts list with the user storage accounts list
32
- * @param options - parameters used for syncing the internal accounts list with the user storage accounts list
33
- * @param entropySourceId - The entropy source ID used to derive the key,
34
- * @returns Promise that resolves when synchronization is complete
35
- */
36
- export declare function syncInternalAccountsWithUserStorage(config: SyncInternalAccountsWithUserStorageConfig, options: AccountSyncingOptions, entropySourceId: string): Promise<void>;
37
- export {};
38
- //# sourceMappingURL=controller-integration.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAQrD;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA8Cf;AAED;;;;;;;GAOG;AACH,wBAAsB,qCAAqC,CACzD,OAAO,EAAE,qBAAqB,EAC9B,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CAwBf;AAED,KAAK,yCAAyC,GAAG;IAC/C,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,EAC9B,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CAiSf"}
@@ -1,38 +0,0 @@
1
- import type { InternalAccount } from "@metamask/keyring-internal-api";
2
- import type { AccountSyncingOptions } from "./types.mjs";
3
- /**
4
- * Saves an individual internal account to the user storage.
5
- *
6
- * @param internalAccount - The internal account to save
7
- * @param options - parameters used for saving the internal account
8
- * @returns Promise that resolves when the account is saved
9
- */
10
- export declare function saveInternalAccountToUserStorage(internalAccount: InternalAccount, options: AccountSyncingOptions): Promise<void>;
11
- /**
12
- * Saves the list of internal accounts to the user storage.
13
- *
14
- * @param options - parameters used for saving the list of internal accounts
15
- * @param entropySourceId - The entropy source ID used to derive the key,
16
- * when multiple sources are available (Multi-SRP).
17
- * @returns Promise that resolves when all accounts are saved
18
- */
19
- export declare function saveInternalAccountsListToUserStorage(options: AccountSyncingOptions, entropySourceId: string): Promise<void>;
20
- type SyncInternalAccountsWithUserStorageConfig = {
21
- maxNumberOfAccountsToAdd?: number;
22
- onAccountAdded?: () => void;
23
- onAccountNameUpdated?: () => void;
24
- onAccountSyncErroneousSituation?: (errorMessage: string, sentryContext?: Record<string, unknown>) => void;
25
- };
26
- /**
27
- * Syncs the internal accounts list with the user storage accounts list.
28
- * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.
29
- * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.
30
- *
31
- * @param config - parameters used for syncing the internal accounts list with the user storage accounts list
32
- * @param options - parameters used for syncing the internal accounts list with the user storage accounts list
33
- * @param entropySourceId - The entropy source ID used to derive the key,
34
- * @returns Promise that resolves when synchronization is complete
35
- */
36
- export declare function syncInternalAccountsWithUserStorage(config: SyncInternalAccountsWithUserStorageConfig, options: AccountSyncingOptions, entropySourceId: string): Promise<void>;
37
- export {};
38
- //# sourceMappingURL=controller-integration.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/controller-integration.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAOtE,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAQrD;;;;;;GAMG;AACH,wBAAsB,gCAAgC,CACpD,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CA8Cf;AAED;;;;;;;GAOG;AACH,wBAAsB,qCAAqC,CACzD,OAAO,EAAE,qBAAqB,EAC9B,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CAwBf;AAED,KAAK,yCAAyC,GAAG;IAC/C,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,MAAM,IAAI,CAAC;IAClC,+BAA+B,CAAC,EAAE,CAChC,YAAY,EAAE,MAAM,EACpB,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACpC,IAAI,CAAC;CACX,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,mCAAmC,CACvD,MAAM,EAAE,yCAAyC,EACjD,OAAO,EAAE,qBAAqB,EAC9B,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC,CAiSf"}