@metamask/assets-controllers 111.1.3 → 111.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +22 -1
  2. package/dist/AccountTrackerController.cjs +1 -1
  3. package/dist/AccountTrackerController.cjs.map +1 -1
  4. package/dist/AccountTrackerController.mjs +1 -1
  5. package/dist/AccountTrackerController.mjs.map +1 -1
  6. package/dist/CurrencyRateController.cjs +2 -2
  7. package/dist/CurrencyRateController.cjs.map +1 -1
  8. package/dist/CurrencyRateController.mjs +2 -2
  9. package/dist/CurrencyRateController.mjs.map +1 -1
  10. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.cjs +1 -1
  11. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.cjs.map +1 -1
  12. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.mjs +1 -1
  13. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.mjs.map +1 -1
  14. package/dist/MultichainAssetsController/MultichainAssetsController.cjs +3 -3
  15. package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
  16. package/dist/MultichainAssetsController/MultichainAssetsController.mjs +3 -3
  17. package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
  18. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs +1 -1
  19. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
  20. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs +1 -1
  21. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
  22. package/dist/MultichainBalancesController/MultichainBalancesController.cjs +1 -1
  23. package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
  24. package/dist/MultichainBalancesController/MultichainBalancesController.mjs +1 -1
  25. package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
  26. package/dist/TokenBalancesController.cjs +1 -1
  27. package/dist/TokenBalancesController.cjs.map +1 -1
  28. package/dist/TokenBalancesController.mjs +1 -1
  29. package/dist/TokenBalancesController.mjs.map +1 -1
  30. package/dist/TokenRatesController.cjs +1 -1
  31. package/dist/TokenRatesController.cjs.map +1 -1
  32. package/dist/TokenRatesController.mjs +1 -1
  33. package/dist/TokenRatesController.mjs.map +1 -1
  34. package/dist/TokensController.cjs +3 -3
  35. package/dist/TokensController.cjs.map +1 -1
  36. package/dist/TokensController.mjs +3 -3
  37. package/dist/TokensController.mjs.map +1 -1
  38. package/package.json +9 -8
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAA2D;AAU3D,kFAAwE;AAExE,8FAA+E;AAG/E,8EAAoE;AAEpE,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,yBAAyB,GAAG,CAAC,oBAAoB,CAAU,CAAC;AAElE;;;GAGG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC;AAmBD,MAAM,kBAAkB,GAAkD;IACxE,kBAAkB,EAAE;QAClB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEK,MAAM,wCAAwC,GACnD,GAAmC,EAAE;IACnC,OAAO;QACL,kBAAkB,EAAE,EAAE;KACvB,CAAC;AACJ,CAAC,CAAC;AALS,QAAA,wCAAwC,4CAKjD;AA2CJ;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,yBAA0B,SAAQ,gCAI9C;IAeC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,SAAS,EACT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AC;QAED,MAAM,EAAE,QAAQ,EAAE,GAChB,uBAAA,IAAI,4CAAW,CAAC,QAAQ,CAAC,qCAAqC,CAC5D,UAAU,EACV,YAAY,EACZ,YAAY,CACb,CAAC;QACJ,MAAM,uBAAA,IAAI,4CAAW,CAAC,QAAQ,CAAC,WAAW,CAAC,iBAAiB,CAAC;YAC3D,QAAQ;SACT,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,OAAO,IAAI,WAAW,GAAG,CAAC,CAAC;QACjD,IAAI,aAAa,EAAE,CAAC;YAClB,oEAAoE;YACpE,0DAA0D;YAC1D,MAAM,qBAAqB,GAAG,IAAI,KAAK,CACrC,qDAAqD,WAAW,aAAa,CAC9E,CAAC;YACF,qBAAqB,CAAC,IAAI,GAAG,wCAAwC,CAAC;YACtE,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,CAAC;YACzD,OAAO;QACT,CAAC;QAED,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query.js';\nimport type { DeFiBalancesQuery } from './build-defi-balances-query.js';\nimport { getProcessingPollConfig } from './defi-controller-v2-feature-flag.js';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types.js';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6.js';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6.js';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\n/**\n * @param ms - Milliseconds to wait.\n * @returns A promise that resolves after `ms`.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n | AccountTreeControllerGetAccountsFromSelectedAccountGroupAction\n | RemoteFeatureFlagControllerGetStateAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache on the first attempt (e.g.\n * pull-to-refresh); later processing polls always bypass the cache.\n *\n * When the API reports account IDs in the response-level\n * `processingDefiPositions` array, this controller polls until indexing\n * finishes or the attempt limit is reached, and only then processes and writes\n * state — responses that still list processing accounts leave prior state\n * untouched. Concurrent calls for the same selected accounts and `vsCurrency`\n * share one in-flight promise so the UI can treat the pending promise as a\n * loading signal. Calls for a different selection or fiat currency start their\n * own fetch and leave any prior poll running, so switching back can join an\n * in-flight fetch for that group and currency.\n *\n * Processing-poll `maxAttempts` / `pollInterval` are read via\n * {@link getProcessingPollConfig} from the `defiControllerV2` remote feature\n * flag (`RemoteFeatureFlagController:getState`), falling back to built-in\n * defaults when unset or invalid. Clients must delegate that action to this\n * controller's messenger.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * In-flight fetches keyed by selected DeFi-queryable account IDs plus\n * `vsCurrency`. Concurrent callers for the same selection and currency share\n * a promise; different selections or fiat currencies keep independent\n * fetches so fast switching can join an earlier matching poll.\n */\n readonly #inFlightFetches = new Map<string, Promise<void>>();\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. State is updated\n * only when the response lists no accounts in its `processingDefiPositions`\n * array; each resolved account then has its state replaced (other accounts\n * stay). While any account is still indexing, prior state is kept and the\n * method polls (invalidating the balances cache between attempts) until no\n * accounts are processing, the attempt limit is reached, or a request fails.\n * Concurrent calls for the same selected accounts and `vsCurrency` share one\n * in-flight promise; calls for a different selection or fiat currency start\n * a new fetch and leave prior polls running so a later switch back can join\n * them. When a successful ready response required more than one attempt, or\n * when polling hits the attempt limit while still processing, reports to\n * Sentry via `messenger.captureException` (error names\n * `DeFiPositionsV2FetchAttempts` /\n * `DeFiPositionsV2ProcessingPollExhausted`) so poll limits can be tuned.\n * No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache on the\n * first attempt (e.g. pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache on the\n * first attempt and fetch immediately.\n * @returns Resolves when the fetch (and any processing polls) finish.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n const query = buildDeFiBalancesQuery(selectedAccounts);\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n // Include vsCurrency so a fiat change does not join a poll priced in the\n // previous currency (TanStack also keys the balances cache on vsCurrency).\n const inFlightKey = [\n ...[...query.internalAccountIdByCaip.keys()].sort(),\n vsCurrency,\n ].join('\\0');\n\n const existing = this.#inFlightFetches.get(inFlightKey);\n if (existing) {\n await existing;\n return;\n }\n\n // Same-key callers join this promise instead of replacing it, so cleanup\n // can always delete without checking identity.\n const fetchPromise = this.#fetchDeFiPositions(\n options,\n query,\n vsCurrency,\n ).finally(() => {\n this.#inFlightFetches.delete(inFlightKey);\n });\n this.#inFlightFetches.set(inFlightKey, fetchPromise);\n\n await fetchPromise;\n }\n\n async #fetchDeFiPositions(\n options: { forceRefresh?: boolean } | undefined,\n { networks, internalAccountIdByCaip }: DeFiBalancesQuery,\n vsCurrency: string,\n ): Promise<void> {\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const queryOptions = {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: true,\n includePrices: true,\n vsCurrency,\n };\n\n // Resolve once per fetch so a mid-poll remote-flag change cannot stretch\n // or shrink this poll sequence inconsistently.\n const { maxAttempts, pollInterval } = getProcessingPollConfig(\n this.messenger,\n );\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n // First attempt respects forceRefresh; later polls always bypass cache\n // so we do not spin on a stale processing snapshot.\n const fetchOptions = {\n ...(options?.forceRefresh || attempt > 0 ? { staleTime: 0 } : {}),\n };\n\n let response;\n try {\n response = await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n } catch (error) {\n // Soft-fail so prior state stays and the in-flight promise settles.\n console.error('Failed to fetch DeFi positions', error);\n return;\n }\n\n const stillProcessing =\n (response.processingDefiPositions?.length ?? 0) > 0;\n\n // Only process and write when no account is still indexing, so a\n // partial response (whose DeFi rows for processing accounts are\n // omitted) cannot clear or overwrite positions for those accounts.\n if (!stillProcessing) {\n const positionsByAccount = groupDeFiPositionsV6(\n response,\n internalAccountIdByCaip,\n );\n\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n\n // Report how many attempts were needed (only when polling was\n // required) so Sentry can inform remote-flag / default poll-limit\n // tuning without flooding on first-try successes.\n const attemptsTaken = attempt + 1;\n if (attemptsTaken > 1) {\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: positions ready after ${attemptsTaken} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2FetchAttempts';\n this.messenger.captureException?.(multipleAttemptsError);\n }\n return;\n }\n\n const { queryKey } =\n this.#apiClient.accounts.getV6MultiAccountBalancesQueryOptions(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n await this.#apiClient.accounts.queryClient.invalidateQueries({\n queryKey,\n });\n\n const isLastAttempt = attempt >= maxAttempts - 1;\n if (isLastAttempt) {\n // Report exhausted polls so Sentry can inform remote-flag / default\n // poll-limit tuning when indexing never finishes in time.\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: still processing after ${maxAttempts} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2ProcessingPollExhausted';\n this.messenger.captureException?.(multipleAttemptsError);\n return;\n }\n\n await delay(pollInterval);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsControllerV2.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;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ACF,qBAAqB,CAAC,IAAI,GAAG,wCAAwC,CAAC;YACtE,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,CAAC;YACzD,OAAO;QACT,CAAC;QAED,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query.js';\nimport type { DeFiBalancesQuery } from './build-defi-balances-query.js';\nimport { getProcessingPollConfig } from './defi-controller-v2-feature-flag.js';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types.js';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6.js';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6.js';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\n/**\n * @param ms - Milliseconds to wait.\n * @returns A promise that resolves after `ms`.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n | AccountTreeControllerGetAccountsFromSelectedAccountGroupAction\n | RemoteFeatureFlagControllerGetStateAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache on the first attempt (e.g.\n * pull-to-refresh); later processing polls always bypass the cache.\n *\n * When the API reports account IDs in the response-level\n * `processingDefiPositions` array, this controller polls until indexing\n * finishes or the attempt limit is reached, and only then processes and writes\n * state — responses that still list processing accounts leave prior state\n * untouched. Concurrent calls for the same selected accounts and `vsCurrency`\n * share one in-flight promise so the UI can treat the pending promise as a\n * loading signal. Calls for a different selection or fiat currency start their\n * own fetch and leave any prior poll running, so switching back can join an\n * in-flight fetch for that group and currency.\n *\n * Processing-poll `maxAttempts` / `pollInterval` are read via\n * {@link getProcessingPollConfig} from the `defiControllerV2` remote feature\n * flag (`RemoteFeatureFlagController:getState`), falling back to built-in\n * defaults when unset or invalid. Clients must delegate that action to this\n * controller's messenger.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * In-flight fetches keyed by selected DeFi-queryable account IDs plus\n * `vsCurrency`. Concurrent callers for the same selection and currency share\n * a promise; different selections or fiat currencies keep independent\n * fetches so fast switching can join an earlier matching poll.\n */\n readonly #inFlightFetches = new Map<string, Promise<void>>();\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. State is updated\n * only when the response lists no accounts in its `processingDefiPositions`\n * array; each resolved account then has its state replaced (other accounts\n * stay). While any account is still indexing, prior state is kept and the\n * method polls (invalidating the balances cache between attempts) until no\n * accounts are processing, the attempt limit is reached, or a request fails.\n * Concurrent calls for the same selected accounts and `vsCurrency` share one\n * in-flight promise; calls for a different selection or fiat currency start\n * a new fetch and leave prior polls running so a later switch back can join\n * them. When a successful ready response required more than one attempt, or\n * when polling hits the attempt limit while still processing, reports to\n * Sentry via `messenger.captureException` (error names\n * `DeFiPositionsV2FetchAttempts` /\n * `DeFiPositionsV2ProcessingPollExhausted`) so poll limits can be tuned.\n * No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache on the\n * first attempt (e.g. pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache on the\n * first attempt and fetch immediately.\n * @returns Resolves when the fetch (and any processing polls) finish.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n const query = buildDeFiBalancesQuery(selectedAccounts);\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n // Include vsCurrency so a fiat change does not join a poll priced in the\n // previous currency (TanStack also keys the balances cache on vsCurrency).\n const inFlightKey = [\n ...[...query.internalAccountIdByCaip.keys()].sort(),\n vsCurrency,\n ].join('\\0');\n\n const existing = this.#inFlightFetches.get(inFlightKey);\n if (existing) {\n await existing;\n return;\n }\n\n // Same-key callers join this promise instead of replacing it, so cleanup\n // can always delete without checking identity.\n const fetchPromise = this.#fetchDeFiPositions(\n options,\n query,\n vsCurrency,\n ).finally(() => {\n this.#inFlightFetches.delete(inFlightKey);\n });\n this.#inFlightFetches.set(inFlightKey, fetchPromise);\n\n await fetchPromise;\n }\n\n async #fetchDeFiPositions(\n options: { forceRefresh?: boolean } | undefined,\n { networks, internalAccountIdByCaip }: DeFiBalancesQuery,\n vsCurrency: string,\n ): Promise<void> {\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const queryOptions = {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: options?.forceRefresh === true,\n includePrices: true,\n vsCurrency,\n };\n\n // Resolve once per fetch so a mid-poll remote-flag change cannot stretch\n // or shrink this poll sequence inconsistently.\n const { maxAttempts, pollInterval } = getProcessingPollConfig(\n this.messenger,\n );\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n // First attempt respects forceRefresh; later polls always bypass cache\n // so we do not spin on a stale processing snapshot.\n const fetchOptions = {\n ...(options?.forceRefresh || attempt > 0 ? { staleTime: 0 } : {}),\n };\n\n let response;\n try {\n response = await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n } catch (error) {\n // Soft-fail so prior state stays and the in-flight promise settles.\n console.error('Failed to fetch DeFi positions', error);\n return;\n }\n\n const stillProcessing =\n (response.processingDefiPositions?.length ?? 0) > 0;\n\n // Only process and write when no account is still indexing, so a\n // partial response (whose DeFi rows for processing accounts are\n // omitted) cannot clear or overwrite positions for those accounts.\n if (!stillProcessing) {\n const positionsByAccount = groupDeFiPositionsV6(\n response,\n internalAccountIdByCaip,\n );\n\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n\n // Report how many attempts were needed (only when polling was\n // required) so Sentry can inform remote-flag / default poll-limit\n // tuning without flooding on first-try successes.\n const attemptsTaken = attempt + 1;\n if (attemptsTaken > 1) {\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: positions ready after ${attemptsTaken} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2FetchAttempts';\n this.messenger.captureException?.(multipleAttemptsError);\n }\n return;\n }\n\n const { queryKey } =\n this.#apiClient.accounts.getV6MultiAccountBalancesQueryOptions(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n await this.#apiClient.accounts.queryClient.invalidateQueries({\n queryKey,\n });\n\n const isLastAttempt = attempt >= maxAttempts - 1;\n if (isLastAttempt) {\n // Report exhausted polls so Sentry can inform remote-flag / default\n // poll-limit tuning when indexing never finishes in time.\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: still processing after ${maxAttempts} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2ProcessingPollExhausted';\n this.messenger.captureException?.(multipleAttemptsError);\n return;\n }\n\n await delay(pollInterval);\n }\n }\n}\n"]}
@@ -158,7 +158,7 @@ _DeFiPositionsControllerV2_apiClient = new WeakMap(), _DeFiPositionsControllerV2
158
158
  const queryOptions = {
159
159
  networks,
160
160
  includeDeFiBalances: true,
161
- forceFetchDeFiPositions: true,
161
+ forceFetchDeFiPositions: options?.forceRefresh === true,
162
162
  includePrices: true,
163
163
  vsCurrency,
164
164
  };
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAU3D,OAAO,EAAE,sBAAsB,EAAE,wCAAuC;AAExE,OAAO,EAAE,uBAAuB,EAAE,8CAA6C;AAG/E,OAAO,EAAE,oBAAoB,EAAE,sCAAqC;AAEpE,MAAM,cAAc,GAAG,2BAA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,CAAC;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query.js';\nimport type { DeFiBalancesQuery } from './build-defi-balances-query.js';\nimport { getProcessingPollConfig } from './defi-controller-v2-feature-flag.js';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types.js';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6.js';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6.js';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\n/**\n * @param ms - Milliseconds to wait.\n * @returns A promise that resolves after `ms`.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n | AccountTreeControllerGetAccountsFromSelectedAccountGroupAction\n | RemoteFeatureFlagControllerGetStateAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache on the first attempt (e.g.\n * pull-to-refresh); later processing polls always bypass the cache.\n *\n * When the API reports account IDs in the response-level\n * `processingDefiPositions` array, this controller polls until indexing\n * finishes or the attempt limit is reached, and only then processes and writes\n * state — responses that still list processing accounts leave prior state\n * untouched. Concurrent calls for the same selected accounts and `vsCurrency`\n * share one in-flight promise so the UI can treat the pending promise as a\n * loading signal. Calls for a different selection or fiat currency start their\n * own fetch and leave any prior poll running, so switching back can join an\n * in-flight fetch for that group and currency.\n *\n * Processing-poll `maxAttempts` / `pollInterval` are read via\n * {@link getProcessingPollConfig} from the `defiControllerV2` remote feature\n * flag (`RemoteFeatureFlagController:getState`), falling back to built-in\n * defaults when unset or invalid. Clients must delegate that action to this\n * controller's messenger.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * In-flight fetches keyed by selected DeFi-queryable account IDs plus\n * `vsCurrency`. Concurrent callers for the same selection and currency share\n * a promise; different selections or fiat currencies keep independent\n * fetches so fast switching can join an earlier matching poll.\n */\n readonly #inFlightFetches = new Map<string, Promise<void>>();\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. State is updated\n * only when the response lists no accounts in its `processingDefiPositions`\n * array; each resolved account then has its state replaced (other accounts\n * stay). While any account is still indexing, prior state is kept and the\n * method polls (invalidating the balances cache between attempts) until no\n * accounts are processing, the attempt limit is reached, or a request fails.\n * Concurrent calls for the same selected accounts and `vsCurrency` share one\n * in-flight promise; calls for a different selection or fiat currency start\n * a new fetch and leave prior polls running so a later switch back can join\n * them. When a successful ready response required more than one attempt, or\n * when polling hits the attempt limit while still processing, reports to\n * Sentry via `messenger.captureException` (error names\n * `DeFiPositionsV2FetchAttempts` /\n * `DeFiPositionsV2ProcessingPollExhausted`) so poll limits can be tuned.\n * No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache on the\n * first attempt (e.g. pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache on the\n * first attempt and fetch immediately.\n * @returns Resolves when the fetch (and any processing polls) finish.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n const query = buildDeFiBalancesQuery(selectedAccounts);\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n // Include vsCurrency so a fiat change does not join a poll priced in the\n // previous currency (TanStack also keys the balances cache on vsCurrency).\n const inFlightKey = [\n ...[...query.internalAccountIdByCaip.keys()].sort(),\n vsCurrency,\n ].join('\\0');\n\n const existing = this.#inFlightFetches.get(inFlightKey);\n if (existing) {\n await existing;\n return;\n }\n\n // Same-key callers join this promise instead of replacing it, so cleanup\n // can always delete without checking identity.\n const fetchPromise = this.#fetchDeFiPositions(\n options,\n query,\n vsCurrency,\n ).finally(() => {\n this.#inFlightFetches.delete(inFlightKey);\n });\n this.#inFlightFetches.set(inFlightKey, fetchPromise);\n\n await fetchPromise;\n }\n\n async #fetchDeFiPositions(\n options: { forceRefresh?: boolean } | undefined,\n { networks, internalAccountIdByCaip }: DeFiBalancesQuery,\n vsCurrency: string,\n ): Promise<void> {\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const queryOptions = {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: true,\n includePrices: true,\n vsCurrency,\n };\n\n // Resolve once per fetch so a mid-poll remote-flag change cannot stretch\n // or shrink this poll sequence inconsistently.\n const { maxAttempts, pollInterval } = getProcessingPollConfig(\n this.messenger,\n );\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n // First attempt respects forceRefresh; later polls always bypass cache\n // so we do not spin on a stale processing snapshot.\n const fetchOptions = {\n ...(options?.forceRefresh || attempt > 0 ? { staleTime: 0 } : {}),\n };\n\n let response;\n try {\n response = await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n } catch (error) {\n // Soft-fail so prior state stays and the in-flight promise settles.\n console.error('Failed to fetch DeFi positions', error);\n return;\n }\n\n const stillProcessing =\n (response.processingDefiPositions?.length ?? 0) > 0;\n\n // Only process and write when no account is still indexing, so a\n // partial response (whose DeFi rows for processing accounts are\n // omitted) cannot clear or overwrite positions for those accounts.\n if (!stillProcessing) {\n const positionsByAccount = groupDeFiPositionsV6(\n response,\n internalAccountIdByCaip,\n );\n\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n\n // Report how many attempts were needed (only when polling was\n // required) so Sentry can inform remote-flag / default poll-limit\n // tuning without flooding on first-try successes.\n const attemptsTaken = attempt + 1;\n if (attemptsTaken > 1) {\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: positions ready after ${attemptsTaken} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2FetchAttempts';\n this.messenger.captureException?.(multipleAttemptsError);\n }\n return;\n }\n\n const { queryKey } =\n this.#apiClient.accounts.getV6MultiAccountBalancesQueryOptions(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n await this.#apiClient.accounts.queryClient.invalidateQueries({\n queryKey,\n });\n\n const isLastAttempt = attempt >= maxAttempts - 1;\n if (isLastAttempt) {\n // Report exhausted polls so Sentry can inform remote-flag / default\n // poll-limit tuning when indexing never finishes in time.\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: still processing after ${maxAttempts} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2ProcessingPollExhausted';\n this.messenger.captureException?.(multipleAttemptsError);\n return;\n }\n\n await delay(pollInterval);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsControllerV2.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAU3D,OAAO,EAAE,sBAAsB,EAAE,wCAAuC;AAExE,OAAO,EAAE,uBAAuB,EAAE,8CAA6C;AAG/E,OAAO,EAAE,oBAAoB,EAAE,sCAAqC;AAEpE,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,yBAAyB,GAAG,CAAC,oBAAoB,CAAU,CAAC;AAElE;;;GAGG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC;AAmBD,MAAM,kBAAkB,GAAkD;IACxE,kBAAkB,EAAE;QAClB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,CAAC,MA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AAM,qBAAqB,GAAG,IAAI,KAAK,CACrC,oDAAoD,aAAa,aAAa,CAC/E,CAAC;gBACF,qBAAqB,CAAC,IAAI,GAAG,8BAA8B,CAAC;gBAC5D,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,CAAC;YAC3D,CAAC;YACD,OAAO;QACT,CAAC;QAED,MAAM,EAAE,QAAQ,EAAE,GAChB,uBAAA,IAAI,4CAAW,CAAC,QAAQ,CAAC,qCAAqC,CAC5D,UAAU,EACV,YAAY,EACZ,YAAY,CACb,CAAC;QACJ,MAAM,uBAAA,IAAI,4CAAW,CAAC,QAAQ,CAAC,WAAW,CAAC,iBAAiB,CAAC;YAC3D,QAAQ;SACT,CAAC,CAAC;QAEH,MAAM,aAAa,GAAG,OAAO,IAAI,WAAW,GAAG,CAAC,CAAC;QACjD,IAAI,aAAa,EAAE,CAAC;YAClB,oEAAoE;YACpE,0DAA0D;YAC1D,MAAM,qBAAqB,GAAG,IAAI,KAAK,CACrC,qDAAqD,WAAW,aAAa,CAC9E,CAAC;YACF,qBAAqB,CAAC,IAAI,GAAG,wCAAwC,CAAC;YACtE,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC,qBAAqB,CAAC,CAAC;YACzD,OAAO;QACT,CAAC;QAED,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query.js';\nimport type { DeFiBalancesQuery } from './build-defi-balances-query.js';\nimport { getProcessingPollConfig } from './defi-controller-v2-feature-flag.js';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types.js';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6.js';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6.js';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\n/**\n * @param ms - Milliseconds to wait.\n * @returns A promise that resolves after `ms`.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n | AccountTreeControllerGetAccountsFromSelectedAccountGroupAction\n | RemoteFeatureFlagControllerGetStateAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache on the first attempt (e.g.\n * pull-to-refresh); later processing polls always bypass the cache.\n *\n * When the API reports account IDs in the response-level\n * `processingDefiPositions` array, this controller polls until indexing\n * finishes or the attempt limit is reached, and only then processes and writes\n * state — responses that still list processing accounts leave prior state\n * untouched. Concurrent calls for the same selected accounts and `vsCurrency`\n * share one in-flight promise so the UI can treat the pending promise as a\n * loading signal. Calls for a different selection or fiat currency start their\n * own fetch and leave any prior poll running, so switching back can join an\n * in-flight fetch for that group and currency.\n *\n * Processing-poll `maxAttempts` / `pollInterval` are read via\n * {@link getProcessingPollConfig} from the `defiControllerV2` remote feature\n * flag (`RemoteFeatureFlagController:getState`), falling back to built-in\n * defaults when unset or invalid. Clients must delegate that action to this\n * controller's messenger.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * In-flight fetches keyed by selected DeFi-queryable account IDs plus\n * `vsCurrency`. Concurrent callers for the same selection and currency share\n * a promise; different selections or fiat currencies keep independent\n * fetches so fast switching can join an earlier matching poll.\n */\n readonly #inFlightFetches = new Map<string, Promise<void>>();\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. State is updated\n * only when the response lists no accounts in its `processingDefiPositions`\n * array; each resolved account then has its state replaced (other accounts\n * stay). While any account is still indexing, prior state is kept and the\n * method polls (invalidating the balances cache between attempts) until no\n * accounts are processing, the attempt limit is reached, or a request fails.\n * Concurrent calls for the same selected accounts and `vsCurrency` share one\n * in-flight promise; calls for a different selection or fiat currency start\n * a new fetch and leave prior polls running so a later switch back can join\n * them. When a successful ready response required more than one attempt, or\n * when polling hits the attempt limit while still processing, reports to\n * Sentry via `messenger.captureException` (error names\n * `DeFiPositionsV2FetchAttempts` /\n * `DeFiPositionsV2ProcessingPollExhausted`) so poll limits can be tuned.\n * No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache on the\n * first attempt (e.g. pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache on the\n * first attempt and fetch immediately.\n * @returns Resolves when the fetch (and any processing polls) finish.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n const query = buildDeFiBalancesQuery(selectedAccounts);\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n // Include vsCurrency so a fiat change does not join a poll priced in the\n // previous currency (TanStack also keys the balances cache on vsCurrency).\n const inFlightKey = [\n ...[...query.internalAccountIdByCaip.keys()].sort(),\n vsCurrency,\n ].join('\\0');\n\n const existing = this.#inFlightFetches.get(inFlightKey);\n if (existing) {\n await existing;\n return;\n }\n\n // Same-key callers join this promise instead of replacing it, so cleanup\n // can always delete without checking identity.\n const fetchPromise = this.#fetchDeFiPositions(\n options,\n query,\n vsCurrency,\n ).finally(() => {\n this.#inFlightFetches.delete(inFlightKey);\n });\n this.#inFlightFetches.set(inFlightKey, fetchPromise);\n\n await fetchPromise;\n }\n\n async #fetchDeFiPositions(\n options: { forceRefresh?: boolean } | undefined,\n { networks, internalAccountIdByCaip }: DeFiBalancesQuery,\n vsCurrency: string,\n ): Promise<void> {\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const queryOptions = {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: options?.forceRefresh === true,\n includePrices: true,\n vsCurrency,\n };\n\n // Resolve once per fetch so a mid-poll remote-flag change cannot stretch\n // or shrink this poll sequence inconsistently.\n const { maxAttempts, pollInterval } = getProcessingPollConfig(\n this.messenger,\n );\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n // First attempt respects forceRefresh; later polls always bypass cache\n // so we do not spin on a stale processing snapshot.\n const fetchOptions = {\n ...(options?.forceRefresh || attempt > 0 ? { staleTime: 0 } : {}),\n };\n\n let response;\n try {\n response = await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n } catch (error) {\n // Soft-fail so prior state stays and the in-flight promise settles.\n console.error('Failed to fetch DeFi positions', error);\n return;\n }\n\n const stillProcessing =\n (response.processingDefiPositions?.length ?? 0) > 0;\n\n // Only process and write when no account is still indexing, so a\n // partial response (whose DeFi rows for processing accounts are\n // omitted) cannot clear or overwrite positions for those accounts.\n if (!stillProcessing) {\n const positionsByAccount = groupDeFiPositionsV6(\n response,\n internalAccountIdByCaip,\n );\n\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n\n // Report how many attempts were needed (only when polling was\n // required) so Sentry can inform remote-flag / default poll-limit\n // tuning without flooding on first-try successes.\n const attemptsTaken = attempt + 1;\n if (attemptsTaken > 1) {\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: positions ready after ${attemptsTaken} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2FetchAttempts';\n this.messenger.captureException?.(multipleAttemptsError);\n }\n return;\n }\n\n const { queryKey } =\n this.#apiClient.accounts.getV6MultiAccountBalancesQueryOptions(\n accountIds,\n queryOptions,\n fetchOptions,\n );\n await this.#apiClient.accounts.queryClient.invalidateQueries({\n queryKey,\n });\n\n const isLastAttempt = attempt >= maxAttempts - 1;\n if (isLastAttempt) {\n // Report exhausted polls so Sentry can inform remote-flag / default\n // poll-limit tuning when indexing never finishes in time.\n const multipleAttemptsError = new Error(\n `DeFiPositionsControllerV2: still processing after ${maxAttempts} attempt(s)`,\n );\n multipleAttemptsError.name = 'DeFiPositionsV2ProcessingPollExhausted';\n this.messenger.captureException?.(multipleAttemptsError);\n return;\n }\n\n await delay(pollInterval);\n }\n }\n}\n"]}
@@ -44,19 +44,19 @@ exports.getDefaultMultichainAssetsControllerState = getDefaultMultichainAssetsCo
44
44
  const assetsControllerMetadata = {
45
45
  assetsMetadata: {
46
46
  includeInStateLogs: false,
47
- persist: true,
47
+ persist: false,
48
48
  includeInDebugSnapshot: false,
49
49
  usedInUi: true,
50
50
  },
51
51
  accountsAssets: {
52
52
  includeInStateLogs: false,
53
- persist: true,
53
+ persist: false,
54
54
  includeInDebugSnapshot: false,
55
55
  usedInUi: true,
56
56
  },
57
57
  allIgnoredAssets: {
58
58
  includeInStateLogs: false,
59
- persist: true,
59
+ persist: false,
60
60
  includeInDebugSnapshot: false,
61
61
  usedInUi: true,
62
62
  },
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainAssetsController.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAWA,uDAAyD;AAOzD,uEAA8D;AAW9D,uEAAoE;AACpE,qEAA+E;AAM/E,uDAAoD;AACpD,2CAAsE;AAItE,6CAAoC;AAGpC,0CAA+C;AAE/C,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAsBpD;;;;;;;GAOG;AACH,SAAgB,yCAAyC;IACvD,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,gBAAgB,EAAE,EAAE,EAAE,CAAC;AAC1E,CAAC;AAFD,8FAEC;AAwED;;;;;;GAMG;AACH,MAAM,wBAAwB,GAC5B;IACE,cAAc,EAAE;QACd,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QAC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ListUpdatedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n AccountAssetListUpdatedEventPayload,\n CaipAssetType,\n CaipAssetTypeOrId,\n} from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n GetPermissions,\n PermissionConstraint,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n BulkTokenScanResponse,\n PhishingControllerBulkScanTokensAction,\n} from '@metamask/phishing-controller';\nimport { TokenScanResultType } from '@metamask/phishing-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n SnapControllerGetRunnableSnapsAction,\n SnapControllerHandleRequestAction,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { isCaipAssetType, parseCaipAssetType } from '@metamask/utils';\nimport type { CaipChainId } from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport type { MultichainAssetsControllerMethodActions } from './MultichainAssetsController-method-action-types.js';\nimport { getChainIdsCaveat } from './utils.js';\n\nconst controllerName = 'MultichainAssetsController';\n\nexport type MultichainAssetsControllerState = {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n allIgnoredAssets: { [account: string]: CaipAssetType[] };\n};\n\n// Represents the response of the asset snap's onAssetLookup handler\nexport type AssetMetadataResponse = {\n assets: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n};\n\nexport type MultichainAssetsControllerAccountAssetListUpdatedEvent = {\n type: `${typeof controllerName}:accountAssetListUpdated`;\n payload: AccountsControllerAccountAssetListUpdatedEvent['payload'];\n};\n\n/**\n * Constructs the default {@link MultichainAssetsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainAssetsController} state.\n */\nexport function getDefaultMultichainAssetsControllerState(): MultichainAssetsControllerState {\n return { accountsAssets: {}, assetsMetadata: {}, allIgnoredAssets: {} };\n}\n\n/**\n * Returns the state of the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsControllerState\n>;\n\n/**\n * Event emitted when the state of the {@link MultichainAssetsController} changes.\n */\nexport type MultichainAssetsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerActions =\n | MultichainAssetsControllerGetStateAction\n | MultichainAssetsControllerMethodActions;\n\n/**\n * Events emitted by {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerEvents =\n | MultichainAssetsControllerStateChangeEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | SnapControllerGetRunnableSnapsAction\n | SnapControllerHandleRequestAction\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction\n | PhishingControllerBulkScanTokensAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountAssetListUpdatedEvent;\n\n/**\n * Messenger type for the MultichainAssetsController.\n */\nexport type MultichainAssetsControllerMessenger = Messenger<\n typeof controllerName,\n MultichainAssetsControllerActions | AllowedActions,\n MultichainAssetsControllerEvents | AllowedEvents\n>;\n\n/**\n * {@link MultichainAssetsController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst assetsControllerMetadata: StateMetadata<MultichainAssetsControllerState> =\n {\n assetsMetadata: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n accountsAssets: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n allIgnoredAssets: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n };\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getAssetMetadata',\n 'ignoreAssets',\n 'addAssets',\n] as const;\n\n/** Phishing API allows at most this many token addresses per bulk scan request. */\nconst BLOCKAID_BULK_TOKEN_SCAN_BATCH_SIZE = 100;\n\n/**\n * Default interval for re-scanning stored SPL (`token:`) assets with Blockaid.\n * Once per day limits API load while still catching tokens reclassified after add.\n */\nconst DEFAULT_BLOCKAID_TOKEN_RESCAN_INTERVAL_MS = 24 * 60 * 60 * 1000;\n\ntype ChainTokenEntry = { asset: CaipAssetType; address: string };\n\ntype BulkTokenScanBatchOutcome =\n | {\n status: 'fulfilled';\n response: BulkTokenScanResponse;\n entries: ChainTokenEntry[];\n }\n | { status: 'rejected'; entries: ChainTokenEntry[] };\n\nexport class MultichainAssetsController extends StaticIntervalPollingController<null>()<\n typeof controllerName,\n MultichainAssetsControllerState,\n MultichainAssetsControllerMessenger\n> {\n // Mapping of CAIP-2 Chain ID to Asset Snaps.\n #snaps: Record<CaipChainId, Snap[]>;\n\n readonly #controllerOperationMutex = new Mutex();\n\n readonly #isDeprecated: () => boolean;\n\n constructor({\n messenger,\n state = {},\n blockaidTokenRescanInterval = DEFAULT_BLOCKAID_TOKEN_RESCAN_INTERVAL_MS,\n isDeprecated = (): boolean => false,\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n /** Blockaid re-scan interval (ms); default daily. `0` disables. */\n blockaidTokenRescanInterval?: number;\n isDeprecated?: () => boolean;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n this.#isDeprecated = isDeprecated;\n\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n } else if (blockaidTokenRescanInterval > 0) {\n this.setIntervalLength(blockaidTokenRescanInterval);\n this.startPolling(null);\n }\n\n this.messenger.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountRemoved',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => await this.#handleOnAccountRemovedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountAssetListUpdated',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);\n }\n\n /**\n * Clears all persisted `accountsAssets`, `assetsMetadata`, and\n * `allIgnoredAssets` so that no stale asset data remains in state.\n */\n #enforceDisabledState(): void {\n if (\n Object.keys(this.state.accountsAssets).length === 0 &&\n Object.keys(this.state.assetsMetadata).length === 0 &&\n Object.keys(this.state.allIgnoredAssets).length === 0\n ) {\n return;\n }\n this.update((state) => {\n state.accountsAssets = {};\n state.assetsMetadata = {};\n state.allIgnoredAssets = {};\n });\n }\n\n async _executePoll(_input: null): Promise<void> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n await this.#withControllerLock(async () => {\n const assetsByAccount: Record<\n string,\n { added: CaipAssetType[]; removed: CaipAssetType[] }\n > = {};\n\n for (const [accountId, assets] of Object.entries(\n this.state.accountsAssets,\n )) {\n const splTokens = assets.filter((asset) => {\n if (!isCaipAssetType(asset)) {\n return false;\n }\n try {\n return parseCaipAssetType(asset).assetNamespace === 'token';\n } catch {\n return false;\n }\n });\n\n if (splTokens.length === 0) {\n continue;\n }\n\n const malicious = await this.#findMaliciousTokensAmong(splTokens);\n if (malicious.length > 0) {\n this.ignoreAssets(malicious, accountId);\n assetsByAccount[accountId] = {\n added: [],\n removed: malicious,\n };\n }\n }\n\n if (Object.keys(assetsByAccount).length > 0) {\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: assetsByAccount,\n });\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n await this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n await this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Returns the metadata for the given asset\n *\n * @param asset - The asset to get metadata for\n * @returns The metadata for the asset or undefined if not found.\n */\n getAssetMetadata(asset: CaipAssetType): FungibleAssetMetadata | undefined {\n return this.state.assetsMetadata[asset];\n }\n\n /**\n * Ignores a batch of assets for a specific account.\n *\n * @param assetsToIgnore - Array of asset IDs to ignore.\n * @param accountId - The account ID to ignore assets for.\n */\n ignoreAssets(assetsToIgnore: CaipAssetType[], accountId: string): void {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n this.update((state) => {\n if (state.accountsAssets[accountId]) {\n state.accountsAssets[accountId] = state.accountsAssets[\n accountId\n ].filter((asset) => !assetsToIgnore.includes(asset));\n }\n\n if (!state.allIgnoredAssets[accountId]) {\n state.allIgnoredAssets[accountId] = [];\n }\n\n const newIgnoredAssets = assetsToIgnore.filter(\n (asset) => !state.allIgnoredAssets[accountId].includes(asset),\n );\n state.allIgnoredAssets[accountId].push(...newIgnoredAssets);\n });\n }\n\n /**\n * Adds multiple assets to the stored asset list for a specific account.\n * All assets must belong to the same chain.\n *\n * @param assetIds - Array of CAIP asset IDs to add (must be from same chain).\n * @param accountId - The account ID to add the assets to.\n * @returns The updated asset list for the account.\n * @throws Error if assets are from different chains.\n */\n async addAssets(\n assetIds: CaipAssetType[],\n accountId: string,\n ): Promise<CaipAssetType[]> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return [];\n }\n\n if (assetIds.length === 0) {\n return this.state.accountsAssets[accountId] || [];\n }\n\n // Validate that all assets are from the same chain\n const chainIds = new Set(\n assetIds.map((assetId) => parseCaipAssetType(assetId).chainId),\n );\n if (chainIds.size > 1) {\n throw new Error(\n `All assets must belong to the same chain. Found assets from chains: ${Array.from(chainIds).join(', ')}`,\n );\n }\n\n return this.#withControllerLock(async () => {\n // Refresh metadata for all assets\n await this.#refreshAssetsMetadata(assetIds);\n\n const addedAssets: CaipAssetType[] = [];\n\n this.update((state) => {\n // Initialize account assets if it doesn't exist\n if (!state.accountsAssets[accountId]) {\n state.accountsAssets[accountId] = [];\n }\n\n // Add assets if they don't already exist\n for (const assetId of assetIds) {\n if (!state.accountsAssets[accountId].includes(assetId)) {\n state.accountsAssets[accountId].push(assetId);\n addedAssets.push(assetId);\n }\n }\n\n // Remove from ignored list if they exist there (inline logic like EVM)\n if (state.allIgnoredAssets[accountId]) {\n state.allIgnoredAssets[accountId] = state.allIgnoredAssets[\n accountId\n ].filter((asset) => !assetIds.includes(asset));\n\n // Clean up empty arrays\n if (state.allIgnoredAssets[accountId].length === 0) {\n delete state.allIgnoredAssets[accountId];\n }\n }\n });\n\n // Publish event to notify other controllers (balances, rates) about the new assets\n if (addedAssets.length > 0) {\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: {\n [accountId]: {\n added: addedAssets,\n removed: [],\n },\n },\n });\n }\n\n return this.state.accountsAssets[accountId] || [];\n });\n }\n\n /**\n * Checks if an asset is ignored for a specific account.\n *\n * @param asset - The asset ID to check.\n * @param accountId - The account ID to check for.\n * @returns True if the asset is ignored, false otherwise.\n */\n #isAssetIgnored(asset: CaipAssetType, accountId: string): boolean {\n return this.state.allIgnoredAssets[accountId]?.includes(asset) ?? false;\n }\n\n /**\n * Function to update the assets list for an account\n *\n * @param event - The list of assets to update\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #handleAccountAssetListUpdated(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n this.#assertControllerMutexIsLocked();\n\n const assetsForMetadataRefresh = new Set<CaipAssetType>([]);\n const accountsAndAssetsToUpdate: AccountAssetListUpdatedEventPayload['assets'] =\n {};\n for (const [accountId, { added, removed }] of Object.entries(\n event.assets,\n )) {\n if (added.length > 0 || removed.length > 0) {\n const existing = this.state.accountsAssets[accountId] || [];\n\n // In case accountsAndAssetsToUpdate event is fired with \"added\" assets that already exist, we don't want to add them again\n // Also filter out ignored assets\n const preFilteredToBeAddedAssets = added.filter(\n (asset) =>\n !existing.includes(asset) &&\n isCaipAssetType(asset) &&\n !this.#isAssetIgnored(asset, accountId),\n );\n\n // Filter out tokens that cannot be verified or are flagged malicious\n const filteredToBeAddedAssets =\n await this.#filterBlockaidSpamTokensOnAdd(preFilteredToBeAddedAssets);\n\n // In case accountsAndAssetsToUpdate event is fired with \"removed\" assets that don't exist, we don't want to remove them\n const filteredToBeRemovedAssets = removed.filter(\n (asset) => existing.includes(asset) && isCaipAssetType(asset),\n );\n\n if (\n filteredToBeAddedAssets.length > 0 ||\n filteredToBeRemovedAssets.length > 0\n ) {\n accountsAndAssetsToUpdate[accountId] = {\n added: filteredToBeAddedAssets,\n removed: filteredToBeRemovedAssets,\n };\n }\n\n for (const asset of existing) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeAddedAssets) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeRemovedAssets) {\n assetsForMetadataRefresh.delete(asset);\n }\n }\n }\n\n this.update((state) => {\n for (const [accountId, { added, removed }] of Object.entries(\n accountsAndAssetsToUpdate,\n )) {\n const assets = new Set([\n ...(state.accountsAssets[accountId] || []),\n ...added,\n ]);\n for (const asset of removed) {\n assets.delete(asset);\n }\n\n state.accountsAssets[accountId] = Array.from(assets);\n }\n });\n\n // Trigger fetching metadata for new assets\n await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));\n\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: accountsAndAssetsToUpdate,\n });\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles changes when a new account has been added.\n *\n * @param account - The new account being added.\n */\n async #handleOnAccountAdded(account: InternalAccount): Promise<void> {\n if (!this.#isNonEvmAccount(account)) {\n // Nothing to do here for EVM accounts\n return;\n }\n this.#assertControllerMutexIsLocked();\n\n // Get assets list\n if (account.metadata.snap) {\n const allAssets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\n );\n const caipAssets = allAssets.filter(isCaipAssetType);\n const filteredCaip =\n await this.#filterBlockaidSpamTokensOnAdd(caipAssets);\n const filteredCaipSet = new Set(filteredCaip);\n const assets = allAssets.filter(\n (asset) => !isCaipAssetType(asset) || filteredCaipSet.has(asset),\n );\n await this.#refreshAssetsMetadata(assets);\n this.update((state) => {\n state.accountsAssets[account.id] = assets;\n });\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: {\n [account.id]: {\n added: assets,\n removed: [],\n },\n },\n });\n }\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The new account id being removed.\n */\n async #handleOnAccountRemovedEvent(accountId: string): Promise<void> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n this.update((state) => {\n if (state.accountsAssets[accountId]) {\n delete state.accountsAssets[accountId];\n }\n if (state.allIgnoredAssets[accountId]) {\n delete state.allIgnoredAssets[accountId];\n }\n // TODO: We are not deleting the assetsMetadata because we will soon make this controller extends StaticIntervalPollingController\n // and update all assetsMetadata once a day.\n });\n }\n\n /**\n * Refreshes the assets snaps and metadata for the given list of assets\n *\n * @param assets - The assets to refresh\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #refreshAssetsMetadata(assets: CaipAssetType[]) {\n this.#assertControllerMutexIsLocked();\n\n const assetsWithoutMetadata: CaipAssetType[] = assets.filter(\n (asset) => !this.state.assetsMetadata[asset],\n );\n\n // Call the snap to get the metadata\n if (assetsWithoutMetadata.length > 0) {\n // Check if for every asset in assetsWithoutMetadata there is a snap in snaps by chainId else call getAssetSnaps\n if (\n !assetsWithoutMetadata.every((asset: CaipAssetType) => {\n const { chainId } = parseCaipAssetType(asset);\n return Boolean(this.#getAssetSnapFor(chainId));\n })\n ) {\n this.#snaps = this.#getAssetSnaps();\n }\n await this.#updateAssetsMetadata(assetsWithoutMetadata);\n }\n }\n\n /**\n * Updates the assets metadata for the given list of assets\n *\n * @param assets - The assets to update\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #updateAssetsMetadata(assets: CaipAssetType[]) {\n // Creates a mapping of scope to their respective assets list.\n const assetsByScope: Record<CaipChainId, CaipAssetType[]> = {};\n for (const asset of assets) {\n const { chainId } = parseCaipAssetType(asset);\n if (!assetsByScope[chainId]) {\n assetsByScope[chainId] = [];\n }\n assetsByScope[chainId].push(asset);\n }\n\n let newMetadata: Record<CaipAssetType, FungibleAssetMetadata> = {};\n for (const chainId of Object.keys(assetsByScope) as CaipChainId[]) {\n const assetsForChain = assetsByScope[chainId];\n // Now fetch metadata from the associated asset Snaps:\n const snap = this.#getAssetSnapFor(chainId);\n if (snap) {\n const metadata = await this.#getAssetsMetadataFrom(\n assetsForChain,\n snap.id,\n );\n newMetadata = {\n ...newMetadata,\n ...(metadata?.assets ?? {}),\n };\n }\n }\n this.update((state) => {\n state.assetsMetadata = {\n ...this.state.assetsMetadata,\n ...newMetadata,\n };\n });\n }\n\n /**\n * Creates a mapping of CAIP-2 Chain ID to Asset Snaps.\n *\n * @returns A mapping of CAIP-2 Chain ID to Asset Snaps.\n */\n #getAssetSnaps(): Record<CaipChainId, Snap[]> {\n const snaps: Record<CaipChainId, Snap[]> = {};\n const allSnaps = this.#getAllSnaps();\n const allPermissions = allSnaps.map((snap) =>\n this.#getSnapsPermissions(snap.id),\n );\n\n for (const [index, permission] of allPermissions.entries()) {\n let scopes;\n for (const singlePermissionConstraint of Object.values(permission)) {\n scopes = getChainIdsCaveat(singlePermissionConstraint);\n if (!scopes) {\n continue;\n }\n for (const scope of scopes as CaipChainId[]) {\n if (!snaps[scope]) {\n snaps[scope] = [];\n }\n snaps[scope].push(allSnaps[index]);\n }\n }\n }\n return snaps;\n }\n\n /**\n * Returns the first asset snap for the given scope\n *\n * @param scope - The scope to get the asset snap for\n * @returns The asset snap for the given scope\n */\n #getAssetSnapFor(scope: CaipChainId): Snap | undefined {\n const allSnaps = this.#snaps[scope];\n // Pick only the first one, we ignore the other Snaps if there are multiple candidates for now.\n return allSnaps?.[0]; // Will be undefined if there's no Snaps candidate for this scope.\n }\n\n /**\n * Returns all the asset snaps\n *\n * @returns All the asset snaps\n */\n #getAllSnaps(): Snap[] {\n return this.messenger.call('SnapController:getRunnableSnaps');\n }\n\n /**\n * Returns the permissions for the given origin\n *\n * @param origin - The origin to get the permissions for\n * @returns The permissions for the given origin\n */\n #getSnapsPermissions(\n origin: string,\n ): SubjectPermissions<PermissionConstraint> {\n return this.messenger.call(\n 'PermissionController:getPermissions',\n origin,\n ) as SubjectPermissions<PermissionConstraint>;\n }\n\n /**\n * Returns the metadata for the given assets\n *\n * @param assets - The assets to get metadata for\n * @param snapId - The snap ID to get metadata from\n * @returns The metadata for the assets\n */\n async #getAssetsMetadataFrom(\n assets: CaipAssetType[],\n snapId: string,\n ): Promise<AssetMetadataResponse | undefined> {\n try {\n return (await this.messenger.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetsLookup,\n request: {\n jsonrpc: '2.0',\n method: 'onAssetLookup',\n params: {\n assets,\n },\n },\n })) as Promise<AssetMetadataResponse>;\n } catch (error) {\n // Ignore\n console.error(error);\n return undefined;\n }\n }\n\n /**\n * Groups `token:` CAIP assets by chain namespace for bulk scan.\n *\n * @param assets - CAIP assets to inspect.\n * @returns Map of chain namespace to token entries.\n */\n #groupTokenAssetsByChain(\n assets: CaipAssetType[],\n ): Record<string, ChainTokenEntry[]> {\n const tokensByChain: Record<string, ChainTokenEntry[]> = {};\n\n for (const asset of assets) {\n const { assetNamespace, assetReference, chain } =\n parseCaipAssetType(asset);\n\n if (assetNamespace === 'token') {\n const chainName = chain.namespace;\n if (!tokensByChain[chainName]) {\n tokensByChain[chainName] = [];\n }\n tokensByChain[chainName].push({ asset, address: assetReference });\n }\n }\n\n return tokensByChain;\n }\n\n async #runBatchedBulkTokenScans(\n chainName: string,\n tokenEntries: ChainTokenEntry[],\n ): Promise<BulkTokenScanBatchOutcome[]> {\n const batches: ChainTokenEntry[][] = [];\n for (\n let i = 0;\n i < tokenEntries.length;\n i += BLOCKAID_BULK_TOKEN_SCAN_BATCH_SIZE\n ) {\n batches.push(\n tokenEntries.slice(i, i + BLOCKAID_BULK_TOKEN_SCAN_BATCH_SIZE),\n );\n }\n\n const batchResults = await Promise.allSettled(\n batches.map((batch) =>\n this.messenger.call('PhishingController:bulkScanTokens', {\n chainId: chainName,\n tokens: batch.map((entry) => entry.address),\n }),\n ),\n );\n\n return batches.map((entries, index) => {\n const result = batchResults[index];\n if (result.status === 'fulfilled') {\n return {\n status: 'fulfilled' as const,\n response: result.value,\n entries,\n };\n }\n return { status: 'rejected' as const, entries };\n });\n }\n\n /**\n * Fail-open Blockaid filter for newly detected `token:` assets (native/other namespaces unchanged).\n *\n * @param assets - CAIP assets to filter.\n * @returns Filtered list, original order preserved.\n */\n async #filterBlockaidSpamTokensOnAdd(\n assets: CaipAssetType[],\n ): Promise<CaipAssetType[]> {\n const tokensByChain = this.#groupTokenAssetsByChain(assets);\n\n if (Object.keys(tokensByChain).length === 0) {\n return [...assets];\n }\n\n const rejectedAssets = new Set<CaipAssetType>();\n\n for (const [chainName, tokenEntries] of Object.entries(tokensByChain)) {\n const batchOutcomes = await this.#runBatchedBulkTokenScans(\n chainName,\n tokenEntries,\n );\n\n for (const outcome of batchOutcomes) {\n if (outcome.status === 'rejected') {\n // Fail-open: if API fails, allow all tokens in this batch through\n continue;\n }\n for (const entry of outcome.entries) {\n const scanned = outcome.response[entry.address];\n // Reject only if we have a definitive malicious result\n if (\n scanned?.result_type &&\n scanned.result_type === TokenScanResultType.Malicious\n ) {\n rejectedAssets.add(entry.asset);\n }\n }\n }\n }\n\n return assets.filter((asset) => !rejectedAssets.has(asset));\n }\n\n /**\n * SPL `token:` assets in state that Blockaid marks malicious (failed batches skipped).\n *\n * @param assets - CAIP `token:` assets to scan.\n * @returns Subset marked malicious.\n */\n async #findMaliciousTokensAmong(\n assets: CaipAssetType[],\n ): Promise<CaipAssetType[]> {\n const tokensByChain = this.#groupTokenAssetsByChain(assets);\n\n const maliciousAssets: CaipAssetType[] = [];\n\n for (const [chainName, tokenEntries] of Object.entries(tokensByChain)) {\n const batchOutcomes = await this.#runBatchedBulkTokenScans(\n chainName,\n tokenEntries,\n );\n\n for (const outcome of batchOutcomes) {\n if (outcome.status === 'rejected') {\n continue;\n }\n for (const entry of outcome.entries) {\n if (\n outcome.response[entry.address]?.result_type ===\n TokenScanResultType.Malicious\n ) {\n maliciousAssets.push(entry.asset);\n }\n }\n }\n }\n\n return maliciousAssets;\n }\n\n /**\n * Get assets list for an account\n *\n * @param accountId - AccountId to get assets for\n * @param snapId - Snap ID for the account\n * @returns list of assets\n */\n async #getAssetsList(\n accountId: string,\n snapId: string,\n ): Promise<CaipAssetTypeOrId[]> {\n return await this.#getClient(snapId).listAccountAssets(accountId);\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messenger.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(\n 'MultichainAssetsControllerError - Attempt to update state',\n );\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n"]}
1
+ {"version":3,"file":"MultichainAssetsController.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAWA,uDAAyD;AAOzD,uEAA8D;AAW9D,uEAAoE;AACpE,qEAA+E;AAM/E,uDAAoD;AACpD,2CAAsE;AAItE,6CAAoC;AAGpC,0CAA+C;AAE/C,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAsBpD;;;;;;;GAOG;AACH,SAAgB,yCAAyC;IACvD,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,gBAAgB,EAAE,EAAE,EAAE,CAAC;AAC1E,CAAC;AAFD,8FAEC;AAwED;;;;;;GAMG;AACH,MAAM,wBAAwB,GAC5B;IACE,cAAc,EAAE;QACd,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEJ,MAAM,yBAAyB,GAAG;IAChC,kBAAkB;IAClB,cAAc;IACd,WAAW;CACH,CAAC;AAEX,mFAAmF;AACnF,MAAM,mCAAmC,GAAG,GAAG,CAAC;AAEhD;;;GAGG;AACH,MAAM,yCAAyC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAYtE,MAAa,0BAA2B,SAAQ,IAAA,oDAA+B,GAI9E;IAQC,YAAY,EACV,SAA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AM,EAAE,MAAgB;YACxB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,yBAAW,CAAC,gBAAgB;YACrC,OAAO;SACR,CAAC,CAAkB;KACvB,CAAC,CAAC;AACL,CAAC;IASC,IAAI,CAAC,uBAAA,IAAI,4DAA0B,CAAC,QAAQ,EAAE,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;;;GAWG;AACH,KAAK,yDACH,QAA2C;IAE3C,OAAO,QAAQ,CAAC,uBAAA,IAAI,4DAA0B,EAAE,QAAQ,CAAC,CAAC;AAC5D,CAAC;AAGH;;;;;;;;GAQG;AACH,KAAK,UAAU,QAAQ,CACrB,KAAY,EACZ,QAA2C;IAE3C,MAAM,WAAW,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;IAE1C,IAAI,CAAC;QACH,OAAO,MAAM,QAAQ,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;IACzC,CAAC;YAAS,CAAC;QACT,WAAW,EAAE,CAAC;IAChB,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountAssetListUpdatedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n AccountAssetListUpdatedEventPayload,\n CaipAssetType,\n CaipAssetTypeOrId,\n} from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n GetPermissions,\n PermissionConstraint,\n SubjectPermissions,\n} from '@metamask/permission-controller';\nimport type {\n BulkTokenScanResponse,\n PhishingControllerBulkScanTokensAction,\n} from '@metamask/phishing-controller';\nimport { TokenScanResultType } from '@metamask/phishing-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n SnapControllerGetRunnableSnapsAction,\n SnapControllerHandleRequestAction,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { isCaipAssetType, parseCaipAssetType } from '@metamask/utils';\nimport type { CaipChainId } from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport type { MultichainAssetsControllerMethodActions } from './MultichainAssetsController-method-action-types.js';\nimport { getChainIdsCaveat } from './utils.js';\n\nconst controllerName = 'MultichainAssetsController';\n\nexport type MultichainAssetsControllerState = {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n allIgnoredAssets: { [account: string]: CaipAssetType[] };\n};\n\n// Represents the response of the asset snap's onAssetLookup handler\nexport type AssetMetadataResponse = {\n assets: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n};\n\nexport type MultichainAssetsControllerAccountAssetListUpdatedEvent = {\n type: `${typeof controllerName}:accountAssetListUpdated`;\n payload: AccountsControllerAccountAssetListUpdatedEvent['payload'];\n};\n\n/**\n * Constructs the default {@link MultichainAssetsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link MultichainAssetsController} state.\n */\nexport function getDefaultMultichainAssetsControllerState(): MultichainAssetsControllerState {\n return { accountsAssets: {}, assetsMetadata: {}, allIgnoredAssets: {} };\n}\n\n/**\n * Returns the state of the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsControllerState\n>;\n\n/**\n * Event emitted when the state of the {@link MultichainAssetsController} changes.\n */\nexport type MultichainAssetsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsControllerState\n >;\n\n/**\n * Actions exposed by the {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerActions =\n | MultichainAssetsControllerGetStateAction\n | MultichainAssetsControllerMethodActions;\n\n/**\n * Events emitted by {@link MultichainAssetsController}.\n */\nexport type MultichainAssetsControllerEvents =\n | MultichainAssetsControllerStateChangeEvent\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n\n/**\n * A function executed within a mutually exclusive lock, with\n * a mutex releaser in its option bag.\n *\n * @param releaseLock - A function to release the lock.\n */\ntype MutuallyExclusiveCallback<Result> = ({\n releaseLock,\n}: {\n releaseLock: MutexInterface.Releaser;\n}) => Promise<Result>;\n\n/**\n * Actions that this controller is allowed to call.\n */\ntype AllowedActions =\n | SnapControllerGetRunnableSnapsAction\n | SnapControllerHandleRequestAction\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction\n | PhishingControllerBulkScanTokensAction;\n\n/**\n * Events that this controller is allowed to subscribe.\n */\ntype AllowedEvents =\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | AccountsControllerAccountAssetListUpdatedEvent;\n\n/**\n * Messenger type for the MultichainAssetsController.\n */\nexport type MultichainAssetsControllerMessenger = Messenger<\n typeof controllerName,\n MultichainAssetsControllerActions | AllowedActions,\n MultichainAssetsControllerEvents | AllowedEvents\n>;\n\n/**\n * {@link MultichainAssetsController}'s metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst assetsControllerMetadata: StateMetadata<MultichainAssetsControllerState> =\n {\n assetsMetadata: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n accountsAssets: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n allIgnoredAssets: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n };\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getAssetMetadata',\n 'ignoreAssets',\n 'addAssets',\n] as const;\n\n/** Phishing API allows at most this many token addresses per bulk scan request. */\nconst BLOCKAID_BULK_TOKEN_SCAN_BATCH_SIZE = 100;\n\n/**\n * Default interval for re-scanning stored SPL (`token:`) assets with Blockaid.\n * Once per day limits API load while still catching tokens reclassified after add.\n */\nconst DEFAULT_BLOCKAID_TOKEN_RESCAN_INTERVAL_MS = 24 * 60 * 60 * 1000;\n\ntype ChainTokenEntry = { asset: CaipAssetType; address: string };\n\ntype BulkTokenScanBatchOutcome =\n | {\n status: 'fulfilled';\n response: BulkTokenScanResponse;\n entries: ChainTokenEntry[];\n }\n | { status: 'rejected'; entries: ChainTokenEntry[] };\n\nexport class MultichainAssetsController extends StaticIntervalPollingController<null>()<\n typeof controllerName,\n MultichainAssetsControllerState,\n MultichainAssetsControllerMessenger\n> {\n // Mapping of CAIP-2 Chain ID to Asset Snaps.\n #snaps: Record<CaipChainId, Snap[]>;\n\n readonly #controllerOperationMutex = new Mutex();\n\n readonly #isDeprecated: () => boolean;\n\n constructor({\n messenger,\n state = {},\n blockaidTokenRescanInterval = DEFAULT_BLOCKAID_TOKEN_RESCAN_INTERVAL_MS,\n isDeprecated = (): boolean => false,\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n /** Blockaid re-scan interval (ms); default daily. `0` disables. */\n blockaidTokenRescanInterval?: number;\n isDeprecated?: () => boolean;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n this.#isDeprecated = isDeprecated;\n\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n } else if (blockaidTokenRescanInterval > 0) {\n this.setIntervalLength(blockaidTokenRescanInterval);\n this.startPolling(null);\n }\n\n this.messenger.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountRemoved',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => await this.#handleOnAccountRemovedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountAssetListUpdated',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);\n }\n\n /**\n * Clears all persisted `accountsAssets`, `assetsMetadata`, and\n * `allIgnoredAssets` so that no stale asset data remains in state.\n */\n #enforceDisabledState(): void {\n if (\n Object.keys(this.state.accountsAssets).length === 0 &&\n Object.keys(this.state.assetsMetadata).length === 0 &&\n Object.keys(this.state.allIgnoredAssets).length === 0\n ) {\n return;\n }\n this.update((state) => {\n state.accountsAssets = {};\n state.assetsMetadata = {};\n state.allIgnoredAssets = {};\n });\n }\n\n async _executePoll(_input: null): Promise<void> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n await this.#withControllerLock(async () => {\n const assetsByAccount: Record<\n string,\n { added: CaipAssetType[]; removed: CaipAssetType[] }\n > = {};\n\n for (const [accountId, assets] of Object.entries(\n this.state.accountsAssets,\n )) {\n const splTokens = assets.filter((asset) => {\n if (!isCaipAssetType(asset)) {\n return false;\n }\n try {\n return parseCaipAssetType(asset).assetNamespace === 'token';\n } catch {\n return false;\n }\n });\n\n if (splTokens.length === 0) {\n continue;\n }\n\n const malicious = await this.#findMaliciousTokensAmong(splTokens);\n if (malicious.length > 0) {\n this.ignoreAssets(malicious, accountId);\n assetsByAccount[accountId] = {\n added: [],\n removed: malicious,\n };\n }\n }\n\n if (Object.keys(assetsByAccount).length > 0) {\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: assetsByAccount,\n });\n }\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n await this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n await this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Returns the metadata for the given asset\n *\n * @param asset - The asset to get metadata for\n * @returns The metadata for the asset or undefined if not found.\n */\n getAssetMetadata(asset: CaipAssetType): FungibleAssetMetadata | undefined {\n return this.state.assetsMetadata[asset];\n }\n\n /**\n * Ignores a batch of assets for a specific account.\n *\n * @param assetsToIgnore - Array of asset IDs to ignore.\n * @param accountId - The account ID to ignore assets for.\n */\n ignoreAssets(assetsToIgnore: CaipAssetType[], accountId: string): void {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n this.update((state) => {\n if (state.accountsAssets[accountId]) {\n state.accountsAssets[accountId] = state.accountsAssets[\n accountId\n ].filter((asset) => !assetsToIgnore.includes(asset));\n }\n\n if (!state.allIgnoredAssets[accountId]) {\n state.allIgnoredAssets[accountId] = [];\n }\n\n const newIgnoredAssets = assetsToIgnore.filter(\n (asset) => !state.allIgnoredAssets[accountId].includes(asset),\n );\n state.allIgnoredAssets[accountId].push(...newIgnoredAssets);\n });\n }\n\n /**\n * Adds multiple assets to the stored asset list for a specific account.\n * All assets must belong to the same chain.\n *\n * @param assetIds - Array of CAIP asset IDs to add (must be from same chain).\n * @param accountId - The account ID to add the assets to.\n * @returns The updated asset list for the account.\n * @throws Error if assets are from different chains.\n */\n async addAssets(\n assetIds: CaipAssetType[],\n accountId: string,\n ): Promise<CaipAssetType[]> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return [];\n }\n\n if (assetIds.length === 0) {\n return this.state.accountsAssets[accountId] || [];\n }\n\n // Validate that all assets are from the same chain\n const chainIds = new Set(\n assetIds.map((assetId) => parseCaipAssetType(assetId).chainId),\n );\n if (chainIds.size > 1) {\n throw new Error(\n `All assets must belong to the same chain. Found assets from chains: ${Array.from(chainIds).join(', ')}`,\n );\n }\n\n return this.#withControllerLock(async () => {\n // Refresh metadata for all assets\n await this.#refreshAssetsMetadata(assetIds);\n\n const addedAssets: CaipAssetType[] = [];\n\n this.update((state) => {\n // Initialize account assets if it doesn't exist\n if (!state.accountsAssets[accountId]) {\n state.accountsAssets[accountId] = [];\n }\n\n // Add assets if they don't already exist\n for (const assetId of assetIds) {\n if (!state.accountsAssets[accountId].includes(assetId)) {\n state.accountsAssets[accountId].push(assetId);\n addedAssets.push(assetId);\n }\n }\n\n // Remove from ignored list if they exist there (inline logic like EVM)\n if (state.allIgnoredAssets[accountId]) {\n state.allIgnoredAssets[accountId] = state.allIgnoredAssets[\n accountId\n ].filter((asset) => !assetIds.includes(asset));\n\n // Clean up empty arrays\n if (state.allIgnoredAssets[accountId].length === 0) {\n delete state.allIgnoredAssets[accountId];\n }\n }\n });\n\n // Publish event to notify other controllers (balances, rates) about the new assets\n if (addedAssets.length > 0) {\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: {\n [accountId]: {\n added: addedAssets,\n removed: [],\n },\n },\n });\n }\n\n return this.state.accountsAssets[accountId] || [];\n });\n }\n\n /**\n * Checks if an asset is ignored for a specific account.\n *\n * @param asset - The asset ID to check.\n * @param accountId - The account ID to check for.\n * @returns True if the asset is ignored, false otherwise.\n */\n #isAssetIgnored(asset: CaipAssetType, accountId: string): boolean {\n return this.state.allIgnoredAssets[accountId]?.includes(asset) ?? false;\n }\n\n /**\n * Function to update the assets list for an account\n *\n * @param event - The list of assets to update\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #handleAccountAssetListUpdated(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n this.#assertControllerMutexIsLocked();\n\n const assetsForMetadataRefresh = new Set<CaipAssetType>([]);\n const accountsAndAssetsToUpdate: AccountAssetListUpdatedEventPayload['assets'] =\n {};\n for (const [accountId, { added, removed }] of Object.entries(\n event.assets,\n )) {\n if (added.length > 0 || removed.length > 0) {\n const existing = this.state.accountsAssets[accountId] || [];\n\n // In case accountsAndAssetsToUpdate event is fired with \"added\" assets that already exist, we don't want to add them again\n // Also filter out ignored assets\n const preFilteredToBeAddedAssets = added.filter(\n (asset) =>\n !existing.includes(asset) &&\n isCaipAssetType(asset) &&\n !this.#isAssetIgnored(asset, accountId),\n );\n\n // Filter out tokens that cannot be verified or are flagged malicious\n const filteredToBeAddedAssets =\n await this.#filterBlockaidSpamTokensOnAdd(preFilteredToBeAddedAssets);\n\n // In case accountsAndAssetsToUpdate event is fired with \"removed\" assets that don't exist, we don't want to remove them\n const filteredToBeRemovedAssets = removed.filter(\n (asset) => existing.includes(asset) && isCaipAssetType(asset),\n );\n\n if (\n filteredToBeAddedAssets.length > 0 ||\n filteredToBeRemovedAssets.length > 0\n ) {\n accountsAndAssetsToUpdate[accountId] = {\n added: filteredToBeAddedAssets,\n removed: filteredToBeRemovedAssets,\n };\n }\n\n for (const asset of existing) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeAddedAssets) {\n assetsForMetadataRefresh.add(asset);\n }\n for (const asset of filteredToBeRemovedAssets) {\n assetsForMetadataRefresh.delete(asset);\n }\n }\n }\n\n this.update((state) => {\n for (const [accountId, { added, removed }] of Object.entries(\n accountsAndAssetsToUpdate,\n )) {\n const assets = new Set([\n ...(state.accountsAssets[accountId] || []),\n ...added,\n ]);\n for (const asset of removed) {\n assets.delete(asset);\n }\n\n state.accountsAssets[accountId] = Array.from(assets);\n }\n });\n\n // Trigger fetching metadata for new assets\n await this.#refreshAssetsMetadata(Array.from(assetsForMetadataRefresh));\n\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: accountsAndAssetsToUpdate,\n });\n }\n\n /**\n * Checks for non-EVM accounts.\n *\n * @param account - The new account to be checked.\n * @returns True if the account is a non-EVM account, false otherwise.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) &&\n // Non-EVM accounts are backed by a Snap for now\n account.metadata.snap !== undefined\n );\n }\n\n /**\n * Handles changes when a new account has been added.\n *\n * @param account - The new account being added.\n */\n async #handleOnAccountAdded(account: InternalAccount): Promise<void> {\n if (!this.#isNonEvmAccount(account)) {\n // Nothing to do here for EVM accounts\n return;\n }\n this.#assertControllerMutexIsLocked();\n\n // Get assets list\n if (account.metadata.snap) {\n const allAssets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\n );\n const caipAssets = allAssets.filter(isCaipAssetType);\n const filteredCaip =\n await this.#filterBlockaidSpamTokensOnAdd(caipAssets);\n const filteredCaipSet = new Set(filteredCaip);\n const assets = allAssets.filter(\n (asset) => !isCaipAssetType(asset) || filteredCaipSet.has(asset),\n );\n await this.#refreshAssetsMetadata(assets);\n this.update((state) => {\n state.accountsAssets[account.id] = assets;\n });\n this.messenger.publish(`${controllerName}:accountAssetListUpdated`, {\n assets: {\n [account.id]: {\n added: assets,\n removed: [],\n },\n },\n });\n }\n }\n\n /**\n * Handles changes when a new account has been removed.\n *\n * @param accountId - The new account id being removed.\n */\n async #handleOnAccountRemovedEvent(accountId: string): Promise<void> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n this.update((state) => {\n if (state.accountsAssets[accountId]) {\n delete state.accountsAssets[accountId];\n }\n if (state.allIgnoredAssets[accountId]) {\n delete state.allIgnoredAssets[accountId];\n }\n // TODO: We are not deleting the assetsMetadata because we will soon make this controller extends StaticIntervalPollingController\n // and update all assetsMetadata once a day.\n });\n }\n\n /**\n * Refreshes the assets snaps and metadata for the given list of assets\n *\n * @param assets - The assets to refresh\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #refreshAssetsMetadata(assets: CaipAssetType[]) {\n this.#assertControllerMutexIsLocked();\n\n const assetsWithoutMetadata: CaipAssetType[] = assets.filter(\n (asset) => !this.state.assetsMetadata[asset],\n );\n\n // Call the snap to get the metadata\n if (assetsWithoutMetadata.length > 0) {\n // Check if for every asset in assetsWithoutMetadata there is a snap in snaps by chainId else call getAssetSnaps\n if (\n !assetsWithoutMetadata.every((asset: CaipAssetType) => {\n const { chainId } = parseCaipAssetType(asset);\n return Boolean(this.#getAssetSnapFor(chainId));\n })\n ) {\n this.#snaps = this.#getAssetSnaps();\n }\n await this.#updateAssetsMetadata(assetsWithoutMetadata);\n }\n }\n\n /**\n * Updates the assets metadata for the given list of assets\n *\n * @param assets - The assets to update\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n async #updateAssetsMetadata(assets: CaipAssetType[]) {\n // Creates a mapping of scope to their respective assets list.\n const assetsByScope: Record<CaipChainId, CaipAssetType[]> = {};\n for (const asset of assets) {\n const { chainId } = parseCaipAssetType(asset);\n if (!assetsByScope[chainId]) {\n assetsByScope[chainId] = [];\n }\n assetsByScope[chainId].push(asset);\n }\n\n let newMetadata: Record<CaipAssetType, FungibleAssetMetadata> = {};\n for (const chainId of Object.keys(assetsByScope) as CaipChainId[]) {\n const assetsForChain = assetsByScope[chainId];\n // Now fetch metadata from the associated asset Snaps:\n const snap = this.#getAssetSnapFor(chainId);\n if (snap) {\n const metadata = await this.#getAssetsMetadataFrom(\n assetsForChain,\n snap.id,\n );\n newMetadata = {\n ...newMetadata,\n ...(metadata?.assets ?? {}),\n };\n }\n }\n this.update((state) => {\n state.assetsMetadata = {\n ...this.state.assetsMetadata,\n ...newMetadata,\n };\n });\n }\n\n /**\n * Creates a mapping of CAIP-2 Chain ID to Asset Snaps.\n *\n * @returns A mapping of CAIP-2 Chain ID to Asset Snaps.\n */\n #getAssetSnaps(): Record<CaipChainId, Snap[]> {\n const snaps: Record<CaipChainId, Snap[]> = {};\n const allSnaps = this.#getAllSnaps();\n const allPermissions = allSnaps.map((snap) =>\n this.#getSnapsPermissions(snap.id),\n );\n\n for (const [index, permission] of allPermissions.entries()) {\n let scopes;\n for (const singlePermissionConstraint of Object.values(permission)) {\n scopes = getChainIdsCaveat(singlePermissionConstraint);\n if (!scopes) {\n continue;\n }\n for (const scope of scopes as CaipChainId[]) {\n if (!snaps[scope]) {\n snaps[scope] = [];\n }\n snaps[scope].push(allSnaps[index]);\n }\n }\n }\n return snaps;\n }\n\n /**\n * Returns the first asset snap for the given scope\n *\n * @param scope - The scope to get the asset snap for\n * @returns The asset snap for the given scope\n */\n #getAssetSnapFor(scope: CaipChainId): Snap | undefined {\n const allSnaps = this.#snaps[scope];\n // Pick only the first one, we ignore the other Snaps if there are multiple candidates for now.\n return allSnaps?.[0]; // Will be undefined if there's no Snaps candidate for this scope.\n }\n\n /**\n * Returns all the asset snaps\n *\n * @returns All the asset snaps\n */\n #getAllSnaps(): Snap[] {\n return this.messenger.call('SnapController:getRunnableSnaps');\n }\n\n /**\n * Returns the permissions for the given origin\n *\n * @param origin - The origin to get the permissions for\n * @returns The permissions for the given origin\n */\n #getSnapsPermissions(\n origin: string,\n ): SubjectPermissions<PermissionConstraint> {\n return this.messenger.call(\n 'PermissionController:getPermissions',\n origin,\n ) as SubjectPermissions<PermissionConstraint>;\n }\n\n /**\n * Returns the metadata for the given assets\n *\n * @param assets - The assets to get metadata for\n * @param snapId - The snap ID to get metadata from\n * @returns The metadata for the assets\n */\n async #getAssetsMetadataFrom(\n assets: CaipAssetType[],\n snapId: string,\n ): Promise<AssetMetadataResponse | undefined> {\n try {\n return (await this.messenger.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetsLookup,\n request: {\n jsonrpc: '2.0',\n method: 'onAssetLookup',\n params: {\n assets,\n },\n },\n })) as Promise<AssetMetadataResponse>;\n } catch (error) {\n // Ignore\n console.error(error);\n return undefined;\n }\n }\n\n /**\n * Groups `token:` CAIP assets by chain namespace for bulk scan.\n *\n * @param assets - CAIP assets to inspect.\n * @returns Map of chain namespace to token entries.\n */\n #groupTokenAssetsByChain(\n assets: CaipAssetType[],\n ): Record<string, ChainTokenEntry[]> {\n const tokensByChain: Record<string, ChainTokenEntry[]> = {};\n\n for (const asset of assets) {\n const { assetNamespace, assetReference, chain } =\n parseCaipAssetType(asset);\n\n if (assetNamespace === 'token') {\n const chainName = chain.namespace;\n if (!tokensByChain[chainName]) {\n tokensByChain[chainName] = [];\n }\n tokensByChain[chainName].push({ asset, address: assetReference });\n }\n }\n\n return tokensByChain;\n }\n\n async #runBatchedBulkTokenScans(\n chainName: string,\n tokenEntries: ChainTokenEntry[],\n ): Promise<BulkTokenScanBatchOutcome[]> {\n const batches: ChainTokenEntry[][] = [];\n for (\n let i = 0;\n i < tokenEntries.length;\n i += BLOCKAID_BULK_TOKEN_SCAN_BATCH_SIZE\n ) {\n batches.push(\n tokenEntries.slice(i, i + BLOCKAID_BULK_TOKEN_SCAN_BATCH_SIZE),\n );\n }\n\n const batchResults = await Promise.allSettled(\n batches.map((batch) =>\n this.messenger.call('PhishingController:bulkScanTokens', {\n chainId: chainName,\n tokens: batch.map((entry) => entry.address),\n }),\n ),\n );\n\n return batches.map((entries, index) => {\n const result = batchResults[index];\n if (result.status === 'fulfilled') {\n return {\n status: 'fulfilled' as const,\n response: result.value,\n entries,\n };\n }\n return { status: 'rejected' as const, entries };\n });\n }\n\n /**\n * Fail-open Blockaid filter for newly detected `token:` assets (native/other namespaces unchanged).\n *\n * @param assets - CAIP assets to filter.\n * @returns Filtered list, original order preserved.\n */\n async #filterBlockaidSpamTokensOnAdd(\n assets: CaipAssetType[],\n ): Promise<CaipAssetType[]> {\n const tokensByChain = this.#groupTokenAssetsByChain(assets);\n\n if (Object.keys(tokensByChain).length === 0) {\n return [...assets];\n }\n\n const rejectedAssets = new Set<CaipAssetType>();\n\n for (const [chainName, tokenEntries] of Object.entries(tokensByChain)) {\n const batchOutcomes = await this.#runBatchedBulkTokenScans(\n chainName,\n tokenEntries,\n );\n\n for (const outcome of batchOutcomes) {\n if (outcome.status === 'rejected') {\n // Fail-open: if API fails, allow all tokens in this batch through\n continue;\n }\n for (const entry of outcome.entries) {\n const scanned = outcome.response[entry.address];\n // Reject only if we have a definitive malicious result\n if (\n scanned?.result_type &&\n scanned.result_type === TokenScanResultType.Malicious\n ) {\n rejectedAssets.add(entry.asset);\n }\n }\n }\n }\n\n return assets.filter((asset) => !rejectedAssets.has(asset));\n }\n\n /**\n * SPL `token:` assets in state that Blockaid marks malicious (failed batches skipped).\n *\n * @param assets - CAIP `token:` assets to scan.\n * @returns Subset marked malicious.\n */\n async #findMaliciousTokensAmong(\n assets: CaipAssetType[],\n ): Promise<CaipAssetType[]> {\n const tokensByChain = this.#groupTokenAssetsByChain(assets);\n\n const maliciousAssets: CaipAssetType[] = [];\n\n for (const [chainName, tokenEntries] of Object.entries(tokensByChain)) {\n const batchOutcomes = await this.#runBatchedBulkTokenScans(\n chainName,\n tokenEntries,\n );\n\n for (const outcome of batchOutcomes) {\n if (outcome.status === 'rejected') {\n continue;\n }\n for (const entry of outcome.entries) {\n if (\n outcome.response[entry.address]?.result_type ===\n TokenScanResultType.Malicious\n ) {\n maliciousAssets.push(entry.asset);\n }\n }\n }\n }\n\n return maliciousAssets;\n }\n\n /**\n * Get assets list for an account\n *\n * @param accountId - AccountId to get assets for\n * @param snapId - Snap ID for the account\n * @returns list of assets\n */\n async #getAssetsList(\n accountId: string,\n snapId: string,\n ): Promise<CaipAssetTypeOrId[]> {\n return await this.#getClient(snapId).listAccountAssets(accountId);\n }\n\n /**\n * Gets a `KeyringClient` for a Snap.\n *\n * @param snapId - ID of the Snap to get the client for.\n * @returns A `KeyringClient` for the Snap.\n */\n #getClient(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) =>\n (await this.messenger.call('SnapController:handleRequest', {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n })) as Promise<Json>,\n });\n }\n\n /**\n * Assert that the controller mutex is locked.\n *\n * @throws If the controller mutex is not locked.\n */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n #assertControllerMutexIsLocked() {\n if (!this.#controllerOperationMutex.isLocked()) {\n throw new Error(\n 'MultichainAssetsControllerError - Attempt to update state',\n );\n }\n }\n\n /**\n * Lock the controller mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * This wrapper ensures that each mutable operation that interacts with the\n * controller and that changes its state is executed in a mutually exclusive way,\n * preventing unsafe concurrent access that could lead to unpredictable behavior.\n *\n * @param callback - The function to execute while the controller mutex is locked.\n * @returns The result of the function.\n */\n async #withControllerLock<Result>(\n callback: MutuallyExclusiveCallback<Result>,\n ): Promise<Result> {\n return withLock(this.#controllerOperationMutex, callback);\n }\n}\n\n/**\n * Lock the given mutex before executing the given function,\n * and release it after the function is resolved or after an\n * error is thrown.\n *\n * @param mutex - The mutex to lock.\n * @param callback - The function to execute while the mutex is locked.\n * @returns The result of the function.\n */\nasync function withLock<Result>(\n mutex: Mutex,\n callback: MutuallyExclusiveCallback<Result>,\n): Promise<Result> {\n const releaseLock = await mutex.acquire();\n\n try {\n return await callback({ releaseLock });\n } finally {\n releaseLock();\n }\n}\n"]}
@@ -40,19 +40,19 @@ export function getDefaultMultichainAssetsControllerState() {
40
40
  const assetsControllerMetadata = {
41
41
  assetsMetadata: {
42
42
  includeInStateLogs: false,
43
- persist: true,
43
+ persist: false,
44
44
  includeInDebugSnapshot: false,
45
45
  usedInUi: true,
46
46
  },
47
47
  accountsAssets: {
48
48
  includeInStateLogs: false,
49
- persist: true,
49
+ persist: false,
50
50
  includeInDebugSnapshot: false,
51
51
  usedInUi: true,
52
52
  },
53
53
  allIgnoredAssets: {
54
54
  includeInStateLogs: false,
55
- persist: true,
55
+ persist: false,
56
56
  includeInDebugSnapshot: false,
57
57
  usedInUi: true,
58
58
  },