@metamask-previews/multichain-account-service 4.0.0-preview-a2f1e6f9 → 4.0.0-preview-7334bbce

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