@metamask-previews/multichain-account-service 2.0.1-preview-60778d92 → 2.1.0-preview-578568f

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 (60) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/dist/MultichainAccountService.cjs.map +1 -1
  3. package/dist/MultichainAccountService.d.cts +2 -2
  4. package/dist/MultichainAccountService.d.cts.map +1 -1
  5. package/dist/MultichainAccountService.d.mts +2 -2
  6. package/dist/MultichainAccountService.d.mts.map +1 -1
  7. package/dist/MultichainAccountService.mjs.map +1 -1
  8. package/dist/MultichainAccountWallet.cjs +70 -51
  9. package/dist/MultichainAccountWallet.cjs.map +1 -1
  10. package/dist/MultichainAccountWallet.d.cts.map +1 -1
  11. package/dist/MultichainAccountWallet.d.mts.map +1 -1
  12. package/dist/MultichainAccountWallet.mjs +70 -51
  13. package/dist/MultichainAccountWallet.mjs.map +1 -1
  14. package/dist/providers/BtcAccountProvider.cjs +17 -17
  15. package/dist/providers/BtcAccountProvider.cjs.map +1 -1
  16. package/dist/providers/BtcAccountProvider.d.cts +2 -11
  17. package/dist/providers/BtcAccountProvider.d.cts.map +1 -1
  18. package/dist/providers/BtcAccountProvider.d.mts +2 -11
  19. package/dist/providers/BtcAccountProvider.d.mts.map +1 -1
  20. package/dist/providers/BtcAccountProvider.mjs +17 -17
  21. package/dist/providers/BtcAccountProvider.mjs.map +1 -1
  22. package/dist/providers/EvmAccountProvider.cjs.map +1 -1
  23. package/dist/providers/EvmAccountProvider.d.cts +1 -1
  24. package/dist/providers/EvmAccountProvider.d.cts.map +1 -1
  25. package/dist/providers/EvmAccountProvider.d.mts +1 -1
  26. package/dist/providers/EvmAccountProvider.d.mts.map +1 -1
  27. package/dist/providers/EvmAccountProvider.mjs.map +1 -1
  28. package/dist/providers/SnapAccountProvider.cjs +39 -1
  29. package/dist/providers/SnapAccountProvider.cjs.map +1 -1
  30. package/dist/providers/SnapAccountProvider.d.cts +24 -2
  31. package/dist/providers/SnapAccountProvider.d.cts.map +1 -1
  32. package/dist/providers/SnapAccountProvider.d.mts +24 -2
  33. package/dist/providers/SnapAccountProvider.d.mts.map +1 -1
  34. package/dist/providers/SnapAccountProvider.mjs +39 -1
  35. package/dist/providers/SnapAccountProvider.mjs.map +1 -1
  36. package/dist/providers/SolAccountProvider.cjs +16 -15
  37. package/dist/providers/SolAccountProvider.cjs.map +1 -1
  38. package/dist/providers/SolAccountProvider.d.cts +3 -12
  39. package/dist/providers/SolAccountProvider.d.cts.map +1 -1
  40. package/dist/providers/SolAccountProvider.d.mts +3 -12
  41. package/dist/providers/SolAccountProvider.d.mts.map +1 -1
  42. package/dist/providers/SolAccountProvider.mjs +16 -15
  43. package/dist/providers/SolAccountProvider.mjs.map +1 -1
  44. package/dist/providers/TrxAccountProvider.cjs +17 -17
  45. package/dist/providers/TrxAccountProvider.cjs.map +1 -1
  46. package/dist/providers/TrxAccountProvider.d.cts +3 -12
  47. package/dist/providers/TrxAccountProvider.d.cts.map +1 -1
  48. package/dist/providers/TrxAccountProvider.d.mts +3 -12
  49. package/dist/providers/TrxAccountProvider.d.mts.map +1 -1
  50. package/dist/providers/TrxAccountProvider.mjs +17 -17
  51. package/dist/providers/TrxAccountProvider.mjs.map +1 -1
  52. package/dist/utils.cjs +14 -0
  53. package/dist/utils.cjs.map +1 -0
  54. package/dist/utils.d.cts +2 -0
  55. package/dist/utils.d.cts.map +1 -0
  56. package/dist/utils.d.mts +2 -0
  57. package/dist/utils.d.mts.map +1 -0
  58. package/dist/utils.mjs +10 -0
  59. package/dist/utils.mjs.map +1 -0
  60. package/package.json +3 -1
@@ -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,qDAA4E;AAe5E;;;G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AA,IAAI,uCAAQ,CACb,CAAC;QACF,OAAO,EAAE,CAAC;QACV,uBAAA,IAAI,oCAAK,MAAT,IAAI,EAAM,+BAA+B,MAAM,IAAI,CAAC,CAAC;KACtD;AACH,CAAC;AAwPD;;;;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, type NamedAccountProvider } from './providers';\nimport type { MultichainAccountServiceMessenger } from './types';\n\n/**\n * The context for a provider discovery.\n */\ntype AccountProviderDiscoveryContext<\n Account extends Bip44Account<KeyringAccount>,\n> = {\n provider: NamedAccountProvider<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: NamedAccountProvider<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: NamedAccountProvider<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 * 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 if (options?.waitForAllProvidersToFinishCreatingAccounts) {\n // Create account with all providers and await them.\n const results = await Promise.allSettled(\n this.#providers.map((provider) =>\n provider.createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n }),\n ),\n );\n\n // If any of the provider failed to create their accounts, then we consider the\n // multichain account group to have failed too.\n if (results.some((result) => result.status === 'rejected')) {\n // NOTE: Some accounts might still have been created on other account providers. We\n // don't rollback them.\n const error = `Unable to create multichain account group for index: ${groupIndex}`;\n\n let message = `${error}:`;\n for (const result of results) {\n if (result.status === 'rejected') {\n message += `\\n- ${result.reason}`;\n }\n }\n this.#log(`${WARNING_PREFIX} ${message}`);\n console.warn(message);\n\n throw new Error(error);\n }\n } else {\n // Extract the EVM provider from the list of providers.\n // We will only await the EVM provider to create its accounts, while\n // all other providers will be started in the background.\n const [evmProvider, ...otherProviders] = this.#providers;\n assert(\n evmProvider instanceof EvmAccountProvider,\n 'EVM account provider must be first',\n );\n\n // Create account with the EVM provider first and await it.\n // If it fails, we don't start creating accounts with other providers.\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 throw new Error(errorMessage);\n }\n\n // Create account with other providers in the background\n otherProviders.forEach((provider) => {\n provider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .catch((error) => {\n // Log errors from background providers but don't fail the operation\n const errorMessage = `Could not to create account with provider \"${provider.getName()}\" for multichain account group index: ${groupIndex}`;\n this.#log(`${WARNING_PREFIX} ${errorMessage}:`, error);\n });\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 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;AAClB,yEAAkE;AAClE,qDAA4E;AAE5E,uCAAiD;AAcjD;;;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,sCAAc,SAAS,MAAA,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,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, type NamedAccountProvider } from './providers';\nimport type { MultichainAccountServiceMessenger } from './types';\nimport { toRejectedErrorMessage } from './utils';\n\n/**\n * The context for a provider discovery.\n */\ntype AccountProviderDiscoveryContext<\n Account extends Bip44Account<KeyringAccount>,\n> = {\n provider: NamedAccountProvider<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: NamedAccountProvider<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: NamedAccountProvider<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: NamedAccountProvider<Account>[];\n awaitAll: boolean;\n }): Promise<void> {\n if (awaitAll) {\n const tasks = providers.map((provider) =>\n provider.createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\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 });\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 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 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 +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;AAW7E,OAAO,EAAE,sBAAsB,EAAE,qCAAi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,CAEpC;IAED;;;;OAIG;IACH,IAAI,aAAa,IAAI,eAAe,CAEnC;IAED;;;;OAIG;IACH,IAAI,MAAM,IAAI,6BAA6B,CAE1C;IA+FD;;;;;;OAMG;IACH,eAAe,CACb,EAAE,EAAE,cAAc,GACjB,sBAAsB,CAAC,OAAO,CAAC,GAAG,SAAS;IAgB9C;;;;OAIG;IACH,gBAAgB,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE;IAIrD;;;;;OAKG;IACH,yBAAyB,CACvB,UAAU,EAAE,MAAM,GACjB,sBAAsB,CAAC,OAAO,CAAC,GAAG,SAAS;IAI9C;;;;OAIG;IACH,0BAA0B,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE;IAI/D;;;;OAIG;IACH,iBAAiB,IAAI,MAAM;IAU3B;;;;;;;;;;;;;;;;OAgBG;IACG,4BAA4B,CAChC,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE;QACP,2CAA2C,CAAC,EAAE,OAAO,CAAC;KACE,GACzD,OAAO,CAAC,sBAAsB,CAAC,OAAO,CAAC,CAAC;IA6G3C;;;;;OAKG;IACG,gCAAgC,IAAI,OAAO,CAC/C,sBAAsB,CAAC,OAAO,CAAC,CAChC;IAgBD;;;;OAIG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAMpC;;;;;;OAMG;IACG,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASxD;;;;;;OAMG;IACG,gBAAgB,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;CAkF7C"}
@@ -9,13 +9,14 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _MultichainAccountWallet_instances, _MultichainAccountWallet_lock, _MultichainAccountWallet_id, _MultichainAccountWallet_providers, _MultichainAccountWallet_entropySource, _MultichainAccountWallet_accountGroups, _MultichainAccountWallet_messenger, _MultichainAccountWallet_log, _MultichainAccountWallet_initialized, _MultichainAccountWallet_status, _MultichainAccountWallet_withLock, _MultichainAccountWallet_alignAccounts;
12
+ var _MultichainAccountWallet_instances, _MultichainAccountWallet_lock, _MultichainAccountWallet_id, _MultichainAccountWallet_providers, _MultichainAccountWallet_entropySource, _MultichainAccountWallet_accountGroups, _MultichainAccountWallet_messenger, _MultichainAccountWallet_log, _MultichainAccountWallet_initialized, _MultichainAccountWallet_status, _MultichainAccountWallet_withLock, _MultichainAccountWallet_createNonEvmAccounts, _MultichainAccountWallet_alignAccounts;
13
13
  import { AccountWalletType, getGroupIndexFromMultichainAccountGroupId, isMultichainAccountGroupId, toDefaultAccountGroupId, toMultichainAccountWalletId } from "@metamask/account-api";
14
14
  import { assert } from "@metamask/utils";
15
15
  import { Mutex } from "async-mutex";
16
16
  import { createModuleLogger, ERROR_PREFIX, projectLogger as log, WARNING_PREFIX } from "./logger.mjs";
17
17
  import { MultichainAccountGroup } from "./MultichainAccountGroup.mjs";
18
18
  import { EvmAccountProvider } from "./providers/index.mjs";
19
+ import { toRejectedErrorMessage } from "./utils.mjs";
19
20
  /**
20
21
  * A multichain account wallet that holds multiple multichain accounts (one multichain account per
21
22
  * group index).
@@ -213,60 +214,36 @@ export class MultichainAccountWallet {
213
214
  return group;
214
215
  }
215
216
  __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `Creating new group for index ${groupIndex}...`);
216
- if (options?.waitForAllProvidersToFinishCreatingAccounts) {
217
- // Create account with all providers and await them.
218
- const results = await Promise.allSettled(__classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f").map((provider) => provider.createAccounts({
217
+ // Extract the EVM provider from the list of providers.
218
+ // We always await EVM account creation first.
219
+ const [evmProvider, ...otherProviders] = __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f");
220
+ assert(evmProvider instanceof EvmAccountProvider, 'EVM account provider must be first');
221
+ try {
222
+ await evmProvider.createAccounts({
219
223
  entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
220
224
  groupIndex,
221
- })));
222
- // If any of the provider failed to create their accounts, then we consider the
223
- // multichain account group to have failed too.
224
- if (results.some((result) => result.status === 'rejected')) {
225
- // NOTE: Some accounts might still have been created on other account providers. We
226
- // don't rollback them.
227
- const error = `Unable to create multichain account group for index: ${groupIndex}`;
228
- let message = `${error}:`;
229
- for (const result of results) {
230
- if (result.status === 'rejected') {
231
- message += `\n- ${result.reason}`;
232
- }
233
- }
234
- __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${WARNING_PREFIX} ${message}`);
235
- console.warn(message);
236
- throw new Error(error);
237
- }
225
+ });
226
+ }
227
+ catch (error) {
228
+ const errorMessage = `Unable to create multichain account group for index: ${groupIndex} with provider "${evmProvider.getName()}". Error: ${error.message}`;
229
+ __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${ERROR_PREFIX} ${errorMessage}:`, error);
230
+ throw new Error(errorMessage);
231
+ }
232
+ // We then create accounts with other providers (some being throttled if configured).
233
+ // Depending on the options, we either await all providers or run them in background.
234
+ if (options?.waitForAllProvidersToFinishCreatingAccounts) {
235
+ await __classPrivateFieldGet(this, _MultichainAccountWallet_instances, "m", _MultichainAccountWallet_createNonEvmAccounts).call(this, {
236
+ groupIndex,
237
+ providers: otherProviders,
238
+ awaitAll: true,
239
+ });
238
240
  }
239
241
  else {
240
- // Extract the EVM provider from the list of providers.
241
- // We will only await the EVM provider to create its accounts, while
242
- // all other providers will be started in the background.
243
- const [evmProvider, ...otherProviders] = __classPrivateFieldGet(this, _MultichainAccountWallet_providers, "f");
244
- assert(evmProvider instanceof EvmAccountProvider, 'EVM account provider must be first');
245
- // Create account with the EVM provider first and await it.
246
- // If it fails, we don't start creating accounts with other providers.
247
- try {
248
- await evmProvider.createAccounts({
249
- entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
250
- groupIndex,
251
- });
252
- }
253
- catch (error) {
254
- const errorMessage = `Unable to create multichain account group for index: ${groupIndex} with provider "${evmProvider.getName()}". Error: ${error.message}`;
255
- __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${ERROR_PREFIX} ${errorMessage}:`, error);
256
- throw new Error(errorMessage);
257
- }
258
- // Create account with other providers in the background
259
- otherProviders.forEach((provider) => {
260
- provider
261
- .createAccounts({
262
- entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
263
- groupIndex,
264
- })
265
- .catch((error) => {
266
- // Log errors from background providers but don't fail the operation
267
- const errorMessage = `Could not to create account with provider "${provider.getName()}" for multichain account group index: ${groupIndex}`;
268
- __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${WARNING_PREFIX} ${errorMessage}:`, error);
269
- });
242
+ // eslint-disable-next-line no-void
243
+ void __classPrivateFieldGet(this, _MultichainAccountWallet_instances, "m", _MultichainAccountWallet_createNonEvmAccounts).call(this, {
244
+ groupIndex,
245
+ providers: otherProviders,
246
+ awaitAll: false,
270
247
  });
271
248
  }
272
249
  // --------------------------------------------------------------------------------
@@ -435,6 +412,48 @@ async function _MultichainAccountWallet_withLock(status, operation) {
435
412
  release();
436
413
  __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `Releasing wallet lock (was "${status}")`);
437
414
  }
415
+ }, _MultichainAccountWallet_createNonEvmAccounts =
416
+ /**
417
+ * Create accounts with non‑EVM providers. Optional throttling is managed by each provider internally.
418
+ * When awaitAll is true, waits for all providers and throws if any failed.
419
+ * When false, starts work in background and logs errors without throwing.
420
+ *
421
+ * @param options - Method options.
422
+ * @param options.groupIndex - The group index to create accounts for.
423
+ * @param options.providers - The non‑EVM account providers.
424
+ * @param options.awaitAll - Whether to wait for all providers to finish.
425
+ * @throws If awaitAll is true and any provider fails to create accounts.
426
+ * @returns A promise that resolves when done (if awaitAll is true) or immediately (if false).
427
+ */
428
+ async function _MultichainAccountWallet_createNonEvmAccounts({ groupIndex, providers, awaitAll, }) {
429
+ if (awaitAll) {
430
+ const tasks = providers.map((provider) => provider.createAccounts({
431
+ entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
432
+ groupIndex,
433
+ }));
434
+ const results = await Promise.allSettled(tasks);
435
+ if (results.some((r) => r.status === 'rejected')) {
436
+ const errorMessage = toRejectedErrorMessage(`Unable to create multichain account group for index: ${groupIndex}`, results);
437
+ __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${WARNING_PREFIX} ${errorMessage}`);
438
+ console.warn(errorMessage);
439
+ throw new Error(errorMessage);
440
+ }
441
+ return;
442
+ }
443
+ // Background mode: start tasks and log errors.
444
+ // Optional throttling is handled internally by each provider based on its config.
445
+ providers.forEach((provider) => {
446
+ // eslint-disable-next-line no-void
447
+ void provider
448
+ .createAccounts({
449
+ entropySource: __classPrivateFieldGet(this, _MultichainAccountWallet_entropySource, "f"),
450
+ groupIndex,
451
+ })
452
+ .catch((error) => {
453
+ const errorMessage = `Unable to create multichain account group for index: ${groupIndex} (background mode with provider "${provider.getName()}")`;
454
+ __classPrivateFieldGet(this, _MultichainAccountWallet_log, "f").call(this, `${WARNING_PREFIX} ${errorMessage}:`, error);
455
+ });
456
+ });
438
457
  }, _MultichainAccountWallet_alignAccounts =
439
458
  /**
440
459
  * Align all multichain account groups.
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainAccountWallet.mjs","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,OAAO,EACL,iBAAiB,EACjB,yCAAyC,EACzC,0BAA0B,EAC1B,uBAAuB,EACvB,2BAA2B,EAC5B,8BAA8B;AAE/B,OAAO,EAAE,MAAM,EAAE,wBAAwB;AACzC,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,aA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AAO,CACrB,6CAA6C,EAC7C,IAAI,CAAC,EAAE,EACP,uBAAA,IAAI,uCAAQ,CACb,CAAC;QACF,OAAO,EAAE,CAAC;QACV,uBAAA,IAAI,oCAAK,MAAT,IAAI,EAAM,+BAA+B,MAAM,IAAI,CAAC,CAAC;KACtD;AACH,CAAC;AAwPD;;;;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, type NamedAccountProvider } from './providers';\nimport type { MultichainAccountServiceMessenger } from './types';\n\n/**\n * The context for a provider discovery.\n */\ntype AccountProviderDiscoveryContext<\n Account extends Bip44Account<KeyringAccount>,\n> = {\n provider: NamedAccountProvider<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: NamedAccountProvider<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: NamedAccountProvider<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 * 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 if (options?.waitForAllProvidersToFinishCreatingAccounts) {\n // Create account with all providers and await them.\n const results = await Promise.allSettled(\n this.#providers.map((provider) =>\n provider.createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n }),\n ),\n );\n\n // If any of the provider failed to create their accounts, then we consider the\n // multichain account group to have failed too.\n if (results.some((result) => result.status === 'rejected')) {\n // NOTE: Some accounts might still have been created on other account providers. We\n // don't rollback them.\n const error = `Unable to create multichain account group for index: ${groupIndex}`;\n\n let message = `${error}:`;\n for (const result of results) {\n if (result.status === 'rejected') {\n message += `\\n- ${result.reason}`;\n }\n }\n this.#log(`${WARNING_PREFIX} ${message}`);\n console.warn(message);\n\n throw new Error(error);\n }\n } else {\n // Extract the EVM provider from the list of providers.\n // We will only await the EVM provider to create its accounts, while\n // all other providers will be started in the background.\n const [evmProvider, ...otherProviders] = this.#providers;\n assert(\n evmProvider instanceof EvmAccountProvider,\n 'EVM account provider must be first',\n );\n\n // Create account with the EVM provider first and await it.\n // If it fails, we don't start creating accounts with other providers.\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 throw new Error(errorMessage);\n }\n\n // Create account with other providers in the background\n otherProviders.forEach((provider) => {\n provider\n .createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\n })\n .catch((error) => {\n // Log errors from background providers but don't fail the operation\n const errorMessage = `Could not to create account with provider \"${provider.getName()}\" for multichain account group index: ${groupIndex}`;\n this.#log(`${WARNING_PREFIX} ${errorMessage}:`, error);\n });\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 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.mjs","sourceRoot":"","sources":["../src/MultichainAccountWallet.ts"],"names":[],"mappings":";;;;;;;;;;;;AAOA,OAAO,EACL,iBAAiB,EACjB,yCAAyC,EACzC,0BAA0B,EAC1B,uBAAuB,EACvB,2BAA2B,EAC5B,8BAA8B;AAE/B,OAAO,EAAE,MAAM,EAAE,wBAAwB;AACzC,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,aAAa,IAAI,GAAG,EACpB,cAAc,EACf,qBAAiB;AAClB,OAAO,EAAE,sBAAsB,EAAE,qCAAiC;AAClE,OAAO,EAAE,kBAAkB,EAA6B,8BAAoB;AAE5E,OAAO,EAAE,sBAAsB,EAAE,oBAAgB;AAcjD;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IAuBlC,YAAY,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AE,IAAI,CAAC;YAClJ,uBAAA,IAAI,oCAAK,MAAT,IAAI,EAAM,GAAG,cAAc,IAAI,YAAY,GAAG,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACL,CAAC;AAyND;;;;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, type NamedAccountProvider } from './providers';\nimport type { MultichainAccountServiceMessenger } from './types';\nimport { toRejectedErrorMessage } from './utils';\n\n/**\n * The context for a provider discovery.\n */\ntype AccountProviderDiscoveryContext<\n Account extends Bip44Account<KeyringAccount>,\n> = {\n provider: NamedAccountProvider<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: NamedAccountProvider<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: NamedAccountProvider<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: NamedAccountProvider<Account>[];\n awaitAll: boolean;\n }): Promise<void> {\n if (awaitAll) {\n const tasks = providers.map((provider) =>\n provider.createAccounts({\n entropySource: this.#entropySource,\n groupIndex,\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 });\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 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 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"]}
@@ -10,7 +10,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
11
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
12
  };
13
- var _BtcAccountProvider_instances, _BtcAccountProvider_client, _BtcAccountProvider_config, _BtcAccountProvider_getKeyringClientFromSnapId;
13
+ var _BtcAccountProvider_instances, _BtcAccountProvider_client, _BtcAccountProvider_getKeyringClientFromSnapId;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.BtcAccountProvider = exports.BTC_ACCOUNT_PROVIDER_NAME = void 0;
16
16
  const account_api_1 = require("@metamask/account-api");
@@ -31,12 +31,10 @@ class BtcAccountProvider extends SnapAccountProvider_1.SnapAccountProvider {
31
31
  backOffMs: 1000,
32
32
  },
33
33
  }) {
34
- super(BtcAccountProvider.BTC_SNAP_ID, messenger);
34
+ super(BtcAccountProvider.BTC_SNAP_ID, messenger, config);
35
35
  _BtcAccountProvider_instances.add(this);
36
36
  _BtcAccountProvider_client.set(this, void 0);
37
- _BtcAccountProvider_config.set(this, void 0);
38
37
  __classPrivateFieldSet(this, _BtcAccountProvider_client, __classPrivateFieldGet(this, _BtcAccountProvider_instances, "m", _BtcAccountProvider_getKeyringClientFromSnapId).call(this, BtcAccountProvider.BTC_SNAP_ID), "f");
39
- __classPrivateFieldSet(this, _BtcAccountProvider_config, config, "f");
40
38
  }
41
39
  getName() {
42
40
  return BtcAccountProvider.NAME;
@@ -46,20 +44,22 @@ class BtcAccountProvider extends SnapAccountProvider_1.SnapAccountProvider {
46
44
  Object.values(keyring_api_1.BtcAccountType).includes(account.type));
47
45
  }
48
46
  async createAccounts({ entropySource, groupIndex: index, }) {
49
- const createAccount = await this.getRestrictedSnapAccountCreator();
50
- const account = await (0, utils_1.withTimeout)(createAccount({
51
- entropySource,
52
- index,
53
- addressType: keyring_api_1.BtcAccountType.P2wpkh,
54
- scope: keyring_api_1.BtcScope.Mainnet,
55
- }), __classPrivateFieldGet(this, _BtcAccountProvider_config, "f").createAccounts.timeoutMs);
56
- (0, account_api_1.assertIsBip44Account)(account);
57
- return [account];
47
+ return this.withMaxConcurrency(async () => {
48
+ const createAccount = await this.getRestrictedSnapAccountCreator();
49
+ const account = await (0, utils_1.withTimeout)(createAccount({
50
+ entropySource,
51
+ index,
52
+ addressType: keyring_api_1.BtcAccountType.P2wpkh,
53
+ scope: keyring_api_1.BtcScope.Mainnet,
54
+ }), this.config.createAccounts.timeoutMs);
55
+ (0, account_api_1.assertIsBip44Account)(account);
56
+ return [account];
57
+ });
58
58
  }
59
59
  async discoverAccounts({ entropySource, groupIndex, }) {
60
- const discoveredAccounts = await (0, utils_1.withRetry)(() => (0, utils_1.withTimeout)(__classPrivateFieldGet(this, _BtcAccountProvider_client, "f").discoverAccounts([keyring_api_1.BtcScope.Mainnet], entropySource, groupIndex), __classPrivateFieldGet(this, _BtcAccountProvider_config, "f").discovery.timeoutMs), {
61
- maxAttempts: __classPrivateFieldGet(this, _BtcAccountProvider_config, "f").discovery.maxAttempts,
62
- backOffMs: __classPrivateFieldGet(this, _BtcAccountProvider_config, "f").discovery.backOffMs,
60
+ const discoveredAccounts = await (0, utils_1.withRetry)(() => (0, utils_1.withTimeout)(__classPrivateFieldGet(this, _BtcAccountProvider_client, "f").discoverAccounts([keyring_api_1.BtcScope.Mainnet], entropySource, groupIndex), this.config.discovery.timeoutMs), {
61
+ maxAttempts: this.config.discovery.maxAttempts,
62
+ backOffMs: this.config.discovery.backOffMs,
63
63
  });
64
64
  if (!Array.isArray(discoveredAccounts) || discoveredAccounts.length === 0) {
65
65
  return [];
@@ -72,7 +72,7 @@ class BtcAccountProvider extends SnapAccountProvider_1.SnapAccountProvider {
72
72
  }
73
73
  }
74
74
  exports.BtcAccountProvider = BtcAccountProvider;
75
- _BtcAccountProvider_client = new WeakMap(), _BtcAccountProvider_config = new WeakMap(), _BtcAccountProvider_instances = new WeakSet(), _BtcAccountProvider_getKeyringClientFromSnapId = function _BtcAccountProvider_getKeyringClientFromSnapId(snapId) {
75
+ _BtcAccountProvider_client = new WeakMap(), _BtcAccountProvider_instances = new WeakSet(), _BtcAccountProvider_getKeyringClientFromSnapId = function _BtcAccountProvider_getKeyringClientFromSnapId(snapId) {
76
76
  return new keyring_snap_client_1.KeyringClient({
77
77
  send: async (request) => {
78
78
  const response = await this.messenger.call('SnapController:handleRequest', {
@@ -1 +1 @@
1
- {"version":3,"file":"BtcAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/BtcAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAAgF;AAEhF,uDAAiE;AAEjE,uEAA8D;AAE9D,uDAAoD;AAGpD,mEAA4D;AAC5D,uCAAiD;AAcpC,QAAA,yBAAyB,GAAG,SAAkB,CAAC;AAE5D,MAAa,kBAAmB,SAAQ,yCAAmB;IASzD,YACE,SAA4C,EAC5C,SAAmC;QACjC,cAAc,EAAE;YACd,SAAS,EAAE,IAAI;SAChB;QACD,SAAS,EAAE;YACT,SAAS,EAAE,IAAI;YACf,WAAW,EAAE,CAAC;YACd,SAAS,EAAE,IAAI;SAChB;KACF;QAED,KAAK,CAAC,kBAAkB,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;;QAjB1C,6CAAuB;QAEvB,6CAAkC;QAgBzC,uBAAA,IAAI,8BAAW,uBAAA,IAAI,qFAA4B,MAAhC,IAAI,EACjB,kBAAkB,CAAC,WAAW,CAC/B,MAAA,CAAC;QACF,uBAAA,IAAI,8BAAW,MAAM,MAAA,CAAC;IACxB,CAAC;IAED,OAAO;QACL,OAAO,kBAAkB,CAAC,IAAI,CAAC;IACjC,CAAC;IAmBD,mBAAmB,CAAC,OAAsC;QACxD,OAAO,CACL,OAAO,CAAC,IAAI,KAAK,4BAAc,CAAC,MAAM;YACtC,MAAM,CAAC,MAAM,CAAS,4BAAc,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAC7D,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,EACnB,aAAa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AAuB,EAAE,EAAE;YACtC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACxC,8BAA8B,EAC9B;gBACE,MAAM,EAAE,MAAgB;gBACxB,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,yBAAW,CAAC,gBAAgB;gBACrC,OAAO;aACR,CACF,CAAC;YACF,OAAO,QAAgB,CAAC;QAC1B,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AA/CM,uBAAI,GAAG,iCAAyB,AAA5B,CAA6B;AAEjC,8BAAW,GAAG,mCAA6C,AAAhD,CAAiD","sourcesContent":["import { assertIsBip44Account, type Bip44Account } from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { BtcAccountType, BtcScope } from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport { SnapAccountProvider } from './SnapAccountProvider';\nimport { withRetry, withTimeout } from './utils';\nimport type { MultichainAccountServiceMessenger } from '../types';\n\nexport type BtcAccountProviderConfig = {\n discovery: {\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport const BTC_ACCOUNT_PROVIDER_NAME = 'Bitcoin' as const;\n\nexport class BtcAccountProvider extends SnapAccountProvider {\n static NAME = BTC_ACCOUNT_PROVIDER_NAME;\n\n static BTC_SNAP_ID = 'npm:@metamask/bitcoin-wallet-snap' as SnapId;\n\n readonly #client: KeyringClient;\n\n readonly #config: BtcAccountProviderConfig;\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: BtcAccountProviderConfig = {\n createAccounts: {\n timeoutMs: 3000,\n },\n discovery: {\n timeoutMs: 2000,\n maxAttempts: 3,\n backOffMs: 1000,\n },\n },\n ) {\n super(BtcAccountProvider.BTC_SNAP_ID, messenger);\n this.#client = this.#getKeyringClientFromSnapId(\n BtcAccountProvider.BTC_SNAP_ID,\n );\n this.#config = config;\n }\n\n getName(): string {\n return BtcAccountProvider.NAME;\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) => {\n const response = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n },\n );\n return response as Json;\n },\n });\n }\n\n isAccountCompatible(account: Bip44Account<InternalAccount>): boolean {\n return (\n account.type === BtcAccountType.P2wpkh &&\n Object.values<string>(BtcAccountType).includes(account.type)\n );\n }\n\n async createAccounts({\n entropySource,\n groupIndex: index,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]> {\n const createAccount = await this.getRestrictedSnapAccountCreator();\n\n const account = await withTimeout(\n createAccount({\n entropySource,\n index,\n addressType: BtcAccountType.P2wpkh,\n scope: BtcScope.Mainnet,\n }),\n this.#config.createAccounts.timeoutMs,\n );\n\n assertIsBip44Account(account);\n return [account];\n }\n\n async discoverAccounts({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }) {\n const discoveredAccounts = await withRetry(\n () =>\n withTimeout(\n this.#client.discoverAccounts(\n [BtcScope.Mainnet],\n entropySource,\n groupIndex,\n ),\n this.#config.discovery.timeoutMs,\n ),\n {\n maxAttempts: this.#config.discovery.maxAttempts,\n backOffMs: this.#config.discovery.backOffMs,\n },\n );\n\n if (!Array.isArray(discoveredAccounts) || discoveredAccounts.length === 0) {\n return [];\n }\n\n const createdAccounts = await this.createAccounts({\n entropySource,\n groupIndex,\n });\n\n return createdAccounts;\n }\n}\n"]}
1
+ {"version":3,"file":"BtcAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/BtcAccountProvider.ts"],"names":[],"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CAAC;AA5CM,uBAAI,GAAG,iCAAyB,AAA5B,CAA6B;AAEjC,8BAAW,GAAG,mCAA6C,AAAhD,CAAiD","sourcesContent":["import { assertIsBip44Account, type Bip44Account } from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { BtcAccountType, BtcScope } from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\n\nimport {\n SnapAccountProvider,\n type SnapAccountProviderConfig,\n} from './SnapAccountProvider';\nimport { withRetry, withTimeout } from './utils';\nimport type { MultichainAccountServiceMessenger } from '../types';\n\nexport type BtcAccountProviderConfig = SnapAccountProviderConfig;\n\nexport const BTC_ACCOUNT_PROVIDER_NAME = 'Bitcoin' as const;\n\nexport class BtcAccountProvider extends SnapAccountProvider {\n static NAME = BTC_ACCOUNT_PROVIDER_NAME;\n\n static BTC_SNAP_ID = 'npm:@metamask/bitcoin-wallet-snap' as SnapId;\n\n readonly #client: KeyringClient;\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: BtcAccountProviderConfig = {\n createAccounts: {\n timeoutMs: 3000,\n },\n discovery: {\n timeoutMs: 2000,\n maxAttempts: 3,\n backOffMs: 1000,\n },\n },\n ) {\n super(BtcAccountProvider.BTC_SNAP_ID, messenger, config);\n this.#client = this.#getKeyringClientFromSnapId(\n BtcAccountProvider.BTC_SNAP_ID,\n );\n }\n\n getName(): string {\n return BtcAccountProvider.NAME;\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) => {\n const response = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n },\n );\n return response as Json;\n },\n });\n }\n\n isAccountCompatible(account: Bip44Account<InternalAccount>): boolean {\n return (\n account.type === BtcAccountType.P2wpkh &&\n Object.values<string>(BtcAccountType).includes(account.type)\n );\n }\n\n async createAccounts({\n entropySource,\n groupIndex: index,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]> {\n return this.withMaxConcurrency(async () => {\n const createAccount = await this.getRestrictedSnapAccountCreator();\n\n const account = await withTimeout(\n createAccount({\n entropySource,\n index,\n addressType: BtcAccountType.P2wpkh,\n scope: BtcScope.Mainnet,\n }),\n this.config.createAccounts.timeoutMs,\n );\n\n assertIsBip44Account(account);\n return [account];\n });\n }\n\n async discoverAccounts({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }) {\n const discoveredAccounts = await withRetry(\n () =>\n withTimeout(\n this.#client.discoverAccounts(\n [BtcScope.Mainnet],\n entropySource,\n groupIndex,\n ),\n this.config.discovery.timeoutMs,\n ),\n {\n maxAttempts: this.config.discovery.maxAttempts,\n backOffMs: this.config.discovery.backOffMs,\n },\n );\n\n if (!Array.isArray(discoveredAccounts) || discoveredAccounts.length === 0) {\n return [];\n }\n\n const createdAccounts = await this.createAccounts({\n entropySource,\n groupIndex,\n });\n\n return createdAccounts;\n }\n}\n"]}