@metamask/assets-controllers 40.0.0 → 42.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +28 -1
  2. package/dist/AccountTrackerController.d.cts +4 -4
  3. package/dist/AccountTrackerController.d.mts +4 -4
  4. package/dist/CurrencyRateController.cjs +40 -58
  5. package/dist/CurrencyRateController.cjs.map +1 -1
  6. package/dist/CurrencyRateController.d.cts +15 -15
  7. package/dist/CurrencyRateController.d.cts.map +1 -1
  8. package/dist/CurrencyRateController.d.mts +15 -15
  9. package/dist/CurrencyRateController.d.mts.map +1 -1
  10. package/dist/CurrencyRateController.mjs +41 -59
  11. package/dist/CurrencyRateController.mjs.map +1 -1
  12. package/dist/NftController.cjs +8 -0
  13. package/dist/NftController.cjs.map +1 -1
  14. package/dist/NftController.d.cts +4 -0
  15. package/dist/NftController.d.cts.map +1 -1
  16. package/dist/NftController.d.mts +4 -0
  17. package/dist/NftController.d.mts.map +1 -1
  18. package/dist/NftController.mjs +8 -0
  19. package/dist/NftController.mjs.map +1 -1
  20. package/dist/RatesController/RatesController.cjs +1 -1
  21. package/dist/RatesController/RatesController.cjs.map +1 -1
  22. package/dist/RatesController/RatesController.mjs +1 -1
  23. package/dist/RatesController/RatesController.mjs.map +1 -1
  24. package/dist/RatesController/types.cjs.map +1 -1
  25. package/dist/RatesController/types.d.cts +6 -7
  26. package/dist/RatesController/types.d.cts.map +1 -1
  27. package/dist/RatesController/types.d.mts +6 -7
  28. package/dist/RatesController/types.d.mts.map +1 -1
  29. package/dist/RatesController/types.mjs.map +1 -1
  30. package/dist/TokenBalancesController.cjs +8 -0
  31. package/dist/TokenBalancesController.cjs.map +1 -1
  32. package/dist/TokenBalancesController.d.cts +4 -0
  33. package/dist/TokenBalancesController.d.cts.map +1 -1
  34. package/dist/TokenBalancesController.d.mts +4 -0
  35. package/dist/TokenBalancesController.d.mts.map +1 -1
  36. package/dist/TokenBalancesController.mjs +8 -0
  37. package/dist/TokenBalancesController.mjs.map +1 -1
  38. package/dist/TokenDetectionController.cjs +58 -16
  39. package/dist/TokenDetectionController.cjs.map +1 -1
  40. package/dist/TokenDetectionController.d.cts +7 -5
  41. package/dist/TokenDetectionController.d.cts.map +1 -1
  42. package/dist/TokenDetectionController.d.mts +7 -5
  43. package/dist/TokenDetectionController.d.mts.map +1 -1
  44. package/dist/TokenDetectionController.mjs +59 -16
  45. package/dist/TokenDetectionController.mjs.map +1 -1
  46. package/dist/TokenListController.cjs.map +1 -1
  47. package/dist/TokenListController.d.cts +5 -5
  48. package/dist/TokenListController.d.cts.map +1 -1
  49. package/dist/TokenListController.d.mts +5 -5
  50. package/dist/TokenListController.d.mts.map +1 -1
  51. package/dist/TokenListController.mjs.map +1 -1
  52. package/dist/TokenRatesController.cjs +43 -13
  53. package/dist/TokenRatesController.cjs.map +1 -1
  54. package/dist/TokenRatesController.d.cts +12 -8
  55. package/dist/TokenRatesController.d.cts.map +1 -1
  56. package/dist/TokenRatesController.d.mts +12 -8
  57. package/dist/TokenRatesController.d.mts.map +1 -1
  58. package/dist/TokenRatesController.mjs +43 -13
  59. package/dist/TokenRatesController.mjs.map +1 -1
  60. package/dist/TokensController.cjs +8 -0
  61. package/dist/TokensController.cjs.map +1 -1
  62. package/dist/TokensController.d.cts +4 -0
  63. package/dist/TokensController.d.cts.map +1 -1
  64. package/dist/TokensController.d.mts +4 -0
  65. package/dist/TokensController.d.mts.map +1 -1
  66. package/dist/TokensController.mjs +8 -0
  67. package/dist/TokensController.mjs.map +1 -1
  68. package/dist/crypto-compare-service/crypto-compare.cjs +8 -6
  69. package/dist/crypto-compare-service/crypto-compare.cjs.map +1 -1
  70. package/dist/crypto-compare-service/crypto-compare.d.cts +1 -1
  71. package/dist/crypto-compare-service/crypto-compare.d.cts.map +1 -1
  72. package/dist/crypto-compare-service/crypto-compare.d.mts +1 -1
  73. package/dist/crypto-compare-service/crypto-compare.d.mts.map +1 -1
  74. package/dist/crypto-compare-service/crypto-compare.mjs +8 -6
  75. package/dist/crypto-compare-service/crypto-compare.mjs.map +1 -1
  76. package/dist/multi-chain-accounts-service/multi-chain-accounts.cjs +7 -2
  77. package/dist/multi-chain-accounts-service/multi-chain-accounts.cjs.map +1 -1
  78. package/dist/multi-chain-accounts-service/multi-chain-accounts.d.cts +3 -2
  79. package/dist/multi-chain-accounts-service/multi-chain-accounts.d.cts.map +1 -1
  80. package/dist/multi-chain-accounts-service/multi-chain-accounts.d.mts +3 -2
  81. package/dist/multi-chain-accounts-service/multi-chain-accounts.d.mts.map +1 -1
  82. package/dist/multi-chain-accounts-service/multi-chain-accounts.mjs +7 -2
  83. package/dist/multi-chain-accounts-service/multi-chain-accounts.mjs.map +1 -1
  84. package/package.json +9 -9
@@ -29,7 +29,7 @@ const defaultState = {
29
29
  rates: {
30
30
  [Cryptocurrency.Btc]: {
31
31
  conversionDate: 0,
32
- conversionRate: '0',
32
+ conversionRate: 0,
33
33
  },
34
34
  },
35
35
  cryptocurrencies: [Cryptocurrency.Btc],
@@ -1 +1 @@
1
- {"version":3,"file":"RatesController.mjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AAQ/F,MAAM,CAAC,MAAM,IAAI,GAAG,iBAAiB,CAAC;AAEtC,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACxB,6BAAW,CAAA;AACb,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,QAAQ,GAAG;IACf,YAAY,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IAChD,KAAK,EAAE,EAAE,OAAO,EAAE,IA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EAAgE;AAChE,KAAK,oCAAc,QAAiB;IAClC,MAAM,WAAW,GAAG,MAAM,uBAAA,IAAI,8BAAO,CAAC,OAAO,EAAE,CAAC;IAChD,IAAI;QACF,OAAO,QAAQ,EAAE,CAAC;KACnB;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,gEAAa,MAAjB,IAAI,CAAe,CAAC;AAC5B,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,6DAAU,MAAd,IAAI,EAAW,KAAK,IAAI,EAAE;QAC9B,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QACtD,MAAM,QAAQ,GAGV,MAAM,uBAAA,IAAI,+CAAwB,MAA5B,IAAI,EACZ,YAAY,EACZ,gBAAgB,EAChB,uBAAA,IAAI,uCAAgB,CACrB,CAAC;QAEF,MAAM,YAAY,GAAoB,EAAE,CAAC;QACzC,KAAK,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC/D,YAAY,CAAC,cAAc,CAAC,GAAG;gBAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;SACH;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: '0',\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, string>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
1
+ {"version":3,"file":"RatesController.mjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AAQ/F,MAAM,CAAC,MAAM,IAAI,GAAG,iBAAiB,CAAC;AAEtC,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACxB,6BAAW,CAAA;AACb,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,QAAQ,GAAG;IACf,YAAY,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IAChD,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACzC,gBAAgB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CACrD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,YAAY,EAAE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;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,gEAAa,MAAjB,IAAI,CAAe,CAAC;AAC5B,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,6DAAU,MAAd,IAAI,EAAW,KAAK,IAAI,EAAE;QAC9B,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QACtD,MAAM,QAAQ,GAGV,MAAM,uBAAA,IAAI,+CAAwB,MAA5B,IAAI,EACZ,YAAY,EACZ,gBAAgB,EAChB,uBAAA,IAAI,uCAAgB,CACrB,CAAC;QAEF,MAAM,YAAY,GAAoB,EAAE,CAAC;QACzC,KAAK,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC/D,YAAY,CAAC,cAAc,CAAC,GAAG;gBAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;SACH;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a string that maps a cryptocurrency code (e.g., \"BTC\") to its\n * conversion rate. For this field we use string as the data type to avoid potential rounding\n * errors and precision loss.\n * The `usdConversionRate` provides the conversion rate to USD as a string, or `null` if the\n * conversion rate to USD is not available. We also use string for the same reason as stated before.\n * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.\n */\nexport type Rate = {\n conversionRate: string;\n conversionDate: number;\n usdConversionRate?: string;\n};\n\n/**\n * Represents the conversion rates for multiple cryptocurrencies.\n * Each key is a string representing the cryptocurrency symbol (e.g., \"BTC\", \"SOL\"),\n * and its value is a `Rate` object containing conversion rates from that cryptocurrency\n * to a fiat currencies and an optional USD rate.\n */\nexport type ConversionRates = Record<string, Rate>;\n\n/**\n * Represents the state structure for the RatesController.\n */\nexport type RatesControllerState = {\n /**\n * The fiat currency in which conversion rates are expressed\n * (i.e., the \"to\" currency).\n */\n fiatCurrency: string;\n /**\n * The conversion rates for multiple cryptocurrencies.\n */\n rates: ConversionRates;\n /**\n * A list of supported cryptocurrency symbols.\n * (i.e., the \"from\" currencies).\n */\n cryptocurrencies: Cryptocurrency[];\n};\n\n/**\n * Type definition for RatesController state change events.\n */\nexport type RatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Type definition for the RatesController polling started event.\n */\nexport type RatesControllerPollingStartedEvent = {\n type: `${typeof ratesControllerName}:pollingStarted`;\n payload: [];\n};\n\n/**\n * Type definition for the RatesController polling stopped event.\n */\nexport type RatesControllerPollingStoppedEvent = {\n type: `${typeof ratesControllerName}:pollingStopped`;\n payload: [];\n};\n\n/**\n * Defines the events that the RatesController can emit.\n */\nexport type RatesControllerEvents =\n | RatesControllerStateChangeEvent\n | RatesControllerPollingStartedEvent\n | RatesControllerPollingStoppedEvent;\n\nexport type RatesControllerGetStateAction = ControllerGetStateAction<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Defines the actions that can be performed to get the state of the RatesController.\n */\nexport type RatesControllerActions = RatesControllerGetStateAction;\n\n/**\n * Defines the actions that the RatesController can perform.\n */\nexport type RatesControllerMessenger = RestrictedControllerMessenger<\n typeof ratesControllerName,\n RatesControllerActions,\n RatesControllerEvents,\n never,\n never\n>;\n\n/**\n * The options required to initialize a RatesController.\n */\nexport type RatesControllerOptions = {\n /**\n * Whether to include USD rates in the conversion rates.\n */\n includeUsdRate: boolean;\n /**\n * The polling interval in milliseconds.\n */\n interval?: number;\n /**\n * The messenger instance for communication.\n */\n messenger: RatesControllerMessenger;\n /**\n * The initial state of the controller.\n */\n state?: Partial<RatesControllerState>;\n /**\n * The function to fetch exchange rates.\n */\n fetchMultiExchangeRate?: typeof defaultFetchExchangeRate;\n};\n"]}
1
+ {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a number that maps a cryptocurrency code (e.g., \"BTC\") to its\n * conversion rate.\n * The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the\n * conversion rate to USD is not available.\n * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.\n */\nexport type Rate = {\n conversionRate: number;\n conversionDate: number;\n usdConversionRate?: number;\n};\n\n/**\n * Represents the conversion rates for multiple cryptocurrencies.\n * Each key is a string representing the cryptocurrency symbol (e.g., \"BTC\", \"SOL\"),\n * and its value is a `Rate` object containing conversion rates from that cryptocurrency\n * to a fiat currencies and an optional USD rate.\n */\nexport type ConversionRates = Record<string, Rate>;\n\n/**\n * Represents the state structure for the RatesController.\n */\nexport type RatesControllerState = {\n /**\n * The fiat currency in which conversion rates are expressed\n * (i.e., the \"to\" currency).\n */\n fiatCurrency: string;\n /**\n * The conversion rates for multiple cryptocurrencies.\n */\n rates: ConversionRates;\n /**\n * A list of supported cryptocurrency symbols.\n * (i.e., the \"from\" currencies).\n */\n cryptocurrencies: Cryptocurrency[];\n};\n\n/**\n * Type definition for RatesController state change events.\n */\nexport type RatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Type definition for the RatesController polling started event.\n */\nexport type RatesControllerPollingStartedEvent = {\n type: `${typeof ratesControllerName}:pollingStarted`;\n payload: [];\n};\n\n/**\n * Type definition for the RatesController polling stopped event.\n */\nexport type RatesControllerPollingStoppedEvent = {\n type: `${typeof ratesControllerName}:pollingStopped`;\n payload: [];\n};\n\n/**\n * Defines the events that the RatesController can emit.\n */\nexport type RatesControllerEvents =\n | RatesControllerStateChangeEvent\n | RatesControllerPollingStartedEvent\n | RatesControllerPollingStoppedEvent;\n\nexport type RatesControllerGetStateAction = ControllerGetStateAction<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Defines the actions that can be performed to get the state of the RatesController.\n */\nexport type RatesControllerActions = RatesControllerGetStateAction;\n\n/**\n * Defines the actions that the RatesController can perform.\n */\nexport type RatesControllerMessenger = RestrictedControllerMessenger<\n typeof ratesControllerName,\n RatesControllerActions,\n RatesControllerEvents,\n never,\n never\n>;\n\n/**\n * The options required to initialize a RatesController.\n */\nexport type RatesControllerOptions = {\n /**\n * Whether to include USD rates in the conversion rates.\n */\n includeUsdRate: boolean;\n /**\n * The polling interval in milliseconds.\n */\n interval?: number;\n /**\n * The messenger instance for communication.\n */\n messenger: RatesControllerMessenger;\n /**\n * The initial state of the controller.\n */\n state?: Partial<RatesControllerState>;\n /**\n * The function to fetch exchange rates.\n */\n fetchMultiExchangeRate?: typeof defaultFetchExchangeRate;\n};\n"]}
@@ -3,17 +3,16 @@ import type { fetchMultiExchangeRate as defaultFetchExchangeRate } from "../cryp
3
3
  import type { name as ratesControllerName, Cryptocurrency } from "./RatesController.cjs";
4
4
  /**
5
5
  * Represents the conversion rates from one currency to others, including the conversion date.
6
- * The `conversionRate` field is a string that maps a cryptocurrency code (e.g., "BTC") to its
7
- * conversion rate. For this field we use string as the data type to avoid potential rounding
8
- * errors and precision loss.
9
- * The `usdConversionRate` provides the conversion rate to USD as a string, or `null` if the
10
- * conversion rate to USD is not available. We also use string for the same reason as stated before.
6
+ * The `conversionRate` field is a number that maps a cryptocurrency code (e.g., "BTC") to its
7
+ * conversion rate.
8
+ * The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the
9
+ * conversion rate to USD is not available.
11
10
  * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.
12
11
  */
13
12
  export type Rate = {
14
- conversionRate: string;
13
+ conversionRate: number;
15
14
  conversionDate: number;
16
- usdConversionRate?: string;
15
+ usdConversionRate?: number;
17
16
  };
18
17
  /**
19
18
  * Represents the conversion rates for multiple cryptocurrencies.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AACpG,OAAO,KAAK,EACV,IAAI,IAAI,mBAAmB,EAC3B,cAAc,EACf,8BAA0B;AAE3B;;;;;;;;GAQG;AACH,MAAM,MAAM,IAAI,GAAG;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEnD;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;OAGG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,KAAK,EAAE,eAAe,CAAC;IACvB;;;OAGG;IACH,gBAAgB,EAAE,cAAc,EAAE,CAAC;CACpC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG,0BAA0B,CACtE,OAAO,mBAAmB,EAC1B,oBAAoB,CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,GAAG,OAAO,mBAAmB,iBAAiB,CAAC;IACrD,OAAO,EAAE,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,GAAG,OAAO,mBAAmB,iBAAiB,CAAC;IACrD,OAAO,EAAE,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAC7B,+BAA+B,GAC/B,kCAAkC,GA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ultiExchangeRate as defaultFetchExchangeRate } from "../cryp
3
3
  import type { name as ratesControllerName, Cryptocurrency } from "./RatesController.mjs";
4
4
  /**
5
5
  * Represents the conversion rates from one currency to others, including the conversion date.
6
- * The `conversionRate` field is a string that maps a cryptocurrency code (e.g., "BTC") to its
7
- * conversion rate. For this field we use string as the data type to avoid potential rounding
8
- * errors and precision loss.
9
- * The `usdConversionRate` provides the conversion rate to USD as a string, or `null` if the
10
- * conversion rate to USD is not available. We also use string for the same reason as stated before.
6
+ * The `conversionRate` field is a number that maps a cryptocurrency code (e.g., "BTC") to its
7
+ * conversion rate.
8
+ * The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the
9
+ * conversion rate to USD is not available.
11
10
  * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.
12
11
  */
13
12
  export type Rate = {
14
- conversionRate: string;
13
+ conversionRate: number;
15
14
  conversionDate: number;
16
- usdConversionRate?: string;
15
+ usdConversionRate?: number;
17
16
  };
18
17
  /**
19
18
  * Represents the conversion rates for multiple cryptocurrencies.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AACpG,OAAO,KAAK,EACV,IAAI,IAAI,mBAAmB,EAC3B,cAAc,EACf,8BAA0B;AAE3B;;;;;;;;GAQG;AACH,MAAM,MAAM,IAAI,GAAG;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEnD;;GAEG;AACH,MAAM,MAAM,oB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B,GAAG,wBAAwB,CAClE,OAAO,mBAAmB,EAC1B,oBAAoB,CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEnE;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,6BAA6B,CAClE,OAAO,mBAAmB,EAC1B,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,EACL,KAAK,CACN,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC;;OAEG;IACH,cAAc,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,EAAE,wBAAwB,CAAC;IACpC;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACtC;;OAEG;IACH,sBAAsB,CAAC,EAAE,OAAO,wBAAwB,CAAC;CAC1D,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a string that maps a cryptocurrency code (e.g., \"BTC\") to its\n * conversion rate. For this field we use string as the data type to avoid potential rounding\n * errors and precision loss.\n * The `usdConversionRate` provides the conversion rate to USD as a string, or `null` if the\n * conversion rate to USD is not available. We also use string for the same reason as stated before.\n * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.\n */\nexport type Rate = {\n conversionRate: string;\n conversionDate: number;\n usdConversionRate?: string;\n};\n\n/**\n * Represents the conversion rates for multiple cryptocurrencies.\n * Each key is a string representing the cryptocurrency symbol (e.g., \"BTC\", \"SOL\"),\n * and its value is a `Rate` object containing conversion rates from that cryptocurrency\n * to a fiat currencies and an optional USD rate.\n */\nexport type ConversionRates = Record<string, Rate>;\n\n/**\n * Represents the state structure for the RatesController.\n */\nexport type RatesControllerState = {\n /**\n * The fiat currency in which conversion rates are expressed\n * (i.e., the \"to\" currency).\n */\n fiatCurrency: string;\n /**\n * The conversion rates for multiple cryptocurrencies.\n */\n rates: ConversionRates;\n /**\n * A list of supported cryptocurrency symbols.\n * (i.e., the \"from\" currencies).\n */\n cryptocurrencies: Cryptocurrency[];\n};\n\n/**\n * Type definition for RatesController state change events.\n */\nexport type RatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Type definition for the RatesController polling started event.\n */\nexport type RatesControllerPollingStartedEvent = {\n type: `${typeof ratesControllerName}:pollingStarted`;\n payload: [];\n};\n\n/**\n * Type definition for the RatesController polling stopped event.\n */\nexport type RatesControllerPollingStoppedEvent = {\n type: `${typeof ratesControllerName}:pollingStopped`;\n payload: [];\n};\n\n/**\n * Defines the events that the RatesController can emit.\n */\nexport type RatesControllerEvents =\n | RatesControllerStateChangeEvent\n | RatesControllerPollingStartedEvent\n | RatesControllerPollingStoppedEvent;\n\nexport type RatesControllerGetStateAction = ControllerGetStateAction<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Defines the actions that can be performed to get the state of the RatesController.\n */\nexport type RatesControllerActions = RatesControllerGetStateAction;\n\n/**\n * Defines the actions that the RatesController can perform.\n */\nexport type RatesControllerMessenger = RestrictedControllerMessenger<\n typeof ratesControllerName,\n RatesControllerActions,\n RatesControllerEvents,\n never,\n never\n>;\n\n/**\n * The options required to initialize a RatesController.\n */\nexport type RatesControllerOptions = {\n /**\n * Whether to include USD rates in the conversion rates.\n */\n includeUsdRate: boolean;\n /**\n * The polling interval in milliseconds.\n */\n interval?: number;\n /**\n * The messenger instance for communication.\n */\n messenger: RatesControllerMessenger;\n /**\n * The initial state of the controller.\n */\n state?: Partial<RatesControllerState>;\n /**\n * The function to fetch exchange rates.\n */\n fetchMultiExchangeRate?: typeof defaultFetchExchangeRate;\n};\n"]}
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a number that maps a cryptocurrency code (e.g., \"BTC\") to its\n * conversion rate.\n * The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the\n * conversion rate to USD is not available.\n * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.\n */\nexport type Rate = {\n conversionRate: number;\n conversionDate: number;\n usdConversionRate?: number;\n};\n\n/**\n * Represents the conversion rates for multiple cryptocurrencies.\n * Each key is a string representing the cryptocurrency symbol (e.g., \"BTC\", \"SOL\"),\n * and its value is a `Rate` object containing conversion rates from that cryptocurrency\n * to a fiat currencies and an optional USD rate.\n */\nexport type ConversionRates = Record<string, Rate>;\n\n/**\n * Represents the state structure for the RatesController.\n */\nexport type RatesControllerState = {\n /**\n * The fiat currency in which conversion rates are expressed\n * (i.e., the \"to\" currency).\n */\n fiatCurrency: string;\n /**\n * The conversion rates for multiple cryptocurrencies.\n */\n rates: ConversionRates;\n /**\n * A list of supported cryptocurrency symbols.\n * (i.e., the \"from\" currencies).\n */\n cryptocurrencies: Cryptocurrency[];\n};\n\n/**\n * Type definition for RatesController state change events.\n */\nexport type RatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Type definition for the RatesController polling started event.\n */\nexport type RatesControllerPollingStartedEvent = {\n type: `${typeof ratesControllerName}:pollingStarted`;\n payload: [];\n};\n\n/**\n * Type definition for the RatesController polling stopped event.\n */\nexport type RatesControllerPollingStoppedEvent = {\n type: `${typeof ratesControllerName}:pollingStopped`;\n payload: [];\n};\n\n/**\n * Defines the events that the RatesController can emit.\n */\nexport type RatesControllerEvents =\n | RatesControllerStateChangeEvent\n | RatesControllerPollingStartedEvent\n | RatesControllerPollingStoppedEvent;\n\nexport type RatesControllerGetStateAction = ControllerGetStateAction<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Defines the actions that can be performed to get the state of the RatesController.\n */\nexport type RatesControllerActions = RatesControllerGetStateAction;\n\n/**\n * Defines the actions that the RatesController can perform.\n */\nexport type RatesControllerMessenger = RestrictedControllerMessenger<\n typeof ratesControllerName,\n RatesControllerActions,\n RatesControllerEvents,\n never,\n never\n>;\n\n/**\n * The options required to initialize a RatesController.\n */\nexport type RatesControllerOptions = {\n /**\n * Whether to include USD rates in the conversion rates.\n */\n includeUsdRate: boolean;\n /**\n * The polling interval in milliseconds.\n */\n interval?: number;\n /**\n * The messenger instance for communication.\n */\n messenger: RatesControllerMessenger;\n /**\n * The initial state of the controller.\n */\n state?: Partial<RatesControllerState>;\n /**\n * The function to fetch exchange rates.\n */\n fetchMultiExchangeRate?: typeof defaultFetchExchangeRate;\n};\n"]}
@@ -129,6 +129,14 @@ class TokenBalancesController extends base_controller_1.BaseController {
129
129
  state.contractBalances = newContractBalances;
130
130
  });
131
131
  }
132
+ /**
133
+ * Reset the controller state to the default state.
134
+ */
135
+ resetState() {
136
+ this.update(() => {
137
+ return getDefaultTokenBalancesState();
138
+ });
139
+ }
132
140
  }
133
141
  exports.TokenBalancesController = TokenBalancesController;
134
142
  _TokenBalancesController_handle = new WeakMap(), _TokenBalancesController_interval = new WeakMap(), _TokenBalancesController_tokens = new WeakMap(), _TokenBalancesController_disabled = new WeakMap();
@@ -1 +1 @@
1
- {"version":3,"file":"TokenBalancesController.cjs","sourceRoot":"","sources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,CAAC,GAAG,IAAA,wBAAK,EAAC,OAAO,CAAC,CAAC;gBAC9C,KAAK,CAAC,eAAe,GAAG,KAAK,CAAC;aAC/B;YAAC,OAAO,KAAK,EAAE;gBACd,mBAAmB,CAAC,OAAO,CAAC,GAAG,IAAA,wBAAK,EAAC,CAAC,CAAC,CAAC;gBACxC,KAAK,CAAC,eAAe,GAAG,IAAI,CAAC;aAC9B;SACF;QAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAhID,0DAgIC;;AAED,kBAAe,uBAAuB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { safelyExecute, toHex } from '@metamask/controller-utils';\n\nimport type { AssetsContractControllerGetERC20BalanceOfAction } from './AssetsContractController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensControllerStateChangeEvent } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n contractBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property tokens - List of tokens to track balances for.\n * @property disabled - If set to true, all tracked tokens contract balances updates are blocked.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n tokens?: Token[];\n disabled?: boolean;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * Represents a mapping of hash token contract addresses to their balances.\n */\ntype ContractBalances = Record<string, string>;\n\n/**\n * Token balances controller state\n * @property contractBalances - Hash of token contract addresses to balances\n */\nexport type TokenBalancesControllerState = {\n contractBalances: ContractBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | AssetsContractControllerGetERC20BalanceOfAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents = TokensControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n contractBalances: {},\n };\n}\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends BaseController<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #interval: number;\n\n #tokens: Token[];\n\n #disabled: boolean;\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.tokens - List of tokens to track balances for.\n * @param options.disabled - If set to true, all tracked tokens contract balances updates are blocked.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n tokens = [],\n disabled = false,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.#disabled = disabled;\n this.#interval = interval;\n this.#tokens = tokens;\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n ({ tokens: newTokens, detectedTokens }) => {\n this.#tokens = [...newTokens, ...detectedTokens];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateBalances();\n },\n );\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll();\n }\n\n /**\n * Allows controller to update tracked tokens contract balances.\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from updating tracked tokens contract balances.\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval used to fetch new token balances.\n */\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n\n await safelyExecute(() => this.updateBalances());\n\n this.#handle = setTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll(this.#interval);\n }, this.#interval);\n }\n\n /**\n * Updates balances for all tokens.\n */\n async updateBalances() {\n if (this.#disabled) {\n return;\n }\n const selectedInternalAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const newContractBalances: ContractBalances = {};\n for (const token of this.#tokens) {\n const { address } = token;\n try {\n const balance = await this.messagingSystem.call(\n 'AssetsContractController:getERC20BalanceOf',\n address,\n selectedInternalAccount.address,\n );\n newContractBalances[address] = toHex(balance);\n token.hasBalanceError = false;\n } catch (error) {\n newContractBalances[address] = toHex(0);\n token.hasBalanceError = true;\n }\n }\n\n this.update((state) => {\n state.contractBalances = newContractBalances;\n });\n }\n}\n\nexport default TokenBalancesController;\n"]}
1
+ {"version":3,"file":"TokenBalancesController.cjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAMA,+DAA2D;AAC3D,iEAAkE;AAMlE,MA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AC;aAC/B;YAAC,OAAO,KAAK,EAAE;gBACd,mBAAmB,CAAC,OAAO,CAAC,GAAG,IAAA,wBAAK,EAAC,CAAC,CAAC,CAAC;gBACxC,KAAK,CAAC,eAAe,GAAG,IAAI,CAAC;aAC9B;SACF;QAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACf,OAAO,4BAA4B,EAAE,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAzID,0DAyIC;;AAED,kBAAe,uBAAuB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { safelyExecute, toHex } from '@metamask/controller-utils';\n\nimport type { AssetsContractControllerGetERC20BalanceOfAction } from './AssetsContractController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensControllerStateChangeEvent } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n contractBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property tokens - List of tokens to track balances for.\n * @property disabled - If set to true, all tracked tokens contract balances updates are blocked.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n tokens?: Token[];\n disabled?: boolean;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * Represents a mapping of hash token contract addresses to their balances.\n */\ntype ContractBalances = Record<string, string>;\n\n/**\n * Token balances controller state\n * @property contractBalances - Hash of token contract addresses to balances\n */\nexport type TokenBalancesControllerState = {\n contractBalances: ContractBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | AssetsContractControllerGetERC20BalanceOfAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents = TokensControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n contractBalances: {},\n };\n}\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends BaseController<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #interval: number;\n\n #tokens: Token[];\n\n #disabled: boolean;\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.tokens - List of tokens to track balances for.\n * @param options.disabled - If set to true, all tracked tokens contract balances updates are blocked.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n tokens = [],\n disabled = false,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.#disabled = disabled;\n this.#interval = interval;\n this.#tokens = tokens;\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n ({ tokens: newTokens, detectedTokens }) => {\n this.#tokens = [...newTokens, ...detectedTokens];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateBalances();\n },\n );\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll();\n }\n\n /**\n * Allows controller to update tracked tokens contract balances.\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from updating tracked tokens contract balances.\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval used to fetch new token balances.\n */\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n\n await safelyExecute(() => this.updateBalances());\n\n this.#handle = setTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll(this.#interval);\n }, this.#interval);\n }\n\n /**\n * Updates balances for all tokens.\n */\n async updateBalances() {\n if (this.#disabled) {\n return;\n }\n const selectedInternalAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const newContractBalances: ContractBalances = {};\n for (const token of this.#tokens) {\n const { address } = token;\n try {\n const balance = await this.messagingSystem.call(\n 'AssetsContractController:getERC20BalanceOf',\n address,\n selectedInternalAccount.address,\n );\n newContractBalances[address] = toHex(balance);\n token.hasBalanceError = false;\n } catch (error) {\n newContractBalances[address] = toHex(0);\n token.hasBalanceError = true;\n }\n }\n\n this.update((state) => {\n state.contractBalances = newContractBalances;\n });\n }\n\n /**\n * Reset the controller state to the default state.\n */\n resetState() {\n this.update(() => {\n return getDefaultTokenBalancesState();\n });\n }\n}\n\nexport default TokenBalancesController;\n"]}
@@ -77,6 +77,10 @@ export declare class TokenBalancesController extends BaseController<typeof contr
77
77
  * Updates balances for all tokens.
78
78
  */
79
79
  updateBalances(): Promise<void>;
80
+ /**
81
+ * Reset the controller state to the default state.
82
+ */
83
+ resetState(): void;
80
84
  }
81
85
  export default TokenBalancesController;
82
86
  //# sourceMappingURL=TokenBalancesController.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"TokenBalancesController.d.cts","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0CAA0C,EAAE,sCAAsC;AAChG,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAG3D,OAAO,KAAK,EAAE,+CAA+C,EAAE,uCAAmC;AAClG,OAAO,KAAK,EAAE,KAAK,EAAE,mCAA+B;AACpD,OAAO,KAAK,EAAE,gCAAgC,EAAE,+BAA2B;AAI3E,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAMjD;;;;;GAKG;AACH,KAAK,8BAA8B,GAAG;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,gCAAgC,CAAC;IAC5C,KAAK,CAAC,EAAE,OAAO,CAAC,4BAA4B,CAAC,CAAC;CAC/C,CAAC;AAEF;;GAEG;AACH,KAAK,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/C;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG;IACzC,gBAAgB,EAAE,gBAAgB,CAAC;CACpC,CAAC;AAEF,MAAM,MAAM,qCAAqC,GAAG,wBAAwB,CAC1E,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEF,MAAM,MAAM,8BAA8B,GACxC,qCAAqC,CAAC;AAExC,MAAM,MAAM,cAAc,GACtB,0CAA0C,GAC1C,+CAA+C,CAAC;AAEpD,MAAM,MAAM,uCAAuC,GACjD,0BAA0B,CACxB,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEJ,MAAM,MAAM,6BAA6B,GACvC,uCAAuC,CAAC;AAE1C,MAAM,MAAM,aAAa,GAAG,gCAAgC,CAAC;AAE7D,MAAM,MAAM,gCAAgC,GAAG,6BAA6B,CAC1E,OAAO,cAAc,EACrB,8BAA8B,GAAG,cAAc,EAC/C,6BAA6B,GAAG,aAAa,EAC7C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,4BAA4B,IAAI,4BAA4B,CAI3E;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,cAAc,CACzD,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IASC;;;;;;;;;OASG;gBACS,EACV,QAA2B,EAC3B,MAAW,EACX,QAAgB,EAChB,SAAS,EACT,KAAU,GACX,EAAE,8BAA8B;IA8BjC;;OAEG;IACH,MAAM;IAIN;;OAEG;IACH,OAAO;IAIP;;;;OAIG;IACG,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB5C;;OAEG;IACG,cAAc;CA6BrB;AAED,eAAe,uBAAuB,CAAC"}
1
+ {"version":3,"file":"TokenBalancesController.d.cts","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0CAA0C,EAAE,sCAAsC;AAChG,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAG3D,OAAO,KAAK,EAAE,+CAA+C,EAAE,uCAAmC;AAClG,OAAO,KAAK,EAAE,KAAK,EAAE,mCAA+B;AACpD,OAAO,KAAK,EA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ASC;;;;;;;;;OASG;gBACS,EACV,QAA2B,EAC3B,MAAW,EACX,QAAgB,EAChB,SAAS,EACT,KAAU,GACX,EAAE,8BAA8B;IA8BjC;;OAEG;IACH,MAAM;IAIN;;OAEG;IACH,OAAO;IAIP;;;;OAIG;IACG,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB5C;;OAEG;IACG,cAAc;IA8BpB;;OAEG;IACH,UAAU;CAKX;AAED,eAAe,uBAAuB,CAAC"}
@@ -77,6 +77,10 @@ export declare class TokenBalancesController extends BaseController<typeof contr
77
77
  * Updates balances for all tokens.
78
78
  */
79
79
  updateBalances(): Promise<void>;
80
+ /**
81
+ * Reset the controller state to the default state.
82
+ */
83
+ resetState(): void;
80
84
  }
81
85
  export default TokenBalancesController;
82
86
  //# sourceMappingURL=TokenBalancesController.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"TokenBalancesController.d.mts","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0CAA0C,EAAE,sCAAsC;AAChG,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAG3D,OAAO,KAAK,EAAE,+CAA+C,EAAE,uCAAmC;AAClG,OAAO,KAAK,EAAE,KAAK,EAAE,mCAA+B;AACpD,OAAO,KAAK,EAAE,gCAAgC,EAAE,+BAA2B;AAI3E,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAMjD;;;;;GAKG;AACH,KAAK,8BAA8B,GAAG;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,gCAAgC,CAAC;IAC5C,KAAK,CAAC,EAAE,OAAO,CAAC,4BAA4B,CAAC,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AAE7D,MAAM,MAAM,gCAAgC,GAAG,6BAA6B,CAC1E,OAAO,cAAc,EACrB,8BAA8B,GAAG,cAAc,EAC/C,6BAA6B,GAAG,aAAa,EAC7C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,4BAA4B,IAAI,4BAA4B,CAI3E;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,cAAc,CACzD,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IASC;;;;;;;;;OASG;gBACS,EACV,QAA2B,EAC3B,MAAW,EACX,QAAgB,EAChB,SAAS,EACT,KAAU,GACX,EAAE,8BAA8B;IA8BjC;;OAEG;IACH,MAAM;IAIN;;OAEG;IACH,OAAO;IAIP;;;;OAIG;IACG,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB5C;;OAEG;IACG,cAAc;IA8BpB;;OAEG;IACH,UAAU;CAKX;AAED,eAAe,uBAAuB,CAAC"}
@@ -125,6 +125,14 @@ export class TokenBalancesController extends BaseController {
125
125
  state.contractBalances = newContractBalances;
126
126
  });
127
127
  }
128
+ /**
129
+ * Reset the controller state to the default state.
130
+ */
131
+ resetState() {
132
+ this.update(() => {
133
+ return getDefaultTokenBalancesState();
134
+ });
135
+ }
128
136
  }
129
137
  _TokenBalancesController_handle = new WeakMap(), _TokenBalancesController_interval = new WeakMap(), _TokenBalancesController_tokens = new WeakMap(), _TokenBalancesController_disabled = new WeakMap();
130
138
  export default TokenBalancesController;
@@ -1 +1 @@
1
- {"version":3,"file":"TokenBalancesController.mjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,mCAAmC;AAMlE,MAAM,gBAAgB,GAAG,MAA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,mBAAmB,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;gBACxC,KAAK,CAAC,eAAe,GAAG,IAAI,CAAC;aAC9B;SACF;QAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;CACF;;AAED,eAAe,uBAAuB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { safelyExecute, toHex } from '@metamask/controller-utils';\n\nimport type { AssetsContractControllerGetERC20BalanceOfAction } from './AssetsContractController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensControllerStateChangeEvent } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n contractBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property tokens - List of tokens to track balances for.\n * @property disabled - If set to true, all tracked tokens contract balances updates are blocked.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n tokens?: Token[];\n disabled?: boolean;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * Represents a mapping of hash token contract addresses to their balances.\n */\ntype ContractBalances = Record<string, string>;\n\n/**\n * Token balances controller state\n * @property contractBalances - Hash of token contract addresses to balances\n */\nexport type TokenBalancesControllerState = {\n contractBalances: ContractBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | AssetsContractControllerGetERC20BalanceOfAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents = TokensControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n contractBalances: {},\n };\n}\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends BaseController<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #interval: number;\n\n #tokens: Token[];\n\n #disabled: boolean;\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.tokens - List of tokens to track balances for.\n * @param options.disabled - If set to true, all tracked tokens contract balances updates are blocked.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n tokens = [],\n disabled = false,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.#disabled = disabled;\n this.#interval = interval;\n this.#tokens = tokens;\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n ({ tokens: newTokens, detectedTokens }) => {\n this.#tokens = [...newTokens, ...detectedTokens];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateBalances();\n },\n );\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll();\n }\n\n /**\n * Allows controller to update tracked tokens contract balances.\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from updating tracked tokens contract balances.\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval used to fetch new token balances.\n */\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n\n await safelyExecute(() => this.updateBalances());\n\n this.#handle = setTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll(this.#interval);\n }, this.#interval);\n }\n\n /**\n * Updates balances for all tokens.\n */\n async updateBalances() {\n if (this.#disabled) {\n return;\n }\n const selectedInternalAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const newContractBalances: ContractBalances = {};\n for (const token of this.#tokens) {\n const { address } = token;\n try {\n const balance = await this.messagingSystem.call(\n 'AssetsContractController:getERC20BalanceOf',\n address,\n selectedInternalAccount.address,\n );\n newContractBalances[address] = toHex(balance);\n token.hasBalanceError = false;\n } catch (error) {\n newContractBalances[address] = toHex(0);\n token.hasBalanceError = true;\n }\n }\n\n this.update((state) => {\n state.contractBalances = newContractBalances;\n });\n }\n}\n\nexport default TokenBalancesController;\n"]}
1
+ {"version":3,"file":"TokenBalancesController.mjs","sourceRoot":"","sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,mCAAmC;AAMlE,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAEjD,MAAM,QAAQ,GAAG;I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,CAAC,eAAe,GAAG,IAAI,CAAC;aAC9B;SACF;QAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;QAC/C,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;YACf,OAAO,4BAA4B,EAAE,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;;AAED,eAAe,uBAAuB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { safelyExecute, toHex } from '@metamask/controller-utils';\n\nimport type { AssetsContractControllerGetERC20BalanceOfAction } from './AssetsContractController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensControllerStateChangeEvent } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n contractBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property tokens - List of tokens to track balances for.\n * @property disabled - If set to true, all tracked tokens contract balances updates are blocked.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n tokens?: Token[];\n disabled?: boolean;\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * Represents a mapping of hash token contract addresses to their balances.\n */\ntype ContractBalances = Record<string, string>;\n\n/**\n * Token balances controller state\n * @property contractBalances - Hash of token contract addresses to balances\n */\nexport type TokenBalancesControllerState = {\n contractBalances: ContractBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | AssetsContractControllerGetERC20BalanceOfAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents = TokensControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n contractBalances: {},\n };\n}\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends BaseController<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #interval: number;\n\n #tokens: Token[];\n\n #disabled: boolean;\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.tokens - List of tokens to track balances for.\n * @param options.disabled - If set to true, all tracked tokens contract balances updates are blocked.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n tokens = [],\n disabled = false,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.#disabled = disabled;\n this.#interval = interval;\n this.#tokens = tokens;\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n ({ tokens: newTokens, detectedTokens }) => {\n this.#tokens = [...newTokens, ...detectedTokens];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateBalances();\n },\n );\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll();\n }\n\n /**\n * Allows controller to update tracked tokens contract balances.\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from updating tracked tokens contract balances.\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval used to fetch new token balances.\n */\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n\n await safelyExecute(() => this.updateBalances());\n\n this.#handle = setTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.poll(this.#interval);\n }, this.#interval);\n }\n\n /**\n * Updates balances for all tokens.\n */\n async updateBalances() {\n if (this.#disabled) {\n return;\n }\n const selectedInternalAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n\n const newContractBalances: ContractBalances = {};\n for (const token of this.#tokens) {\n const { address } = token;\n try {\n const balance = await this.messagingSystem.call(\n 'AssetsContractController:getERC20BalanceOf',\n address,\n selectedInternalAccount.address,\n );\n newContractBalances[address] = toHex(balance);\n token.hasBalanceError = false;\n } catch (error) {\n newContractBalances[address] = toHex(0);\n token.hasBalanceError = true;\n }\n }\n\n this.update((state) => {\n state.contractBalances = newContractBalances;\n });\n }\n\n /**\n * Reset the controller state to the default state.\n */\n resetState() {\n this.update(() => {\n return getDefaultTokenBalancesState();\n });\n }\n}\n\nexport default TokenBalancesController;\n"]}
@@ -13,13 +13,14 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
13
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
- var _TokenDetectionController_instances, _TokenDetectionController_intervalId, _TokenDetectionController_selectedAccountId, _TokenDetectionController_networkClientId, _TokenDetectionController_tokenList, _TokenDetectionController_disabled, _TokenDetectionController_isUnlocked, _TokenDetectionController_isDetectionEnabledFromPreferences, _TokenDetectionController_isDetectionEnabledForNetwork, _TokenDetectionController_getBalancesInSingleCall, _TokenDetectionController_trackMetaMetricsEvent, _TokenDetectionController_accountsAPI, _TokenDetectionController_registerEventListeners, _TokenDetectionController_stopPolling, _TokenDetectionController_startPolling, _TokenDetectionController_getCorrectChainIdAndNetworkClientId, _TokenDetectionController_restartTokenDetection, _TokenDetectionController_getSlicesOfTokensToDetect, _TokenDetectionController_addDetectedTokensViaAPI, _TokenDetectionController_addDetectedTokens, _TokenDetectionController_getSelectedAccount, _TokenDetectionController_getSelectedAddress;
16
+ var _TokenDetectionController_instances, _TokenDetectionController_intervalId, _TokenDetectionController_selectedAccountId, _TokenDetectionController_networkClientId, _TokenDetectionController_tokensChainsCache, _TokenDetectionController_disabled, _TokenDetectionController_isUnlocked, _TokenDetectionController_isDetectionEnabledFromPreferences, _TokenDetectionController_isDetectionEnabledForNetwork, _TokenDetectionController_getBalancesInSingleCall, _TokenDetectionController_trackMetaMetricsEvent, _TokenDetectionController_accountsAPI, _TokenDetectionController_registerEventListeners, _TokenDetectionController_stopPolling, _TokenDetectionController_startPolling, _TokenDetectionController_compareTokensChainsCache, _TokenDetectionController_getCorrectChainIdAndNetworkClientId, _TokenDetectionController_restartTokenDetection, _TokenDetectionController_getSlicesOfTokensToDetect, _TokenDetectionController_getConvertedStaticMainnetTokenList, _TokenDetectionController_addDetectedTokensViaAPI, _TokenDetectionController_addDetectedTokens, _TokenDetectionController_getSelectedAccount, _TokenDetectionController_getSelectedAddress;
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.TokenDetectionController = exports.controllerName = exports.STATIC_MAINNET_TOKEN_LIST = void 0;
19
19
  const contract_metadata_1 = __importDefault(require("@metamask/contract-metadata"));
20
20
  const controller_utils_1 = require("@metamask/controller-utils");
21
21
  const polling_controller_1 = require("@metamask/polling-controller");
22
22
  const utils_1 = require("@metamask/utils");
23
+ const lodash_1 = require("lodash");
23
24
  const assetsUtil_1 = require("./assetsUtil.cjs");
24
25
  const multi_chain_accounts_service_1 = require("./multi-chain-accounts-service/index.cjs");
25
26
  const DEFAULT_INTERVAL = 180000;
@@ -35,6 +36,19 @@ exports.STATIC_MAINNET_TOKEN_LIST = Object.entries(contract_metadata_1.default).
35
36
  },
36
37
  };
37
38
  }, {});
39
+ /**
40
+ * Function that takes a TokensChainsCache object and maps chainId with TokenListMap.
41
+ * @param tokensChainsCache - TokensChainsCache input object
42
+ * @returns returns the map of chainId with TokenListMap
43
+ */
44
+ function mapChainIdWithTokenListMap(tokensChainsCache) {
45
+ return (0, lodash_1.mapValues)(tokensChainsCache, (value) => {
46
+ if ((0, lodash_1.isObject)(value) && 'data' in value) {
47
+ return (0, lodash_1.get)(value, ['data']);
48
+ }
49
+ return value;
50
+ });
51
+ }
38
52
  exports.controllerName = 'TokenDetectionController';
39
53
  /**
40
54
  * Controller that passively polls on a set interval for Tokens auto detection
@@ -57,8 +71,9 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
57
71
  * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.
58
72
  * @param options.trackMetaMetricsEvent - Sets options for MetaMetrics event tracking.
59
73
  * @param options.useAccountsAPI - Feature Switch for using the accounts API when detecting tokens (default: true)
74
+ * @param options.platform - Indicates whether the platform is extension or mobile
60
75
  */
61
- constructor({ interval = DEFAULT_INTERVAL, disabled = true, getBalancesInSingleCall, trackMetaMetricsEvent, messenger, useAccountsAPI = true, }) {
76
+ constructor({ interval = DEFAULT_INTERVAL, disabled = true, getBalancesInSingleCall, trackMetaMetricsEvent, messenger, useAccountsAPI = true, platform, }) {
62
77
  super({
63
78
  name: exports.controllerName,
64
79
  messenger,
@@ -69,7 +84,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
69
84
  _TokenDetectionController_intervalId.set(this, void 0);
70
85
  _TokenDetectionController_selectedAccountId.set(this, void 0);
71
86
  _TokenDetectionController_networkClientId.set(this, void 0);
72
- _TokenDetectionController_tokenList.set(this, {});
87
+ _TokenDetectionController_tokensChainsCache.set(this, {});
73
88
  _TokenDetectionController_disabled.set(this, void 0);
74
89
  _TokenDetectionController_isUnlocked.set(this, void 0);
75
90
  _TokenDetectionController_isDetectionEnabledFromPreferences.set(this, void 0);
@@ -79,6 +94,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
79
94
  _TokenDetectionController_accountsAPI.set(this, {
80
95
  isAccountsAPIEnabled: true,
81
96
  supportedNetworksCache: null,
97
+ platform: '',
82
98
  async getSupportedNetworks() {
83
99
  /* istanbul ignore next */
84
100
  if (!this.isAccountsAPIEnabled) {
@@ -104,7 +120,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
104
120
  }
105
121
  const result = await (0, multi_chain_accounts_service_1.fetchMultiChainBalances)(address, {
106
122
  networks: [chainIdNumber],
107
- });
123
+ }, this.platform);
108
124
  return result.balances;
109
125
  },
110
126
  });
@@ -113,6 +129,8 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
113
129
  __classPrivateFieldSet(this, _TokenDetectionController_selectedAccountId, __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getSelectedAccount).call(this).id, "f");
114
130
  const { chainId, networkClientId } = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getCorrectChainIdAndNetworkClientId).call(this);
115
131
  __classPrivateFieldSet(this, _TokenDetectionController_networkClientId, networkClientId, "f");
132
+ const { tokensChainsCache } = this.messagingSystem.call('TokenListController:getState');
133
+ __classPrivateFieldSet(this, _TokenDetectionController_tokensChainsCache, tokensChainsCache, "f");
116
134
  const { useTokenDetection: defaultUseTokenDetection } = this.messagingSystem.call('PreferencesController:getState');
117
135
  __classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, defaultUseTokenDetection, "f");
118
136
  __classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledForNetwork, (0, assetsUtil_1.isTokenDetectionSupportedForNetwork)(chainId), "f");
@@ -121,6 +139,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
121
139
  const { isUnlocked } = this.messagingSystem.call('KeyringController:getState');
122
140
  __classPrivateFieldSet(this, _TokenDetectionController_isUnlocked, isUnlocked, "f");
123
141
  __classPrivateFieldGet(this, _TokenDetectionController_accountsAPI, "f").isAccountsAPIEnabled = useAccountsAPI;
142
+ __classPrivateFieldGet(this, _TokenDetectionController_accountsAPI, "f").platform = platform;
124
143
  __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_registerEventListeners).call(this);
125
144
  }
126
145
  /**
@@ -191,9 +210,9 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
191
210
  const isTokenDetectionInactiveInMainnet = !__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f") &&
192
211
  chainIdAgainstWhichToDetect === controller_utils_1.ChainId.mainnet;
193
212
  const { tokensChainsCache } = this.messagingSystem.call('TokenListController:getState');
194
- __classPrivateFieldSet(this, _TokenDetectionController_tokenList, isTokenDetectionInactiveInMainnet
195
- ? exports.STATIC_MAINNET_TOKEN_LIST
196
- : tokensChainsCache[chainIdAgainstWhichToDetect]?.data ?? {}, "f");
213
+ __classPrivateFieldSet(this, _TokenDetectionController_tokensChainsCache, isTokenDetectionInactiveInMainnet
214
+ ? __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getConvertedStaticMainnetTokenList).call(this)
215
+ : tokensChainsCache ?? {}, "f");
197
216
  const tokenCandidateSlices = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getSlicesOfTokensToDetect).call(this, {
198
217
  chainId: chainIdAgainstWhichToDetect,
199
218
  selectedAddress: addressAgainstWhichToDetect,
@@ -218,7 +237,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
218
237
  }
219
238
  }
220
239
  exports.TokenDetectionController = TokenDetectionController;
221
- _TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_selectedAccountId = new WeakMap(), _TokenDetectionController_networkClientId = new WeakMap(), _TokenDetectionController_tokenList = new WeakMap(), _TokenDetectionController_disabled = new WeakMap(), _TokenDetectionController_isUnlocked = new WeakMap(), _TokenDetectionController_isDetectionEnabledFromPreferences = new WeakMap(), _TokenDetectionController_isDetectionEnabledForNetwork = new WeakMap(), _TokenDetectionController_getBalancesInSingleCall = new WeakMap(), _TokenDetectionController_trackMetaMetricsEvent = new WeakMap(), _TokenDetectionController_accountsAPI = new WeakMap(), _TokenDetectionController_instances = new WeakSet(), _TokenDetectionController_registerEventListeners = function _TokenDetectionController_registerEventListeners() {
240
+ _TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_selectedAccountId = new WeakMap(), _TokenDetectionController_networkClientId = new WeakMap(), _TokenDetectionController_tokensChainsCache = new WeakMap(), _TokenDetectionController_disabled = new WeakMap(), _TokenDetectionController_isUnlocked = new WeakMap(), _TokenDetectionController_isDetectionEnabledFromPreferences = new WeakMap(), _TokenDetectionController_isDetectionEnabledForNetwork = new WeakMap(), _TokenDetectionController_getBalancesInSingleCall = new WeakMap(), _TokenDetectionController_trackMetaMetricsEvent = new WeakMap(), _TokenDetectionController_accountsAPI = new WeakMap(), _TokenDetectionController_instances = new WeakSet(), _TokenDetectionController_registerEventListeners = function _TokenDetectionController_registerEventListeners() {
222
241
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
223
242
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
224
243
  this.messagingSystem.subscribe('KeyringController:unlock', async () => {
@@ -232,9 +251,9 @@ _TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_
232
251
  this.messagingSystem.subscribe('TokenListController:stateChange',
233
252
  // TODO: Either fix this lint violation or explain why it's necessary to ignore.
234
253
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
235
- async ({ tokenList }) => {
236
- const hasTokens = Object.keys(tokenList).length;
237
- if (hasTokens) {
254
+ async ({ tokensChainsCache }) => {
255
+ const isEqualValues = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_compareTokensChainsCache).call(this, tokensChainsCache, __classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f"));
256
+ if (!isEqualValues) {
238
257
  await __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this);
239
258
  }
240
259
  });
@@ -296,6 +315,11 @@ async function _TokenDetectionController_startPolling() {
296
315
  __classPrivateFieldSet(this, _TokenDetectionController_intervalId, setInterval(async () => {
297
316
  await this.detectTokens();
298
317
  }, this.getIntervalLength()), "f");
318
+ }, _TokenDetectionController_compareTokensChainsCache = function _TokenDetectionController_compareTokensChainsCache(tokensChainsCache, previousTokensChainsCache) {
319
+ const cleanPreviousTokensChainsCache = mapChainIdWithTokenListMap(previousTokensChainsCache);
320
+ const cleanTokensChainsCache = mapChainIdWithTokenListMap(tokensChainsCache);
321
+ const isEqualValues = (0, lodash_1.isEqual)(cleanTokensChainsCache, cleanPreviousTokensChainsCache);
322
+ return isEqualValues;
299
323
  }, _TokenDetectionController_getCorrectChainIdAndNetworkClientId = function _TokenDetectionController_getCorrectChainIdAndNetworkClientId(networkClientId) {
300
324
  if (networkClientId) {
301
325
  const networkConfiguration = this.messagingSystem.call('NetworkController:getNetworkConfigurationByNetworkClientId', networkClientId);
@@ -335,7 +359,7 @@ async function _TokenDetectionController_restartTokenDetection({ selectedAddress
335
359
  allIgnoredTokens,
336
360
  ].map((tokens) => (tokens[chainId]?.[selectedAddress] ?? []).map((value) => typeof value === 'string' ? value : value.address));
337
361
  const tokensToDetect = [];
338
- for (const tokenAddress of Object.keys(__classPrivateFieldGet(this, _TokenDetectionController_tokenList, "f"))) {
362
+ for (const tokenAddress of Object.keys(__classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")?.[chainId]?.data || {})) {
339
363
  if ([
340
364
  tokensAddresses,
341
365
  detectedTokensAddresses,
@@ -349,6 +373,24 @@ async function _TokenDetectionController_restartTokenDetection({ selectedAddress
349
373
  slicesOfTokensToDetect.push(tokensToDetect.slice(i, i + size));
350
374
  }
351
375
  return slicesOfTokensToDetect;
376
+ }, _TokenDetectionController_getConvertedStaticMainnetTokenList = function _TokenDetectionController_getConvertedStaticMainnetTokenList() {
377
+ const data = Object.entries(exports.STATIC_MAINNET_TOKEN_LIST).reduce((acc, [key, value]) => ({
378
+ ...acc,
379
+ [key]: {
380
+ name: value.name,
381
+ symbol: value.symbol,
382
+ decimals: value.decimals,
383
+ address: value.address,
384
+ aggregators: [],
385
+ iconUrl: value?.iconUrl,
386
+ },
387
+ }), {});
388
+ return {
389
+ '0x1': {
390
+ data,
391
+ timestamp: 0,
392
+ },
393
+ };
352
394
  }, _TokenDetectionController_addDetectedTokensViaAPI =
353
395
  /**
354
396
  * This adds detected tokens from the Accounts API, avoiding the multi-call RPC calls for balances
@@ -378,12 +420,12 @@ async function _TokenDetectionController_addDetectedTokensViaAPI({ selectedAddre
378
420
  if (!tokenCandidateSet.has(token.address)) {
379
421
  return;
380
422
  }
381
- // We need specific data from tokenList to correctly create a token
423
+ // We need specific data from tokensChainsCache to correctly create a token
382
424
  // So even if we have a token that was detected correctly by the API, if its missing data we cannot safely add it.
383
- if (!__classPrivateFieldGet(this, _TokenDetectionController_tokenList, "f")[token.address]) {
425
+ if (!__classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")[chainId].data[token.address]) {
384
426
  return;
385
427
  }
386
- const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this, _TokenDetectionController_tokenList, "f")[token.address];
428
+ const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")[chainId].data[token.address];
387
429
  eventTokensDetails.push(`${symbol} - ${tokenAddress}`);
388
430
  tokensWithBalance.push({
389
431
  address: tokenAddress,
@@ -422,7 +464,7 @@ async function _TokenDetectionController_addDetectedTokensViaAPI({ selectedAddre
422
464
  const tokensWithBalance = [];
423
465
  const eventTokensDetails = [];
424
466
  for (const nonZeroTokenAddress of Object.keys(balances)) {
425
- const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this, _TokenDetectionController_tokenList, "f")[nonZeroTokenAddress];
467
+ const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")[chainId].data[nonZeroTokenAddress];
426
468
  eventTokensDetails.push(`${symbol} - ${nonZeroTokenAddress}`);
427
469
  tokensWithBalance.push({
428
470
  address: nonZeroTokenAddress,