@metamask-previews/multichain-account-service 4.1.0-preview-a9886279 → 5.0.0-preview-6a568504
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -1
- package/dist/MultichainAccountGroup.cjs +84 -45
- package/dist/MultichainAccountGroup.cjs.map +1 -1
- package/dist/MultichainAccountGroup.d.cts +17 -4
- package/dist/MultichainAccountGroup.d.cts.map +1 -1
- package/dist/MultichainAccountGroup.d.mts +17 -4
- package/dist/MultichainAccountGroup.d.mts.map +1 -1
- package/dist/MultichainAccountGroup.mjs +84 -45
- package/dist/MultichainAccountGroup.mjs.map +1 -1
- package/dist/MultichainAccountService.cjs +150 -112
- package/dist/MultichainAccountService.cjs.map +1 -1
- package/dist/MultichainAccountService.d.cts +49 -20
- package/dist/MultichainAccountService.d.cts.map +1 -1
- package/dist/MultichainAccountService.d.mts +49 -20
- package/dist/MultichainAccountService.d.mts.map +1 -1
- package/dist/MultichainAccountService.mjs +151 -113
- package/dist/MultichainAccountService.mjs.map +1 -1
- package/dist/MultichainAccountWallet.cjs +108 -123
- package/dist/MultichainAccountWallet.cjs.map +1 -1
- package/dist/MultichainAccountWallet.d.cts +5 -4
- package/dist/MultichainAccountWallet.d.cts.map +1 -1
- package/dist/MultichainAccountWallet.d.mts +5 -4
- package/dist/MultichainAccountWallet.d.mts.map +1 -1
- package/dist/MultichainAccountWallet.mjs +108 -123
- package/dist/MultichainAccountWallet.mjs.map +1 -1
- package/dist/providers/AccountProviderWrapper.cjs +18 -0
- package/dist/providers/AccountProviderWrapper.cjs.map +1 -1
- package/dist/providers/AccountProviderWrapper.d.cts +12 -0
- package/dist/providers/AccountProviderWrapper.d.cts.map +1 -1
- package/dist/providers/AccountProviderWrapper.d.mts +12 -0
- package/dist/providers/AccountProviderWrapper.d.mts.map +1 -1
- package/dist/providers/AccountProviderWrapper.mjs +18 -0
- package/dist/providers/AccountProviderWrapper.mjs.map +1 -1
- package/dist/providers/BaseBip44AccountProvider.cjs +45 -20
- package/dist/providers/BaseBip44AccountProvider.cjs.map +1 -1
- package/dist/providers/BaseBip44AccountProvider.d.cts +58 -6
- package/dist/providers/BaseBip44AccountProvider.d.cts.map +1 -1
- package/dist/providers/BaseBip44AccountProvider.d.mts +58 -6
- package/dist/providers/BaseBip44AccountProvider.d.mts.map +1 -1
- package/dist/providers/BaseBip44AccountProvider.mjs +45 -20
- package/dist/providers/BaseBip44AccountProvider.mjs.map +1 -1
- package/dist/providers/BtcAccountProvider.cjs +47 -32
- package/dist/providers/BtcAccountProvider.cjs.map +1 -1
- package/dist/providers/BtcAccountProvider.d.cts +2 -1
- package/dist/providers/BtcAccountProvider.d.cts.map +1 -1
- package/dist/providers/BtcAccountProvider.d.mts +2 -1
- package/dist/providers/BtcAccountProvider.d.mts.map +1 -1
- package/dist/providers/BtcAccountProvider.mjs +47 -32
- package/dist/providers/BtcAccountProvider.mjs.map +1 -1
- package/dist/providers/EvmAccountProvider.cjs +39 -5
- package/dist/providers/EvmAccountProvider.cjs.map +1 -1
- package/dist/providers/EvmAccountProvider.d.cts +8 -0
- package/dist/providers/EvmAccountProvider.d.cts.map +1 -1
- package/dist/providers/EvmAccountProvider.d.mts +8 -0
- package/dist/providers/EvmAccountProvider.d.mts.map +1 -1
- package/dist/providers/EvmAccountProvider.mjs +39 -5
- package/dist/providers/EvmAccountProvider.mjs.map +1 -1
- package/dist/providers/SnapAccountProvider.cjs +81 -54
- package/dist/providers/SnapAccountProvider.cjs.map +1 -1
- package/dist/providers/SnapAccountProvider.d.cts +16 -4
- package/dist/providers/SnapAccountProvider.d.cts.map +1 -1
- package/dist/providers/SnapAccountProvider.d.mts +16 -4
- package/dist/providers/SnapAccountProvider.d.mts.map +1 -1
- package/dist/providers/SnapAccountProvider.mjs +81 -54
- package/dist/providers/SnapAccountProvider.mjs.map +1 -1
- package/dist/providers/SolAccountProvider.cjs +40 -31
- package/dist/providers/SolAccountProvider.cjs.map +1 -1
- package/dist/providers/SolAccountProvider.d.cts.map +1 -1
- package/dist/providers/SolAccountProvider.d.mts.map +1 -1
- package/dist/providers/SolAccountProvider.mjs +40 -31
- package/dist/providers/SolAccountProvider.mjs.map +1 -1
- package/dist/providers/TrxAccountProvider.cjs +48 -29
- package/dist/providers/TrxAccountProvider.cjs.map +1 -1
- package/dist/providers/TrxAccountProvider.d.cts +1 -0
- package/dist/providers/TrxAccountProvider.d.cts.map +1 -1
- package/dist/providers/TrxAccountProvider.d.mts +1 -0
- package/dist/providers/TrxAccountProvider.d.mts.map +1 -1
- package/dist/providers/TrxAccountProvider.mjs +48 -29
- package/dist/providers/TrxAccountProvider.mjs.map +1 -1
- package/dist/snaps/SnapPlatformWatcher.cjs +60 -0
- package/dist/snaps/SnapPlatformWatcher.cjs.map +1 -0
- package/dist/snaps/SnapPlatformWatcher.d.cts +8 -0
- package/dist/snaps/SnapPlatformWatcher.d.cts.map +1 -0
- package/dist/snaps/SnapPlatformWatcher.d.mts +8 -0
- package/dist/snaps/SnapPlatformWatcher.d.mts.map +1 -0
- package/dist/snaps/SnapPlatformWatcher.mjs +57 -0
- package/dist/snaps/SnapPlatformWatcher.mjs.map +1 -0
- package/dist/tests/messenger.cjs +12 -1
- package/dist/tests/messenger.cjs.map +1 -1
- package/dist/tests/messenger.d.cts +9 -4
- package/dist/tests/messenger.d.cts.map +1 -1
- package/dist/tests/messenger.d.mts +9 -4
- package/dist/tests/messenger.d.mts.map +1 -1
- package/dist/tests/messenger.mjs +12 -1
- package/dist/tests/messenger.mjs.map +1 -1
- package/dist/tests/providers.cjs +62 -7
- package/dist/tests/providers.cjs.map +1 -1
- package/dist/tests/providers.d.cts +17 -3
- package/dist/tests/providers.d.cts.map +1 -1
- package/dist/tests/providers.d.mts +17 -3
- package/dist/tests/providers.d.mts.map +1 -1
- package/dist/tests/providers.mjs +60 -6
- package/dist/tests/providers.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +14 -6
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +14 -6
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils.cjs +1 -11
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +0 -1
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +0 -1
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +0 -9
- package/dist/utils.mjs.map +1 -1
- package/package.json +3 -2
|
@@ -18,7 +18,7 @@ const utils_1 = require("@metamask/utils");
|
|
|
18
18
|
const async_mutex_1 = require("async-mutex");
|
|
19
19
|
const logger_1 = require("./logger.cjs");
|
|
20
20
|
const MultichainAccountGroup_1 = require("./MultichainAccountGroup.cjs");
|
|
21
|
-
const
|
|
21
|
+
const EvmAccountProvider_1 = require("./providers/EvmAccountProvider.cjs");
|
|
22
22
|
const utils_2 = require("./utils.cjs");
|
|
23
23
|
/**
|
|
24
24
|
* A multichain account wallet that holds multiple multichain accounts (one multichain account per
|
|
@@ -34,7 +34,6 @@ class MultichainAccountWallet {
|
|
|
34
34
|
_MultichainAccountWallet_accountGroups.set(this, void 0);
|
|
35
35
|
_MultichainAccountWallet_messenger.set(this, void 0);
|
|
36
36
|
_MultichainAccountWallet_log.set(this, void 0);
|
|
37
|
-
// eslint-disable-next-line @typescript-eslint/prefer-readonly
|
|
38
37
|
_MultichainAccountWallet_initialized.set(this, false);
|
|
39
38
|
_MultichainAccountWallet_status.set(this, void 0);
|
|
40
39
|
__classPrivateFieldSet(this, _MultichainAccountWallet_id, (0, account_api_1.toMultichainAccountWalletId)(entropySource), "f");
|
|
@@ -45,58 +44,32 @@ class MultichainAccountWallet {
|
|
|
45
44
|
__classPrivateFieldSet(this, _MultichainAccountWallet_log, (0, logger_1.createModuleLogger)(logger_1.projectLogger, `[${__classPrivateFieldGet(this, _MultichainAccountWallet_id, "f")}]`), "f");
|
|
46
45
|
// Initial synchronization (don't emit events during initialization).
|
|
47
46
|
__classPrivateFieldSet(this, _MultichainAccountWallet_status, 'uninitialized', "f");
|
|
48
|
-
this.sync();
|
|
49
|
-
__classPrivateFieldSet(this, _MultichainAccountWallet_initialized, true, "f");
|
|
50
|
-
__classPrivateFieldSet(this, _MultichainAccountWallet_status, 'ready', "f");
|
|
51
47
|
}
|
|
52
48
|
/**
|
|
53
|
-
*
|
|
49
|
+
* Initialize the wallet and construct the internal representation of multichain account groups.
|
|
54
50
|
*
|
|
55
|
-
*
|
|
56
|
-
* doesn't know about.
|
|
51
|
+
* @param walletState - The wallet state.
|
|
57
52
|
*/
|
|
58
|
-
|
|
59
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, '
|
|
60
|
-
for (const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
wallet: this,
|
|
73
|
-
providers: __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f"),
|
|
74
|
-
messenger: __classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f"),
|
|
75
|
-
});
|
|
76
|
-
// This existing multichain account group might differ from the
|
|
77
|
-
// `createMultichainAccountGroup` behavior. When creating a new
|
|
78
|
-
// group, we expect the providers to all succeed. But here, we're
|
|
79
|
-
// just fetching the account lists from them, so this group might
|
|
80
|
-
// not be "aligned" yet (e.g having a missing Solana account).
|
|
81
|
-
//
|
|
82
|
-
// Since "aligning" is an async operation, it would have to be run
|
|
83
|
-
// after the first-sync.
|
|
84
|
-
// TODO: Implement align mechanism to create "missing" accounts.
|
|
85
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `Found a new group: [${multichainAccount.id}]`);
|
|
86
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_accountGroups, "f").set(entropy.groupIndex, multichainAccount);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
53
|
+
init(walletState) {
|
|
54
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, 'Initializing wallet state...');
|
|
55
|
+
for (const [groupIndexString, groupState] of Object.entries(walletState)) {
|
|
56
|
+
// Have to convert to number because the state keys become strings when we construct the state object in the service
|
|
57
|
+
const groupIndex = Number(groupIndexString);
|
|
58
|
+
const group = new MultichainAccountGroup_1.MultichainAccountGroup({
|
|
59
|
+
groupIndex,
|
|
60
|
+
wallet: this,
|
|
61
|
+
providers: __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f"),
|
|
62
|
+
messenger: __classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f"),
|
|
63
|
+
});
|
|
64
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `Creating new group for index ${groupIndex}...`);
|
|
65
|
+
group.init(groupState);
|
|
66
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_accountGroups, "f").set(groupIndex, group);
|
|
89
67
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
// Clean up old multichain accounts.
|
|
94
|
-
if (!multichainAccount.hasAccounts()) {
|
|
95
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `Deleting group: [${multichainAccount.id}]`);
|
|
96
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_accountGroups, "f").delete(groupIndex);
|
|
97
|
-
}
|
|
68
|
+
if (!__classPrivateFieldGet(this, _MultichainAccountWallet_initialized, "f")) {
|
|
69
|
+
__classPrivateFieldSet(this, _MultichainAccountWallet_initialized, true, "f");
|
|
70
|
+
__classPrivateFieldSet(this, _MultichainAccountWallet_status, 'ready', "f");
|
|
98
71
|
}
|
|
99
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, '
|
|
72
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, 'Finished initializing wallet state...');
|
|
100
73
|
}
|
|
101
74
|
/**
|
|
102
75
|
* Gets the multichain account wallet ID.
|
|
@@ -210,9 +183,6 @@ class MultichainAccountWallet {
|
|
|
210
183
|
}
|
|
211
184
|
let group = this.getMultichainAccountGroup(groupIndex);
|
|
212
185
|
if (group) {
|
|
213
|
-
// If the group already exists, we just `sync` it and returns the same
|
|
214
|
-
// reference.
|
|
215
|
-
group.sync();
|
|
216
186
|
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `Trying to re-create existing group: [${group.id}] (idempotent)`);
|
|
217
187
|
return group;
|
|
218
188
|
}
|
|
@@ -220,23 +190,31 @@ class MultichainAccountWallet {
|
|
|
220
190
|
// Extract the EVM provider from the list of providers.
|
|
221
191
|
// We always await EVM account creation first.
|
|
222
192
|
const [evmProvider, ...otherProviders] = __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f");
|
|
223
|
-
(0, utils_1.assert)(evmProvider instanceof
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const errorMessage = `Unable to create
|
|
193
|
+
(0, utils_1.assert)(evmProvider instanceof EvmAccountProvider_1.EvmAccountProvider, 'EVM account provider must be first');
|
|
194
|
+
const evmAccounts = await evmProvider
|
|
195
|
+
.createAccounts({
|
|
196
|
+
entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
|
|
197
|
+
groupIndex,
|
|
198
|
+
})
|
|
199
|
+
.then((accounts) => accounts.map((account) => account.id))
|
|
200
|
+
.catch((error) => {
|
|
201
|
+
const errorMessage = `Unable to create some accounts for group index: ${groupIndex} with provider "${evmProvider.getName()}". Error: ${error.message}`;
|
|
202
|
+
console.warn(errorMessage);
|
|
232
203
|
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${logger_1.ERROR_PREFIX} ${errorMessage}:`, error);
|
|
233
204
|
const sentryError = (0, utils_2.createSentryError)(`Unable to create account with provider "${evmProvider.getName()}"`, error, {
|
|
234
205
|
groupIndex,
|
|
235
206
|
provider: evmProvider.getName(),
|
|
236
207
|
});
|
|
237
208
|
__classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f").captureException?.(sentryError);
|
|
238
|
-
throw
|
|
239
|
-
}
|
|
209
|
+
throw error;
|
|
210
|
+
});
|
|
211
|
+
group = new MultichainAccountGroup_1.MultichainAccountGroup({
|
|
212
|
+
wallet: this,
|
|
213
|
+
providers: __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f"),
|
|
214
|
+
groupIndex,
|
|
215
|
+
messenger: __classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f"),
|
|
216
|
+
});
|
|
217
|
+
group.init({ [evmProvider.getName()]: evmAccounts });
|
|
240
218
|
// We then create accounts with other providers (some being throttled if configured).
|
|
241
219
|
// Depending on the options, we either await all providers or run them in background.
|
|
242
220
|
if (options?.waitForAllProvidersToFinishCreatingAccounts) {
|
|
@@ -244,6 +222,7 @@ class MultichainAccountWallet {
|
|
|
244
222
|
groupIndex,
|
|
245
223
|
providers: otherProviders,
|
|
246
224
|
awaitAll: true,
|
|
225
|
+
group,
|
|
247
226
|
});
|
|
248
227
|
}
|
|
249
228
|
else {
|
|
@@ -252,43 +231,11 @@ class MultichainAccountWallet {
|
|
|
252
231
|
groupIndex,
|
|
253
232
|
providers: otherProviders,
|
|
254
233
|
awaitAll: false,
|
|
234
|
+
group,
|
|
255
235
|
});
|
|
256
236
|
}
|
|
257
|
-
//
|
|
258
|
-
|
|
259
|
-
//
|
|
260
|
-
// Since we're not "fully supporting multichain" for now, we still rely on single
|
|
261
|
-
// :accountCreated events to sync multichain account groups and wallets. Which means
|
|
262
|
-
// that even if of the provider fails, some accounts will still be created on some
|
|
263
|
-
// other providers and will become "available" on the `AccountsController`, like:
|
|
264
|
-
//
|
|
265
|
-
// 1. Creating a multichain account group for index 1
|
|
266
|
-
// 2. EvmAccountProvider.createAccounts returns the EVM account for index 1
|
|
267
|
-
// * AccountsController WILL fire :accountCreated for this account
|
|
268
|
-
// * This account WILL BE "available" on the AccountsController state
|
|
269
|
-
// 3. SolAccountProvider.createAccounts fails to create a Solana account for index 1
|
|
270
|
-
// * AccountsController WON't fire :accountCreated for this account
|
|
271
|
-
// * This account WON'T be "available" on the Account
|
|
272
|
-
// 4. MultichainAccountService will receive a :accountCreated for the EVM account from
|
|
273
|
-
// step 2 and will create a new multichain account group for index 1, but it won't
|
|
274
|
-
// receive any event for the Solana account of this group. Thus, this group won't be
|
|
275
|
-
// "aligned" (missing "blockchain account" on this group).
|
|
276
|
-
//
|
|
277
|
-
// --------------------------------------------------------------------------------
|
|
278
|
-
// Because of the :accountAdded automatic sync, we might already have created the
|
|
279
|
-
// group, so we first try to get it.
|
|
280
|
-
group = this.getMultichainAccountGroup(groupIndex);
|
|
281
|
-
if (!group) {
|
|
282
|
-
// If for some reason it's still not created, we're creating it explicitly now:
|
|
283
|
-
group = new MultichainAccountGroup_1.MultichainAccountGroup({
|
|
284
|
-
wallet: this,
|
|
285
|
-
providers: __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f"),
|
|
286
|
-
groupIndex,
|
|
287
|
-
messenger: __classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f"),
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
// Register the account to our internal map.
|
|
291
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_accountGroups, "f").set(groupIndex, group); // `group` cannot be undefined here.
|
|
237
|
+
// Register the account(s) to our internal map.
|
|
238
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_accountGroups, "f").set(groupIndex, group);
|
|
292
239
|
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `New group created: [${group.id}]`);
|
|
293
240
|
if (__classPrivateFieldGet(this, _MultichainAccountWallet_initialized, "f")) {
|
|
294
241
|
__classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f").publish('MultichainAccountService:multichainAccountGroupCreated', group);
|
|
@@ -344,6 +291,12 @@ class MultichainAccountWallet {
|
|
|
344
291
|
// Start with the next available group index (so we can resume the discovery
|
|
345
292
|
// from there).
|
|
346
293
|
let maxGroupIndex = this.getNextGroupIndex();
|
|
294
|
+
const discoveredGroupsState = {};
|
|
295
|
+
const addDiscoveryResultToState = (result, providerName, groupIndex) => {
|
|
296
|
+
const accountIds = result.map((account) => account.id);
|
|
297
|
+
discoveredGroupsState[groupIndex] ?? (discoveredGroupsState[groupIndex] = {});
|
|
298
|
+
discoveredGroupsState[groupIndex][providerName] = accountIds;
|
|
299
|
+
};
|
|
347
300
|
// One serialized loop per provider; all run concurrently
|
|
348
301
|
const runProviderDiscovery = async (context) => {
|
|
349
302
|
const providerName = context.provider.getName();
|
|
@@ -377,6 +330,7 @@ class MultichainAccountWallet {
|
|
|
377
330
|
}
|
|
378
331
|
(0, logger_1.projectLogger)(message('**succeeded**', targetGroupIndex));
|
|
379
332
|
context.accounts = context.accounts.concat(accounts);
|
|
333
|
+
addDiscoveryResultToState(accounts, providerName, targetGroupIndex);
|
|
380
334
|
const nextGroupIndex = targetGroupIndex + 1;
|
|
381
335
|
context.groupIndex = nextGroupIndex;
|
|
382
336
|
if (nextGroupIndex > maxGroupIndex) {
|
|
@@ -392,9 +346,18 @@ class MultichainAccountWallet {
|
|
|
392
346
|
}));
|
|
393
347
|
// Start discovery for each providers.
|
|
394
348
|
await Promise.all(providerContexts.map(runProviderDiscovery));
|
|
395
|
-
//
|
|
396
|
-
|
|
397
|
-
|
|
349
|
+
// Create discovered groups
|
|
350
|
+
for (const [groupIndexString, groupState] of Object.entries(discoveredGroupsState)) {
|
|
351
|
+
const groupIndex = Number(groupIndexString);
|
|
352
|
+
const group = new MultichainAccountGroup_1.MultichainAccountGroup({
|
|
353
|
+
wallet: this,
|
|
354
|
+
providers: __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f"),
|
|
355
|
+
groupIndex,
|
|
356
|
+
messenger: __classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f"),
|
|
357
|
+
});
|
|
358
|
+
group.init(groupState);
|
|
359
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_accountGroups, "f").set(groupIndex, group);
|
|
360
|
+
}
|
|
398
361
|
// Align missing accounts from group. This is required to create missing account from non-discovered
|
|
399
362
|
// indexes for some providers.
|
|
400
363
|
await __classPrivateFieldGet(this, _MultichainAccountWallet_instances, "m", _MultichainAccountWallet_alignAccounts).call(this);
|
|
@@ -436,10 +399,11 @@ async function _MultichainAccountWallet_withLock(status, operation) {
|
|
|
436
399
|
* @param options.groupIndex - The group index to create accounts for.
|
|
437
400
|
* @param options.providers - The non‑EVM account providers.
|
|
438
401
|
* @param options.awaitAll - Whether to wait for all providers to finish.
|
|
402
|
+
* @param options.group - The group object pertaining to the group index to create accounts for.
|
|
439
403
|
* @throws If awaitAll is true and any provider fails to create accounts.
|
|
440
404
|
* @returns A promise that resolves when done (if awaitAll is true) or immediately (if false).
|
|
441
405
|
*/
|
|
442
|
-
async function _MultichainAccountWallet_createNonEvmAccounts({ groupIndex, providers, awaitAll, }) {
|
|
406
|
+
async function _MultichainAccountWallet_createNonEvmAccounts({ groupIndex, providers, awaitAll, group, }) {
|
|
443
407
|
if (awaitAll) {
|
|
444
408
|
const tasks = providers.map((provider) => provider
|
|
445
409
|
.createAccounts({
|
|
@@ -455,33 +419,54 @@ async function _MultichainAccountWallet_createNonEvmAccounts({ groupIndex, provi
|
|
|
455
419
|
throw error;
|
|
456
420
|
}));
|
|
457
421
|
const results = await Promise.allSettled(tasks);
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
422
|
+
const providerFailures = results.reduce((acc, result, idx) => {
|
|
423
|
+
let newAcc = acc;
|
|
424
|
+
if (result.status === 'rejected') {
|
|
425
|
+
newAcc += `\n- ${providers[idx].getName()}: ${result.reason.message}`;
|
|
426
|
+
}
|
|
427
|
+
return newAcc;
|
|
428
|
+
}, '');
|
|
429
|
+
if (providerFailures.length) {
|
|
430
|
+
// We warn there's failures on some providers and thus misalignment, but we still create the group
|
|
431
|
+
const message = `Unable to create some accounts for group index: ${groupIndex}. Providers threw the following errors:${providerFailures}`;
|
|
432
|
+
console.warn(message);
|
|
433
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${logger_1.WARNING_PREFIX} ${message}`);
|
|
463
434
|
}
|
|
464
|
-
|
|
435
|
+
// No need to fetch the accounts list from the AccountsController since we already have the account IDs to be used in the controller
|
|
436
|
+
const groupState = results.reduce((state, result, idx) => {
|
|
437
|
+
if (result.status === 'fulfilled') {
|
|
438
|
+
state[providers[idx].getName()] = result.value.map((account) => account.id);
|
|
439
|
+
}
|
|
440
|
+
return state;
|
|
441
|
+
}, {});
|
|
442
|
+
group.update(groupState);
|
|
465
443
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
|
|
473
|
-
groupIndex,
|
|
474
|
-
})
|
|
475
|
-
.catch((error) => {
|
|
476
|
-
const errorMessage = `Unable to create multichain account group for index: ${groupIndex} (background mode with provider "${provider.getName()}")`;
|
|
477
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${logger_1.WARNING_PREFIX} ${errorMessage}:`, error);
|
|
478
|
-
const sentryError = (0, utils_2.createSentryError)(`Unable to create account with provider "${provider.getName()}"`, error, {
|
|
444
|
+
else {
|
|
445
|
+
// Create account with other providers in the background
|
|
446
|
+
providers.forEach((provider) => {
|
|
447
|
+
provider
|
|
448
|
+
.createAccounts({
|
|
449
|
+
entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
|
|
479
450
|
groupIndex,
|
|
480
|
-
|
|
451
|
+
})
|
|
452
|
+
.then((accounts) => {
|
|
453
|
+
const accountIds = accounts.map((account) => account.id);
|
|
454
|
+
group.update({ [provider.getName()]: accountIds });
|
|
455
|
+
return group;
|
|
456
|
+
})
|
|
457
|
+
.catch((error) => {
|
|
458
|
+
// Log errors from background providers but don't fail the operation
|
|
459
|
+
const errorMessage = `Unable to create some accounts for group index: ${groupIndex} with provider "${provider.getName()}". Error: ${error.message}`;
|
|
460
|
+
console.warn(errorMessage);
|
|
461
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${logger_1.WARNING_PREFIX} ${errorMessage}:`, error);
|
|
462
|
+
const sentryError = (0, utils_2.createSentryError)(`Unable to create account with provider "${provider.getName()}"`, error, {
|
|
463
|
+
groupIndex,
|
|
464
|
+
provider: provider.getName(),
|
|
465
|
+
});
|
|
466
|
+
__classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f").captureException?.(sentryError);
|
|
481
467
|
});
|
|
482
|
-
__classPrivateFieldGet(this, _MultichainAccountWallet_messenger, "f").captureException?.(sentryError);
|
|
483
468
|
});
|
|
484
|
-
}
|
|
469
|
+
}
|
|
485
470
|
}, _MultichainAccountWallet_alignAccounts =
|
|
486
471
|
/**
|
|
487
472
|
* Align all multichain account groups.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountWallet.cjs","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA,uDAM+B;AAE/B,2CAAyC;AACzC,6CAAoC;AAGpC,yCAKkB;AAClB,yEAAkE;AAClE,qDAAiD;AAGjD,uCAAoE;AAcpE;;;GAGG;AACH,MAAa,uBAAuB;IAuBlC,YAAY,EACV,SAAS,EACT,aAAa,EACb,SAAS,GAKV;;QA3BQ,wCAAQ,IAAI,mBAAK,EAAE,EAAC;QAEpB,8CAA+B;QAE/B,qDAA4C;QAE5C,yDAAgC;QAEhC,yDAA6D;QAE7D,qDAA8C;QAE9C,+CAAa;QAEtB,8DAA8D;QAC9D,+CAAe,KAAK,EAAC;QAErB,kDAAuC;QAWrC,uBAAA,IAAI,+BAAO,IAAA,yCAA2B,EAAC,aAAa,CAAC,MAAA,CAAC;QACtD,uBAAA,IAAI,sC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AAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC;AAkOD;;;;GAIG;AACH,KAAK;IACH,MAAM,MAAM,GAAG,IAAI,CAAC,0BAA0B,EAAE,CAAC;IACjD,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;AAClE,CAAC","sourcesContent":["import type {\n AccountGroupId,\n Bip44Account,\n MultichainAccountWalletId,\n MultichainAccountWallet as MultichainAccountWalletDefinition,\n MultichainAccountWalletStatus,\n} from '@metamask/account-api';\nimport {\n AccountWalletType,\n getGroupIndexFromMultichainAccountGroupId,\n isMultichainAccountGroupId,\n toDefaultAccountGroupId,\n toMultichainAccountWalletId,\n} from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { assert } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { Logger } from './logger';\nimport {\n createModuleLogger,\n ERROR_PREFIX,\n projectLogger as log,\n WARNING_PREFIX,\n} from './logger';\nimport { MultichainAccountGroup } from './MultichainAccountGroup';\nimport { EvmAccountProvider } from './providers';\nimport type { Bip44AccountProvider } from './providers';\nimport type { MultichainAccountServiceMessenger } from './types';\nimport { createSentryError, toRejectedErrorMessage } from './utils';\n\n/**\n * The context for a provider discovery.\n */\ntype AccountProviderDiscoveryContext<\n Account extends Bip44Account<KeyringAccount>,\n> = {\n provider: Bip44AccountProvider<Account>;\n stopped: boolean;\n groupIndex: number;\n accounts: Account[];\n};\n\n/**\n * A multichain account wallet that holds multiple multichain accounts (one multichain account per\n * group index).\n */\nexport class MultichainAccountWallet<\n Account extends Bip44Account<KeyringAccount>,\n> implements MultichainAccountWalletDefinition<Account>\n{\n readonly #lock = new Mutex();\n\n readonly #id: MultichainAccountWalletId;\n\n readonly #providers: Bip44AccountProvider<Account>[];\n\n readonly #entropySource: EntropySourceId;\n\n readonly #accountGroups: Map<number, MultichainAccountGroup<Account>>;\n\n readonly #messenger: MultichainAccountServiceMessenger;\n\n readonly #log: Logger;\n\n // eslint-disable-next-line @typescript-eslint/prefer-readonly\n #initialized = false;\n\n #status: MultichainAccountWalletStatus;\n\n constructor({\n providers,\n entropySource,\n messenger,\n }: {\n providers: Bip44AccountProvider<Account>[];\n entropySource: EntropySourceId;\n messenger: MultichainAccountServiceMessenger;\n }) {\n this.#id = toMultichainAccountWalletId(entropySource);\n this.#providers = providers;\n this.#entropySource = entropySource;\n this.#messenger = messenger;\n this.#accountGroups = new Map();\n\n this.#log = createModuleLogger(log, `[${this.#id}]`);\n\n // Initial synchronization (don't emit events during initialization).\n this.#status = 'uninitialized';\n this.sync();\n this.#initialized = true;\n this.#status = 'ready';\n }\n\n /**\n * Force wallet synchronization.\n *\n * This can be used if account providers got new accounts that the wallet\n * doesn't know about.\n */\n sync(): void {\n this.#log('Synchronizing with account providers...');\n for (const provider of this.#providers) {\n for (const account of provider.getAccounts()) {\n const { entropy } = account.options;\n\n // Filter for this wallet only.\n if (entropy.id !== this.entropySource) {\n continue;\n }\n\n // This multichain account might exists already.\n let multichainAccount = this.#accountGroups.get(entropy.groupIndex);\n if (!multichainAccount) {\n multichainAccount = new MultichainAccountGroup<Account>({\n groupIndex: entropy.groupIndex,\n wallet: this,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n\n // This existing multichain account group might differ from the\n // `createMultichainAccountGroup` behavior. When creating a new\n // group, we expect the providers to all succeed. But here, we're\n // just fetching the account lists from them, so this group might\n // not be \"aligned\" yet (e.g having a missing Solana account).\n //\n // Since \"aligning\" is an async operation, it would have to be run\n // after the first-sync.\n // TODO: Implement align mechanism to create \"missing\" accounts.\n\n this.#log(`Found a new group: [${multichainAccount.id}]`);\n this.#accountGroups.set(entropy.groupIndex, multichainAccount);\n }\n }\n }\n\n // Now force-sync all remaining multichain accounts.\n for (const [\n groupIndex,\n multichainAccount,\n ] of this.#accountGroups.entries()) {\n multichainAccount.sync();\n\n // Clean up old multichain accounts.\n if (!multichainAccount.hasAccounts()) {\n this.#log(`Deleting group: [${multichainAccount.id}]`);\n this.#accountGroups.delete(groupIndex);\n }\n }\n\n this.#log('Synchronized');\n }\n\n /**\n * Gets the multichain account wallet ID.\n *\n * @returns The multichain account wallet ID.\n */\n get id(): MultichainAccountWalletId {\n return this.#id;\n }\n\n /**\n * Gets the multichain account wallet type, which is always {@link AccountWalletType.Entropy}.\n *\n * @returns The multichain account wallet type.\n */\n get type(): AccountWalletType.Entropy {\n return AccountWalletType.Entropy;\n }\n\n /**\n * Gets the multichain account wallet entropy source.\n *\n * @returns The multichain account wallet entropy source.\n */\n get entropySource(): EntropySourceId {\n return this.#entropySource;\n }\n\n /**\n * Gets the multichain account wallet current status.\n *\n * @returns The multichain account wallet current status.\n */\n get status(): MultichainAccountWalletStatus {\n return this.#status;\n }\n\n /**\n * Set the wallet status and run the associated operation callback.\n *\n * @param status - Wallet status associated with this operation.\n * @param operation - Operation to run.\n * @returns The operation's result.\n * @throws {Error} If the wallet is already running a mutable operation.\n */\n async #withLock<Return>(\n status: MultichainAccountWalletStatus,\n operation: () => Promise<Return>,\n ) {\n const release = await this.#lock.acquire();\n try {\n this.#log(`Locking wallet with status \"${status}\"...`);\n this.#status = status;\n this.#messenger.publish(\n 'MultichainAccountService:walletStatusChange',\n this.id,\n this.#status,\n );\n return await operation();\n } finally {\n this.#status = 'ready';\n this.#messenger.publish(\n 'MultichainAccountService:walletStatusChange',\n this.id,\n this.#status,\n );\n release();\n this.#log(`Releasing wallet lock (was \"${status}\")`);\n }\n }\n\n /**\n * Create accounts with non‑EVM providers. Optional throttling is managed by each provider internally.\n * When awaitAll is true, waits for all providers and throws if any failed.\n * When false, starts work in background and logs errors without throwing.\n *\n * @param options - Method options.\n * @param options.groupIndex - The group index to create accounts for.\n * @param options.providers - The non‑EVM account providers.\n * @param options.awaitAll - Whether to wait for all providers to finish.\n * @throws If awaitAll is true and any provider fails to create accounts.\n * @returns A promise that resolves when done (if awaitAll is true) or immediately (if false).\n */\n async #createNonEvmAccounts({\n groupIndex,\n providers,\n awaitAll,\n }: {\n groupIndex: number;\n providers: Bip44AccountProvider<Account>[];\n awaitAll: boolean;\n }): Promise<void> {\n if (awaitAll) {\n const tasks = providers.map((provider) =>\n provider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .catch((error) => {\n const sentryError = createSentryError(\n `Unable to create account with provider \"${provider.getName()}\"`,\n error,\n {\n groupIndex,\n provider: provider.getName(),\n },\n );\n this.#messenger.captureException?.(sentryError);\n throw error;\n }),\n );\n\n const results = await Promise.allSettled(tasks);\n if (results.some((r) => r.status === 'rejected')) {\n const errorMessage = toRejectedErrorMessage(\n `Unable to create multichain account group for index: ${groupIndex}`,\n results,\n );\n\n this.#log(`${WARNING_PREFIX} ${errorMessage}`);\n console.warn(errorMessage);\n throw new Error(errorMessage);\n }\n return;\n }\n\n // Background mode: start tasks and log errors.\n // Optional throttling is handled internally by each provider based on its config.\n providers.forEach((provider) => {\n // eslint-disable-next-line no-void\n void provider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .catch((error) => {\n const errorMessage = `Unable to create multichain account group for index: ${groupIndex} (background mode with provider \"${provider.getName()}\")`;\n this.#log(`${WARNING_PREFIX} ${errorMessage}:`, error);\n const sentryError = createSentryError(\n `Unable to create account with provider \"${provider.getName()}\"`,\n error,\n {\n groupIndex,\n provider: provider.getName(),\n },\n );\n this.#messenger.captureException?.(sentryError);\n });\n });\n }\n\n /**\n * Gets multichain account for a given ID.\n * The default group ID will default to the multichain account with index 0.\n *\n * @param id - Account group ID.\n * @returns Account group.\n */\n getAccountGroup(\n id: AccountGroupId,\n ): MultichainAccountGroup<Account> | undefined {\n // We consider the \"default case\" to be mapped to index 0.\n if (id === toDefaultAccountGroupId(this.id)) {\n return this.#accountGroups.get(0);\n }\n\n // If it is not a valid ID, we cannot extract the group index\n // from it, so we fail fast.\n if (!isMultichainAccountGroupId(id)) {\n return undefined;\n }\n\n const groupIndex = getGroupIndexFromMultichainAccountGroupId(id);\n return this.#accountGroups.get(groupIndex);\n }\n\n /**\n * Gets all multichain accounts. Similar to {@link MultichainAccountWallet.getMultichainAccountGroups}.\n *\n * @returns The multichain accounts.\n */\n getAccountGroups(): MultichainAccountGroup<Account>[] {\n return this.getMultichainAccountGroups();\n }\n\n /**\n * Gets multichain account group for a given index.\n *\n * @param groupIndex - Multichain account index.\n * @returns The multichain account associated with the given index.\n */\n getMultichainAccountGroup(\n groupIndex: number,\n ): MultichainAccountGroup<Account> | undefined {\n return this.#accountGroups.get(groupIndex);\n }\n\n /**\n * Gets all multichain account groups.\n *\n * @returns The multichain accounts.\n */\n getMultichainAccountGroups(): MultichainAccountGroup<Account>[] {\n return Array.from(this.#accountGroups.values()); // TODO: Prevent copy here.\n }\n\n /**\n * Gets next group index for this wallet.\n *\n * @returns The next group index of this wallet.\n */\n getNextGroupIndex(): number {\n // We do not check for gaps.\n return (\n Math.max(\n -1, // So it will default to 0 if no groups.\n ...this.#accountGroups.keys(),\n ) + 1\n );\n }\n\n /**\n * Creates a multichain account group for a given group index.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n *\n * @param groupIndex - The group index to use.\n * @param options - Options to configure the account creation.\n * @param options.waitForAllProvidersToFinishCreatingAccounts - Whether to wait for all\n * account providers to finish creating their accounts before returning. If `false`, only\n * the EVM provider will be awaited, while all other providers will create their accounts\n * in the background. Defaults to `false`.\n * @throws If any of the account providers fails to create their accounts and\n * the `waitForAllProvidersToFinishCreatingAccounts` option is set to `true`. If `false`,\n * errors from non-EVM providers will be logged but ignored, and only errors from the\n * EVM provider will be thrown.\n * @returns The multichain account group for this group index.\n */\n async createMultichainAccountGroup(\n groupIndex: number,\n options: {\n waitForAllProvidersToFinishCreatingAccounts?: boolean;\n } = { waitForAllProvidersToFinishCreatingAccounts: false },\n ): Promise<MultichainAccountGroup<Account>> {\n return await this.#withLock('in-progress:create-accounts', async () => {\n const nextGroupIndex = this.getNextGroupIndex();\n if (groupIndex > nextGroupIndex) {\n throw new Error(\n `You cannot use a group index that is higher than the next available one: expected <=${nextGroupIndex}, got ${groupIndex}`,\n );\n }\n\n let group = this.getMultichainAccountGroup(groupIndex);\n if (group) {\n // If the group already exists, we just `sync` it and returns the same\n // reference.\n group.sync();\n\n this.#log(\n `Trying to re-create existing group: [${group.id}] (idempotent)`,\n );\n return group;\n }\n\n this.#log(`Creating new group for index ${groupIndex}...`);\n\n // Extract the EVM provider from the list of providers.\n // We always await EVM account creation first.\n const [evmProvider, ...otherProviders] = this.#providers;\n assert(\n evmProvider instanceof EvmAccountProvider,\n 'EVM account provider must be first',\n );\n\n try {\n await evmProvider.createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n });\n } catch (error) {\n const errorMessage = `Unable to create multichain account group for index: ${groupIndex} with provider \"${evmProvider.getName()}\". Error: ${(error as Error).message}`;\n this.#log(`${ERROR_PREFIX} ${errorMessage}:`, error);\n const sentryError = createSentryError(\n `Unable to create account with provider \"${evmProvider.getName()}\"`,\n error as Error,\n {\n groupIndex,\n provider: evmProvider.getName(),\n },\n );\n this.#messenger.captureException?.(sentryError);\n throw new Error(errorMessage);\n }\n\n // We then create accounts with other providers (some being throttled if configured).\n // Depending on the options, we either await all providers or run them in background.\n if (options?.waitForAllProvidersToFinishCreatingAccounts) {\n await this.#createNonEvmAccounts({\n groupIndex,\n providers: otherProviders,\n awaitAll: true,\n });\n } else {\n // eslint-disable-next-line no-void\n void this.#createNonEvmAccounts({\n groupIndex,\n providers: otherProviders,\n awaitAll: false,\n });\n }\n\n // --------------------------------------------------------------------------------\n // READ THIS CAREFULLY:\n //\n // Since we're not \"fully supporting multichain\" for now, we still rely on single\n // :accountCreated events to sync multichain account groups and wallets. Which means\n // that even if of the provider fails, some accounts will still be created on some\n // other providers and will become \"available\" on the `AccountsController`, like:\n //\n // 1. Creating a multichain account group for index 1\n // 2. EvmAccountProvider.createAccounts returns the EVM account for index 1\n // * AccountsController WILL fire :accountCreated for this account\n // * This account WILL BE \"available\" on the AccountsController state\n // 3. SolAccountProvider.createAccounts fails to create a Solana account for index 1\n // * AccountsController WON't fire :accountCreated for this account\n // * This account WON'T be \"available\" on the Account\n // 4. MultichainAccountService will receive a :accountCreated for the EVM account from\n // step 2 and will create a new multichain account group for index 1, but it won't\n // receive any event for the Solana account of this group. Thus, this group won't be\n // \"aligned\" (missing \"blockchain account\" on this group).\n //\n // --------------------------------------------------------------------------------\n\n // Because of the :accountAdded automatic sync, we might already have created the\n // group, so we first try to get it.\n group = this.getMultichainAccountGroup(groupIndex);\n if (!group) {\n // If for some reason it's still not created, we're creating it explicitly now:\n group = new MultichainAccountGroup({\n wallet: this,\n providers: this.#providers,\n groupIndex,\n messenger: this.#messenger,\n });\n }\n\n // Register the account to our internal map.\n this.#accountGroups.set(groupIndex, group); // `group` cannot be undefined here.\n this.#log(`New group created: [${group.id}]`);\n\n if (this.#initialized) {\n this.#messenger.publish(\n 'MultichainAccountService:multichainAccountGroupCreated',\n group,\n );\n }\n\n return group;\n });\n }\n\n /**\n * Creates the next multichain account group.\n *\n * @throws If any of the account providers fails to create their accounts.\n * @returns The multichain account group for the next group index available.\n */\n async createNextMultichainAccountGroup(): Promise<\n MultichainAccountGroup<Account>\n > {\n return this.createMultichainAccountGroup(this.getNextGroupIndex(), {\n waitForAllProvidersToFinishCreatingAccounts: true,\n });\n }\n\n /**\n * Align all multichain account groups.\n *\n * NOTE: This operation WILL NOT lock the wallet's mutex.\n */\n async #alignAccounts(): Promise<void> {\n const groups = this.getMultichainAccountGroups();\n await Promise.all(groups.map((group) => group.alignAccounts()));\n }\n\n /**\n * Align all accounts from each existing multichain account groups.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n */\n async alignAccounts(): Promise<void> {\n await this.#withLock('in-progress:alignment', async () => {\n await this.#alignAccounts();\n });\n }\n\n /**\n * Align a specific multichain account group.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n *\n * @param groupIndex - The group index to align.\n */\n async alignAccountsOf(groupIndex: number): Promise<void> {\n await this.#withLock('in-progress:alignment', async () => {\n const group = this.getMultichainAccountGroup(groupIndex);\n if (group) {\n await group.alignAccounts();\n }\n });\n }\n\n /**\n * Discover and create accounts for all providers.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n *\n * @returns The discovered accounts for each provider.\n */\n async discoverAccounts(): Promise<Account[]> {\n return this.#withLock('in-progress:discovery', async () => {\n // Start with the next available group index (so we can resume the discovery\n // from there).\n let maxGroupIndex = this.getNextGroupIndex();\n\n // One serialized loop per provider; all run concurrently\n const runProviderDiscovery = async (\n context: AccountProviderDiscoveryContext<Account>,\n ) => {\n const providerName = context.provider.getName();\n const message = (stepName: string, groupIndex: number) =>\n `[${providerName}] Discovery ${stepName} for group index: ${groupIndex}`;\n\n while (!context.stopped) {\n // Fast‑forward to current high‑water mark\n const targetGroupIndex = Math.max(context.groupIndex, maxGroupIndex);\n\n log(message('started', targetGroupIndex));\n\n let accounts: Account[] = [];\n try {\n accounts = await context.provider.discoverAccounts({\n entropySource: this.#entropySource,\n groupIndex: targetGroupIndex,\n });\n } catch (error) {\n context.stopped = true;\n console.error(error);\n log(\n message(\n `failed (with: \"${(error as Error).message}\")`,\n targetGroupIndex,\n ),\n error,\n );\n const sentryError = createSentryError(\n 'Unable to discover accounts',\n error as Error,\n {\n provider: providerName,\n groupIndex: targetGroupIndex,\n },\n );\n this.#messenger.captureException?.(sentryError);\n break;\n }\n\n if (!accounts.length) {\n log(\n message('stopped (no accounts got discovered)', targetGroupIndex),\n );\n context.stopped = true;\n break;\n }\n\n log(message('**succeeded**', targetGroupIndex));\n\n context.accounts = context.accounts.concat(accounts);\n\n const nextGroupIndex = targetGroupIndex + 1;\n context.groupIndex = nextGroupIndex;\n\n if (nextGroupIndex > maxGroupIndex) {\n maxGroupIndex = nextGroupIndex;\n }\n }\n };\n\n const providerContexts: AccountProviderDiscoveryContext<Account>[] =\n this.#providers.map((provider) => ({\n provider,\n stopped: false,\n groupIndex: maxGroupIndex,\n accounts: [],\n }));\n\n // Start discovery for each providers.\n await Promise.all(providerContexts.map(runProviderDiscovery));\n\n // Sync the wallet after discovery to ensure that the newly added accounts are added into their groups.\n // We can potentially remove this if we know that this race condition is not an issue in practice.\n this.sync();\n\n // Align missing accounts from group. This is required to create missing account from non-discovered\n // indexes for some providers.\n await this.#alignAccounts();\n\n return providerContexts.flatMap((context) => context.accounts);\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MultichainAccountWallet.cjs","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA,uDAM+B;AAE/B,2CAAyC;AACzC,6CAAoC;AAGpC,yCAKkB;AAElB,yEAAkE;AAGlE,2EAAoE;AAEpE,uCAA4C;AAmB5C;;;GAGG;AACH,MAAa,uBAAuB;IAsBlC,YAAY,EACV,SAAS,EACT,aAAa,EACb,SAAS,GAKV;;QA1BQ,wCAAQ,IAAI,mBAAK,EAAE,EAAC;QAEpB,8CAA+B;QAE/B,qDAA4C;QAE5C,yDAAgC;QAEhC,yDAA6D;QAE7D,qDAA8C;QAE9C,+CAAa;QAEtB,+CAAe,KAAK,EAAC;QAErB,kDAAuC;QAWrC,uBAAA,IAAI,+BAAO,IAAA,yCAA2B,EAAC,aAAa,CAAC,MAAA,CAAC;QACtD,uBAAA,IAAI,sCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,0CAAkB,aAAa,MAAA,CAAC;QACpC,uBAAA,IAAI,sCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,0CAAkB,IAAI,GAAG,EAAE,MAAA,CAAC;QAEhC,uBAAA,IAAI,gCAAQ,IAAA,2BAAkB,EAAC,sBAAG,EAAE,IAAI,uBAAA,IAAI,mCAAI,GAAG,CAAC,MAAA,CAAC;QAErD,qEAAqE;QACrE,uBAAA,IAAI,mCAAW,eAAe,MAAA,CAAC;IACjC,CAAC;IAED;;;;OAIG;IACH,IAAI,CA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EAAE;gBACf,oEAAoE;gBACpE,MAAM,YAAY,GAAG,mDAAmD,UAAU,mBAAmB,QAAQ,CAAC,OAAO,EAAE,aAAc,KAAe,CAAC,OAAO,EAAE,CAAC;gBAC/J,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;gBAC3B,uBAAA,IAAI,oCAAK,MAAT,IAAI,EAAM,GAAG,uBAAc,IAAI,YAAY,GAAG,EAAE,KAAK,CAAC,CAAC;gBACvD,MAAM,WAAW,GAAG,IAAA,yBAAiB,EACnC,2CAA2C,QAAQ,CAAC,OAAO,EAAE,GAAG,EAChE,KAAK,EACL;oBACE,UAAU;oBACV,QAAQ,EAAE,QAAQ,CAAC,OAAO,EAAE;iBAC7B,CACF,CAAC;gBACF,uBAAA,IAAI,0CAAW,CAAC,gBAAgB,EAAE,CAAC,WAAW,CAAC,CAAC;YAClD,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AA0MD;;;;GAIG;AACH,KAAK;IACH,MAAM,MAAM,GAAG,IAAI,CAAC,0BAA0B,EAAE,CAAC;IACjD,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC;AAClE,CAAC","sourcesContent":["import type {\n AccountGroupId,\n Bip44Account,\n MultichainAccountWalletId,\n MultichainAccountWallet as MultichainAccountWalletDefinition,\n MultichainAccountWalletStatus,\n} from '@metamask/account-api';\nimport {\n AccountWalletType,\n getGroupIndexFromMultichainAccountGroupId,\n isMultichainAccountGroupId,\n toDefaultAccountGroupId,\n toMultichainAccountWalletId,\n} from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { assert } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { Logger } from './logger';\nimport {\n createModuleLogger,\n ERROR_PREFIX,\n projectLogger as log,\n WARNING_PREFIX,\n} from './logger';\nimport type { GroupState } from './MultichainAccountGroup';\nimport { MultichainAccountGroup } from './MultichainAccountGroup';\nimport type { ServiceState, StateKeys } from './MultichainAccountService';\nimport type { Bip44AccountProvider } from './providers';\nimport { EvmAccountProvider } from './providers/EvmAccountProvider';\nimport type { MultichainAccountServiceMessenger } from './types';\nimport { createSentryError } from './utils';\n\n/**\n * The context for a provider discovery.\n */\ntype AccountProviderDiscoveryContext<\n Account extends Bip44Account<KeyringAccount>,\n> = {\n provider: Bip44AccountProvider<Account>;\n stopped: boolean;\n groupIndex: number;\n accounts: Account[];\n};\n\nexport type WalletState = ServiceState[StateKeys['entropySource']];\n\n// type alias to make clear this state is generated by discovery\ntype DiscoveredGroupsState = WalletState;\n\n/**\n * A multichain account wallet that holds multiple multichain accounts (one multichain account per\n * group index).\n */\nexport class MultichainAccountWallet<\n Account extends Bip44Account<KeyringAccount>,\n> implements MultichainAccountWalletDefinition<Account>\n{\n readonly #lock = new Mutex();\n\n readonly #id: MultichainAccountWalletId;\n\n readonly #providers: Bip44AccountProvider<Account>[];\n\n readonly #entropySource: EntropySourceId;\n\n readonly #accountGroups: Map<number, MultichainAccountGroup<Account>>;\n\n readonly #messenger: MultichainAccountServiceMessenger;\n\n readonly #log: Logger;\n\n #initialized = false;\n\n #status: MultichainAccountWalletStatus;\n\n constructor({\n providers,\n entropySource,\n messenger,\n }: {\n providers: Bip44AccountProvider<Account>[];\n entropySource: EntropySourceId;\n messenger: MultichainAccountServiceMessenger;\n }) {\n this.#id = toMultichainAccountWalletId(entropySource);\n this.#providers = providers;\n this.#entropySource = entropySource;\n this.#messenger = messenger;\n this.#accountGroups = new Map();\n\n this.#log = createModuleLogger(log, `[${this.#id}]`);\n\n // Initial synchronization (don't emit events during initialization).\n this.#status = 'uninitialized';\n }\n\n /**\n * Initialize the wallet and construct the internal representation of multichain account groups.\n *\n * @param walletState - The wallet state.\n */\n init(walletState: WalletState): void {\n this.#log('Initializing wallet state...');\n for (const [groupIndexString, groupState] of Object.entries(walletState)) {\n // Have to convert to number because the state keys become strings when we construct the state object in the service\n const groupIndex = Number(groupIndexString);\n const group = new MultichainAccountGroup({\n groupIndex,\n wallet: this,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n\n this.#log(`Creating new group for index ${groupIndex}...`);\n\n group.init(groupState);\n\n this.#accountGroups.set(groupIndex, group);\n }\n if (!this.#initialized) {\n this.#initialized = true;\n this.#status = 'ready';\n }\n\n this.#log('Finished initializing wallet state...');\n }\n\n /**\n * Gets the multichain account wallet ID.\n *\n * @returns The multichain account wallet ID.\n */\n get id(): MultichainAccountWalletId {\n return this.#id;\n }\n\n /**\n * Gets the multichain account wallet type, which is always {@link AccountWalletType.Entropy}.\n *\n * @returns The multichain account wallet type.\n */\n get type(): AccountWalletType.Entropy {\n return AccountWalletType.Entropy;\n }\n\n /**\n * Gets the multichain account wallet entropy source.\n *\n * @returns The multichain account wallet entropy source.\n */\n get entropySource(): EntropySourceId {\n return this.#entropySource;\n }\n\n /**\n * Gets the multichain account wallet current status.\n *\n * @returns The multichain account wallet current status.\n */\n get status(): MultichainAccountWalletStatus {\n return this.#status;\n }\n\n /**\n * Set the wallet status and run the associated operation callback.\n *\n * @param status - Wallet status associated with this operation.\n * @param operation - Operation to run.\n * @returns The operation's result.\n * @throws {Error} If the wallet is already running a mutable operation.\n */\n async #withLock<Return>(\n status: MultichainAccountWalletStatus,\n operation: () => Promise<Return>,\n ): Promise<Return> {\n const release = await this.#lock.acquire();\n try {\n this.#log(`Locking wallet with status \"${status}\"...`);\n this.#status = status;\n this.#messenger.publish(\n 'MultichainAccountService:walletStatusChange',\n this.id,\n this.#status,\n );\n return await operation();\n } finally {\n this.#status = 'ready';\n this.#messenger.publish(\n 'MultichainAccountService:walletStatusChange',\n this.id,\n this.#status,\n );\n release();\n this.#log(`Releasing wallet lock (was \"${status}\")`);\n }\n }\n\n /**\n * Create accounts with non‑EVM providers. Optional throttling is managed by each provider internally.\n * When awaitAll is true, waits for all providers and throws if any failed.\n * When false, starts work in background and logs errors without throwing.\n *\n * @param options - Method options.\n * @param options.groupIndex - The group index to create accounts for.\n * @param options.providers - The non‑EVM account providers.\n * @param options.awaitAll - Whether to wait for all providers to finish.\n * @param options.group - The group object pertaining to the group index to create accounts for.\n * @throws If awaitAll is true and any provider fails to create accounts.\n * @returns A promise that resolves when done (if awaitAll is true) or immediately (if false).\n */\n async #createNonEvmAccounts({\n groupIndex,\n providers,\n awaitAll,\n group,\n }: {\n groupIndex: number;\n providers: Bip44AccountProvider<Account>[];\n awaitAll: boolean;\n group: MultichainAccountGroup<Account>;\n }): Promise<void> {\n if (awaitAll) {\n const tasks = providers.map((provider) =>\n provider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .catch((error) => {\n const sentryError = createSentryError(\n `Unable to create account with provider \"${provider.getName()}\"`,\n error,\n {\n groupIndex,\n provider: provider.getName(),\n },\n );\n this.#messenger.captureException?.(sentryError);\n throw error;\n }),\n );\n\n const results = await Promise.allSettled(tasks);\n\n const providerFailures = results.reduce((acc, result, idx) => {\n let newAcc = acc;\n if (result.status === 'rejected') {\n newAcc += `\\n- ${providers[idx].getName()}: ${result.reason.message}`;\n }\n return newAcc;\n }, '');\n\n if (providerFailures.length) {\n // We warn there's failures on some providers and thus misalignment, but we still create the group\n const message = `Unable to create some accounts for group index: ${groupIndex}. Providers threw the following errors:${providerFailures}`;\n console.warn(message);\n this.#log(`${WARNING_PREFIX} ${message}`);\n }\n\n // No need to fetch the accounts list from the AccountsController since we already have the account IDs to be used in the controller\n const groupState = results.reduce<GroupState>((state, result, idx) => {\n if (result.status === 'fulfilled') {\n state[providers[idx].getName()] = result.value.map(\n (account) => account.id,\n );\n }\n return state;\n }, {});\n\n group.update(groupState);\n } else {\n // Create account with other providers in the background\n providers.forEach((provider) => {\n provider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .then((accounts) => {\n const accountIds = accounts.map((account) => account.id);\n group.update({ [provider.getName()]: accountIds });\n return group;\n })\n .catch((error) => {\n // Log errors from background providers but don't fail the operation\n const errorMessage = `Unable to create some accounts for group index: ${groupIndex} with provider \"${provider.getName()}\". Error: ${(error as Error).message}`;\n console.warn(errorMessage);\n this.#log(`${WARNING_PREFIX} ${errorMessage}:`, error);\n const sentryError = createSentryError(\n `Unable to create account with provider \"${provider.getName()}\"`,\n error,\n {\n groupIndex,\n provider: provider.getName(),\n },\n );\n this.#messenger.captureException?.(sentryError);\n });\n });\n }\n }\n\n /**\n * Gets multichain account for a given ID.\n * The default group ID will default to the multichain account with index 0.\n *\n * @param id - Account group ID.\n * @returns Account group.\n */\n getAccountGroup(\n id: AccountGroupId,\n ): MultichainAccountGroup<Account> | undefined {\n // We consider the \"default case\" to be mapped to index 0.\n if (id === toDefaultAccountGroupId(this.id)) {\n return this.#accountGroups.get(0);\n }\n\n // If it is not a valid ID, we cannot extract the group index\n // from it, so we fail fast.\n if (!isMultichainAccountGroupId(id)) {\n return undefined;\n }\n\n const groupIndex = getGroupIndexFromMultichainAccountGroupId(id);\n return this.#accountGroups.get(groupIndex);\n }\n\n /**\n * Gets all multichain accounts. Similar to {@link MultichainAccountWallet.getMultichainAccountGroups}.\n *\n * @returns The multichain accounts.\n */\n getAccountGroups(): MultichainAccountGroup<Account>[] {\n return this.getMultichainAccountGroups();\n }\n\n /**\n * Gets multichain account group for a given index.\n *\n * @param groupIndex - Multichain account index.\n * @returns The multichain account associated with the given index.\n */\n getMultichainAccountGroup(\n groupIndex: number,\n ): MultichainAccountGroup<Account> | undefined {\n return this.#accountGroups.get(groupIndex);\n }\n\n /**\n * Gets all multichain account groups.\n *\n * @returns The multichain accounts.\n */\n getMultichainAccountGroups(): MultichainAccountGroup<Account>[] {\n return Array.from(this.#accountGroups.values()); // TODO: Prevent copy here.\n }\n\n /**\n * Gets next group index for this wallet.\n *\n * @returns The next group index of this wallet.\n */\n getNextGroupIndex(): number {\n // We do not check for gaps.\n return (\n Math.max(\n -1, // So it will default to 0 if no groups.\n ...this.#accountGroups.keys(),\n ) + 1\n );\n }\n\n /**\n * Creates a multichain account group for a given group index.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n *\n * @param groupIndex - The group index to use.\n * @param options - Options to configure the account creation.\n * @param options.waitForAllProvidersToFinishCreatingAccounts - Whether to wait for all\n * account providers to finish creating their accounts before returning. If `false`, only\n * the EVM provider will be awaited, while all other providers will create their accounts\n * in the background. Defaults to `false`.\n * @throws If any of the account providers fails to create their accounts and\n * the `waitForAllProvidersToFinishCreatingAccounts` option is set to `true`. If `false`,\n * errors from non-EVM providers will be logged but ignored, and only errors from the\n * EVM provider will be thrown.\n * @returns The multichain account group for this group index.\n */\n async createMultichainAccountGroup(\n groupIndex: number,\n options: {\n waitForAllProvidersToFinishCreatingAccounts?: boolean;\n } = { waitForAllProvidersToFinishCreatingAccounts: false },\n ): Promise<MultichainAccountGroup<Account>> {\n return await this.#withLock('in-progress:create-accounts', async () => {\n const nextGroupIndex = this.getNextGroupIndex();\n if (groupIndex > nextGroupIndex) {\n throw new Error(\n `You cannot use a group index that is higher than the next available one: expected <=${nextGroupIndex}, got ${groupIndex}`,\n );\n }\n\n let group = this.getMultichainAccountGroup(groupIndex);\n\n if (group) {\n this.#log(\n `Trying to re-create existing group: [${group.id}] (idempotent)`,\n );\n return group;\n }\n\n this.#log(`Creating new group for index ${groupIndex}...`);\n\n // Extract the EVM provider from the list of providers.\n // We always await EVM account creation first.\n const [evmProvider, ...otherProviders] = this.#providers;\n assert(\n evmProvider instanceof EvmAccountProvider,\n 'EVM account provider must be first',\n );\n\n const evmAccounts = await evmProvider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .then((accounts) => accounts.map((account) => account.id))\n .catch((error) => {\n const errorMessage = `Unable to create some accounts for group index: ${groupIndex} with provider \"${evmProvider.getName()}\". Error: ${(error as Error).message}`;\n console.warn(errorMessage);\n this.#log(`${ERROR_PREFIX} ${errorMessage}:`, error);\n const sentryError = createSentryError(\n `Unable to create account with provider \"${evmProvider.getName()}\"`,\n error as Error,\n {\n groupIndex,\n provider: evmProvider.getName(),\n },\n );\n this.#messenger.captureException?.(sentryError);\n throw error;\n });\n\n group = new MultichainAccountGroup({\n wallet: this,\n providers: this.#providers,\n groupIndex,\n messenger: this.#messenger,\n });\n\n group.init({ [evmProvider.getName()]: evmAccounts });\n\n // We then create accounts with other providers (some being throttled if configured).\n // Depending on the options, we either await all providers or run them in background.\n if (options?.waitForAllProvidersToFinishCreatingAccounts) {\n await this.#createNonEvmAccounts({\n groupIndex,\n providers: otherProviders,\n awaitAll: true,\n group,\n });\n } else {\n // eslint-disable-next-line no-void\n void this.#createNonEvmAccounts({\n groupIndex,\n providers: otherProviders,\n awaitAll: false,\n group,\n });\n }\n\n // Register the account(s) to our internal map.\n this.#accountGroups.set(groupIndex, group);\n\n this.#log(`New group created: [${group.id}]`);\n\n if (this.#initialized) {\n this.#messenger.publish(\n 'MultichainAccountService:multichainAccountGroupCreated',\n group,\n );\n }\n\n return group;\n });\n }\n\n /**\n * Creates the next multichain account group.\n *\n * @throws If any of the account providers fails to create their accounts.\n * @returns The multichain account group for the next group index available.\n */\n async createNextMultichainAccountGroup(): Promise<\n MultichainAccountGroup<Account>\n > {\n return this.createMultichainAccountGroup(this.getNextGroupIndex(), {\n waitForAllProvidersToFinishCreatingAccounts: true,\n });\n }\n\n /**\n * Align all multichain account groups.\n *\n * NOTE: This operation WILL NOT lock the wallet's mutex.\n */\n async #alignAccounts(): Promise<void> {\n const groups = this.getMultichainAccountGroups();\n await Promise.all(groups.map((group) => group.alignAccounts()));\n }\n\n /**\n * Align all accounts from each existing multichain account groups.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n */\n async alignAccounts(): Promise<void> {\n await this.#withLock('in-progress:alignment', async () => {\n await this.#alignAccounts();\n });\n }\n\n /**\n * Align a specific multichain account group.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n *\n * @param groupIndex - The group index to align.\n */\n async alignAccountsOf(groupIndex: number): Promise<void> {\n await this.#withLock('in-progress:alignment', async () => {\n const group = this.getMultichainAccountGroup(groupIndex);\n if (group) {\n await group.alignAccounts();\n }\n });\n }\n\n /**\n * Discover and create accounts for all providers.\n *\n * NOTE: This operation WILL lock the wallet's mutex.\n *\n * @returns The discovered accounts for each provider.\n */\n async discoverAccounts(): Promise<Account[]> {\n return this.#withLock('in-progress:discovery', async () => {\n // Start with the next available group index (so we can resume the discovery\n // from there).\n let maxGroupIndex = this.getNextGroupIndex();\n const discoveredGroupsState: DiscoveredGroupsState = {};\n\n const addDiscoveryResultToState = (\n result: Account[],\n providerName: string,\n groupIndex: number,\n ) => {\n const accountIds = result.map((account) => account.id);\n discoveredGroupsState[groupIndex] ??= {};\n discoveredGroupsState[groupIndex][providerName] = accountIds;\n };\n\n // One serialized loop per provider; all run concurrently\n const runProviderDiscovery = async (\n context: AccountProviderDiscoveryContext<Account>,\n ): Promise<void> => {\n const providerName = context.provider.getName();\n const message = (stepName: string, groupIndex: number) =>\n `[${providerName}] Discovery ${stepName} for group index: ${groupIndex}`;\n\n while (!context.stopped) {\n // Fast‑forward to current high‑water mark\n const targetGroupIndex = Math.max(context.groupIndex, maxGroupIndex);\n\n log(message('started', targetGroupIndex));\n\n let accounts: Account[] = [];\n try {\n accounts = await context.provider.discoverAccounts({\n entropySource: this.#entropySource,\n groupIndex: targetGroupIndex,\n });\n } catch (error) {\n context.stopped = true;\n console.error(error);\n log(\n message(\n `failed (with: \"${(error as Error).message}\")`,\n targetGroupIndex,\n ),\n error,\n );\n const sentryError = createSentryError(\n 'Unable to discover accounts',\n error as Error,\n {\n provider: providerName,\n groupIndex: targetGroupIndex,\n },\n );\n this.#messenger.captureException?.(sentryError);\n break;\n }\n\n if (!accounts.length) {\n log(\n message('stopped (no accounts got discovered)', targetGroupIndex),\n );\n context.stopped = true;\n break;\n }\n\n log(message('**succeeded**', targetGroupIndex));\n\n context.accounts = context.accounts.concat(accounts);\n\n addDiscoveryResultToState(accounts, providerName, targetGroupIndex);\n\n const nextGroupIndex = targetGroupIndex + 1;\n context.groupIndex = nextGroupIndex;\n\n if (nextGroupIndex > maxGroupIndex) {\n maxGroupIndex = nextGroupIndex;\n }\n }\n };\n\n const providerContexts: AccountProviderDiscoveryContext<Account>[] =\n this.#providers.map((provider) => ({\n provider,\n stopped: false,\n groupIndex: maxGroupIndex,\n accounts: [],\n }));\n\n // Start discovery for each providers.\n await Promise.all(providerContexts.map(runProviderDiscovery));\n\n // Create discovered groups\n for (const [groupIndexString, groupState] of Object.entries(\n discoveredGroupsState,\n )) {\n const groupIndex = Number(groupIndexString);\n const group = new MultichainAccountGroup({\n wallet: this,\n providers: this.#providers,\n groupIndex,\n messenger: this.#messenger,\n });\n group.init(groupState);\n this.#accountGroups.set(groupIndex, group);\n }\n\n // Align missing accounts from group. This is required to create missing account from non-discovered\n // indexes for some providers.\n await this.#alignAccounts();\n\n return providerContexts.flatMap((context) => context.accounts);\n });\n }\n}\n"]}
|
|
@@ -2,8 +2,10 @@ import type { AccountGroupId, Bip44Account, MultichainAccountWalletId, Multichai
|
|
|
2
2
|
import { AccountWalletType } from "@metamask/account-api";
|
|
3
3
|
import type { EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
|
|
4
4
|
import { MultichainAccountGroup } from "./MultichainAccountGroup.cjs";
|
|
5
|
+
import type { ServiceState, StateKeys } from "./MultichainAccountService.cjs";
|
|
5
6
|
import type { Bip44AccountProvider } from "./providers/index.cjs";
|
|
6
7
|
import type { MultichainAccountServiceMessenger } from "./types.cjs";
|
|
8
|
+
export type WalletState = ServiceState[StateKeys['entropySource']];
|
|
7
9
|
/**
|
|
8
10
|
* A multichain account wallet that holds multiple multichain accounts (one multichain account per
|
|
9
11
|
* group index).
|
|
@@ -16,12 +18,11 @@ export declare class MultichainAccountWallet<Account extends Bip44Account<Keyrin
|
|
|
16
18
|
messenger: MultichainAccountServiceMessenger;
|
|
17
19
|
});
|
|
18
20
|
/**
|
|
19
|
-
*
|
|
21
|
+
* Initialize the wallet and construct the internal representation of multichain account groups.
|
|
20
22
|
*
|
|
21
|
-
*
|
|
22
|
-
* doesn't know about.
|
|
23
|
+
* @param walletState - The wallet state.
|
|
23
24
|
*/
|
|
24
|
-
|
|
25
|
+
init(walletState: WalletState): void;
|
|
25
26
|
/**
|
|
26
27
|
* Gets the multichain account wallet ID.
|
|
27
28
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountWallet.d.cts","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,IAAI,iCAAiC,EAC5D,6BAA6B,EAC9B,8BAA8B;AAC/B,OAAO,EACL,iBAAiB,EAKlB,8BAA8B;AAC/B,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;
|
|
1
|
+
{"version":3,"file":"MultichainAccountWallet.d.cts","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,IAAI,iCAAiC,EAC5D,6BAA6B,EAC9B,8BAA8B;AAC/B,OAAO,EACL,iBAAiB,EAKlB,8BAA8B;AAC/B,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAY7E,OAAO,EAAE,sBAAsB,EAAE,qCAAiC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,uCAAmC;AAC1E,OAAO,KAAK,EAAE,oBAAoB,EAAE,8BAAoB;AAExD,OAAO,KAAK,EAAE,iCAAiC,EAAE,oBAAgB;AAejE,MAAM,MAAM,WAAW,GAAG,YAAY,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC;AAKnE;;;GAGG;AACH,qBAAa,uBAAuB,CAClC,OAAO,SAAS,YAAY,CAAC,cAAc,CAAC,CAC5C,YAAW,iCAAiC,CAAC,O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,GAAG,OAAO,CAAC,IAAI,CAAC;IASxD;;;;;;OAMG;IACG,gBAAgB,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;CAmH7C"}
|
|
@@ -2,8 +2,10 @@ import type { AccountGroupId, Bip44Account, MultichainAccountWalletId, Multichai
|
|
|
2
2
|
import { AccountWalletType } from "@metamask/account-api";
|
|
3
3
|
import type { EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
|
|
4
4
|
import { MultichainAccountGroup } from "./MultichainAccountGroup.mjs";
|
|
5
|
+
import type { ServiceState, StateKeys } from "./MultichainAccountService.mjs";
|
|
5
6
|
import type { Bip44AccountProvider } from "./providers/index.mjs";
|
|
6
7
|
import type { MultichainAccountServiceMessenger } from "./types.mjs";
|
|
8
|
+
export type WalletState = ServiceState[StateKeys['entropySource']];
|
|
7
9
|
/**
|
|
8
10
|
* A multichain account wallet that holds multiple multichain accounts (one multichain account per
|
|
9
11
|
* group index).
|
|
@@ -16,12 +18,11 @@ export declare class MultichainAccountWallet<Account extends Bip44Account<Keyrin
|
|
|
16
18
|
messenger: MultichainAccountServiceMessenger;
|
|
17
19
|
});
|
|
18
20
|
/**
|
|
19
|
-
*
|
|
21
|
+
* Initialize the wallet and construct the internal representation of multichain account groups.
|
|
20
22
|
*
|
|
21
|
-
*
|
|
22
|
-
* doesn't know about.
|
|
23
|
+
* @param walletState - The wallet state.
|
|
23
24
|
*/
|
|
24
|
-
|
|
25
|
+
init(walletState: WalletState): void;
|
|
25
26
|
/**
|
|
26
27
|
* Gets the multichain account wallet ID.
|
|
27
28
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountWallet.d.mts","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,IAAI,iCAAiC,EAC5D,6BAA6B,EAC9B,8BAA8B;AAC/B,OAAO,EACL,iBAAiB,EAKl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