@metamask-previews/assets-controllers 76.0.0-preview-8ccfcb37 → 76.0.0-preview-b896289e

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 (88) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/AccountTrackerController.cjs +18 -19
  3. package/dist/AccountTrackerController.cjs.map +1 -1
  4. package/dist/AccountTrackerController.d.cts +7 -6
  5. package/dist/AccountTrackerController.d.cts.map +1 -1
  6. package/dist/AccountTrackerController.d.mts +7 -6
  7. package/dist/AccountTrackerController.d.mts.map +1 -1
  8. package/dist/AccountTrackerController.mjs +18 -19
  9. package/dist/AccountTrackerController.mjs.map +1 -1
  10. package/dist/AssetsContractController.cjs.map +1 -1
  11. package/dist/AssetsContractController.d.cts +2 -2
  12. package/dist/AssetsContractController.d.cts.map +1 -1
  13. package/dist/AssetsContractController.d.mts +2 -2
  14. package/dist/AssetsContractController.d.mts.map +1 -1
  15. package/dist/AssetsContractController.mjs.map +1 -1
  16. package/dist/CurrencyRateController.cjs +3 -3
  17. package/dist/CurrencyRateController.cjs.map +1 -1
  18. package/dist/CurrencyRateController.d.cts +7 -6
  19. package/dist/CurrencyRateController.d.cts.map +1 -1
  20. package/dist/CurrencyRateController.d.mts +7 -6
  21. package/dist/CurrencyRateController.d.mts.map +1 -1
  22. package/dist/CurrencyRateController.mjs +3 -3
  23. package/dist/CurrencyRateController.mjs.map +1 -1
  24. package/dist/DeFiPositionsController/DeFiPositionsController.cjs +7 -7
  25. package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
  26. package/dist/DeFiPositionsController/DeFiPositionsController.d.cts +6 -5
  27. package/dist/DeFiPositionsController/DeFiPositionsController.d.cts.map +1 -1
  28. package/dist/DeFiPositionsController/DeFiPositionsController.d.mts +6 -5
  29. package/dist/DeFiPositionsController/DeFiPositionsController.d.mts.map +1 -1
  30. package/dist/DeFiPositionsController/DeFiPositionsController.mjs +7 -7
  31. package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
  32. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs +13 -13
  33. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
  34. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts +7 -6
  35. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts.map +1 -1
  36. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts +7 -6
  37. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts.map +1 -1
  38. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs +13 -13
  39. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
  40. package/dist/NftController.cjs +27 -27
  41. package/dist/NftController.cjs.map +1 -1
  42. package/dist/NftController.d.cts +3 -3
  43. package/dist/NftController.d.cts.map +1 -1
  44. package/dist/NftController.d.mts +3 -3
  45. package/dist/NftController.d.mts.map +1 -1
  46. package/dist/NftController.mjs +26 -26
  47. package/dist/NftController.mjs.map +1 -1
  48. package/dist/TokenBalancesController.cjs +17 -17
  49. package/dist/TokenBalancesController.cjs.map +1 -1
  50. package/dist/TokenBalancesController.d.cts +6 -5
  51. package/dist/TokenBalancesController.d.cts.map +1 -1
  52. package/dist/TokenBalancesController.d.mts +6 -5
  53. package/dist/TokenBalancesController.d.mts.map +1 -1
  54. package/dist/TokenBalancesController.mjs +17 -17
  55. package/dist/TokenBalancesController.mjs.map +1 -1
  56. package/dist/TokenDetectionController.cjs +23 -23
  57. package/dist/TokenDetectionController.cjs.map +1 -1
  58. package/dist/TokenDetectionController.d.cts +7 -6
  59. package/dist/TokenDetectionController.d.cts.map +1 -1
  60. package/dist/TokenDetectionController.d.mts +7 -6
  61. package/dist/TokenDetectionController.d.mts.map +1 -1
  62. package/dist/TokenDetectionController.mjs +23 -23
  63. package/dist/TokenDetectionController.mjs.map +1 -1
  64. package/dist/TokenListController.cjs +4 -4
  65. package/dist/TokenListController.cjs.map +1 -1
  66. package/dist/TokenListController.d.cts +6 -5
  67. package/dist/TokenListController.d.cts.map +1 -1
  68. package/dist/TokenListController.d.mts +6 -5
  69. package/dist/TokenListController.d.mts.map +1 -1
  70. package/dist/TokenListController.mjs +4 -4
  71. package/dist/TokenListController.mjs.map +1 -1
  72. package/dist/TokenRatesController.cjs +6 -6
  73. package/dist/TokenRatesController.cjs.map +1 -1
  74. package/dist/TokenRatesController.d.cts +6 -5
  75. package/dist/TokenRatesController.d.cts.map +1 -1
  76. package/dist/TokenRatesController.d.mts +6 -5
  77. package/dist/TokenRatesController.d.mts.map +1 -1
  78. package/dist/TokenRatesController.mjs +6 -6
  79. package/dist/TokenRatesController.mjs.map +1 -1
  80. package/dist/TokensController.cjs +19 -19
  81. package/dist/TokensController.cjs.map +1 -1
  82. package/dist/TokensController.d.cts +4 -3
  83. package/dist/TokensController.d.cts.map +1 -1
  84. package/dist/TokensController.d.mts +4 -3
  85. package/dist/TokensController.d.mts.map +1 -1
  86. package/dist/TokensController.mjs +18 -18
  87. package/dist/TokensController.mjs.map +1 -1
  88. package/package.json +2 -1
@@ -36,13 +36,13 @@ const metadata = {
36
36
  conversionRates: {
37
37
  includeInStateLogs: false,
38
38
  persist: true,
39
- anonymous: true,
39
+ includeInDebugSnapshot: true,
40
40
  usedInUi: true,
41
41
  },
42
42
  historicalPrices: {
43
43
  includeInStateLogs: false,
44
44
  persist: false,
45
- anonymous: true,
45
+ includeInDebugSnapshot: true,
46
46
  usedInUi: true,
47
47
  },
48
48
  };
@@ -58,7 +58,7 @@ export class MultichainAssetsRatesController extends StaticIntervalPollingContro
58
58
  * @param options - Constructor options.
59
59
  * @param options.interval - The polling interval in milliseconds.
60
60
  * @param options.state - The initial state.
61
- * @param options.messenger - A reference to the messaging system.
61
+ * @param options.messenger - A reference to the messenger.
62
62
  */
63
63
  constructor({ interval = 18000, state = {}, messenger, }) {
64
64
  var _a, _b;
@@ -78,19 +78,19 @@ export class MultichainAssetsRatesController extends StaticIntervalPollingContro
78
78
  _MultichainAssetsRatesController_isUnlocked.set(this, true);
79
79
  this.setIntervalLength(interval);
80
80
  // Subscribe to keyring lock/unlock events.
81
- this.messagingSystem.subscribe('KeyringController:lock', () => {
81
+ this.messenger.subscribe('KeyringController:lock', () => {
82
82
  __classPrivateFieldSet(this, _MultichainAssetsRatesController_isUnlocked, false, "f");
83
83
  });
84
- this.messagingSystem.subscribe('KeyringController:unlock', () => {
84
+ this.messenger.subscribe('KeyringController:unlock', () => {
85
85
  __classPrivateFieldSet(this, _MultichainAssetsRatesController_isUnlocked, true, "f");
86
86
  });
87
- (_a = this, { accountsAssets: ({ set value(_c) { __classPrivateFieldSet(_a, _MultichainAssetsRatesController_accountsAssets, _c, "f"); } }).value } = this.messagingSystem.call('MultichainAssetsController:getState'));
88
- (_b = this, { currentCurrency: ({ set value(_c) { __classPrivateFieldSet(_b, _MultichainAssetsRatesController_currentCurrency, _c, "f"); } }).value } = this.messagingSystem.call('CurrencyRateController:getState'));
89
- this.messagingSystem.subscribe('CurrencyRateController:stateChange', async (currentCurrency) => {
87
+ (_a = this, { accountsAssets: ({ set value(_c) { __classPrivateFieldSet(_a, _MultichainAssetsRatesController_accountsAssets, _c, "f"); } }).value } = this.messenger.call('MultichainAssetsController:getState'));
88
+ (_b = this, { currentCurrency: ({ set value(_c) { __classPrivateFieldSet(_b, _MultichainAssetsRatesController_currentCurrency, _c, "f"); } }).value } = this.messenger.call('CurrencyRateController:getState'));
89
+ this.messenger.subscribe('CurrencyRateController:stateChange', async (currentCurrency) => {
90
90
  __classPrivateFieldSet(this, _MultichainAssetsRatesController_currentCurrency, currentCurrency, "f");
91
91
  await this.updateAssetsRates();
92
92
  }, (currencyRateControllerState) => currencyRateControllerState.currentCurrency);
93
- this.messagingSystem.subscribe('MultichainAssetsController:accountAssetListUpdated', async ({ assets }) => {
93
+ this.messenger.subscribe('MultichainAssetsController:accountAssetListUpdated', async ({ assets }) => {
94
94
  const newAccountAssets = Object.entries(assets).map(([accountId, { added }]) => ({
95
95
  accountId,
96
96
  assets: [...added],
@@ -160,9 +160,9 @@ export class MultichainAssetsRatesController extends StaticIntervalPollingContro
160
160
  return;
161
161
  }
162
162
  const selectedAccount = account ??
163
- this.messagingSystem.call('AccountsController:getSelectedMultichainAccount');
163
+ this.messenger.call('AccountsController:getSelectedMultichainAccount');
164
164
  try {
165
- const historicalPricesResponse = await this.messagingSystem.call('SnapController:handleRequest', {
165
+ const historicalPricesResponse = await this.messenger.call('SnapController:handleRequest', {
166
166
  snapId: selectedAccount?.metadata.snap?.id,
167
167
  origin: 'metamask',
168
168
  handler: HandlerType.OnAssetHistoricalPrice,
@@ -200,7 +200,7 @@ export class MultichainAssetsRatesController extends StaticIntervalPollingContro
200
200
  _MultichainAssetsRatesController_mutex = new WeakMap(), _MultichainAssetsRatesController_currentCurrency = new WeakMap(), _MultichainAssetsRatesController_accountsAssets = new WeakMap(), _MultichainAssetsRatesController_isUnlocked = new WeakMap(), _MultichainAssetsRatesController_instances = new WeakSet(), _MultichainAssetsRatesController_isNonEvmAccount = function _MultichainAssetsRatesController_isNonEvmAccount(account) {
201
201
  return (!isEvmAccountType(account.type) && account.metadata.snap !== undefined);
202
202
  }, _MultichainAssetsRatesController_listMultichainAccounts = function _MultichainAssetsRatesController_listMultichainAccounts() {
203
- return this.messagingSystem.call('AccountsController:listMultichainAccounts');
203
+ return this.messenger.call('AccountsController:listMultichainAccounts');
204
204
  }, _MultichainAssetsRatesController_listAccounts = function _MultichainAssetsRatesController_listAccounts() {
205
205
  const accounts = __classPrivateFieldGet(this, _MultichainAssetsRatesController_instances, "m", _MultichainAssetsRatesController_listMultichainAccounts).call(this);
206
206
  return accounts.filter((account) => __classPrivateFieldGet(this, _MultichainAssetsRatesController_instances, "m", _MultichainAssetsRatesController_isNonEvmAccount).call(this, account));
@@ -325,7 +325,7 @@ async function _MultichainAssetsRatesController_updateAssetsRatesForNewAssets(ac
325
325
  */
326
326
  async function _MultichainAssetsRatesController_handleSnapRequest({ snapId, handler, params, }) {
327
327
  try {
328
- return (await this.messagingSystem.call('SnapController:handleRequest', {
328
+ return (await this.messenger.call('SnapController:handleRequest', {
329
329
  snapId,
330
330
  origin: 'metamask',
331
331
  handler,
@@ -1 +1 @@
1
- {"version":3,"file":"MultichainAssetsRatesController.mjs","sourceRoot":"","sources":["../../src/MultichainAssetsRatesController/MultichainAssetsRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAUA,OAAO,EAAsB,gBAAgB,EAAE,8BAA8B;AAM7E,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAc/E,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,KAAK,EAAE,oBAAoB;;;AAIpC,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;AA6DD,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE;QACf,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AASF;;;;GAIG;AACH,MAAM,OAAO,+BAAgC,SAAQ,+BAA+B,EAInF;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,G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AC,YAAY,CAAC,CAAC,aAAa,CAAC,CAAC;YAClE,IAAI,CAAC,YAAY,EAAE;gBACjB,SAAS;aACV;YAED,sDAAsD;YACtD,eAAe,CAAC,YAAY,CAAC,CAAC,aAAa,CAAC,GAAG;gBAC7C,GAAG,YAAY;gBACf,UAAU,EAAE,qBAAqB,IAAI,SAAS;aAC/C,CAAC;SACH;KACF;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n AccountsControllerListMultichainAccountsAction,\n AccountsControllerAccountAddedEvent,\n AccountsControllerGetSelectedMultichainAccountAction,\n} from '@metamask/accounts-controller';\nimport type {\n RestrictedMessenger,\n ControllerStateChangeEvent,\n ControllerGetStateAction,\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 { 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';\nimport { cloneDeep } from 'lodash';\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 = RestrictedMessenger<\n typeof controllerName,\n MultichainAssetsRatesControllerActions | AllowedActions,\n MultichainAssetsRatesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * The input for starting polling in MultichainAssetsRatesController.\n */\nexport type MultichainAssetsRatesPollingInput = {\n accountId: string;\n};\n\nconst metadata = {\n conversionRates: {\n includeInStateLogs: false,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n historicalPrices: {\n includeInStateLogs: false,\n persist: false,\n anonymous: 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 * 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 messaging system.\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.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n ({ accountsAssets: this.#accountsAssets } = this.messagingSystem.call(\n 'MultichainAssetsController:getState',\n ));\n\n ({ currentCurrency: this.#currentCurrency } = this.messagingSystem.call(\n 'CurrencyRateController:getState',\n ));\n\n this.messagingSystem.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.messagingSystem.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.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\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 * 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 const accounts = this.#listAccounts();\n\n for (const account of accounts) {\n const assets = this.#getAssetsForAccount(account.id);\n\n if (assets?.length === 0) {\n continue;\n }\n\n const rates = await this.#getUpdatedRatesFor(account, assets);\n // Apply these updated rates to controller state\n this.#applyUpdatedRates(rates);\n }\n })().finally(() => {\n releaseLock();\n });\n }\n\n async #getUpdatedRatesFor(\n account: InternalAccount,\n assets: CaipAssetType[],\n ): Promise<\n Record<string, UnifiedAssetConversion & { currency: CaipAssetType }>\n > {\n // Do not attempt to retrieve rates from Snap if there are no assets\n if (!assets.length) {\n return {};\n }\n\n // Build the conversions array\n const conversions = this.#buildConversions(assets);\n\n // Retrieve rates from Snap\n const accountRatesResponse = (await this.#handleSnapRequest({\n snapId: account?.metadata.snap?.id as SnapId,\n handler: HandlerType.OnAssetsConversion,\n params: conversions,\n })) as OnAssetsConversionResponse | null;\n\n // If the snap request failed, return empty rates\n if (!accountRatesResponse) {\n return {};\n }\n\n // Prepare assets param for onAssetsMarketData\n const currentCurrencyCaip =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n const assetsParam = {\n assets: assets.map((asset) => ({ asset, unit: currentCurrencyCaip })),\n };\n\n // Retrieve Market Data from Snap\n const marketDataResponse = (await this.#handleSnapRequest({\n snapId: account?.metadata.snap?.id as SnapId,\n handler: HandlerType.OnAssetsMarketData,\n params: assetsParam as OnAssetsMarketDataArguments,\n })) as OnAssetsMarketDataResponse | null;\n\n // Merge market data into conversion rates if available\n const mergedRates = this.#mergeMarketDataIntoConversionRates(\n accountRatesResponse,\n marketDataResponse,\n );\n\n // Flatten nested rates if needed\n const flattenedRates = this.#flattenRates(mergedRates);\n\n // Build the updatedRates object for these assets\n const updatedRates = this.#buildUpdatedRates(assets, flattenedRates);\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.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n try {\n const historicalPricesResponse = await this.messagingSystem.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 const allNewRates: Record<\n string,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n for (const { accountId, assets } of accounts) {\n const account = this.#getAccount(accountId);\n\n const rates = await this.#getUpdatedRatesFor(account, assets);\n // Track new rates\n for (const [asset, rate] of Object.entries(rates)) {\n allNewRates[asset] = rate;\n }\n }\n\n this.#applyUpdatedRates(allNewRates);\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 * Builds a conversions array (from each asset → the current currency).\n *\n * @param assets - The assets to build the conversions for.\n * @returns A conversions array.\n */\n #buildConversions(assets: CaipAssetType[]): OnAssetsConversionArguments {\n const currency =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n return {\n conversions: assets.map((asset) => ({\n from: asset,\n to: currency,\n })),\n };\n }\n\n /**\n * Flattens any nested structure in the conversion rates returned by Snap.\n *\n * @param assetsConversionResponse - The conversion rates to flatten.\n * @returns A flattened rates object.\n */\n #flattenRates(\n assetsConversionResponse: ConversionRatesWithMarketData | null,\n ): Record<CaipAssetType, UnifiedAssetConversion | null> {\n if (!assetsConversionResponse?.conversionRates) {\n return {};\n }\n\n const { conversionRates } = assetsConversionResponse;\n\n return Object.fromEntries(\n Object.entries(conversionRates).map(([asset, nestedObj]) => {\n // e.g., nestedObj might look like: { \"swift:0/iso4217:EUR\": { rate, conversionTime } }\n const singleValue = Object.values(nestedObj)[0];\n return [asset, singleValue];\n }),\n );\n }\n\n /**\n * Builds a rates object that covers all given assets, ensuring that\n * any asset not returned by Snap is set to null for both `rate` and `conversionTime`.\n *\n * @param assets - The assets to build the rates for.\n * @param flattenedRates - The rates to merge.\n * @returns A rates object that covers all given assets.\n */\n #buildUpdatedRates(\n assets: CaipAssetType[],\n flattenedRates: Record<CaipAssetType, UnifiedAssetConversion | null>,\n ): Record<string, UnifiedAssetConversion & { currency: CaipAssetType }> {\n const updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n for (const asset of assets) {\n if (flattenedRates[asset]) {\n updatedRates[asset] = {\n ...(flattenedRates[asset] as UnifiedAssetConversion),\n currency:\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ??\n MAP_CAIP_CURRENCIES.usd,\n };\n }\n }\n return updatedRates;\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 string,\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 snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType;\n params:\n | OnAssetsConversionArguments\n | OnAssetHistoricalPriceArguments\n | OnAssetsMarketDataArguments;\n }): Promise<\n | OnAssetsConversionResponse\n | OnAssetHistoricalPriceResponse\n | OnAssetsMarketDataResponse\n | undefined\n > {\n try {\n return (await this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n jsonrpc: '2.0',\n method: handler,\n params,\n },\n })) as\n | OnAssetsConversionResponse\n | OnAssetHistoricalPriceResponse\n | OnAssetsMarketDataResponse\n | undefined;\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 // Ignore\n return undefined;\n }\n }\n\n #mergeMarketDataIntoConversionRates(\n accountRatesResponse: OnAssetsConversionResponse,\n marketDataResponse: OnAssetsMarketDataResponse | null,\n ): ConversionRatesWithMarketData {\n // Early return if no market data to merge\n if (!marketDataResponse?.marketData) {\n return accountRatesResponse;\n }\n\n const result: ConversionRatesWithMarketData =\n cloneDeep(accountRatesResponse);\n const { conversionRates } = result;\n const { marketData } = marketDataResponse;\n\n // Iterate through each asset in market data\n for (const [assetId, currencyData] of Object.entries(marketData)) {\n const typedAssetId = assetId as CaipAssetType;\n\n // Iterate through each currency for this asset\n for (const [currency, marketDataForCurrency] of Object.entries(\n currencyData,\n )) {\n const typedCurrency = currency as CaipAssetType;\n\n // Check if this currency exists in conversion rates for this asset\n const existingRate = conversionRates[typedAssetId][typedCurrency];\n if (!existingRate) {\n continue;\n }\n\n // Merge market data into the existing conversion rate\n conversionRates[typedAssetId][typedCurrency] = {\n ...existingRate,\n marketData: marketDataForCurrency ?? undefined,\n };\n }\n }\n\n return result;\n }\n}\n"]}
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;;;AAIpC,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;AASF;;;;GAIG;AACH,MAAM,OAAO,+BAAgC,SAAQ,+BAA+B,EAInF;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,KAAK,EAAE,EAAC;QAE9B,mEAAuD;QAE9C,kEAAmE;QAE5E,sDAAc,IAAI,EAAC;QA6BjB,IAAI,CAAC,iBAAiB,CAAC,QAAQ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EAAE,qBAAqB,IAAI,SAAS;aAC/C,CAAC;SACH;KACF;IAED,OAAO,MAAM,CAAC;AAChB,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/next';\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';\nimport { cloneDeep } from 'lodash';\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 * 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 * 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 const accounts = this.#listAccounts();\n\n for (const account of accounts) {\n const assets = this.#getAssetsForAccount(account.id);\n\n if (assets?.length === 0) {\n continue;\n }\n\n const rates = await this.#getUpdatedRatesFor(account, assets);\n // Apply these updated rates to controller state\n this.#applyUpdatedRates(rates);\n }\n })().finally(() => {\n releaseLock();\n });\n }\n\n async #getUpdatedRatesFor(\n account: InternalAccount,\n assets: CaipAssetType[],\n ): Promise<\n Record<string, UnifiedAssetConversion & { currency: CaipAssetType }>\n > {\n // Do not attempt to retrieve rates from Snap if there are no assets\n if (!assets.length) {\n return {};\n }\n\n // Build the conversions array\n const conversions = this.#buildConversions(assets);\n\n // Retrieve rates from Snap\n const accountRatesResponse = (await this.#handleSnapRequest({\n snapId: account?.metadata.snap?.id as SnapId,\n handler: HandlerType.OnAssetsConversion,\n params: conversions,\n })) as OnAssetsConversionResponse | null;\n\n // If the snap request failed, return empty rates\n if (!accountRatesResponse) {\n return {};\n }\n\n // Prepare assets param for onAssetsMarketData\n const currentCurrencyCaip =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n const assetsParam = {\n assets: assets.map((asset) => ({ asset, unit: currentCurrencyCaip })),\n };\n\n // Retrieve Market Data from Snap\n const marketDataResponse = (await this.#handleSnapRequest({\n snapId: account?.metadata.snap?.id as SnapId,\n handler: HandlerType.OnAssetsMarketData,\n params: assetsParam as OnAssetsMarketDataArguments,\n })) as OnAssetsMarketDataResponse | null;\n\n // Merge market data into conversion rates if available\n const mergedRates = this.#mergeMarketDataIntoConversionRates(\n accountRatesResponse,\n marketDataResponse,\n );\n\n // Flatten nested rates if needed\n const flattenedRates = this.#flattenRates(mergedRates);\n\n // Build the updatedRates object for these assets\n const updatedRates = this.#buildUpdatedRates(assets, flattenedRates);\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 const allNewRates: Record<\n string,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n for (const { accountId, assets } of accounts) {\n const account = this.#getAccount(accountId);\n\n const rates = await this.#getUpdatedRatesFor(account, assets);\n // Track new rates\n for (const [asset, rate] of Object.entries(rates)) {\n allNewRates[asset] = rate;\n }\n }\n\n this.#applyUpdatedRates(allNewRates);\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 * Builds a conversions array (from each asset → the current currency).\n *\n * @param assets - The assets to build the conversions for.\n * @returns A conversions array.\n */\n #buildConversions(assets: CaipAssetType[]): OnAssetsConversionArguments {\n const currency =\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ?? MAP_CAIP_CURRENCIES.usd;\n return {\n conversions: assets.map((asset) => ({\n from: asset,\n to: currency,\n })),\n };\n }\n\n /**\n * Flattens any nested structure in the conversion rates returned by Snap.\n *\n * @param assetsConversionResponse - The conversion rates to flatten.\n * @returns A flattened rates object.\n */\n #flattenRates(\n assetsConversionResponse: ConversionRatesWithMarketData | null,\n ): Record<CaipAssetType, UnifiedAssetConversion | null> {\n if (!assetsConversionResponse?.conversionRates) {\n return {};\n }\n\n const { conversionRates } = assetsConversionResponse;\n\n return Object.fromEntries(\n Object.entries(conversionRates).map(([asset, nestedObj]) => {\n // e.g., nestedObj might look like: { \"swift:0/iso4217:EUR\": { rate, conversionTime } }\n const singleValue = Object.values(nestedObj)[0];\n return [asset, singleValue];\n }),\n );\n }\n\n /**\n * Builds a rates object that covers all given assets, ensuring that\n * any asset not returned by Snap is set to null for both `rate` and `conversionTime`.\n *\n * @param assets - The assets to build the rates for.\n * @param flattenedRates - The rates to merge.\n * @returns A rates object that covers all given assets.\n */\n #buildUpdatedRates(\n assets: CaipAssetType[],\n flattenedRates: Record<CaipAssetType, UnifiedAssetConversion | null>,\n ): Record<string, UnifiedAssetConversion & { currency: CaipAssetType }> {\n const updatedRates: Record<\n CaipAssetType,\n UnifiedAssetConversion & { currency: CaipAssetType }\n > = {};\n\n for (const asset of assets) {\n if (flattenedRates[asset]) {\n updatedRates[asset] = {\n ...(flattenedRates[asset] as UnifiedAssetConversion),\n currency:\n MAP_CAIP_CURRENCIES[this.#currentCurrency] ??\n MAP_CAIP_CURRENCIES.usd,\n };\n }\n }\n return updatedRates;\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 string,\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 snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType;\n params:\n | OnAssetsConversionArguments\n | OnAssetHistoricalPriceArguments\n | OnAssetsMarketDataArguments;\n }): Promise<\n | OnAssetsConversionResponse\n | OnAssetHistoricalPriceResponse\n | OnAssetsMarketDataResponse\n | undefined\n > {\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 })) as\n | OnAssetsConversionResponse\n | OnAssetHistoricalPriceResponse\n | OnAssetsMarketDataResponse\n | undefined;\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 // Ignore\n return undefined;\n }\n }\n\n #mergeMarketDataIntoConversionRates(\n accountRatesResponse: OnAssetsConversionResponse,\n marketDataResponse: OnAssetsMarketDataResponse | null,\n ): ConversionRatesWithMarketData {\n // Early return if no market data to merge\n if (!marketDataResponse?.marketData) {\n return accountRatesResponse;\n }\n\n const result: ConversionRatesWithMarketData =\n cloneDeep(accountRatesResponse);\n const { conversionRates } = result;\n const { marketData } = marketDataResponse;\n\n // Iterate through each asset in market data\n for (const [assetId, currencyData] of Object.entries(marketData)) {\n const typedAssetId = assetId as CaipAssetType;\n\n // Iterate through each currency for this asset\n for (const [currency, marketDataForCurrency] of Object.entries(\n currencyData,\n )) {\n const typedCurrency = currency as CaipAssetType;\n\n // Check if this currency exists in conversion rates for this asset\n const existingRate = conversionRates[typedAssetId][typedCurrency];\n if (!existingRate) {\n continue;\n }\n\n // Merge market data into the existing conversion rate\n conversionRates[typedAssetId][typedCurrency] = {\n ...existingRate,\n marketData: marketDataForCurrency ?? undefined,\n };\n }\n }\n\n return result;\n }\n}\n"]}
@@ -17,7 +17,7 @@ var _NftController_instances, _NftController_mutex, _NftController_selectedAccou
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.NftController = exports.getDefaultNftControllerState = void 0;
19
19
  const address_1 = require("@ethersproject/address");
20
- const base_controller_1 = require("@metamask/base-controller");
20
+ const next_1 = require("@metamask/base-controller/next");
21
21
  const controller_utils_1 = require("@metamask/controller-utils");
22
22
  const phishing_controller_1 = require("@metamask/phishing-controller");
23
23
  const rpc_errors_1 = require("@metamask/rpc-errors");
@@ -31,19 +31,19 @@ const nftControllerMetadata = {
31
31
  allNftContracts: {
32
32
  includeInStateLogs: false,
33
33
  persist: true,
34
- anonymous: false,
34
+ includeInDebugSnapshot: false,
35
35
  usedInUi: true,
36
36
  },
37
37
  allNfts: {
38
38
  includeInStateLogs: false,
39
39
  persist: true,
40
- anonymous: false,
40
+ includeInDebugSnapshot: false,
41
41
  usedInUi: true,
42
42
  },
43
43
  ignoredNfts: {
44
44
  includeInStateLogs: false,
45
45
  persist: true,
46
- anonymous: false,
46
+ includeInDebugSnapshot: false,
47
47
  usedInUi: false,
48
48
  },
49
49
  };
@@ -63,7 +63,7 @@ const NFT_UPDATE_THRESHOLD = 500;
63
63
  /**
64
64
  * Controller that stores assets and exposes convenience methods
65
65
  */
66
- class NftController extends base_controller_1.BaseController {
66
+ class NftController extends next_1.BaseController {
67
67
  /**
68
68
  * Creates an NftController instance.
69
69
  *
@@ -95,17 +95,17 @@ class NftController extends base_controller_1.BaseController {
95
95
  _NftController_useIpfsSubdomains.set(this, void 0);
96
96
  _NftController_isIpfsGatewayEnabled.set(this, void 0);
97
97
  _NftController_onNftAdded.set(this, void 0);
98
- __classPrivateFieldSet(this, _NftController_selectedAccountId, this.messagingSystem.call('AccountsController:getSelectedAccount').id, "f");
98
+ __classPrivateFieldSet(this, _NftController_selectedAccountId, this.messenger.call('AccountsController:getSelectedAccount').id, "f");
99
99
  __classPrivateFieldSet(this, _NftController_ipfsGateway, ipfsGateway, "f");
100
100
  __classPrivateFieldSet(this, _NftController_openSeaEnabled, openSeaEnabled, "f");
101
101
  __classPrivateFieldSet(this, _NftController_useIpfsSubdomains, useIpfsSubdomains, "f");
102
102
  __classPrivateFieldSet(this, _NftController_isIpfsGatewayEnabled, isIpfsGatewayEnabled, "f");
103
103
  __classPrivateFieldSet(this, _NftController_onNftAdded, onNftAdded, "f");
104
- this.messagingSystem.subscribe('PreferencesController:stateChange',
104
+ this.messenger.subscribe('PreferencesController:stateChange',
105
105
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
106
106
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
107
107
  __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_onPreferencesControllerStateChange).bind(this));
108
- this.messagingSystem.subscribe('AccountsController:selectedEvmAccountChange',
108
+ this.messenger.subscribe('AccountsController:selectedEvmAccountChange',
109
109
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
110
110
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
111
111
  __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_onSelectedAccountChange).bind(this));
@@ -186,7 +186,7 @@ class NftController extends base_controller_1.BaseController {
186
186
  async isNftOwner(ownerAddress, nftAddress, tokenId, networkClientId) {
187
187
  // Checks the ownership for ERC-721.
188
188
  try {
189
- const owner = await this.messagingSystem.call('AssetsContractController:getERC721OwnerOf', nftAddress, tokenId, networkClientId);
189
+ const owner = await this.messenger.call('AssetsContractController:getERC721OwnerOf', nftAddress, tokenId, networkClientId);
190
190
  return ownerAddress.toLowerCase() === owner.toLowerCase();
191
191
  // eslint-disable-next-line no-empty
192
192
  }
@@ -195,7 +195,7 @@ class NftController extends base_controller_1.BaseController {
195
195
  }
196
196
  // Checks the ownership for ERC-1155.
197
197
  try {
198
- const balance = await this.messagingSystem.call('AssetsContractController:getERC1155BalanceOf', ownerAddress, nftAddress, tokenId, networkClientId);
198
+ const balance = await this.messenger.call('AssetsContractController:getERC1155BalanceOf', ownerAddress, nftAddress, tokenId, networkClientId);
199
199
  return !balance.isZero();
200
200
  // eslint-disable-next-line no-empty
201
201
  }
@@ -260,7 +260,7 @@ class NftController extends base_controller_1.BaseController {
260
260
  });
261
261
  // If NFT contract was not added, do not add individual NFT
262
262
  const nftContract = newNftContracts.find((contract) => contract.address.toLowerCase() === checksumHexAddress.toLowerCase());
263
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
263
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
264
264
  // This is the case when the NFT is added manually and not detected automatically
265
265
  // TODO: An improvement would be to make the chainId a required field and return it when getting the NFT information
266
266
  if (!nftMetadata.chainId) {
@@ -291,7 +291,7 @@ class NftController extends base_controller_1.BaseController {
291
291
  // Get all unsanitized nft metadata
292
292
  const unsanitizedResults = await Promise.all(nftsWithChecksumAdr.map(async (nft) => {
293
293
  // Each NFT should have a chainId; convert nft.chainId to networkClientId
294
- const networkClientId = this.messagingSystem.call('NetworkController:findNetworkClientIdByChainId', (0, controller_utils_1.toHex)(nft.chainId));
294
+ const networkClientId = this.messenger.call('NetworkController:findNetworkClientIdByChainId', (0, controller_utils_1.toHex)(nft.chainId));
295
295
  const resMetadata = networkClientId
296
296
  ? await __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getNftInformation).call(this, nft.address, nft.tokenId, networkClientId)
297
297
  : undefined;
@@ -350,7 +350,7 @@ class NftController extends base_controller_1.BaseController {
350
350
  */
351
351
  removeNft(address, tokenId, networkClientId, { userAddress } = {}) {
352
352
  const addressToSearch = __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getAddressOrSelectedAddress).call(this, userAddress);
353
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
353
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
354
354
  const checksumHexAddress = (0, controller_utils_1.toChecksumHexAddress)(address);
355
355
  __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_removeIndividualNft).call(this, checksumHexAddress, tokenId, {
356
356
  chainId,
@@ -377,7 +377,7 @@ class NftController extends base_controller_1.BaseController {
377
377
  */
378
378
  removeAndIgnoreNft(address, tokenId, networkClientId, { userAddress } = {}) {
379
379
  const addressToSearch = __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getAddressOrSelectedAddress).call(this, userAddress);
380
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
380
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
381
381
  const checksumHexAddress = (0, controller_utils_1.toChecksumHexAddress)(address);
382
382
  __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_removeAndIgnoreIndividualNft).call(this, checksumHexAddress, tokenId, {
383
383
  chainId,
@@ -414,7 +414,7 @@ class NftController extends base_controller_1.BaseController {
414
414
  */
415
415
  async checkAndUpdateSingleNftOwnershipStatus(nft, batch, networkClientId, { userAddress } = {}) {
416
416
  const addressToSearch = __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getAddressOrSelectedAddress).call(this, userAddress);
417
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
417
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
418
418
  const { address, tokenId } = nft;
419
419
  let isOwned = nft.isCurrentlyOwned;
420
420
  try {
@@ -461,7 +461,7 @@ class NftController extends base_controller_1.BaseController {
461
461
  */
462
462
  async checkAndUpdateAllNftsOwnershipStatus(networkClientId, { userAddress, } = {}) {
463
463
  const addressToSearch = __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getAddressOrSelectedAddress).call(this, userAddress);
464
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
464
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
465
465
  const { allNfts } = this.state;
466
466
  const nfts = allNfts[addressToSearch]?.[chainId] || [];
467
467
  const updatedNfts = await Promise.all(nfts.map(async (nft) => {
@@ -486,7 +486,7 @@ class NftController extends base_controller_1.BaseController {
486
486
  */
487
487
  updateNftFavoriteStatus(address, tokenId, favorite, networkClientId, { userAddress, } = {}) {
488
488
  const addressToSearch = __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getAddressOrSelectedAddress).call(this, userAddress);
489
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
489
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
490
490
  const { allNfts } = this.state;
491
491
  const nfts = [...(allNfts[addressToSearch]?.[chainId] || [])];
492
492
  const index = nfts.findIndex((nft) => nft.address === address && nft.tokenId === tokenId);
@@ -602,7 +602,7 @@ class NftController extends base_controller_1.BaseController {
602
602
  });
603
603
  }
604
604
  async _requestApproval(suggestedNftMeta) {
605
- return this.messagingSystem.call('ApprovalController:addRequest', {
605
+ return this.messenger.call('ApprovalController:addRequest', {
606
606
  id: suggestedNftMeta.id,
607
607
  origin: suggestedNftMeta.origin,
608
608
  type: controller_utils_1.ApprovalType.WatchAsset,
@@ -640,7 +640,7 @@ _NftController_mutex = new WeakMap(), _NftController_selectedAccountId = new Wea
640
640
  * @param preferencesState.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.
641
641
  */
642
642
  async function _NftController_onPreferencesControllerStateChange({ ipfsGateway, openSeaEnabled, isIpfsGatewayEnabled, }) {
643
- const selectedAccount = this.messagingSystem.call('AccountsController:getSelectedAccount');
643
+ const selectedAccount = this.messenger.call('AccountsController:getSelectedAccount');
644
644
  __classPrivateFieldSet(this, _NftController_selectedAccountId, selectedAccount.id, "f");
645
645
  // Get current state values
646
646
  if (__classPrivateFieldGet(this, _NftController_ipfsGateway, "f") !== ipfsGateway ||
@@ -844,7 +844,7 @@ async function _NftController_getNftInformationFromTokenURI(contractAddress, tok
844
844
  async function _NftController_getNftURIAndStandard(contractAddress, tokenId, networkClientId) {
845
845
  // try ERC721 uri
846
846
  try {
847
- const uri = await this.messagingSystem.call('AssetsContractController:getERC721TokenURI', contractAddress, tokenId, networkClientId);
847
+ const uri = await this.messenger.call('AssetsContractController:getERC721TokenURI', contractAddress, tokenId, networkClientId);
848
848
  return [uri, controller_utils_1.ERC721];
849
849
  }
850
850
  catch {
@@ -852,7 +852,7 @@ async function _NftController_getNftURIAndStandard(contractAddress, tokenId, net
852
852
  }
853
853
  // try ERC1155 uri
854
854
  try {
855
- const tokenURI = await this.messagingSystem.call('AssetsContractController:getERC1155TokenURI', contractAddress, tokenId, networkClientId);
855
+ const tokenURI = await this.messenger.call('AssetsContractController:getERC1155TokenURI', contractAddress, tokenId, networkClientId);
856
856
  /**
857
857
  * According to EIP1155 the URI value allows for ID substitution
858
858
  * in case the string `{id}` exists.
@@ -880,7 +880,7 @@ async function _NftController_getNftURIAndStandard(contractAddress, tokenId, net
880
880
  * @returns Promise resolving to the current NFT name and image.
881
881
  */
882
882
  async function _NftController_getNftInformation(contractAddress, tokenId, networkClientId) {
883
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
883
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
884
884
  const [blockchainMetadata, nftApiMetadata] = await Promise.all([
885
885
  (0, controller_utils_1.safelyExecute)(() => __classPrivateFieldGet(this, _NftController_instances, "m", _NftController_getNftInformationFromTokenURI).call(this, contractAddress, tokenId, networkClientId)),
886
886
  __classPrivateFieldGet(this, _NftController_openSeaEnabled, "f") && chainId === '0x1'
@@ -909,8 +909,8 @@ async function _NftController_getNftContractInformationFromContract(
909
909
  // TODO for calls to blockchain we need to explicitly pass the currentNetworkClientId since its relying on the provider
910
910
  contractAddress, networkClientId) {
911
911
  const [name, symbol] = await Promise.all([
912
- this.messagingSystem.call('AssetsContractController:getERC721AssetName', contractAddress, networkClientId),
913
- this.messagingSystem.call('AssetsContractController:getERC721AssetSymbol', contractAddress, networkClientId),
912
+ this.messenger.call('AssetsContractController:getERC721AssetName', contractAddress, networkClientId),
913
+ this.messenger.call('AssetsContractController:getERC721AssetSymbol', contractAddress, networkClientId),
914
914
  ]);
915
915
  return {
916
916
  collection: { name },
@@ -1055,7 +1055,7 @@ async function _NftController_addNftContract(networkClientId, { tokenAddress, us
1055
1055
  try {
1056
1056
  const checksumHexAddress = (0, controller_utils_1.toChecksumHexAddress)(tokenAddress);
1057
1057
  const { allNftContracts } = this.state;
1058
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
1058
+ const { configuration: { chainId }, } = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
1059
1059
  const nftContracts = allNftContracts[userAddress]?.[chainId] || [];
1060
1060
  const existingEntry = nftContracts.find((nftContract) => nftContract.address.toLowerCase() ===
1061
1061
  checksumHexAddress.toLowerCase());
@@ -1189,7 +1189,7 @@ async function _NftController_addNftContract(networkClientId, { tokenAddress, us
1189
1189
  return address;
1190
1190
  }
1191
1191
  // If the address is not defined (or empty), we fallback to the currently selected account's address
1192
- const selectedAccount = this.messagingSystem.call('AccountsController:getAccount', __classPrivateFieldGet(this, _NftController_selectedAccountId, "f"));
1192
+ const selectedAccount = this.messenger.call('AccountsController:getAccount', __classPrivateFieldGet(this, _NftController_selectedAccountId, "f"));
1193
1193
  return selectedAccount?.address || '';
1194
1194
  }, _NftController_updateNftUpdateForAccount =
1195
1195
  /**
@@ -1267,7 +1267,7 @@ async function _NftController_bulkSanitizeNftMetadata(metadataList) {
1267
1267
  }
1268
1268
  try {
1269
1269
  // Use bulkScanUrls to check all URLs at once
1270
- const bulkScanResponse = await this.messagingSystem.call('PhishingController:bulkScanUrls', urlsToCheck);
1270
+ const bulkScanResponse = await this.messenger.call('PhishingController:bulkScanUrls', urlsToCheck);
1271
1271
  // Apply scan results to all metadata objects
1272
1272
  Object.entries(bulkScanResponse.results).forEach(([url, result]) => {
1273
1273
  if (result.recommendedAction === phishing_controller_1.RecommendedAction.Block) {