@metamask/assets-controllers 87.0.0 → 87.1.1

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 (114) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/AccountTrackerController.cjs.map +1 -1
  3. package/dist/AccountTrackerController.d.cts +2 -2
  4. package/dist/AccountTrackerController.d.mts +2 -2
  5. package/dist/AccountTrackerController.mjs.map +1 -1
  6. package/dist/AssetsContractController.cjs.map +1 -1
  7. package/dist/AssetsContractController.mjs.map +1 -1
  8. package/dist/CurrencyRateController.cjs.map +1 -1
  9. package/dist/CurrencyRateController.d.cts +2 -2
  10. package/dist/CurrencyRateController.d.mts +2 -2
  11. package/dist/CurrencyRateController.mjs.map +1 -1
  12. package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
  13. package/dist/DeFiPositionsController/DeFiPositionsController.d.cts +2 -2
  14. package/dist/DeFiPositionsController/DeFiPositionsController.d.mts +2 -2
  15. package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
  16. package/dist/DeFiPositionsController/fetch-positions.cjs.map +1 -1
  17. package/dist/DeFiPositionsController/fetch-positions.mjs.map +1 -1
  18. package/dist/DeFiPositionsController/group-defi-positions.cjs.map +1 -1
  19. package/dist/DeFiPositionsController/group-defi-positions.mjs.map +1 -1
  20. package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
  21. package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
  22. package/dist/MultichainAssetsController/utils.cjs.map +1 -1
  23. package/dist/MultichainAssetsController/utils.mjs.map +1 -1
  24. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
  25. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts +2 -2
  26. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts +2 -2
  27. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
  28. package/dist/MultichainBalancesController/MultichainBalancesController.cjs +2 -2
  29. package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
  30. package/dist/MultichainBalancesController/MultichainBalancesController.mjs +2 -2
  31. package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
  32. package/dist/NftController.cjs.map +1 -1
  33. package/dist/NftController.mjs.map +1 -1
  34. package/dist/NftDetectionController.cjs +2 -2
  35. package/dist/NftDetectionController.cjs.map +1 -1
  36. package/dist/NftDetectionController.mjs +2 -2
  37. package/dist/NftDetectionController.mjs.map +1 -1
  38. package/dist/RatesController/RatesController.cjs.map +1 -1
  39. package/dist/RatesController/RatesController.mjs.map +1 -1
  40. package/dist/Standards/ERC20Standard.cjs.map +1 -1
  41. package/dist/Standards/ERC20Standard.mjs.map +1 -1
  42. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.cjs.map +1 -1
  43. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -1
  44. package/dist/Standards/NftStandards/ERC721/ERC721Standard.cjs.map +1 -1
  45. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -1
  46. package/dist/TokenBalancesController.cjs.map +1 -1
  47. package/dist/TokenBalancesController.d.cts +2 -2
  48. package/dist/TokenBalancesController.d.mts +2 -2
  49. package/dist/TokenBalancesController.mjs.map +1 -1
  50. package/dist/TokenDetectionController.cjs.map +1 -1
  51. package/dist/TokenDetectionController.d.cts +2 -2
  52. package/dist/TokenDetectionController.d.mts +2 -2
  53. package/dist/TokenDetectionController.mjs.map +1 -1
  54. package/dist/TokenListController.cjs.map +1 -1
  55. package/dist/TokenListController.d.cts +2 -2
  56. package/dist/TokenListController.d.mts +2 -2
  57. package/dist/TokenListController.mjs.map +1 -1
  58. package/dist/TokenRatesController.cjs.map +1 -1
  59. package/dist/TokenRatesController.d.cts +2 -2
  60. package/dist/TokenRatesController.d.mts +2 -2
  61. package/dist/TokenRatesController.mjs.map +1 -1
  62. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
  63. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
  64. package/dist/TokensController.cjs.map +1 -1
  65. package/dist/TokensController.mjs.map +1 -1
  66. package/dist/assetsUtil.cjs.map +1 -1
  67. package/dist/assetsUtil.d.cts +20 -20
  68. package/dist/assetsUtil.d.cts.map +1 -1
  69. package/dist/assetsUtil.d.mts +20 -20
  70. package/dist/assetsUtil.d.mts.map +1 -1
  71. package/dist/assetsUtil.mjs.map +1 -1
  72. package/dist/balances.cjs.map +1 -1
  73. package/dist/balances.mjs.map +1 -1
  74. package/dist/constants.cjs +9 -9
  75. package/dist/constants.cjs.map +1 -1
  76. package/dist/constants.mjs +9 -9
  77. package/dist/constants.mjs.map +1 -1
  78. package/dist/crypto-compare-service/crypto-compare.cjs.map +1 -1
  79. package/dist/crypto-compare-service/crypto-compare.mjs.map +1 -1
  80. package/dist/index.cjs +2 -1
  81. package/dist/index.cjs.map +1 -1
  82. package/dist/index.d.cts +2 -1
  83. package/dist/index.d.cts.map +1 -1
  84. package/dist/index.d.mts +2 -1
  85. package/dist/index.d.mts.map +1 -1
  86. package/dist/index.mjs +1 -1
  87. package/dist/index.mjs.map +1 -1
  88. package/dist/multi-chain-accounts-service/api-balance-fetcher.cjs.map +1 -1
  89. package/dist/multi-chain-accounts-service/api-balance-fetcher.mjs.map +1 -1
  90. package/dist/multi-chain-accounts-service/multi-chain-accounts.cjs.map +1 -1
  91. package/dist/multi-chain-accounts-service/multi-chain-accounts.mjs.map +1 -1
  92. package/dist/multicall.cjs.map +1 -1
  93. package/dist/multicall.mjs.map +1 -1
  94. package/dist/rpc-service/rpc-balance-fetcher.cjs.map +1 -1
  95. package/dist/rpc-service/rpc-balance-fetcher.mjs.map +1 -1
  96. package/dist/selectors/stringify-balance.cjs.map +1 -1
  97. package/dist/selectors/stringify-balance.mjs.map +1 -1
  98. package/dist/selectors/token-selectors.cjs.map +1 -1
  99. package/dist/selectors/token-selectors.mjs.map +1 -1
  100. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  101. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  102. package/dist/token-service.cjs +72 -12
  103. package/dist/token-service.cjs.map +1 -1
  104. package/dist/token-service.d.cts +48 -0
  105. package/dist/token-service.d.cts.map +1 -1
  106. package/dist/token-service.d.mts +48 -0
  107. package/dist/token-service.d.mts.map +1 -1
  108. package/dist/token-service.mjs +70 -11
  109. package/dist/token-service.mjs.map +1 -1
  110. package/dist/utils/formatters.cjs.map +1 -1
  111. package/dist/utils/formatters.mjs.map +1 -1
  112. package/dist/utils/timeout-with-retry.cjs.map +1 -1
  113. package/dist/utils/timeout-with-retry.mjs.map +1 -1
  114. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainAssetsController.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EACL,cAAc,EAIf,kCAAkC;AACnC,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAOzD,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAY9D,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EACL,eAAe,EACf,kBAAkB,EAEnB,wBAAwB;AAGzB,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,iBAAiB,EAAE,oBAAgB;AAE5C,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAsBpD;;;;;;;GAOG;AACH,MAAM,UAAU,yCAAyC;IACvD,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,gBAAgB,EAAE,EAAE,EAAE,CAAC;AAC1E,CAAC;AAwFD;;;;;;GAMG;AACH,MAAM,wBAAwB,GAC5B;IACE,cAAc,EAAE;QACd,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,E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ountsControllerAccountRemovedEvent,\n AccountsControllerListMultichainAccountsAction,\n} from '@metamask/accounts-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type 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 GetAllSnaps,\n HandleSnapRequest,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport {\n isCaipAssetType,\n parseCaipAssetType,\n type CaipChainId,\n} from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport { getChainIdsCaveat } from './utils';\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\nexport type MultichainAssetsControllerGetAssetMetadataAction = {\n type: `${typeof controllerName}:getAssetMetadata`;\n handler: MultichainAssetsController['getAssetMetadata'];\n};\n\nexport type MultichainAssetsControllerIgnoreAssetsAction = {\n type: `${typeof controllerName}:ignoreAssets`;\n handler: MultichainAssetsController['ignoreAssets'];\n};\n\nexport type MultichainAssetsControllerAddAssetsAction = {\n type: `${typeof controllerName}:addAssets`;\n handler: MultichainAssetsController['addAssets'];\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 | MultichainAssetsControllerGetAssetMetadataAction\n | MultichainAssetsControllerIgnoreAssetsAction\n | MultichainAssetsControllerAddAssetsAction;\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 | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\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\n// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.\n\nexport class MultichainAssetsController extends BaseController<\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 constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n\n this.messenger.subscribe(\n 'AccountsController:accountAdded',\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountRemoved',\n async (account) => await this.#handleOnAccountRemovedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountAssetListUpdated',\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n this.#registerMessageHandlers();\n }\n\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n return this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n return this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messenger.registerActionHandler(\n 'MultichainAssetsController:getAssetMetadata',\n this.getAssetMetadata.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'MultichainAssetsController:ignoreAssets',\n this.ignoreAssets.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'MultichainAssetsController:addAssets',\n this.addAssets.bind(this),\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 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 (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 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 filteredToBeAddedAssets = added.filter(\n (asset) =>\n !existing.includes(asset) &&\n isCaipAssetType(asset) &&\n !this.#isAssetIgnored(asset, accountId),\n );\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 assets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\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 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 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 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 // TODO: Use dedicated SnapController's action once available for this:\n return this.messenger\n .call('SnapController:getAll')\n .filter((snap) => snap.enabled && !snap.blocked);\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 * 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 #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.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/MultichainAssetsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EACL,cAAc,EAIf,kCAAkC;AACnC,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAOzD,OAAO,EAAE,aAAa,EAAE,sCAAsC;AAY9D,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EACL,eAAe,EACf,kBAAkB,EAEnB,wBAAwB;AAGzB,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,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AI,CAAC,SAAS,CAAC,IAAI,CAAC,8BAA8B,EAAE;YACzD,MAAM,EAAE,MAAgB;YACxB,MAAM,EAAE,UAAU;YAClB,OAAO,EAAE,WAAW,CAAC,gBAAgB;YACrC,OAAO;SACR,CAAC,CAAkB;KACvB,CAAC,CAAC;AACL,CAAC;IAQC,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 {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type 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 GetAllSnaps,\n HandleSnapRequest,\n} from '@metamask/snaps-controllers';\nimport type { FungibleAssetMetadata, Snap, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport {\n isCaipAssetType,\n parseCaipAssetType,\n type CaipChainId,\n} from '@metamask/utils';\nimport type { Json, JsonRpcRequest } from '@metamask/utils';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\n\nimport { getChainIdsCaveat } from './utils';\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\nexport type MultichainAssetsControllerGetAssetMetadataAction = {\n type: `${typeof controllerName}:getAssetMetadata`;\n handler: MultichainAssetsController['getAssetMetadata'];\n};\n\nexport type MultichainAssetsControllerIgnoreAssetsAction = {\n type: `${typeof controllerName}:ignoreAssets`;\n handler: MultichainAssetsController['ignoreAssets'];\n};\n\nexport type MultichainAssetsControllerAddAssetsAction = {\n type: `${typeof controllerName}:addAssets`;\n handler: MultichainAssetsController['addAssets'];\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 | MultichainAssetsControllerGetAssetMetadataAction\n | MultichainAssetsControllerIgnoreAssetsAction\n | MultichainAssetsControllerAddAssetsAction;\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 | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | AccountsControllerListMultichainAccountsAction;\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\n// TODO: make this controller extends StaticIntervalPollingController and update all assetsMetadata once a day.\n\nexport class MultichainAssetsController extends BaseController<\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 constructor({\n messenger,\n state = {},\n }: {\n messenger: MultichainAssetsControllerMessenger;\n state?: Partial<MultichainAssetsControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: assetsControllerMetadata,\n state: {\n ...getDefaultMultichainAssetsControllerState(),\n ...state,\n },\n });\n\n this.#snaps = {};\n\n this.messenger.subscribe(\n 'AccountsController:accountAdded',\n async (account) => await this.#handleOnAccountAddedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountRemoved',\n async (account) => await this.#handleOnAccountRemovedEvent(account),\n );\n this.messenger.subscribe(\n 'AccountsController:accountAssetListUpdated',\n async (event) => await this.#handleAccountAssetListUpdatedEvent(event),\n );\n\n this.#registerMessageHandlers();\n }\n\n async #handleAccountAssetListUpdatedEvent(\n event: AccountAssetListUpdatedEventPayload,\n ) {\n return this.#withControllerLock(async () =>\n this.#handleAccountAssetListUpdated(event),\n );\n }\n\n async #handleOnAccountAddedEvent(account: InternalAccount) {\n return this.#withControllerLock(async () =>\n this.#handleOnAccountAdded(account),\n );\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messenger.registerActionHandler(\n 'MultichainAssetsController:getAssetMetadata',\n this.getAssetMetadata.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'MultichainAssetsController:ignoreAssets',\n this.ignoreAssets.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'MultichainAssetsController:addAssets',\n this.addAssets.bind(this),\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 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 (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 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 filteredToBeAddedAssets = added.filter(\n (asset) =>\n !existing.includes(asset) &&\n isCaipAssetType(asset) &&\n !this.#isAssetIgnored(asset, accountId),\n );\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 assets = await this.#getAssetsList(\n account.id,\n account.metadata.snap.id,\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 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 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 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 // TODO: Use dedicated SnapController's action once available for this:\n return this.messenger\n .call('SnapController:getAll')\n .filter((snap) => snap.enabled && !snap.blocked);\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 * 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 #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 +1 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/utils.ts"],"names":[],"mappings":";;;AAIA,uDAAuD;AAEvD,6KAA6K;AAC7K,2DAA2D;AAC3D;;;;;;;;;GASG;AACH,uBAAuB;AACvB,SAAgB,iBAAiB,CAC/B,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE;QACxB,OAAO,IAAI,CAAC;KACb;IAED,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,CACpC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,4BAAc,CAAC,QAAQ,CACpB,CAAC;IAE1C,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC;AAZD,8CAYC","sourcesContent":["import type {\n Caveat,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\n\n// TODO: this is a duplicate of https://github.com/MetaMask/snaps/blob/362208e725db18baed550ade99087d44e7b537ed/packages/snaps-rpc-methods/src/endowments/name-lookup.ts#L151\n// To be removed once core has snaps-rpc-methods dependency\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports.\n */\n// istanbul ignore next\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): string[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n const caveat = permission.caveats.find(\n (permCaveat) => permCaveat.type === SnapCaveatType.ChainIds,\n ) as Caveat<string, string[]> | undefined;\n\n return caveat ? caveat.value : null;\n}\n"]}
1
+ {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/utils.ts"],"names":[],"mappings":";;;AAIA,uDAAuD;AAEvD,6KAA6K;AAC7K,2DAA2D;AAC3D;;;;;;;;;GASG;AACH,uBAAuB;AACvB,SAAgB,iBAAiB,CAC/B,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,CACpC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,4BAAc,CAAC,QAAQ,CACpB,CAAC;IAE1C,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC;AAZD,8CAYC","sourcesContent":["import type {\n Caveat,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\n\n// TODO: this is a duplicate of https://github.com/MetaMask/snaps/blob/362208e725db18baed550ade99087d44e7b537ed/packages/snaps-rpc-methods/src/endowments/name-lookup.ts#L151\n// To be removed once core has snaps-rpc-methods dependency\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports.\n */\n// istanbul ignore next\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): string[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n const caveat = permission.caveats.find(\n (permCaveat) => permCaveat.type === SnapCaveatType.ChainIds,\n ) as Caveat<string, string[]> | undefined;\n\n return caveat ? caveat.value : null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/utils.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,8BAA8B;AAEvD,6KAA6K;AAC7K,2DAA2D;AAC3D;;;;;;;;;GASG;AACH,uBAAuB;AACvB,MAAM,UAAU,iBAAiB,CAC/B,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE;QACxB,OAAO,IAAI,CAAC;KACb;IAED,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,CACpC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,cAAc,CAAC,QAAQ,CACpB,CAAC;IAE1C,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["import type {\n Caveat,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\n\n// TODO: this is a duplicate of https://github.com/MetaMask/snaps/blob/362208e725db18baed550ade99087d44e7b537ed/packages/snaps-rpc-methods/src/endowments/name-lookup.ts#L151\n// To be removed once core has snaps-rpc-methods dependency\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports.\n */\n// istanbul ignore next\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): string[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n const caveat = permission.caveats.find(\n (permCaveat) => permCaveat.type === SnapCaveatType.ChainIds,\n ) as Caveat<string, string[]> | undefined;\n\n return caveat ? caveat.value : null;\n}\n"]}
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsController/utils.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,8BAA8B;AAEvD,6KAA6K;AAC7K,2DAA2D;AAC3D;;;;;;;;;GASG;AACH,uBAAuB;AACvB,MAAM,UAAU,iBAAiB,CAC/B,UAAiC;IAEjC,IAAI,CAAC,UAAU,EAAE,OAAO,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,CACpC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,cAAc,CAAC,QAAQ,CACpB,CAAC;IAE1C,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC","sourcesContent":["import type {\n Caveat,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { SnapCaveatType } from '@metamask/snaps-utils';\n\n// TODO: this is a duplicate of https://github.com/MetaMask/snaps/blob/362208e725db18baed550ade99087d44e7b537ed/packages/snaps-rpc-methods/src/endowments/name-lookup.ts#L151\n// To be removed once core has snaps-rpc-methods dependency\n/**\n * Getter function to get the chainIds caveat from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the `chainIds` caveat from.\n * @returns An array of `chainIds` that the snap supports.\n */\n// istanbul ignore next\nexport function getChainIdsCaveat(\n permission?: PermissionConstraint,\n): string[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n const caveat = permission.caveats.find(\n (permCaveat) => permCaveat.type === SnapCaveatType.ChainIds,\n ) as Caveat<string, string[]> | undefined;\n\n return caveat ? caveat.value : null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainAssetsRatesController.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsRatesController/MultichainAssetsRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAUA,uDAA6E;AAO7E,qEAA+E;AAc/E,uDAAoD;AACpD,6CAAoC;AAGpC,6CAAiD;AAYjD;;GAEG;AACH,MAAM,cAAc,GAAG,iCAAiC,CAAC;AAwCzD;;;;;;;GAOG;AACH,SAAgB,8CAA8C;IAC5D,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,gBAAgB,EAAE,EAAE,EAAE,CAAC;AACvD,CAAC;AAFD,wGAEC;AA2DD,MAAM,QAAQ,GAAwD;IACpE,eAAe,EAAE;QACf,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAkBF;;;;GAIG;AACH,MAAa,+BAAgC,SAAQ,IAAA,oDAA+B,GAInF;IASC;;;;;;;OAOG;IACH,YAAY,EACV,QAAQ,GAAG,KAAK,EAChB,KAAK,GAAG,EAAE,EACV,SAAS,GAKV;;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,SAAS;YACT,KAAK,EAAE;gBACL,GAAG,8CAA8C,EAAE;gBACnD,GAAG,KAAK;aACT;YACD,QAAQ;SACT,CAAC,CAAC;;QAjCI,iDAAS,IAAI,mBAAK,EAAE,EAAC;QAE9B,mEAAuD;QAE9C,kEAAmE;QAE5E,sDAAc,IAAI,EAAC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AC;IAEF,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,oBAAoB,SAAS,EAAE,CAAC,CAAC;KAClD;IAED,OAAO,OAAO,CAAC;AACjB,CAAC,uHASoB,SAAiB;IACpC,OAAO,uBAAA,IAAI,uDAAgB,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;AACjD,CAAC,mHAQC,YAGC;IAED,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;QAC1C,OAAO;KACR;IACD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAkD,EAAE,EAAE;QACjE,KAAK,CAAC,eAAe,GAAG;YACtB,GAAG,KAAK,CAAC,eAAe;YACxB,GAAG,YAAY;SAChB,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,uDAuBD,KAAK,6DAAoB,IAA8B;IACrD,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACzC,IAAI;QACF,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC/D,MAAM;YACN,MAAM,EAAE,UAAU;YAClB,OAAO;YACP,OAAO,EAAE;gBACP,OAAO,EAAE,KAAK;gBACd,MAAM,EAAE,OAAO;gBACf,MAAM;aACP;SACF,CAAC,CAAC;KACJ;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CAAC,2BAA2B,OAAO,GAAG,EAAE;YACnD,MAAM;YACN,OAAO;YACP,OAAO,EAAG,KAAe,CAAC,OAAO;YACjC,MAAM;SACP,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;KAClB;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountAddedEvent,\n AccountsControllerGetSelectedMultichainAccountAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { type CaipAssetType, isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n SnapId,\n AssetConversion,\n OnAssetsConversionArguments,\n OnAssetHistoricalPriceArguments,\n OnAssetHistoricalPriceResponse,\n HistoricalPriceIntervals,\n OnAssetsMarketDataArguments,\n OnAssetsMarketDataResponse,\n FungibleAssetMarketData,\n OnAssetsConversionResponse,\n} from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { MAP_CAIP_CURRENCIES } from './constant';\nimport type {\n CurrencyRateState,\n CurrencyRateStateChange,\n GetCurrencyRateState,\n} from '../CurrencyRateController';\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n MultichainAssetsControllerState,\n} from '../MultichainAssetsController';\n\n/**\n * The name of the MultichainAssetsRatesController.\n */\nconst controllerName = 'MultichainAssetsRatesController';\n\n// This is temporary until its exported from snap\ntype HistoricalPrice = {\n intervals: HistoricalPriceIntervals;\n // The UNIX timestamp of when the historical price was last updated.\n updateTime: number;\n // The UNIX timestamp of when the historical price will expire.\n expirationTime?: number;\n};\n\n/**\n * State used by the MultichainAssetsRatesController to cache token conversion rates.\n */\nexport type MultichainAssetsRatesControllerState = {\n conversionRates: Record<CaipAssetType, UnifiedAssetConversion>;\n historicalPrices: Record<CaipAssetType, Record<string, HistoricalPrice>>; // string being the current currency we fetched historical prices for\n};\n\n/**\n * Returns the state of the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Action to update the rates of all supported tokens.\n */\nexport type MultichainAssetsRatesControllerUpdateRatesAction = {\n type: `${typeof controllerName}:updateAssetsRates`;\n handler: MultichainAssetsRatesController['updateAssetsRates'];\n};\n\ntype UnifiedAssetConversion = AssetConversion & {\n marketData?: FungibleAssetMarketData;\n};\n\n/**\n * Constructs the default {@link MultichainAssetsRatesController} 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 MultichainAssetsRatesController} state.\n */\nexport function getDefaultMultichainAssetsRatesControllerState(): MultichainAssetsRatesControllerState {\n return { conversionRates: {}, historicalPrices: {} };\n}\n\n/**\n * Event emitted when the state of the MultichainAssetsRatesController changes.\n */\nexport type MultichainAssetsRatesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Actions exposed by the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerActions =\n | MultichainAssetsRatesControllerGetStateAction\n | MultichainAssetsRatesControllerUpdateRatesAction;\n\n/**\n * Events emitted by MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerEvents =\n MultichainAssetsRatesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\nexport type AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | GetCurrencyRateState\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction;\n\n/**\n * Events that this controller is allowed to subscribe to.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | AccountsControllerAccountAddedEvent\n | CurrencyRateStateChange\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerMessenger = Messenger<\n typeof controllerName,\n MultichainAssetsRatesControllerActions | AllowedActions,\n MultichainAssetsRatesControllerEvents | AllowedEvents\n>;\n\n/**\n * The input for starting polling in MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesPollingInput = {\n accountId: string;\n};\n\nconst metadata: StateMetadata<MultichainAssetsRatesControllerState> = {\n conversionRates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n historicalPrices: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nexport type ConversionRatesWithMarketData = {\n conversionRates: Record<\n CaipAssetType,\n Record<CaipAssetType, UnifiedAssetConversion | null>\n >;\n};\n\n/**\n * Arguments for a Snap request.\n */\ntype SnapRequestArgs<T> = {\n snapId: SnapId;\n handler: HandlerType;\n params: T;\n};\n\n/**\n * Controller that manages multichain token conversion rates.\n *\n * This controller polls for token conversion rates and updates its state.\n */\nexport class MultichainAssetsRatesController extends StaticIntervalPollingController<MultichainAssetsRatesPollingInput>()<\n typeof controllerName,\n MultichainAssetsRatesControllerState,\n MultichainAssetsRatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n #currentCurrency: CurrencyRateState['currentCurrency'];\n\n readonly #accountsAssets: MultichainAssetsControllerState['accountsAssets'];\n\n #isUnlocked = true;\n\n /**\n * Creates an instance of MultichainAssetsRatesController.\n *\n * @param options - Constructor options.\n * @param options.interval - The polling interval in milliseconds.\n * @param options.state - The initial state.\n * @param options.messenger - A reference to the messenger.\n */\n constructor({\n interval = 18000,\n state = {},\n messenger,\n }: {\n interval?: number;\n state?: Partial<MultichainAssetsRatesControllerState>;\n messenger: MultichainAssetsRatesControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {\n ...getDefaultMultichainAssetsRatesControllerState(),\n ...state,\n },\n metadata,\n });\n\n this.setIntervalLength(interval);\n\n // Subscribe to keyring lock/unlock events.\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n ({ accountsAssets: this.#accountsAssets } = this.messenger.call(\n 'MultichainAssetsController:getState',\n ));\n\n ({ currentCurrency: this.#currentCurrency } = this.messenger.call(\n 'CurrencyRateController:getState',\n ));\n\n this.messenger.subscribe(\n 'CurrencyRateController:stateChange',\n async (currentCurrency: string) => {\n this.#currentCurrency = currentCurrency;\n await this.updateAssetsRates();\n },\n (currencyRateControllerState) =>\n currencyRateControllerState.currentCurrency,\n );\n\n this.messenger.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n // TODO; removed can be used in future for further cleanup\n await this.#updateAssetsRatesForNewAssets(newAccountAssets);\n },\n );\n }\n\n /**\n * Executes a poll by updating token conversion rates for the current account.\n *\n * @returns A promise that resolves when the polling completes.\n */\n async _executePoll(): Promise<void> {\n await this.updateAssetsRates();\n }\n\n /**\n * Determines whether the controller is active.\n *\n * @returns True if the keyring is unlocked; otherwise, false.\n */\n get isActive(): boolean {\n return this.#isUnlocked;\n }\n\n /**\n * Checks if an account is a non-EVM account with a Snap.\n *\n * @param account - The account to check.\n * @returns True if the account is non-EVM and has Snap metadata; otherwise, false.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) && account.metadata.snap !== undefined\n );\n }\n\n /**\n * Retrieves all multichain accounts from the AccountsController.\n *\n * @returns An array of internal accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messenger.call('AccountsController:listMultichainAccounts');\n }\n\n /**\n * Filters and returns non-EVM accounts that should have balances.\n *\n * @returns An array of non-EVM internal accounts.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Adds the assets to a map of Snap ID to assets.\n *\n * @param snapIdToAssets - The map of Snap ID to assets.\n * @param account - The account to add the assets for.\n * @param assets - The assets to add.\n */\n #addAssetsToSnapIdMap(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n account: InternalAccount,\n assets: CaipAssetType[],\n ): void {\n // Prevent creating a new set if there are no assets to add.\n if (assets.length === 0) {\n return;\n }\n\n // FIXME: Instead of using the Snap ID from the account, we should\n // select the Snap based on the supported scopes defined in the Snaps'\n // manifest.\n const snapId = account.metadata.snap?.id as SnapId | undefined;\n if (!snapId) {\n return;\n }\n\n let snapAssets = snapIdToAssets.get(snapId);\n if (!snapAssets) {\n snapAssets = new Set();\n snapIdToAssets.set(snapId, snapAssets);\n }\n\n for (const asset of assets) {\n snapAssets.add(asset);\n }\n }\n\n /**\n * Updates token conversion rates for each non-EVM account.\n *\n * @returns A promise that resolves when the rates are updated.\n */\n async updateAssetsRates(): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // Compute the set of unique assets from all accounts. It's important to\n // deduplicate assets here to avoid duplicate requests to the Snap.\n const accounts = this.#listAccounts();\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n for (const account of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n account,\n this.#getAssetsForAccount(account.id),\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Returns the CAIP-19 asset type for the current selected currency. Defaults\n * to USD if the current selected currency is not supported.\n *\n * @returns The CAIP-19 asset type for the current selected currency.\n */\n #getCaipCurrentCurrency(): CaipAssetType {\n return (\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd\n );\n }\n\n /**\n * Fetches the conversion rates for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the conversion rates for.\n * @param currency - The currency to fetch the conversion rates for.\n * @returns A record of CAIP-19 asset types to conversion rates.\n */\n async #getConversionRates(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, AssetConversion | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsConversion,\n params: {\n conversions: Array.from(assets).map((asset) => ({\n from: asset,\n to: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToConversionRate: Record<\n CaipAssetType,\n AssetConversion | undefined\n > = {};\n\n for (const asset of assets) {\n assetToConversionRate[asset] =\n response.conversionRates?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToConversionRate;\n }\n\n /**\n * Fetches the market data for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the market data for.\n * @param currency - The currency to fetch the market data for.\n * @returns A record of CAIP-19 asset types to market data.\n */\n async #getMarketData(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, FungibleAssetMarketData | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsMarketData,\n params: {\n assets: Array.from(assets).map((asset) => ({\n asset,\n unit: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToMarketData: Record<\n CaipAssetType,\n FungibleAssetMarketData | undefined\n > = {};\n\n for (const asset of assets) {\n assetToMarketData[asset] =\n response.marketData?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToMarketData;\n }\n\n /**\n * Fetches the updated rates for the given assets from the given Snaps.\n *\n * @param snapIdToAssets - A map of Snap ID to CAIP-19 asset types.\n * @returns A record of CAIP-19 asset types to unified asset conversions.\n */\n async #getUpdatedRatesFor(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n ): Promise<\n Record<CaipAssetType, UnifiedAssetConversion & { currency: CaipAssetType }>\n > {\n const updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n // Keep a local copy to ensure that the currency is always the same for the\n // entire loop.\n const currency = this.#getCaipCurrentCurrency();\n\n // Note: Since the assets come from a 1-to-1 mapping with Snap IDs, we know\n // that a given asset will not appear under multiple Snap IDs.\n for (const [snapId, assets] of snapIdToAssets.entries()) {\n const [rates, marketData] = await Promise.all([\n this.#getConversionRates(snapId, assets, currency),\n this.#getMarketData(snapId, assets, currency),\n ]);\n\n for (const asset of assets) {\n const assetRate = rates[asset];\n const assetMarketData = marketData[asset];\n\n // Rates are mandatory, so skip the asset if not available.\n if (!assetRate) {\n continue;\n }\n\n updatedRates[asset] = {\n currency,\n ...assetRate,\n ...(assetMarketData && { marketData: assetMarketData }),\n };\n }\n }\n\n return updatedRates;\n }\n\n /**\n * Fetches historical prices for the current account\n *\n * @param asset - The asset to fetch historical prices for.\n * @param account - optional account to fetch historical prices for\n * @returns The historical prices.\n */\n async fetchHistoricalPricesForAsset(\n asset: CaipAssetType,\n account?: InternalAccount,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n return (async () => {\n const currentCaipCurrency =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n // Check if we already have historical prices for this asset and currency\n const historicalPriceExpirationTime =\n this.state.historicalPrices[asset]?.[this.#currentCurrency]\n ?.expirationTime;\n\n const historicalPriceHasExpired =\n historicalPriceExpirationTime &&\n historicalPriceExpirationTime < Date.now();\n\n if (historicalPriceHasExpired === false) {\n return;\n }\n\n const selectedAccount =\n account ??\n this.messenger.call('AccountsController:getSelectedMultichainAccount');\n try {\n const historicalPricesResponse = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: selectedAccount?.metadata.snap?.id as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetHistoricalPrice,\n request: {\n jsonrpc: '2.0',\n method: HandlerType.OnAssetHistoricalPrice,\n params: {\n from: asset,\n to: currentCaipCurrency,\n },\n },\n },\n );\n\n // skip state update if no historical prices are returned\n if (!historicalPricesResponse) {\n return;\n }\n\n this.update((state) => {\n state.historicalPrices = {\n ...state.historicalPrices,\n [asset]: {\n ...state.historicalPrices[asset],\n [this.#currentCurrency]: (\n historicalPricesResponse as OnAssetHistoricalPriceResponse\n )?.historicalPrice,\n },\n };\n });\n } catch {\n throw new Error(\n `Failed to fetch historical prices for asset: ${asset}`,\n );\n }\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Updates the conversion rates for new assets.\n *\n * @param accounts - The accounts to update the conversion rates for.\n * @returns A promise that resolves when the rates are updated.\n */\n async #updateAssetsRatesForNewAssets(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // First build a map containing all assets that need to be updated per\n // Snap ID, this will be used to batch the requests.\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n\n for (const { accountId, assets } of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n this.#getAccount(accountId),\n assets,\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Returns the array of CAIP-19 assets for the given account ID.\n * If none are found, returns an empty array.\n *\n * @param accountId - The account ID to get the assets for.\n * @returns An array of CAIP-19 assets.\n */\n #getAssetsForAccount(accountId: string): CaipAssetType[] {\n return this.#accountsAssets?.[accountId] ?? [];\n }\n\n /**\n * Merges the new rates into the controller's state.\n *\n * @param updatedRates - The new rates to merge.\n */\n #applyUpdatedRates(\n updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n >,\n ): void {\n if (Object.keys(updatedRates).length === 0) {\n return;\n }\n this.update((state: Draft<MultichainAssetsRatesControllerState>) => {\n state.conversionRates = {\n ...state.conversionRates,\n ...updatedRates,\n };\n });\n }\n\n /**\n * Forwards a Snap request to the SnapController.\n *\n * @param args - The request parameters.\n * @param args.snapId - The ID of the Snap.\n * @param args.handler - The handler type.\n * @param args.params - The asset conversions.\n * @returns A promise that resolves with the account rates.\n */\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsConversionArguments>,\n ): Promise<OnAssetsConversionResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetHistoricalPriceArguments>,\n ): Promise<OnAssetHistoricalPriceResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsMarketDataArguments>,\n ): Promise<OnAssetsMarketDataResponse | undefined>;\n\n async #handleSnapRequest(args: SnapRequestArgs<unknown>): Promise<unknown> {\n const { snapId, handler, params } = args;\n try {\n return await this.messenger.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n jsonrpc: '2.0',\n method: handler,\n params,\n },\n });\n } catch (error) {\n console.error(`Snap request failed for ${handler}:`, {\n snapId,\n handler,\n message: (error as Error).message,\n params,\n });\n return undefined;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"MultichainAssetsRatesController.cjs","sourceRoot":"","sources":["../../src/MultichainAssetsRatesController/MultichainAssetsRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAUA,uDAA6E;AAO7E,qEAA+E;AAc/E,uDAAoD;AACpD,6CAAoC;AAGpC,6CAAiD;AAYjD;;GAEG;AACH,MAAM,cAAc,GAAG,iCAAiC,CAAC;AAwCzD;;;;;;;GAOG;AACH,SAAgB,8CAA8C;IAC5D,OAAO,EAAE,eAAe,EAAE,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AAC,SAAS,CAAC,IAAI,EAAE,CAAC;AACjD,CAAC,mHAQC,YAGC;IAED,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3C,OAAO;IACT,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAkD,EAAE,EAAE;QACjE,KAAK,CAAC,eAAe,GAAG;YACtB,GAAG,KAAK,CAAC,eAAe;YACxB,GAAG,YAAY;SAChB,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,uDAuBD,KAAK,6DAAoB,IAA8B;IACrD,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACzC,IAAI,CAAC;QACH,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,8BAA8B,EAAE;YAC/D,MAAM;YACN,MAAM,EAAE,UAAU;YAClB,OAAO;YACP,OAAO,EAAE;gBACP,OAAO,EAAE,KAAK;gBACd,MAAM,EAAE,OAAO;gBACf,MAAM;aACP;SACF,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,2BAA2B,OAAO,GAAG,EAAE;YACnD,MAAM;YACN,OAAO;YACP,OAAO,EAAG,KAAe,CAAC,OAAO;YACjC,MAAM;SACP,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountAddedEvent,\n AccountsControllerGetSelectedMultichainAccountAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { type CaipAssetType, isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n SnapId,\n AssetConversion,\n OnAssetsConversionArguments,\n OnAssetHistoricalPriceArguments,\n OnAssetHistoricalPriceResponse,\n HistoricalPriceIntervals,\n OnAssetsMarketDataArguments,\n OnAssetsMarketDataResponse,\n FungibleAssetMarketData,\n OnAssetsConversionResponse,\n} from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { MAP_CAIP_CURRENCIES } from './constant';\nimport type {\n CurrencyRateState,\n CurrencyRateStateChange,\n GetCurrencyRateState,\n} from '../CurrencyRateController';\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n MultichainAssetsControllerState,\n} from '../MultichainAssetsController';\n\n/**\n * The name of the MultichainAssetsRatesController.\n */\nconst controllerName = 'MultichainAssetsRatesController';\n\n// This is temporary until its exported from snap\ntype HistoricalPrice = {\n intervals: HistoricalPriceIntervals;\n // The UNIX timestamp of when the historical price was last updated.\n updateTime: number;\n // The UNIX timestamp of when the historical price will expire.\n expirationTime?: number;\n};\n\n/**\n * State used by the MultichainAssetsRatesController to cache token conversion rates.\n */\nexport type MultichainAssetsRatesControllerState = {\n conversionRates: Record<CaipAssetType, UnifiedAssetConversion>;\n historicalPrices: Record<CaipAssetType, Record<string, HistoricalPrice>>; // string being the current currency we fetched historical prices for\n};\n\n/**\n * Returns the state of the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Action to update the rates of all supported tokens.\n */\nexport type MultichainAssetsRatesControllerUpdateRatesAction = {\n type: `${typeof controllerName}:updateAssetsRates`;\n handler: MultichainAssetsRatesController['updateAssetsRates'];\n};\n\ntype UnifiedAssetConversion = AssetConversion & {\n marketData?: FungibleAssetMarketData;\n};\n\n/**\n * Constructs the default {@link MultichainAssetsRatesController} 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 MultichainAssetsRatesController} state.\n */\nexport function getDefaultMultichainAssetsRatesControllerState(): MultichainAssetsRatesControllerState {\n return { conversionRates: {}, historicalPrices: {} };\n}\n\n/**\n * Event emitted when the state of the MultichainAssetsRatesController changes.\n */\nexport type MultichainAssetsRatesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Actions exposed by the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerActions =\n | MultichainAssetsRatesControllerGetStateAction\n | MultichainAssetsRatesControllerUpdateRatesAction;\n\n/**\n * Events emitted by MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerEvents =\n MultichainAssetsRatesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\nexport type AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | GetCurrencyRateState\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction;\n\n/**\n * Events that this controller is allowed to subscribe to.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | AccountsControllerAccountAddedEvent\n | CurrencyRateStateChange\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerMessenger = Messenger<\n typeof controllerName,\n MultichainAssetsRatesControllerActions | AllowedActions,\n MultichainAssetsRatesControllerEvents | AllowedEvents\n>;\n\n/**\n * The input for starting polling in MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesPollingInput = {\n accountId: string;\n};\n\nconst metadata: StateMetadata<MultichainAssetsRatesControllerState> = {\n conversionRates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n historicalPrices: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nexport type ConversionRatesWithMarketData = {\n conversionRates: Record<\n CaipAssetType,\n Record<CaipAssetType, UnifiedAssetConversion | null>\n >;\n};\n\n/**\n * Arguments for a Snap request.\n */\ntype SnapRequestArgs<T> = {\n snapId: SnapId;\n handler: HandlerType;\n params: T;\n};\n\n/**\n * Controller that manages multichain token conversion rates.\n *\n * This controller polls for token conversion rates and updates its state.\n */\nexport class MultichainAssetsRatesController extends StaticIntervalPollingController<MultichainAssetsRatesPollingInput>()<\n typeof controllerName,\n MultichainAssetsRatesControllerState,\n MultichainAssetsRatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n #currentCurrency: CurrencyRateState['currentCurrency'];\n\n readonly #accountsAssets: MultichainAssetsControllerState['accountsAssets'];\n\n #isUnlocked = true;\n\n /**\n * Creates an instance of MultichainAssetsRatesController.\n *\n * @param options - Constructor options.\n * @param options.interval - The polling interval in milliseconds.\n * @param options.state - The initial state.\n * @param options.messenger - A reference to the messenger.\n */\n constructor({\n interval = 18000,\n state = {},\n messenger,\n }: {\n interval?: number;\n state?: Partial<MultichainAssetsRatesControllerState>;\n messenger: MultichainAssetsRatesControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {\n ...getDefaultMultichainAssetsRatesControllerState(),\n ...state,\n },\n metadata,\n });\n\n this.setIntervalLength(interval);\n\n // Subscribe to keyring lock/unlock events.\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n ({ accountsAssets: this.#accountsAssets } = this.messenger.call(\n 'MultichainAssetsController:getState',\n ));\n\n ({ currentCurrency: this.#currentCurrency } = this.messenger.call(\n 'CurrencyRateController:getState',\n ));\n\n this.messenger.subscribe(\n 'CurrencyRateController:stateChange',\n async (currentCurrency: string) => {\n this.#currentCurrency = currentCurrency;\n await this.updateAssetsRates();\n },\n (currencyRateControllerState) =>\n currencyRateControllerState.currentCurrency,\n );\n\n this.messenger.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n // TODO; removed can be used in future for further cleanup\n await this.#updateAssetsRatesForNewAssets(newAccountAssets);\n },\n );\n }\n\n /**\n * Executes a poll by updating token conversion rates for the current account.\n *\n * @returns A promise that resolves when the polling completes.\n */\n async _executePoll(): Promise<void> {\n await this.updateAssetsRates();\n }\n\n /**\n * Determines whether the controller is active.\n *\n * @returns True if the keyring is unlocked; otherwise, false.\n */\n get isActive(): boolean {\n return this.#isUnlocked;\n }\n\n /**\n * Checks if an account is a non-EVM account with a Snap.\n *\n * @param account - The account to check.\n * @returns True if the account is non-EVM and has Snap metadata; otherwise, false.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) && account.metadata.snap !== undefined\n );\n }\n\n /**\n * Retrieves all multichain accounts from the AccountsController.\n *\n * @returns An array of internal accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messenger.call('AccountsController:listMultichainAccounts');\n }\n\n /**\n * Filters and returns non-EVM accounts that should have balances.\n *\n * @returns An array of non-EVM internal accounts.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Adds the assets to a map of Snap ID to assets.\n *\n * @param snapIdToAssets - The map of Snap ID to assets.\n * @param account - The account to add the assets for.\n * @param assets - The assets to add.\n */\n #addAssetsToSnapIdMap(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n account: InternalAccount,\n assets: CaipAssetType[],\n ): void {\n // Prevent creating a new set if there are no assets to add.\n if (assets.length === 0) {\n return;\n }\n\n // FIXME: Instead of using the Snap ID from the account, we should\n // select the Snap based on the supported scopes defined in the Snaps'\n // manifest.\n const snapId = account.metadata.snap?.id as SnapId | undefined;\n if (!snapId) {\n return;\n }\n\n let snapAssets = snapIdToAssets.get(snapId);\n if (!snapAssets) {\n snapAssets = new Set();\n snapIdToAssets.set(snapId, snapAssets);\n }\n\n for (const asset of assets) {\n snapAssets.add(asset);\n }\n }\n\n /**\n * Updates token conversion rates for each non-EVM account.\n *\n * @returns A promise that resolves when the rates are updated.\n */\n async updateAssetsRates(): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // Compute the set of unique assets from all accounts. It's important to\n // deduplicate assets here to avoid duplicate requests to the Snap.\n const accounts = this.#listAccounts();\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n for (const account of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n account,\n this.#getAssetsForAccount(account.id),\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Returns the CAIP-19 asset type for the current selected currency. Defaults\n * to USD if the current selected currency is not supported.\n *\n * @returns The CAIP-19 asset type for the current selected currency.\n */\n #getCaipCurrentCurrency(): CaipAssetType {\n return (\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd\n );\n }\n\n /**\n * Fetches the conversion rates for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the conversion rates for.\n * @param currency - The currency to fetch the conversion rates for.\n * @returns A record of CAIP-19 asset types to conversion rates.\n */\n async #getConversionRates(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, AssetConversion | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsConversion,\n params: {\n conversions: Array.from(assets).map((asset) => ({\n from: asset,\n to: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToConversionRate: Record<\n CaipAssetType,\n AssetConversion | undefined\n > = {};\n\n for (const asset of assets) {\n assetToConversionRate[asset] =\n response.conversionRates?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToConversionRate;\n }\n\n /**\n * Fetches the market data for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the market data for.\n * @param currency - The currency to fetch the market data for.\n * @returns A record of CAIP-19 asset types to market data.\n */\n async #getMarketData(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, FungibleAssetMarketData | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsMarketData,\n params: {\n assets: Array.from(assets).map((asset) => ({\n asset,\n unit: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToMarketData: Record<\n CaipAssetType,\n FungibleAssetMarketData | undefined\n > = {};\n\n for (const asset of assets) {\n assetToMarketData[asset] =\n response.marketData?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToMarketData;\n }\n\n /**\n * Fetches the updated rates for the given assets from the given Snaps.\n *\n * @param snapIdToAssets - A map of Snap ID to CAIP-19 asset types.\n * @returns A record of CAIP-19 asset types to unified asset conversions.\n */\n async #getUpdatedRatesFor(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n ): Promise<\n Record<CaipAssetType, UnifiedAssetConversion & { currency: CaipAssetType }>\n > {\n const updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n // Keep a local copy to ensure that the currency is always the same for the\n // entire loop.\n const currency = this.#getCaipCurrentCurrency();\n\n // Note: Since the assets come from a 1-to-1 mapping with Snap IDs, we know\n // that a given asset will not appear under multiple Snap IDs.\n for (const [snapId, assets] of snapIdToAssets.entries()) {\n const [rates, marketData] = await Promise.all([\n this.#getConversionRates(snapId, assets, currency),\n this.#getMarketData(snapId, assets, currency),\n ]);\n\n for (const asset of assets) {\n const assetRate = rates[asset];\n const assetMarketData = marketData[asset];\n\n // Rates are mandatory, so skip the asset if not available.\n if (!assetRate) {\n continue;\n }\n\n updatedRates[asset] = {\n currency,\n ...assetRate,\n ...(assetMarketData && { marketData: assetMarketData }),\n };\n }\n }\n\n return updatedRates;\n }\n\n /**\n * Fetches historical prices for the current account\n *\n * @param asset - The asset to fetch historical prices for.\n * @param account - optional account to fetch historical prices for\n * @returns The historical prices.\n */\n async fetchHistoricalPricesForAsset(\n asset: CaipAssetType,\n account?: InternalAccount,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n return (async () => {\n const currentCaipCurrency =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n // Check if we already have historical prices for this asset and currency\n const historicalPriceExpirationTime =\n this.state.historicalPrices[asset]?.[this.#currentCurrency]\n ?.expirationTime;\n\n const historicalPriceHasExpired =\n historicalPriceExpirationTime &&\n historicalPriceExpirationTime < Date.now();\n\n if (historicalPriceHasExpired === false) {\n return;\n }\n\n const selectedAccount =\n account ??\n this.messenger.call('AccountsController:getSelectedMultichainAccount');\n try {\n const historicalPricesResponse = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: selectedAccount?.metadata.snap?.id as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetHistoricalPrice,\n request: {\n jsonrpc: '2.0',\n method: HandlerType.OnAssetHistoricalPrice,\n params: {\n from: asset,\n to: currentCaipCurrency,\n },\n },\n },\n );\n\n // skip state update if no historical prices are returned\n if (!historicalPricesResponse) {\n return;\n }\n\n this.update((state) => {\n state.historicalPrices = {\n ...state.historicalPrices,\n [asset]: {\n ...state.historicalPrices[asset],\n [this.#currentCurrency]: (\n historicalPricesResponse as OnAssetHistoricalPriceResponse\n )?.historicalPrice,\n },\n };\n });\n } catch {\n throw new Error(\n `Failed to fetch historical prices for asset: ${asset}`,\n );\n }\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Updates the conversion rates for new assets.\n *\n * @param accounts - The accounts to update the conversion rates for.\n * @returns A promise that resolves when the rates are updated.\n */\n async #updateAssetsRatesForNewAssets(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // First build a map containing all assets that need to be updated per\n // Snap ID, this will be used to batch the requests.\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n\n for (const { accountId, assets } of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n this.#getAccount(accountId),\n assets,\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Returns the array of CAIP-19 assets for the given account ID.\n * If none are found, returns an empty array.\n *\n * @param accountId - The account ID to get the assets for.\n * @returns An array of CAIP-19 assets.\n */\n #getAssetsForAccount(accountId: string): CaipAssetType[] {\n return this.#accountsAssets?.[accountId] ?? [];\n }\n\n /**\n * Merges the new rates into the controller's state.\n *\n * @param updatedRates - The new rates to merge.\n */\n #applyUpdatedRates(\n updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n >,\n ): void {\n if (Object.keys(updatedRates).length === 0) {\n return;\n }\n this.update((state: Draft<MultichainAssetsRatesControllerState>) => {\n state.conversionRates = {\n ...state.conversionRates,\n ...updatedRates,\n };\n });\n }\n\n /**\n * Forwards a Snap request to the SnapController.\n *\n * @param args - The request parameters.\n * @param args.snapId - The ID of the Snap.\n * @param args.handler - The handler type.\n * @param args.params - The asset conversions.\n * @returns A promise that resolves with the account rates.\n */\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsConversionArguments>,\n ): Promise<OnAssetsConversionResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetHistoricalPriceArguments>,\n ): Promise<OnAssetHistoricalPriceResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsMarketDataArguments>,\n ): Promise<OnAssetsMarketDataResponse | undefined>;\n\n async #handleSnapRequest(args: SnapRequestArgs<unknown>): Promise<unknown> {\n const { snapId, handler, params } = args;\n try {\n return await this.messenger.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n jsonrpc: '2.0',\n method: handler,\n params,\n },\n });\n } catch (error) {\n console.error(`Snap request failed for ${handler}:`, {\n snapId,\n handler,\n message: (error as Error).message,\n params,\n });\n return undefined;\n }\n }\n}\n"]}
@@ -81,8 +81,8 @@ export type ConversionRatesWithMarketData = {
81
81
  conversionRates: Record<CaipAssetType, Record<CaipAssetType, UnifiedAssetConversion | null>>;
82
82
  };
83
83
  declare const MultichainAssetsRatesController_base: (abstract new (...args: any[]) => {
84
- readonly "__#14@#intervalIds": Record<string, NodeJS.Timeout>;
85
- "__#14@#intervalLength": number | undefined;
84
+ readonly "__#15@#intervalIds": Record<string, NodeJS.Timeout>;
85
+ "__#15@#intervalLength": number | undefined;
86
86
  setIntervalLength(intervalLength: number): void;
87
87
  getIntervalLength(): number | undefined;
88
88
  _startPolling(input: MultichainAssetsRatesPollingInput): void;
@@ -81,8 +81,8 @@ export type ConversionRatesWithMarketData = {
81
81
  conversionRates: Record<CaipAssetType, Record<CaipAssetType, UnifiedAssetConversion | null>>;
82
82
  };
83
83
  declare const MultichainAssetsRatesController_base: (abstract new (...args: any[]) => {
84
- readonly "__#14@#intervalIds": Record<string, NodeJS.Timeout>;
85
- "__#14@#intervalLength": number | undefined;
84
+ readonly "__#15@#intervalIds": Record<string, NodeJS.Timeout>;
85
+ "__#15@#intervalLength": number | undefined;
86
86
  setIntervalLength(intervalLength: number): void;
87
87
  getIntervalLength(): number | undefined;
88
88
  _startPolling(input: MultichainAssetsRatesPollingInput): void;
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainAssetsRatesController.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsRatesController/MultichainAssetsRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAUA,OAAO,EAAsB,gBAAgB,EAAE,8BAA8B;AAO7E,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAc/E,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,mBAAmB,EAAE,uBAAmB;AAYjD;;GAEG;AACH,MAAM,cAAc,GAAG,iCAAiC,CAAC;AAwCzD;;;;;;;GAOG;AACH,MAAM,UAAU,8CAA8C;IAC5D,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,gBAAgB,EAAE,EAAE,EAAE,CAAC;AACvD,CAAC;AA2DD,MAAM,QAAQ,GAAwD;IACpE,eAAe,EAAE;QACf,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAkBF;;;;GAIG;AACH,MAAM,OAAO,+BAAgC,SAAQ,+BAA+B,EAInF;IASC;;;;;;;OAOG;IACH,YAAY,EACV,QAAQ,GAAG,KAAK,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,EAAG,KAAe,CAAC,OAAO;YACjC,MAAM;SACP,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;KAClB;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountAddedEvent,\n AccountsControllerGetSelectedMultichainAccountAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { type CaipAssetType, isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n SnapId,\n AssetConversion,\n OnAssetsConversionArguments,\n OnAssetHistoricalPriceArguments,\n OnAssetHistoricalPriceResponse,\n HistoricalPriceIntervals,\n OnAssetsMarketDataArguments,\n OnAssetsMarketDataResponse,\n FungibleAssetMarketData,\n OnAssetsConversionResponse,\n} from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { MAP_CAIP_CURRENCIES } from './constant';\nimport type {\n CurrencyRateState,\n CurrencyRateStateChange,\n GetCurrencyRateState,\n} from '../CurrencyRateController';\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n MultichainAssetsControllerState,\n} from '../MultichainAssetsController';\n\n/**\n * The name of the MultichainAssetsRatesController.\n */\nconst controllerName = 'MultichainAssetsRatesController';\n\n// This is temporary until its exported from snap\ntype HistoricalPrice = {\n intervals: HistoricalPriceIntervals;\n // The UNIX timestamp of when the historical price was last updated.\n updateTime: number;\n // The UNIX timestamp of when the historical price will expire.\n expirationTime?: number;\n};\n\n/**\n * State used by the MultichainAssetsRatesController to cache token conversion rates.\n */\nexport type MultichainAssetsRatesControllerState = {\n conversionRates: Record<CaipAssetType, UnifiedAssetConversion>;\n historicalPrices: Record<CaipAssetType, Record<string, HistoricalPrice>>; // string being the current currency we fetched historical prices for\n};\n\n/**\n * Returns the state of the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Action to update the rates of all supported tokens.\n */\nexport type MultichainAssetsRatesControllerUpdateRatesAction = {\n type: `${typeof controllerName}:updateAssetsRates`;\n handler: MultichainAssetsRatesController['updateAssetsRates'];\n};\n\ntype UnifiedAssetConversion = AssetConversion & {\n marketData?: FungibleAssetMarketData;\n};\n\n/**\n * Constructs the default {@link MultichainAssetsRatesController} 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 MultichainAssetsRatesController} state.\n */\nexport function getDefaultMultichainAssetsRatesControllerState(): MultichainAssetsRatesControllerState {\n return { conversionRates: {}, historicalPrices: {} };\n}\n\n/**\n * Event emitted when the state of the MultichainAssetsRatesController changes.\n */\nexport type MultichainAssetsRatesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Actions exposed by the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerActions =\n | MultichainAssetsRatesControllerGetStateAction\n | MultichainAssetsRatesControllerUpdateRatesAction;\n\n/**\n * Events emitted by MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerEvents =\n MultichainAssetsRatesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\nexport type AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | GetCurrencyRateState\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction;\n\n/**\n * Events that this controller is allowed to subscribe to.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | AccountsControllerAccountAddedEvent\n | CurrencyRateStateChange\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerMessenger = Messenger<\n typeof controllerName,\n MultichainAssetsRatesControllerActions | AllowedActions,\n MultichainAssetsRatesControllerEvents | AllowedEvents\n>;\n\n/**\n * The input for starting polling in MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesPollingInput = {\n accountId: string;\n};\n\nconst metadata: StateMetadata<MultichainAssetsRatesControllerState> = {\n conversionRates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n historicalPrices: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nexport type ConversionRatesWithMarketData = {\n conversionRates: Record<\n CaipAssetType,\n Record<CaipAssetType, UnifiedAssetConversion | null>\n >;\n};\n\n/**\n * Arguments for a Snap request.\n */\ntype SnapRequestArgs<T> = {\n snapId: SnapId;\n handler: HandlerType;\n params: T;\n};\n\n/**\n * Controller that manages multichain token conversion rates.\n *\n * This controller polls for token conversion rates and updates its state.\n */\nexport class MultichainAssetsRatesController extends StaticIntervalPollingController<MultichainAssetsRatesPollingInput>()<\n typeof controllerName,\n MultichainAssetsRatesControllerState,\n MultichainAssetsRatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n #currentCurrency: CurrencyRateState['currentCurrency'];\n\n readonly #accountsAssets: MultichainAssetsControllerState['accountsAssets'];\n\n #isUnlocked = true;\n\n /**\n * Creates an instance of MultichainAssetsRatesController.\n *\n * @param options - Constructor options.\n * @param options.interval - The polling interval in milliseconds.\n * @param options.state - The initial state.\n * @param options.messenger - A reference to the messenger.\n */\n constructor({\n interval = 18000,\n state = {},\n messenger,\n }: {\n interval?: number;\n state?: Partial<MultichainAssetsRatesControllerState>;\n messenger: MultichainAssetsRatesControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {\n ...getDefaultMultichainAssetsRatesControllerState(),\n ...state,\n },\n metadata,\n });\n\n this.setIntervalLength(interval);\n\n // Subscribe to keyring lock/unlock events.\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n ({ accountsAssets: this.#accountsAssets } = this.messenger.call(\n 'MultichainAssetsController:getState',\n ));\n\n ({ currentCurrency: this.#currentCurrency } = this.messenger.call(\n 'CurrencyRateController:getState',\n ));\n\n this.messenger.subscribe(\n 'CurrencyRateController:stateChange',\n async (currentCurrency: string) => {\n this.#currentCurrency = currentCurrency;\n await this.updateAssetsRates();\n },\n (currencyRateControllerState) =>\n currencyRateControllerState.currentCurrency,\n );\n\n this.messenger.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n // TODO; removed can be used in future for further cleanup\n await this.#updateAssetsRatesForNewAssets(newAccountAssets);\n },\n );\n }\n\n /**\n * Executes a poll by updating token conversion rates for the current account.\n *\n * @returns A promise that resolves when the polling completes.\n */\n async _executePoll(): Promise<void> {\n await this.updateAssetsRates();\n }\n\n /**\n * Determines whether the controller is active.\n *\n * @returns True if the keyring is unlocked; otherwise, false.\n */\n get isActive(): boolean {\n return this.#isUnlocked;\n }\n\n /**\n * Checks if an account is a non-EVM account with a Snap.\n *\n * @param account - The account to check.\n * @returns True if the account is non-EVM and has Snap metadata; otherwise, false.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) && account.metadata.snap !== undefined\n );\n }\n\n /**\n * Retrieves all multichain accounts from the AccountsController.\n *\n * @returns An array of internal accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messenger.call('AccountsController:listMultichainAccounts');\n }\n\n /**\n * Filters and returns non-EVM accounts that should have balances.\n *\n * @returns An array of non-EVM internal accounts.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Adds the assets to a map of Snap ID to assets.\n *\n * @param snapIdToAssets - The map of Snap ID to assets.\n * @param account - The account to add the assets for.\n * @param assets - The assets to add.\n */\n #addAssetsToSnapIdMap(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n account: InternalAccount,\n assets: CaipAssetType[],\n ): void {\n // Prevent creating a new set if there are no assets to add.\n if (assets.length === 0) {\n return;\n }\n\n // FIXME: Instead of using the Snap ID from the account, we should\n // select the Snap based on the supported scopes defined in the Snaps'\n // manifest.\n const snapId = account.metadata.snap?.id as SnapId | undefined;\n if (!snapId) {\n return;\n }\n\n let snapAssets = snapIdToAssets.get(snapId);\n if (!snapAssets) {\n snapAssets = new Set();\n snapIdToAssets.set(snapId, snapAssets);\n }\n\n for (const asset of assets) {\n snapAssets.add(asset);\n }\n }\n\n /**\n * Updates token conversion rates for each non-EVM account.\n *\n * @returns A promise that resolves when the rates are updated.\n */\n async updateAssetsRates(): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // Compute the set of unique assets from all accounts. It's important to\n // deduplicate assets here to avoid duplicate requests to the Snap.\n const accounts = this.#listAccounts();\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n for (const account of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n account,\n this.#getAssetsForAccount(account.id),\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Returns the CAIP-19 asset type for the current selected currency. Defaults\n * to USD if the current selected currency is not supported.\n *\n * @returns The CAIP-19 asset type for the current selected currency.\n */\n #getCaipCurrentCurrency(): CaipAssetType {\n return (\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd\n );\n }\n\n /**\n * Fetches the conversion rates for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the conversion rates for.\n * @param currency - The currency to fetch the conversion rates for.\n * @returns A record of CAIP-19 asset types to conversion rates.\n */\n async #getConversionRates(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, AssetConversion | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsConversion,\n params: {\n conversions: Array.from(assets).map((asset) => ({\n from: asset,\n to: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToConversionRate: Record<\n CaipAssetType,\n AssetConversion | undefined\n > = {};\n\n for (const asset of assets) {\n assetToConversionRate[asset] =\n response.conversionRates?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToConversionRate;\n }\n\n /**\n * Fetches the market data for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the market data for.\n * @param currency - The currency to fetch the market data for.\n * @returns A record of CAIP-19 asset types to market data.\n */\n async #getMarketData(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, FungibleAssetMarketData | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsMarketData,\n params: {\n assets: Array.from(assets).map((asset) => ({\n asset,\n unit: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToMarketData: Record<\n CaipAssetType,\n FungibleAssetMarketData | undefined\n > = {};\n\n for (const asset of assets) {\n assetToMarketData[asset] =\n response.marketData?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToMarketData;\n }\n\n /**\n * Fetches the updated rates for the given assets from the given Snaps.\n *\n * @param snapIdToAssets - A map of Snap ID to CAIP-19 asset types.\n * @returns A record of CAIP-19 asset types to unified asset conversions.\n */\n async #getUpdatedRatesFor(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n ): Promise<\n Record<CaipAssetType, UnifiedAssetConversion & { currency: CaipAssetType }>\n > {\n const updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n // Keep a local copy to ensure that the currency is always the same for the\n // entire loop.\n const currency = this.#getCaipCurrentCurrency();\n\n // Note: Since the assets come from a 1-to-1 mapping with Snap IDs, we know\n // that a given asset will not appear under multiple Snap IDs.\n for (const [snapId, assets] of snapIdToAssets.entries()) {\n const [rates, marketData] = await Promise.all([\n this.#getConversionRates(snapId, assets, currency),\n this.#getMarketData(snapId, assets, currency),\n ]);\n\n for (const asset of assets) {\n const assetRate = rates[asset];\n const assetMarketData = marketData[asset];\n\n // Rates are mandatory, so skip the asset if not available.\n if (!assetRate) {\n continue;\n }\n\n updatedRates[asset] = {\n currency,\n ...assetRate,\n ...(assetMarketData && { marketData: assetMarketData }),\n };\n }\n }\n\n return updatedRates;\n }\n\n /**\n * Fetches historical prices for the current account\n *\n * @param asset - The asset to fetch historical prices for.\n * @param account - optional account to fetch historical prices for\n * @returns The historical prices.\n */\n async fetchHistoricalPricesForAsset(\n asset: CaipAssetType,\n account?: InternalAccount,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n return (async () => {\n const currentCaipCurrency =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n // Check if we already have historical prices for this asset and currency\n const historicalPriceExpirationTime =\n this.state.historicalPrices[asset]?.[this.#currentCurrency]\n ?.expirationTime;\n\n const historicalPriceHasExpired =\n historicalPriceExpirationTime &&\n historicalPriceExpirationTime < Date.now();\n\n if (historicalPriceHasExpired === false) {\n return;\n }\n\n const selectedAccount =\n account ??\n this.messenger.call('AccountsController:getSelectedMultichainAccount');\n try {\n const historicalPricesResponse = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: selectedAccount?.metadata.snap?.id as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetHistoricalPrice,\n request: {\n jsonrpc: '2.0',\n method: HandlerType.OnAssetHistoricalPrice,\n params: {\n from: asset,\n to: currentCaipCurrency,\n },\n },\n },\n );\n\n // skip state update if no historical prices are returned\n if (!historicalPricesResponse) {\n return;\n }\n\n this.update((state) => {\n state.historicalPrices = {\n ...state.historicalPrices,\n [asset]: {\n ...state.historicalPrices[asset],\n [this.#currentCurrency]: (\n historicalPricesResponse as OnAssetHistoricalPriceResponse\n )?.historicalPrice,\n },\n };\n });\n } catch {\n throw new Error(\n `Failed to fetch historical prices for asset: ${asset}`,\n );\n }\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Updates the conversion rates for new assets.\n *\n * @param accounts - The accounts to update the conversion rates for.\n * @returns A promise that resolves when the rates are updated.\n */\n async #updateAssetsRatesForNewAssets(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // First build a map containing all assets that need to be updated per\n // Snap ID, this will be used to batch the requests.\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n\n for (const { accountId, assets } of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n this.#getAccount(accountId),\n assets,\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Returns the array of CAIP-19 assets for the given account ID.\n * If none are found, returns an empty array.\n *\n * @param accountId - The account ID to get the assets for.\n * @returns An array of CAIP-19 assets.\n */\n #getAssetsForAccount(accountId: string): CaipAssetType[] {\n return this.#accountsAssets?.[accountId] ?? [];\n }\n\n /**\n * Merges the new rates into the controller's state.\n *\n * @param updatedRates - The new rates to merge.\n */\n #applyUpdatedRates(\n updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n >,\n ): void {\n if (Object.keys(updatedRates).length === 0) {\n return;\n }\n this.update((state: Draft<MultichainAssetsRatesControllerState>) => {\n state.conversionRates = {\n ...state.conversionRates,\n ...updatedRates,\n };\n });\n }\n\n /**\n * Forwards a Snap request to the SnapController.\n *\n * @param args - The request parameters.\n * @param args.snapId - The ID of the Snap.\n * @param args.handler - The handler type.\n * @param args.params - The asset conversions.\n * @returns A promise that resolves with the account rates.\n */\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsConversionArguments>,\n ): Promise<OnAssetsConversionResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetHistoricalPriceArguments>,\n ): Promise<OnAssetHistoricalPriceResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsMarketDataArguments>,\n ): Promise<OnAssetsMarketDataResponse | undefined>;\n\n async #handleSnapRequest(args: SnapRequestArgs<unknown>): Promise<unknown> {\n const { snapId, handler, params } = args;\n try {\n return await this.messenger.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n jsonrpc: '2.0',\n method: handler,\n params,\n },\n });\n } catch (error) {\n console.error(`Snap request failed for ${handler}:`, {\n snapId,\n handler,\n message: (error as Error).message,\n params,\n });\n return undefined;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"MultichainAssetsRatesController.mjs","sourceRoot":"","sources":["../../src/MultichainAsset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IACnB,CAAC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountAddedEvent,\n AccountsControllerGetSelectedMultichainAccountAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerStateChangeEvent,\n ControllerGetStateAction,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { type CaipAssetType, isEvmAccountType } from '@metamask/keyring-api';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n SnapId,\n AssetConversion,\n OnAssetsConversionArguments,\n OnAssetHistoricalPriceArguments,\n OnAssetHistoricalPriceResponse,\n HistoricalPriceIntervals,\n OnAssetsMarketDataArguments,\n OnAssetsMarketDataResponse,\n FungibleAssetMarketData,\n OnAssetsConversionResponse,\n} from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { MAP_CAIP_CURRENCIES } from './constant';\nimport type {\n CurrencyRateState,\n CurrencyRateStateChange,\n GetCurrencyRateState,\n} from '../CurrencyRateController';\nimport type {\n MultichainAssetsControllerGetStateAction,\n MultichainAssetsControllerAccountAssetListUpdatedEvent,\n MultichainAssetsControllerState,\n} from '../MultichainAssetsController';\n\n/**\n * The name of the MultichainAssetsRatesController.\n */\nconst controllerName = 'MultichainAssetsRatesController';\n\n// This is temporary until its exported from snap\ntype HistoricalPrice = {\n intervals: HistoricalPriceIntervals;\n // The UNIX timestamp of when the historical price was last updated.\n updateTime: number;\n // The UNIX timestamp of when the historical price will expire.\n expirationTime?: number;\n};\n\n/**\n * State used by the MultichainAssetsRatesController to cache token conversion rates.\n */\nexport type MultichainAssetsRatesControllerState = {\n conversionRates: Record<CaipAssetType, UnifiedAssetConversion>;\n historicalPrices: Record<CaipAssetType, Record<string, HistoricalPrice>>; // string being the current currency we fetched historical prices for\n};\n\n/**\n * Returns the state of the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Action to update the rates of all supported tokens.\n */\nexport type MultichainAssetsRatesControllerUpdateRatesAction = {\n type: `${typeof controllerName}:updateAssetsRates`;\n handler: MultichainAssetsRatesController['updateAssetsRates'];\n};\n\ntype UnifiedAssetConversion = AssetConversion & {\n marketData?: FungibleAssetMarketData;\n};\n\n/**\n * Constructs the default {@link MultichainAssetsRatesController} 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 MultichainAssetsRatesController} state.\n */\nexport function getDefaultMultichainAssetsRatesControllerState(): MultichainAssetsRatesControllerState {\n return { conversionRates: {}, historicalPrices: {} };\n}\n\n/**\n * Event emitted when the state of the MultichainAssetsRatesController changes.\n */\nexport type MultichainAssetsRatesControllerStateChange =\n ControllerStateChangeEvent<\n typeof controllerName,\n MultichainAssetsRatesControllerState\n >;\n\n/**\n * Actions exposed by the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerActions =\n | MultichainAssetsRatesControllerGetStateAction\n | MultichainAssetsRatesControllerUpdateRatesAction;\n\n/**\n * Events emitted by MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerEvents =\n MultichainAssetsRatesControllerStateChange;\n\n/**\n * Actions that this controller is allowed to call.\n */\nexport type AllowedActions =\n | HandleSnapRequest\n | AccountsControllerListMultichainAccountsAction\n | GetCurrencyRateState\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction;\n\n/**\n * Events that this controller is allowed to subscribe to.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | AccountsControllerAccountAddedEvent\n | CurrencyRateStateChange\n | MultichainAssetsControllerAccountAssetListUpdatedEvent;\n/**\n * Messenger type for the MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesControllerMessenger = Messenger<\n typeof controllerName,\n MultichainAssetsRatesControllerActions | AllowedActions,\n MultichainAssetsRatesControllerEvents | AllowedEvents\n>;\n\n/**\n * The input for starting polling in MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesPollingInput = {\n accountId: string;\n};\n\nconst metadata: StateMetadata<MultichainAssetsRatesControllerState> = {\n conversionRates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n historicalPrices: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nexport type ConversionRatesWithMarketData = {\n conversionRates: Record<\n CaipAssetType,\n Record<CaipAssetType, UnifiedAssetConversion | null>\n >;\n};\n\n/**\n * Arguments for a Snap request.\n */\ntype SnapRequestArgs<T> = {\n snapId: SnapId;\n handler: HandlerType;\n params: T;\n};\n\n/**\n * Controller that manages multichain token conversion rates.\n *\n * This controller polls for token conversion rates and updates its state.\n */\nexport class MultichainAssetsRatesController extends StaticIntervalPollingController<MultichainAssetsRatesPollingInput>()<\n typeof controllerName,\n MultichainAssetsRatesControllerState,\n MultichainAssetsRatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n #currentCurrency: CurrencyRateState['currentCurrency'];\n\n readonly #accountsAssets: MultichainAssetsControllerState['accountsAssets'];\n\n #isUnlocked = true;\n\n /**\n * Creates an instance of MultichainAssetsRatesController.\n *\n * @param options - Constructor options.\n * @param options.interval - The polling interval in milliseconds.\n * @param options.state - The initial state.\n * @param options.messenger - A reference to the messenger.\n */\n constructor({\n interval = 18000,\n state = {},\n messenger,\n }: {\n interval?: number;\n state?: Partial<MultichainAssetsRatesControllerState>;\n messenger: MultichainAssetsRatesControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {\n ...getDefaultMultichainAssetsRatesControllerState(),\n ...state,\n },\n metadata,\n });\n\n this.setIntervalLength(interval);\n\n // Subscribe to keyring lock/unlock events.\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n ({ accountsAssets: this.#accountsAssets } = this.messenger.call(\n 'MultichainAssetsController:getState',\n ));\n\n ({ currentCurrency: this.#currentCurrency } = this.messenger.call(\n 'CurrencyRateController:getState',\n ));\n\n this.messenger.subscribe(\n 'CurrencyRateController:stateChange',\n async (currentCurrency: string) => {\n this.#currentCurrency = currentCurrency;\n await this.updateAssetsRates();\n },\n (currencyRateControllerState) =>\n currencyRateControllerState.currentCurrency,\n );\n\n this.messenger.subscribe(\n 'MultichainAssetsController:accountAssetListUpdated',\n async ({ assets }) => {\n const newAccountAssets = Object.entries(assets).map(\n ([accountId, { added }]) => ({\n accountId,\n assets: [...added],\n }),\n );\n // TODO; removed can be used in future for further cleanup\n await this.#updateAssetsRatesForNewAssets(newAccountAssets);\n },\n );\n }\n\n /**\n * Executes a poll by updating token conversion rates for the current account.\n *\n * @returns A promise that resolves when the polling completes.\n */\n async _executePoll(): Promise<void> {\n await this.updateAssetsRates();\n }\n\n /**\n * Determines whether the controller is active.\n *\n * @returns True if the keyring is unlocked; otherwise, false.\n */\n get isActive(): boolean {\n return this.#isUnlocked;\n }\n\n /**\n * Checks if an account is a non-EVM account with a Snap.\n *\n * @param account - The account to check.\n * @returns True if the account is non-EVM and has Snap metadata; otherwise, false.\n */\n #isNonEvmAccount(account: InternalAccount): boolean {\n return (\n !isEvmAccountType(account.type) && account.metadata.snap !== undefined\n );\n }\n\n /**\n * Retrieves all multichain accounts from the AccountsController.\n *\n * @returns An array of internal accounts.\n */\n #listMultichainAccounts(): InternalAccount[] {\n return this.messenger.call('AccountsController:listMultichainAccounts');\n }\n\n /**\n * Filters and returns non-EVM accounts that should have balances.\n *\n * @returns An array of non-EVM internal accounts.\n */\n #listAccounts(): InternalAccount[] {\n const accounts = this.#listMultichainAccounts();\n return accounts.filter((account) => this.#isNonEvmAccount(account));\n }\n\n /**\n * Adds the assets to a map of Snap ID to assets.\n *\n * @param snapIdToAssets - The map of Snap ID to assets.\n * @param account - The account to add the assets for.\n * @param assets - The assets to add.\n */\n #addAssetsToSnapIdMap(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n account: InternalAccount,\n assets: CaipAssetType[],\n ): void {\n // Prevent creating a new set if there are no assets to add.\n if (assets.length === 0) {\n return;\n }\n\n // FIXME: Instead of using the Snap ID from the account, we should\n // select the Snap based on the supported scopes defined in the Snaps'\n // manifest.\n const snapId = account.metadata.snap?.id as SnapId | undefined;\n if (!snapId) {\n return;\n }\n\n let snapAssets = snapIdToAssets.get(snapId);\n if (!snapAssets) {\n snapAssets = new Set();\n snapIdToAssets.set(snapId, snapAssets);\n }\n\n for (const asset of assets) {\n snapAssets.add(asset);\n }\n }\n\n /**\n * Updates token conversion rates for each non-EVM account.\n *\n * @returns A promise that resolves when the rates are updated.\n */\n async updateAssetsRates(): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // Compute the set of unique assets from all accounts. It's important to\n // deduplicate assets here to avoid duplicate requests to the Snap.\n const accounts = this.#listAccounts();\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n for (const account of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n account,\n this.#getAssetsForAccount(account.id),\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Returns the CAIP-19 asset type for the current selected currency. Defaults\n * to USD if the current selected currency is not supported.\n *\n * @returns The CAIP-19 asset type for the current selected currency.\n */\n #getCaipCurrentCurrency(): CaipAssetType {\n return (\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd\n );\n }\n\n /**\n * Fetches the conversion rates for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the conversion rates for.\n * @param currency - The currency to fetch the conversion rates for.\n * @returns A record of CAIP-19 asset types to conversion rates.\n */\n async #getConversionRates(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, AssetConversion | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsConversion,\n params: {\n conversions: Array.from(assets).map((asset) => ({\n from: asset,\n to: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToConversionRate: Record<\n CaipAssetType,\n AssetConversion | undefined\n > = {};\n\n for (const asset of assets) {\n assetToConversionRate[asset] =\n response.conversionRates?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToConversionRate;\n }\n\n /**\n * Fetches the market data for the given assets from the given Snap.\n *\n * @param snapId - The ID of the Snap.\n * @param assets - The assets to fetch the market data for.\n * @param currency - The currency to fetch the market data for.\n * @returns A record of CAIP-19 asset types to market data.\n */\n async #getMarketData(\n snapId: SnapId,\n assets: Set<CaipAssetType>,\n currency: CaipAssetType,\n ): Promise<Record<CaipAssetType, FungibleAssetMarketData | undefined>> {\n // Prevent making a Snap call if there are no assets to fetch.\n if (assets.size === 0) {\n return {};\n }\n\n const response = await this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnAssetsMarketData,\n params: {\n assets: Array.from(assets).map((asset) => ({\n asset,\n unit: currency,\n })),\n },\n });\n\n if (!response) {\n return {};\n }\n\n const assetToMarketData: Record<\n CaipAssetType,\n FungibleAssetMarketData | undefined\n > = {};\n\n for (const asset of assets) {\n assetToMarketData[asset] =\n response.marketData?.[asset]?.[currency] ?? undefined;\n }\n\n return assetToMarketData;\n }\n\n /**\n * Fetches the updated rates for the given assets from the given Snaps.\n *\n * @param snapIdToAssets - A map of Snap ID to CAIP-19 asset types.\n * @returns A record of CAIP-19 asset types to unified asset conversions.\n */\n async #getUpdatedRatesFor(\n snapIdToAssets: Map<SnapId, Set<CaipAssetType>>,\n ): Promise<\n Record<CaipAssetType, UnifiedAssetConversion & { currency: CaipAssetType }>\n > {\n const updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n // Keep a local copy to ensure that the currency is always the same for the\n // entire loop.\n const currency = this.#getCaipCurrentCurrency();\n\n // Note: Since the assets come from a 1-to-1 mapping with Snap IDs, we know\n // that a given asset will not appear under multiple Snap IDs.\n for (const [snapId, assets] of snapIdToAssets.entries()) {\n const [rates, marketData] = await Promise.all([\n this.#getConversionRates(snapId, assets, currency),\n this.#getMarketData(snapId, assets, currency),\n ]);\n\n for (const asset of assets) {\n const assetRate = rates[asset];\n const assetMarketData = marketData[asset];\n\n // Rates are mandatory, so skip the asset if not available.\n if (!assetRate) {\n continue;\n }\n\n updatedRates[asset] = {\n currency,\n ...assetRate,\n ...(assetMarketData && { marketData: assetMarketData }),\n };\n }\n }\n\n return updatedRates;\n }\n\n /**\n * Fetches historical prices for the current account\n *\n * @param asset - The asset to fetch historical prices for.\n * @param account - optional account to fetch historical prices for\n * @returns The historical prices.\n */\n async fetchHistoricalPricesForAsset(\n asset: CaipAssetType,\n account?: InternalAccount,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n return (async () => {\n const currentCaipCurrency =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n // Check if we already have historical prices for this asset and currency\n const historicalPriceExpirationTime =\n this.state.historicalPrices[asset]?.[this.#currentCurrency]\n ?.expirationTime;\n\n const historicalPriceHasExpired =\n historicalPriceExpirationTime &&\n historicalPriceExpirationTime < Date.now();\n\n if (historicalPriceHasExpired === false) {\n return;\n }\n\n const selectedAccount =\n account ??\n this.messenger.call('AccountsController:getSelectedMultichainAccount');\n try {\n const historicalPricesResponse = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: selectedAccount?.metadata.snap?.id as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnAssetHistoricalPrice,\n request: {\n jsonrpc: '2.0',\n method: HandlerType.OnAssetHistoricalPrice,\n params: {\n from: asset,\n to: currentCaipCurrency,\n },\n },\n },\n );\n\n // skip state update if no historical prices are returned\n if (!historicalPricesResponse) {\n return;\n }\n\n this.update((state) => {\n state.historicalPrices = {\n ...state.historicalPrices,\n [asset]: {\n ...state.historicalPrices[asset],\n [this.#currentCurrency]: (\n historicalPricesResponse as OnAssetHistoricalPriceResponse\n )?.historicalPrice,\n },\n };\n });\n } catch {\n throw new Error(\n `Failed to fetch historical prices for asset: ${asset}`,\n );\n }\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Updates the conversion rates for new assets.\n *\n * @param accounts - The accounts to update the conversion rates for.\n * @returns A promise that resolves when the rates are updated.\n */\n async #updateAssetsRatesForNewAssets(\n accounts: {\n accountId: string;\n assets: CaipAssetType[];\n }[],\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n return (async () => {\n if (!this.isActive) {\n return;\n }\n\n // First build a map containing all assets that need to be updated per\n // Snap ID, this will be used to batch the requests.\n const snapIdToAssets = new Map<SnapId, Set<CaipAssetType>>();\n\n for (const { accountId, assets } of accounts) {\n this.#addAssetsToSnapIdMap(\n snapIdToAssets,\n this.#getAccount(accountId),\n assets,\n );\n }\n\n this.#applyUpdatedRates(await this.#getUpdatedRatesFor(snapIdToAssets));\n })().finally(() => {\n releaseLock();\n });\n }\n\n /**\n * Get a non-EVM account from its ID.\n *\n * @param accountId - The account ID.\n * @returns The non-EVM account.\n */\n #getAccount(accountId: string): InternalAccount {\n const account: InternalAccount | undefined = this.#listAccounts().find(\n (multichainAccount) => multichainAccount.id === accountId,\n );\n\n if (!account) {\n throw new Error(`Unknown account: ${accountId}`);\n }\n\n return account;\n }\n\n /**\n * Returns the array of CAIP-19 assets for the given account ID.\n * If none are found, returns an empty array.\n *\n * @param accountId - The account ID to get the assets for.\n * @returns An array of CAIP-19 assets.\n */\n #getAssetsForAccount(accountId: string): CaipAssetType[] {\n return this.#accountsAssets?.[accountId] ?? [];\n }\n\n /**\n * Merges the new rates into the controller's state.\n *\n * @param updatedRates - The new rates to merge.\n */\n #applyUpdatedRates(\n updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n >,\n ): void {\n if (Object.keys(updatedRates).length === 0) {\n return;\n }\n this.update((state: Draft<MultichainAssetsRatesControllerState>) => {\n state.conversionRates = {\n ...state.conversionRates,\n ...updatedRates,\n };\n });\n }\n\n /**\n * Forwards a Snap request to the SnapController.\n *\n * @param args - The request parameters.\n * @param args.snapId - The ID of the Snap.\n * @param args.handler - The handler type.\n * @param args.params - The asset conversions.\n * @returns A promise that resolves with the account rates.\n */\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsConversionArguments>,\n ): Promise<OnAssetsConversionResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetHistoricalPriceArguments>,\n ): Promise<OnAssetHistoricalPriceResponse | undefined>;\n\n async #handleSnapRequest(\n args: SnapRequestArgs<OnAssetsMarketDataArguments>,\n ): Promise<OnAssetsMarketDataResponse | undefined>;\n\n async #handleSnapRequest(args: SnapRequestArgs<unknown>): Promise<unknown> {\n const { snapId, handler, params } = args;\n try {\n return await this.messenger.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n jsonrpc: '2.0',\n method: handler,\n params,\n },\n });\n } catch (error) {\n console.error(`Snap request failed for ${handler}:`, {\n snapId,\n handler,\n message: (error as Error).message,\n params,\n });\n return undefined;\n }\n }\n}\n"]}
@@ -114,11 +114,11 @@ async function _MultichainBalancesController_handleOnAccountAssetListUpdated(acc
114
114
  else {
115
115
  const acc = accountsMap.get(accountId);
116
116
  const assetsWithoutBalance = new Set(acc?.assets || []);
117
- for (const assetId in accountBalances) {
117
+ for (const assetId of Object.keys(accountBalances)) {
118
118
  if (!state.balances[accountId][assetId]) {
119
119
  state.balances[accountId][assetId] = accountBalances[assetId];
120
- assetsWithoutBalance.delete(assetId);
121
120
  }
121
+ assetsWithoutBalance.delete(assetId);
122
122
  }
123
123
  // Triggered when an asset is added to the accountAssets list manually
124
124
  for (const assetId of assetsWithoutBalance) {