@metamask-previews/multichain-account-service 5.0.0-preview-fa81dffb → 5.1.0-preview-ab102d86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,9 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [5.1.0]
11
+
12
+ ### Added
13
+
14
+ - Recover from Snap account de-sync when Snap has more accounts than MetaMask ([#7671](https://github.com/MetaMask/core/pull/7671))
15
+
10
16
  ### Changed
11
17
 
12
18
  - Bump `@metamask/accounts-controller` from `^35.0.0` to `^35.0.2` ([#7604](https://github.com/MetaMask/core/pull/7604), [#7642](https://github.com/MetaMask/core/pull/7642))
19
+ - Remove Sentry log before attempting Snap account re-sync ([#7675](https://github.com/MetaMask/core/pull/7675))
13
20
 
14
21
  ## [5.0.0]
15
22
 
@@ -334,7 +341,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
334
341
  - Add `MultichainAccountService` ([#6141](https://github.com/MetaMask/core/pull/6141)), ([#6165](https://github.com/MetaMask/core/pull/6165))
335
342
  - This service manages multichain accounts/wallets.
336
343
 
337
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/multichain-account-service@5.0.0...HEAD
344
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/multichain-account-service@5.1.0...HEAD
345
+ [5.1.0]: https://github.com/MetaMask/core/compare/@metamask/multichain-account-service@5.0.0...@metamask/multichain-account-service@5.1.0
338
346
  [5.0.0]: https://github.com/MetaMask/core/compare/@metamask/multichain-account-service@4.1.0...@metamask/multichain-account-service@5.0.0
339
347
  [4.1.0]: https://github.com/MetaMask/core/compare/@metamask/multichain-account-service@4.0.1...@metamask/multichain-account-service@4.1.0
340
348
  [4.0.1]: https://github.com/MetaMask/core/compare/@metamask/multichain-account-service@4.0.0...@metamask/multichain-account-service@4.0.1
@@ -76,19 +76,31 @@ class SnapAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountPro
76
76
  await this.withSnap(async ({ keyring }) => {
77
77
  const localSnapAccounts = accounts.filter((account) => account.metadata.snap && account.metadata.snap.id === this.snapId);
78
78
  const snapAccounts = new Set((await __classPrivateFieldGet(this, _SnapAccountProvider_client, "f").listAccounts()).map((account) => account.id));
79
- // NOTE: This should never happen, but we want to report that kind of errors still
80
- // in case states are de-sync.
79
+ // NOTE: This should never happen, but if it does, we recover by deleting the
80
+ // extra accounts from the Snap to bring it back in sync with MetaMask.
81
81
  if (localSnapAccounts.length < snapAccounts.size) {
82
- this.messenger.captureException?.(new Error(`Snap "${this.snapId}" has de-synced accounts, Snap has more accounts than MetaMask!`));
83
- // We don't recover from this case yet.
84
- return;
82
+ // Build a set of local account IDs for quick lookup
83
+ const localAccountIds = new Set(localSnapAccounts.map((account) => account.id));
84
+ // Find and delete accounts that exist in Snap but not in MetaMask
85
+ await Promise.all([...snapAccounts].map(async (snapAccountId) => {
86
+ try {
87
+ if (!localAccountIds.has(snapAccountId)) {
88
+ // This account exists in the Snap but not in MetaMask, delete it from
89
+ // the Snap.
90
+ await __classPrivateFieldGet(this, _SnapAccountProvider_client, "f").deleteAccount(snapAccountId);
91
+ // Update the local Set so subsequent checks use the correct size
92
+ snapAccounts.delete(snapAccountId);
93
+ }
94
+ }
95
+ catch (error) {
96
+ const sentryError = (0, utils_1.createSentryError)(`Unable to delete de-synced Snap account: ${this.snapId}`, error, { provider: this.getName(), snapAccountId });
97
+ this.messenger.captureException?.(sentryError);
98
+ }
99
+ }));
85
100
  }
86
101
  // We want this part to be fast, so we only check for sizes, but we might need
87
102
  // to make a real "diff" between the 2 states to not miss any de-sync.
88
103
  if (localSnapAccounts.length > snapAccounts.size) {
89
- // Accounts should never really be de-synced, so we want to log this to see how often this
90
- // happens, cause that means that something else is buggy elsewhere...
91
- this.messenger.captureException?.(new Error(`Snap "${this.snapId}" has de-synced accounts, we'll attempt to re-sync them...`));
92
104
  // We always use the MetaMask list as the main reference here.
93
105
  await Promise.all(localSnapAccounts.map(async (account) => {
94
106
  const { id: entropySource, groupIndex } = account.options.entropy;
@@ -1 +1 @@
1
- {"version":3,"file":"SnapAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,qEAA4D;AAE5D,uEAA8D;AAE9D,uDAAoD;AACpD,6CAAwC;AAExC,6EAAsE;AACtE,sDAA6C;AAE7C,wCAA6C;AAoB7C,MAAsB,mBAAoB,SAAQ,mDAAwB;IAWxE,YACE,MAAc,EACd,SAA4C,EAC5C,MAAiC;IACjC,0BAA0B;IAC1B,QAAuB,yBAAa;QAEpC,KAAK,CAAC,SAAS,CAAC,CAAC;;QAbV,8CAAuB;QAEvB,6CAAmB;QAEnB,6CAAsB;QAW7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,uBAAA,IAAI,+BAAW,uBAAA,IAAI,uFAA4B,MAAhC,IAAI,EAA6B,MAAM,CAAC,MAAA,CAAC;QAExD,MAAM,cAAc,GAAG,MAAM,CAAC,cAAc,IAAI,QAAQ,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG;YACZ,GAAG,MAAM;YACT,SAAS,EAAE;gBACT,GAAG,MAAM,CAAC,SAAS;gBACnB,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI;aAC1C;YACD,cAAc;SACf,CAAC;QAEF,kDAAkD;QAClD,IAAI,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC;YAC7B,uBAAA,IAAI,8BAAU,IAAI,uBAAS,CAAC,cAAc,CAAC,MAAA,CAAC;QAC9C,CAAC;QAED,uBAAA,IAAI,8BAAU,KAAK,MAAA,CAAC;IACtB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,wBAAwB;QAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CACxB,mDAAmD,CACpD,CAAC;IAC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6B;IAE7B,OAAO,IAAI,CAAC,WAAW,CACrB,EAAE,IAAI,EAAE,iCAAY,CAAC,IAAI,EAAE,EAC3B,CAAC,IAAI,EAAE,EAAE;QACP,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC;AA6BI,MAAM,qBAAqB,GAAG,CACnC,QAAiB,EACgB,EAAE;IACnC,OAAO,QAAQ,YAAY,mBAAmB,CAAC;AACjD,CAAC,CAAC;AAJW,QAAA,qBAAqB,yBAIhC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback, TraceRequest } from '@metamask/controller-utils';\nimport type { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport type { KeyringMetadata } from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Semaphore } from 'async-mutex';\n\nimport { BaseBip44AccountProvider } from './BaseBip44AccountProvider';\nimport { traceFallback } from '../analytics';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport { createSentryError } from '../utils';\n\nexport type RestrictedSnapKeyring = {\n createAccount: (options: Record<string, Json>) => Promise<KeyringAccount>;\n removeAccount: (address: string) => Promise<void>;\n};\n\nexport type SnapAccountProviderConfig = {\n maxConcurrency?: number;\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport abstract class SnapAccountProvider extends BaseBip44AccountProvider {\n readonly snapId: SnapId;\n\n protected readonly config: SnapAccountProviderConfig;\n\n readonly #client: KeyringClient;\n\n readonly #queue?: Semaphore;\n\n readonly #trace: TraceCallback;\n\n constructor(\n snapId: SnapId,\n messenger: MultichainAccountServiceMessenger,\n config: SnapAccountProviderConfig,\n /* istanbul ignore next */\n trace: TraceCallback = traceFallback,\n ) {\n super(messenger);\n\n this.snapId = snapId;\n this.#client = this.#getKeyringClientFromSnapId(snapId);\n\n const maxConcurrency = config.maxConcurrency ?? Infinity;\n this.config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n maxConcurrency,\n };\n\n // Create semaphore only if concurrency is limited\n if (isFinite(maxConcurrency)) {\n this.#queue = new Semaphore(maxConcurrency);\n }\n\n this.#trace = trace;\n }\n\n /**\n * Ensures that the Snap platform is ready to be used.\n *\n * @returns A promise that resolves when the platform is ready.\n * @throws An error if the platform is not ready (only effective once the platform has been ready at least once).\n */\n async ensureCanUseSnapPlatform(): Promise<void> {\n return this.messenger.call(\n 'MultichainAccountService:ensureCanUseSnapPlatform',\n );\n }\n\n /**\n * Wraps an async operation with concurrency limiting based on maxConcurrency config.\n * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.\n * Otherwise, it's queued through the semaphore to respect the concurrency limit.\n *\n * @param operation - The async operation to execute.\n * @returns The result of the operation.\n */\n protected async withMaxConcurrency<Result>(\n operation: () => Promise<Result>,\n ): Promise<Result> {\n if (this.#queue) {\n return this.#queue.runExclusive(operation);\n }\n return operation();\n }\n\n protected async trace<ReturnType>(\n request: TraceRequest,\n fn: () => Promise<ReturnType>,\n ): Promise<ReturnType> {\n return this.#trace(request, fn);\n }\n\n async #getRestrictedSnapKeyring(): Promise<RestrictedSnapKeyring> {\n // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but\n // we have to use the `SnapKeyring` instance to be able to create Solana account\n // without triggering UI confirmation.\n // Also, creating account that way won't invalidate the Snap keyring state. The\n // account will get created and persisted properly with the Snap account creation\n // flow \"asynchronously\" (with `notify:accountCreated`).\n const createAccount = await this.#withSnapKeyring<\n SnapKeyring['createAccount']\n >(async ({ keyring }) => keyring.createAccount.bind(keyring));\n\n return {\n createAccount: async (options) =>\n // We use the \"unguarded\" account creation here (see explanation above).\n await createAccount(this.snapId, options, {\n displayAccountNameSuggestion: false,\n displayConfirmation: false,\n setSelectedAccount: false,\n }),\n removeAccount: async (address: string) =>\n // Though, when removing account, we can use the normal flow.\n await this.#withSnapKeyring(async ({ keyring }) => {\n await keyring.removeAccount(address);\n }),\n };\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest): Promise<Json> => {\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 async resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void> {\n await this.withSnap(async ({ keyring }) => {\n const localSnapAccounts = accounts.filter(\n (account) =>\n account.metadata.snap && account.metadata.snap.id === this.snapId,\n );\n const snapAccounts = new Set(\n (await this.#client.listAccounts()).map((account) => account.id),\n );\n\n // NOTE: This should never happen, but we want to report that kind of errors still\n // in case states are de-sync.\n if (localSnapAccounts.length < snapAccounts.size) {\n this.messenger.captureException?.(\n new Error(\n `Snap \"${this.snapId}\" has de-synced accounts, Snap has more accounts than MetaMask!`,\n ),\n );\n\n // We don't recover from this case yet.\n return;\n }\n\n // We want this part to be fast, so we only check for sizes, but we might need\n // to make a real \"diff\" between the 2 states to not miss any de-sync.\n if (localSnapAccounts.length > snapAccounts.size) {\n // Accounts should never really be de-synced, so we want to log this to see how often this\n // happens, cause that means that something else is buggy elsewhere...\n this.messenger.captureException?.(\n new Error(\n `Snap \"${this.snapId}\" has de-synced accounts, we'll attempt to re-sync them...`,\n ),\n );\n\n // We always use the MetaMask list as the main reference here.\n await Promise.all(\n localSnapAccounts.map(async (account) => {\n const { id: entropySource, groupIndex } = account.options.entropy;\n\n try {\n if (!snapAccounts.has(account.id)) {\n // We still need to remove the accounts from the Snap keyring since we're\n // about to create the same account again, which will use a new ID, but will\n // keep using the same address, and the Snap keyring does not allow this.\n await keyring.removeAccount(account.address);\n // The Snap has no account in its state for this one, we re-create it.\n await this.createAccounts({\n entropySource,\n groupIndex,\n });\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to re-sync account: ${groupIndex}`,\n error as Error,\n {\n provider: this.getName(),\n groupIndex,\n },\n );\n this.messenger.captureException?.(sentryError);\n }\n }),\n );\n }\n });\n }\n\n async #withSnapKeyring<CallbackResult = void>(\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SnapKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n return this.withKeyring<SnapKeyring, CallbackResult>(\n { type: KeyringTypes.snap },\n (args) => {\n return operation(args);\n },\n );\n }\n\n protected async withSnap<CallbackResult = void>(\n operation: (snap: {\n client: KeyringClient;\n keyring: RestrictedSnapKeyring;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n await this.ensureCanUseSnapPlatform();\n\n return await operation({\n client: this.#client,\n keyring: await this.#getRestrictedSnapKeyring(),\n });\n }\n\n abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;\n\n abstract createAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n\n abstract discoverAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n}\n\nexport const isSnapAccountProvider = (\n provider: unknown,\n): provider is SnapAccountProvider => {\n return provider instanceof SnapAccountProvider;\n};\n"]}
1
+ {"version":3,"file":"SnapAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,qEAA4D;AAE5D,uEAA8D;AAE9D,uDAAoD;AACpD,6CAAwC;AAExC,6EAAsE;AACtE,sDAA6C;AAE7C,wCAA6C;AAoB7C,MAAsB,mBAAoB,SAAQ,mDAAwB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AM,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,yCAkFD,KAAK,+CACH,SAM6B;IAE7B,OAAO,IAAI,CAAC,WAAW,CACrB,EAAE,IAAI,EAAE,iCAAY,CAAC,IAAI,EAAE,EAC3B,CAAC,IAAI,EAAE,EAAE;QACP,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC;AA6BI,MAAM,qBAAqB,GAAG,CACnC,QAAiB,EACgB,EAAE;IACnC,OAAO,QAAQ,YAAY,mBAAmB,CAAC;AACjD,CAAC,CAAC;AAJW,QAAA,qBAAqB,yBAIhC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback, TraceRequest } from '@metamask/controller-utils';\nimport type { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport type { KeyringMetadata } from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Semaphore } from 'async-mutex';\n\nimport { BaseBip44AccountProvider } from './BaseBip44AccountProvider';\nimport { traceFallback } from '../analytics';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport { createSentryError } from '../utils';\n\nexport type RestrictedSnapKeyring = {\n createAccount: (options: Record<string, Json>) => Promise<KeyringAccount>;\n removeAccount: (address: string) => Promise<void>;\n};\n\nexport type SnapAccountProviderConfig = {\n maxConcurrency?: number;\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport abstract class SnapAccountProvider extends BaseBip44AccountProvider {\n readonly snapId: SnapId;\n\n protected readonly config: SnapAccountProviderConfig;\n\n readonly #client: KeyringClient;\n\n readonly #queue?: Semaphore;\n\n readonly #trace: TraceCallback;\n\n constructor(\n snapId: SnapId,\n messenger: MultichainAccountServiceMessenger,\n config: SnapAccountProviderConfig,\n /* istanbul ignore next */\n trace: TraceCallback = traceFallback,\n ) {\n super(messenger);\n\n this.snapId = snapId;\n this.#client = this.#getKeyringClientFromSnapId(snapId);\n\n const maxConcurrency = config.maxConcurrency ?? Infinity;\n this.config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n maxConcurrency,\n };\n\n // Create semaphore only if concurrency is limited\n if (isFinite(maxConcurrency)) {\n this.#queue = new Semaphore(maxConcurrency);\n }\n\n this.#trace = trace;\n }\n\n /**\n * Ensures that the Snap platform is ready to be used.\n *\n * @returns A promise that resolves when the platform is ready.\n * @throws An error if the platform is not ready (only effective once the platform has been ready at least once).\n */\n async ensureCanUseSnapPlatform(): Promise<void> {\n return this.messenger.call(\n 'MultichainAccountService:ensureCanUseSnapPlatform',\n );\n }\n\n /**\n * Wraps an async operation with concurrency limiting based on maxConcurrency config.\n * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.\n * Otherwise, it's queued through the semaphore to respect the concurrency limit.\n *\n * @param operation - The async operation to execute.\n * @returns The result of the operation.\n */\n protected async withMaxConcurrency<Result>(\n operation: () => Promise<Result>,\n ): Promise<Result> {\n if (this.#queue) {\n return this.#queue.runExclusive(operation);\n }\n return operation();\n }\n\n protected async trace<ReturnType>(\n request: TraceRequest,\n fn: () => Promise<ReturnType>,\n ): Promise<ReturnType> {\n return this.#trace(request, fn);\n }\n\n async #getRestrictedSnapKeyring(): Promise<RestrictedSnapKeyring> {\n // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but\n // we have to use the `SnapKeyring` instance to be able to create Solana account\n // without triggering UI confirmation.\n // Also, creating account that way won't invalidate the Snap keyring state. The\n // account will get created and persisted properly with the Snap account creation\n // flow \"asynchronously\" (with `notify:accountCreated`).\n const createAccount = await this.#withSnapKeyring<\n SnapKeyring['createAccount']\n >(async ({ keyring }) => keyring.createAccount.bind(keyring));\n\n return {\n createAccount: async (options) =>\n // We use the \"unguarded\" account creation here (see explanation above).\n await createAccount(this.snapId, options, {\n displayAccountNameSuggestion: false,\n displayConfirmation: false,\n setSelectedAccount: false,\n }),\n removeAccount: async (address: string) =>\n // Though, when removing account, we can use the normal flow.\n await this.#withSnapKeyring(async ({ keyring }) => {\n await keyring.removeAccount(address);\n }),\n };\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest): Promise<Json> => {\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 async resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void> {\n await this.withSnap(async ({ keyring }) => {\n const localSnapAccounts = accounts.filter(\n (account) =>\n account.metadata.snap && account.metadata.snap.id === this.snapId,\n );\n const snapAccounts = new Set(\n (await this.#client.listAccounts()).map((account) => account.id),\n );\n\n // NOTE: This should never happen, but if it does, we recover by deleting the\n // extra accounts from the Snap to bring it back in sync with MetaMask.\n if (localSnapAccounts.length < snapAccounts.size) {\n // Build a set of local account IDs for quick lookup\n const localAccountIds = new Set(\n localSnapAccounts.map((account) => account.id),\n );\n\n // Find and delete accounts that exist in Snap but not in MetaMask\n await Promise.all(\n [...snapAccounts].map(async (snapAccountId) => {\n try {\n if (!localAccountIds.has(snapAccountId)) {\n // This account exists in the Snap but not in MetaMask, delete it from\n // the Snap.\n await this.#client.deleteAccount(snapAccountId);\n // Update the local Set so subsequent checks use the correct size\n snapAccounts.delete(snapAccountId);\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to delete de-synced Snap account: ${this.snapId}`,\n error as Error,\n { provider: this.getName(), snapAccountId },\n );\n this.messenger.captureException?.(sentryError);\n }\n }),\n );\n }\n\n // We want this part to be fast, so we only check for sizes, but we might need\n // to make a real \"diff\" between the 2 states to not miss any de-sync.\n if (localSnapAccounts.length > snapAccounts.size) {\n // We always use the MetaMask list as the main reference here.\n await Promise.all(\n localSnapAccounts.map(async (account) => {\n const { id: entropySource, groupIndex } = account.options.entropy;\n\n try {\n if (!snapAccounts.has(account.id)) {\n // We still need to remove the accounts from the Snap keyring since we're\n // about to create the same account again, which will use a new ID, but will\n // keep using the same address, and the Snap keyring does not allow this.\n await keyring.removeAccount(account.address);\n // The Snap has no account in its state for this one, we re-create it.\n await this.createAccounts({\n entropySource,\n groupIndex,\n });\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to re-sync account: ${groupIndex}`,\n error as Error,\n {\n provider: this.getName(),\n groupIndex,\n },\n );\n this.messenger.captureException?.(sentryError);\n }\n }),\n );\n }\n });\n }\n\n async #withSnapKeyring<CallbackResult = void>(\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SnapKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n return this.withKeyring<SnapKeyring, CallbackResult>(\n { type: KeyringTypes.snap },\n (args) => {\n return operation(args);\n },\n );\n }\n\n protected async withSnap<CallbackResult = void>(\n operation: (snap: {\n client: KeyringClient;\n keyring: RestrictedSnapKeyring;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n await this.ensureCanUseSnapPlatform();\n\n return await operation({\n client: this.#client,\n keyring: await this.#getRestrictedSnapKeyring(),\n });\n }\n\n abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;\n\n abstract createAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n\n abstract discoverAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n}\n\nexport const isSnapAccountProvider = (\n provider: unknown,\n): provider is SnapAccountProvider => {\n return provider instanceof SnapAccountProvider;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"SnapAccountProvider.d.cts","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,mCAAmC;AAE9E,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAG7E,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AACtE,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAC9D,OAAO,KAAK,EAAE,IAAI,EAAkB,MAAM,EAAE,4BAA4B;AAIxE,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AAEtE,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAGlE,MAAM,MAAM,qBAAqB,GAAG;IAClC,aAAa,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAC1E,aAAa,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACnD,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACtC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE;QACT,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,cAAc,EAAE;QACd,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH,CAAC;AAEF,8BAAsB,mBAAoB,SAAQ,wBAAwB;;IACxE,QAAQ,CAAC,MAAM,EA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AAC,GAC/B,OAAO,CAAC,MAAM,CAAC;cAOF,KAAK,CAAC,UAAU,EAC9B,OAAO,EAAE,YAAY,EACrB,EAAE,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,GAC5B,OAAO,CAAC,UAAU,CAAC;IAgDhB,cAAc,CAClB,QAAQ,EAAE,YAAY,CAAC,eAAe,CAAC,EAAE,GACxC,OAAO,CAAC,IAAI,CAAC;cA+FA,QAAQ,CAAC,cAAc,GAAG,IAAI,EAC5C,SAAS,EAAE,CAAC,IAAI,EAAE;QAChB,MAAM,EAAE,aAAa,CAAC;QACtB,OAAO,EAAE,qBAAqB,CAAC;KAChC,KAAK,OAAO,CAAC,cAAc,CAAC,GAC5B,OAAO,CAAC,cAAc,CAAC;IAS1B,QAAQ,CAAC,mBAAmB,CAAC,OAAO,EAAE,YAAY,CAAC,eAAe,CAAC,GAAG,OAAO;IAE7E,QAAQ,CAAC,cAAc,CAAC,OAAO,EAAE;QAC/B,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAE3C,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE;QACjC,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;CAC5C;AAED,eAAO,MAAM,qBAAqB,aACtB,OAAO,oCAGlB,CAAC"}
@@ -73,19 +73,31 @@ export class SnapAccountProvider extends BaseBip44AccountProvider {
73
73
  await this.withSnap(async ({ keyring }) => {
74
74
  const localSnapAccounts = accounts.filter((account) => account.metadata.snap && account.metadata.snap.id === this.snapId);
75
75
  const snapAccounts = new Set((await __classPrivateFieldGet(this, _SnapAccountProvider_client, "f").listAccounts()).map((account) => account.id));
76
- // NOTE: This should never happen, but we want to report that kind of errors still
77
- // in case states are de-sync.
76
+ // NOTE: This should never happen, but if it does, we recover by deleting the
77
+ // extra accounts from the Snap to bring it back in sync with MetaMask.
78
78
  if (localSnapAccounts.length < snapAccounts.size) {
79
- this.messenger.captureException?.(new Error(`Snap "${this.snapId}" has de-synced accounts, Snap has more accounts than MetaMask!`));
80
- // We don't recover from this case yet.
81
- return;
79
+ // Build a set of local account IDs for quick lookup
80
+ const localAccountIds = new Set(localSnapAccounts.map((account) => account.id));
81
+ // Find and delete accounts that exist in Snap but not in MetaMask
82
+ await Promise.all([...snapAccounts].map(async (snapAccountId) => {
83
+ try {
84
+ if (!localAccountIds.has(snapAccountId)) {
85
+ // This account exists in the Snap but not in MetaMask, delete it from
86
+ // the Snap.
87
+ await __classPrivateFieldGet(this, _SnapAccountProvider_client, "f").deleteAccount(snapAccountId);
88
+ // Update the local Set so subsequent checks use the correct size
89
+ snapAccounts.delete(snapAccountId);
90
+ }
91
+ }
92
+ catch (error) {
93
+ const sentryError = createSentryError(`Unable to delete de-synced Snap account: ${this.snapId}`, error, { provider: this.getName(), snapAccountId });
94
+ this.messenger.captureException?.(sentryError);
95
+ }
96
+ }));
82
97
  }
83
98
  // We want this part to be fast, so we only check for sizes, but we might need
84
99
  // to make a real "diff" between the 2 states to not miss any de-sync.
85
100
  if (localSnapAccounts.length > snapAccounts.size) {
86
- // Accounts should never really be de-synced, so we want to log this to see how often this
87
- // happens, cause that means that something else is buggy elsewhere...
88
- this.messenger.captureException?.(new Error(`Snap "${this.snapId}" has de-synced accounts, we'll attempt to re-sync them...`));
89
101
  // We always use the MetaMask list as the main reference here.
90
102
  await Promise.all(localSnapAccounts.map(async (account) => {
91
103
  const { id: entropySource, groupIndex } = account.options.entropy;
@@ -1 +1 @@
1
- {"version":3,"file":"SnapAccountProvider.mjs","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAE5D,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAE9D,O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zB,CAAC,CACF,CAAC;AACJ,CAAC;AA6BH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,QAAiB,EACgB,EAAE;IACnC,OAAO,QAAQ,YAAY,mBAAmB,CAAC;AACjD,CAAC,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback, TraceRequest } from '@metamask/controller-utils';\nimport type { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport type { KeyringMetadata } from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Semaphore } from 'async-mutex';\n\nimport { BaseBip44AccountProvider } from './BaseBip44AccountProvider';\nimport { traceFallback } from '../analytics';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport { createSentryError } from '../utils';\n\nexport type RestrictedSnapKeyring = {\n createAccount: (options: Record<string, Json>) => Promise<KeyringAccount>;\n removeAccount: (address: string) => Promise<void>;\n};\n\nexport type SnapAccountProviderConfig = {\n maxConcurrency?: number;\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport abstract class SnapAccountProvider extends BaseBip44AccountProvider {\n readonly snapId: SnapId;\n\n protected readonly config: SnapAccountProviderConfig;\n\n readonly #client: KeyringClient;\n\n readonly #queue?: Semaphore;\n\n readonly #trace: TraceCallback;\n\n constructor(\n snapId: SnapId,\n messenger: MultichainAccountServiceMessenger,\n config: SnapAccountProviderConfig,\n /* istanbul ignore next */\n trace: TraceCallback = traceFallback,\n ) {\n super(messenger);\n\n this.snapId = snapId;\n this.#client = this.#getKeyringClientFromSnapId(snapId);\n\n const maxConcurrency = config.maxConcurrency ?? Infinity;\n this.config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n maxConcurrency,\n };\n\n // Create semaphore only if concurrency is limited\n if (isFinite(maxConcurrency)) {\n this.#queue = new Semaphore(maxConcurrency);\n }\n\n this.#trace = trace;\n }\n\n /**\n * Ensures that the Snap platform is ready to be used.\n *\n * @returns A promise that resolves when the platform is ready.\n * @throws An error if the platform is not ready (only effective once the platform has been ready at least once).\n */\n async ensureCanUseSnapPlatform(): Promise<void> {\n return this.messenger.call(\n 'MultichainAccountService:ensureCanUseSnapPlatform',\n );\n }\n\n /**\n * Wraps an async operation with concurrency limiting based on maxConcurrency config.\n * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.\n * Otherwise, it's queued through the semaphore to respect the concurrency limit.\n *\n * @param operation - The async operation to execute.\n * @returns The result of the operation.\n */\n protected async withMaxConcurrency<Result>(\n operation: () => Promise<Result>,\n ): Promise<Result> {\n if (this.#queue) {\n return this.#queue.runExclusive(operation);\n }\n return operation();\n }\n\n protected async trace<ReturnType>(\n request: TraceRequest,\n fn: () => Promise<ReturnType>,\n ): Promise<ReturnType> {\n return this.#trace(request, fn);\n }\n\n async #getRestrictedSnapKeyring(): Promise<RestrictedSnapKeyring> {\n // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but\n // we have to use the `SnapKeyring` instance to be able to create Solana account\n // without triggering UI confirmation.\n // Also, creating account that way won't invalidate the Snap keyring state. The\n // account will get created and persisted properly with the Snap account creation\n // flow \"asynchronously\" (with `notify:accountCreated`).\n const createAccount = await this.#withSnapKeyring<\n SnapKeyring['createAccount']\n >(async ({ keyring }) => keyring.createAccount.bind(keyring));\n\n return {\n createAccount: async (options) =>\n // We use the \"unguarded\" account creation here (see explanation above).\n await createAccount(this.snapId, options, {\n displayAccountNameSuggestion: false,\n displayConfirmation: false,\n setSelectedAccount: false,\n }),\n removeAccount: async (address: string) =>\n // Though, when removing account, we can use the normal flow.\n await this.#withSnapKeyring(async ({ keyring }) => {\n await keyring.removeAccount(address);\n }),\n };\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest): Promise<Json> => {\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 async resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void> {\n await this.withSnap(async ({ keyring }) => {\n const localSnapAccounts = accounts.filter(\n (account) =>\n account.metadata.snap && account.metadata.snap.id === this.snapId,\n );\n const snapAccounts = new Set(\n (await this.#client.listAccounts()).map((account) => account.id),\n );\n\n // NOTE: This should never happen, but we want to report that kind of errors still\n // in case states are de-sync.\n if (localSnapAccounts.length < snapAccounts.size) {\n this.messenger.captureException?.(\n new Error(\n `Snap \"${this.snapId}\" has de-synced accounts, Snap has more accounts than MetaMask!`,\n ),\n );\n\n // We don't recover from this case yet.\n return;\n }\n\n // We want this part to be fast, so we only check for sizes, but we might need\n // to make a real \"diff\" between the 2 states to not miss any de-sync.\n if (localSnapAccounts.length > snapAccounts.size) {\n // Accounts should never really be de-synced, so we want to log this to see how often this\n // happens, cause that means that something else is buggy elsewhere...\n this.messenger.captureException?.(\n new Error(\n `Snap \"${this.snapId}\" has de-synced accounts, we'll attempt to re-sync them...`,\n ),\n );\n\n // We always use the MetaMask list as the main reference here.\n await Promise.all(\n localSnapAccounts.map(async (account) => {\n const { id: entropySource, groupIndex } = account.options.entropy;\n\n try {\n if (!snapAccounts.has(account.id)) {\n // We still need to remove the accounts from the Snap keyring since we're\n // about to create the same account again, which will use a new ID, but will\n // keep using the same address, and the Snap keyring does not allow this.\n await keyring.removeAccount(account.address);\n // The Snap has no account in its state for this one, we re-create it.\n await this.createAccounts({\n entropySource,\n groupIndex,\n });\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to re-sync account: ${groupIndex}`,\n error as Error,\n {\n provider: this.getName(),\n groupIndex,\n },\n );\n this.messenger.captureException?.(sentryError);\n }\n }),\n );\n }\n });\n }\n\n async #withSnapKeyring<CallbackResult = void>(\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SnapKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n return this.withKeyring<SnapKeyring, CallbackResult>(\n { type: KeyringTypes.snap },\n (args) => {\n return operation(args);\n },\n );\n }\n\n protected async withSnap<CallbackResult = void>(\n operation: (snap: {\n client: KeyringClient;\n keyring: RestrictedSnapKeyring;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n await this.ensureCanUseSnapPlatform();\n\n return await operation({\n client: this.#client,\n keyring: await this.#getRestrictedSnapKeyring(),\n });\n }\n\n abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;\n\n abstract createAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n\n abstract discoverAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n}\n\nexport const isSnapAccountProvider = (\n provider: unknown,\n): provider is SnapAccountProvider => {\n return provider instanceof SnapAccountProvider;\n};\n"]}
1
+ {"version":3,"file":"SnapAccountProvider.mjs","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAE5D,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAE9D,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,SAAS,EAAE,oBAAoB;AAExC,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,EAAE,aAAa,EAAE,+BAAqB;AAE7C,OAAO,EAAE,iBAAiB,EAAE,qBAAiB;AAoB7C,MAAM,OAAgB,mBAAoB,SAAQ,wBAAwB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AAE,UAAU;gBAClB,OAAO,EAAE,WAAW,CAAC,gBAAgB;gBACrC,OAAO;aACR,CACF,CAAC;YACF,OAAO,QAAgB,CAAC;QAC1B,CAAC;KACF,CAAC,CAAC;AACL,CAAC,yCAkFD,KAAK,+CACH,SAM6B;IAE7B,OAAO,IAAI,CAAC,WAAW,CACrB,EAAE,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,EAC3B,CAAC,IAAI,EAAE,EAAE;QACP,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC;AA6BH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,QAAiB,EACgB,EAAE;IACnC,OAAO,QAAQ,YAAY,mBAAmB,CAAC;AACjD,CAAC,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback, TraceRequest } from '@metamask/controller-utils';\nimport type { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport type { KeyringMetadata } from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Semaphore } from 'async-mutex';\n\nimport { BaseBip44AccountProvider } from './BaseBip44AccountProvider';\nimport { traceFallback } from '../analytics';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport { createSentryError } from '../utils';\n\nexport type RestrictedSnapKeyring = {\n createAccount: (options: Record<string, Json>) => Promise<KeyringAccount>;\n removeAccount: (address: string) => Promise<void>;\n};\n\nexport type SnapAccountProviderConfig = {\n maxConcurrency?: number;\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport abstract class SnapAccountProvider extends BaseBip44AccountProvider {\n readonly snapId: SnapId;\n\n protected readonly config: SnapAccountProviderConfig;\n\n readonly #client: KeyringClient;\n\n readonly #queue?: Semaphore;\n\n readonly #trace: TraceCallback;\n\n constructor(\n snapId: SnapId,\n messenger: MultichainAccountServiceMessenger,\n config: SnapAccountProviderConfig,\n /* istanbul ignore next */\n trace: TraceCallback = traceFallback,\n ) {\n super(messenger);\n\n this.snapId = snapId;\n this.#client = this.#getKeyringClientFromSnapId(snapId);\n\n const maxConcurrency = config.maxConcurrency ?? Infinity;\n this.config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n maxConcurrency,\n };\n\n // Create semaphore only if concurrency is limited\n if (isFinite(maxConcurrency)) {\n this.#queue = new Semaphore(maxConcurrency);\n }\n\n this.#trace = trace;\n }\n\n /**\n * Ensures that the Snap platform is ready to be used.\n *\n * @returns A promise that resolves when the platform is ready.\n * @throws An error if the platform is not ready (only effective once the platform has been ready at least once).\n */\n async ensureCanUseSnapPlatform(): Promise<void> {\n return this.messenger.call(\n 'MultichainAccountService:ensureCanUseSnapPlatform',\n );\n }\n\n /**\n * Wraps an async operation with concurrency limiting based on maxConcurrency config.\n * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.\n * Otherwise, it's queued through the semaphore to respect the concurrency limit.\n *\n * @param operation - The async operation to execute.\n * @returns The result of the operation.\n */\n protected async withMaxConcurrency<Result>(\n operation: () => Promise<Result>,\n ): Promise<Result> {\n if (this.#queue) {\n return this.#queue.runExclusive(operation);\n }\n return operation();\n }\n\n protected async trace<ReturnType>(\n request: TraceRequest,\n fn: () => Promise<ReturnType>,\n ): Promise<ReturnType> {\n return this.#trace(request, fn);\n }\n\n async #getRestrictedSnapKeyring(): Promise<RestrictedSnapKeyring> {\n // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but\n // we have to use the `SnapKeyring` instance to be able to create Solana account\n // without triggering UI confirmation.\n // Also, creating account that way won't invalidate the Snap keyring state. The\n // account will get created and persisted properly with the Snap account creation\n // flow \"asynchronously\" (with `notify:accountCreated`).\n const createAccount = await this.#withSnapKeyring<\n SnapKeyring['createAccount']\n >(async ({ keyring }) => keyring.createAccount.bind(keyring));\n\n return {\n createAccount: async (options) =>\n // We use the \"unguarded\" account creation here (see explanation above).\n await createAccount(this.snapId, options, {\n displayAccountNameSuggestion: false,\n displayConfirmation: false,\n setSelectedAccount: false,\n }),\n removeAccount: async (address: string) =>\n // Though, when removing account, we can use the normal flow.\n await this.#withSnapKeyring(async ({ keyring }) => {\n await keyring.removeAccount(address);\n }),\n };\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest): Promise<Json> => {\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 async resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void> {\n await this.withSnap(async ({ keyring }) => {\n const localSnapAccounts = accounts.filter(\n (account) =>\n account.metadata.snap && account.metadata.snap.id === this.snapId,\n );\n const snapAccounts = new Set(\n (await this.#client.listAccounts()).map((account) => account.id),\n );\n\n // NOTE: This should never happen, but if it does, we recover by deleting the\n // extra accounts from the Snap to bring it back in sync with MetaMask.\n if (localSnapAccounts.length < snapAccounts.size) {\n // Build a set of local account IDs for quick lookup\n const localAccountIds = new Set(\n localSnapAccounts.map((account) => account.id),\n );\n\n // Find and delete accounts that exist in Snap but not in MetaMask\n await Promise.all(\n [...snapAccounts].map(async (snapAccountId) => {\n try {\n if (!localAccountIds.has(snapAccountId)) {\n // This account exists in the Snap but not in MetaMask, delete it from\n // the Snap.\n await this.#client.deleteAccount(snapAccountId);\n // Update the local Set so subsequent checks use the correct size\n snapAccounts.delete(snapAccountId);\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to delete de-synced Snap account: ${this.snapId}`,\n error as Error,\n { provider: this.getName(), snapAccountId },\n );\n this.messenger.captureException?.(sentryError);\n }\n }),\n );\n }\n\n // We want this part to be fast, so we only check for sizes, but we might need\n // to make a real \"diff\" between the 2 states to not miss any de-sync.\n if (localSnapAccounts.length > snapAccounts.size) {\n // We always use the MetaMask list as the main reference here.\n await Promise.all(\n localSnapAccounts.map(async (account) => {\n const { id: entropySource, groupIndex } = account.options.entropy;\n\n try {\n if (!snapAccounts.has(account.id)) {\n // We still need to remove the accounts from the Snap keyring since we're\n // about to create the same account again, which will use a new ID, but will\n // keep using the same address, and the Snap keyring does not allow this.\n await keyring.removeAccount(account.address);\n // The Snap has no account in its state for this one, we re-create it.\n await this.createAccounts({\n entropySource,\n groupIndex,\n });\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to re-sync account: ${groupIndex}`,\n error as Error,\n {\n provider: this.getName(),\n groupIndex,\n },\n );\n this.messenger.captureException?.(sentryError);\n }\n }),\n );\n }\n });\n }\n\n async #withSnapKeyring<CallbackResult = void>(\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SnapKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n return this.withKeyring<SnapKeyring, CallbackResult>(\n { type: KeyringTypes.snap },\n (args) => {\n return operation(args);\n },\n );\n }\n\n protected async withSnap<CallbackResult = void>(\n operation: (snap: {\n client: KeyringClient;\n keyring: RestrictedSnapKeyring;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n await this.ensureCanUseSnapPlatform();\n\n return await operation({\n client: this.#client,\n keyring: await this.#getRestrictedSnapKeyring(),\n });\n }\n\n abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;\n\n abstract createAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n\n abstract discoverAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n}\n\nexport const isSnapAccountProvider = (\n provider: unknown,\n): provider is SnapAccountProvider => {\n return provider instanceof SnapAccountProvider;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/multichain-account-service",
3
- "version": "5.0.0-preview-fa81dffb",
3
+ "version": "5.1.0-preview-ab102d86",
4
4
  "description": "Service to manage multichain accounts",
5
5
  "keywords": [
6
6
  "MetaMask",