@metamask/assets-controllers 31.0.0 → 33.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 (172) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/dist/AccountTrackerController.js +2 -2
  3. package/dist/AccountTrackerController.mjs +1 -1
  4. package/dist/AssetsContractController.js +6 -6
  5. package/dist/AssetsContractController.mjs +5 -5
  6. package/dist/CurrencyRateController.js +3 -3
  7. package/dist/CurrencyRateController.mjs +2 -2
  8. package/dist/NftController.js +3 -3
  9. package/dist/NftController.mjs +2 -2
  10. package/dist/NftDetectionController.js +2 -2
  11. package/dist/NftDetectionController.mjs +1 -1
  12. package/dist/RatesController/RatesController.js +3 -3
  13. package/dist/RatesController/RatesController.mjs +2 -2
  14. package/dist/RatesController/index.js +3 -3
  15. package/dist/RatesController/index.mjs +2 -2
  16. package/dist/Standards/ERC20Standard.js +3 -3
  17. package/dist/Standards/ERC20Standard.mjs +2 -2
  18. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +3 -3
  19. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +2 -2
  20. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +3 -3
  21. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +2 -2
  22. package/dist/TokenBalancesController.js +2 -2
  23. package/dist/TokenBalancesController.mjs +1 -1
  24. package/dist/TokenDetectionController.js +3 -3
  25. package/dist/TokenDetectionController.mjs +2 -2
  26. package/dist/TokenListController.js +4 -4
  27. package/dist/TokenListController.mjs +3 -3
  28. package/dist/TokenRatesController.js +9 -5
  29. package/dist/TokenRatesController.mjs +10 -6
  30. package/dist/TokensController.js +6 -6
  31. package/dist/TokensController.mjs +5 -5
  32. package/dist/assetsUtil.js +2 -2
  33. package/dist/assetsUtil.mjs +1 -1
  34. package/dist/chunk-2IIQTSLV.mjs +236 -0
  35. package/dist/chunk-2IIQTSLV.mjs.map +1 -0
  36. package/dist/chunk-354SINOH.js +236 -0
  37. package/dist/chunk-354SINOH.js.map +1 -0
  38. package/dist/{chunk-MR6EF4B7.mjs → chunk-3K3LE2CZ.mjs} +14 -2
  39. package/dist/chunk-3K3LE2CZ.mjs.map +1 -0
  40. package/dist/{chunk-5W5OO2Q5.mjs → chunk-47CRHAUE.mjs} +2 -2
  41. package/dist/chunk-47CRHAUE.mjs.map +1 -0
  42. package/dist/{chunk-65PB33TE.mjs → chunk-526TATMH.mjs} +25 -17
  43. package/dist/chunk-526TATMH.mjs.map +1 -0
  44. package/dist/{chunk-D3K5MPMW.mjs → chunk-56O7BVZV.mjs} +2 -2
  45. package/dist/{chunk-B5YY22QQ.js → chunk-6PPM4ETZ.js} +3 -3
  46. package/dist/{chunk-CGLUTXI7.js → chunk-7JWDWDXT.js} +190 -107
  47. package/dist/chunk-7JWDWDXT.js.map +1 -0
  48. package/dist/{chunk-JUI3XNEF.js → chunk-7OZL6IDY.js} +16 -9
  49. package/dist/chunk-7OZL6IDY.js.map +1 -0
  50. package/dist/{chunk-GU53EI7A.js → chunk-AZ6SRJVI.js} +24 -16
  51. package/dist/chunk-AZ6SRJVI.js.map +1 -0
  52. package/dist/{chunk-YIFA2HXH.js → chunk-F6L3DFOZ.js} +5 -3
  53. package/dist/chunk-F6L3DFOZ.js.map +1 -0
  54. package/dist/{chunk-UEDNQBJN.js → chunk-FGAZXVKS.js} +200 -104
  55. package/dist/chunk-FGAZXVKS.js.map +1 -0
  56. package/dist/{chunk-B6W4CQOR.mjs → chunk-HJ5GXVDT.mjs} +2 -2
  57. package/dist/chunk-HJ5GXVDT.mjs.map +1 -0
  58. package/dist/{chunk-BOTVAG4A.js → chunk-JBF4XEGR.js} +5 -5
  59. package/dist/{chunk-ASA5RLBY.mjs → chunk-JEIAMJGS.mjs} +2 -2
  60. package/dist/{chunk-CNKVITJO.mjs → chunk-JTXPJ6TK.mjs} +4 -2
  61. package/dist/chunk-JTXPJ6TK.mjs.map +1 -0
  62. package/dist/{chunk-U3DJJN4X.js → chunk-LBJTMJFA.js} +4 -4
  63. package/dist/{chunk-IBK6AXPP.js → chunk-NWVMFCSC.js} +1 -1
  64. package/dist/{chunk-IBK6AXPP.js.map → chunk-NWVMFCSC.js.map} +1 -1
  65. package/dist/{chunk-NEXY7SE2.js → chunk-NYVA7ZTQ.js} +2 -2
  66. package/dist/chunk-NYVA7ZTQ.js.map +1 -0
  67. package/dist/{chunk-WCCLSUOI.mjs → chunk-OEEFNXR7.mjs} +1 -1
  68. package/dist/{chunk-WCCLSUOI.mjs.map → chunk-OEEFNXR7.mjs.map} +1 -1
  69. package/dist/{chunk-E4ECCGJV.mjs → chunk-P3O5CVAH.mjs} +195 -99
  70. package/dist/chunk-P3O5CVAH.mjs.map +1 -0
  71. package/dist/{chunk-4AC3X2U5.js → chunk-RJBYLTY5.js} +29 -14
  72. package/dist/chunk-RJBYLTY5.js.map +1 -0
  73. package/dist/{chunk-B5YVX5IO.mjs → chunk-SBWPU4VT.mjs} +4 -2
  74. package/dist/chunk-SBWPU4VT.mjs.map +1 -0
  75. package/dist/{chunk-ELSMS5S7.js → chunk-T5ZX5BV7.js} +3 -3
  76. package/dist/{chunk-ELSMS5S7.js.map → chunk-T5ZX5BV7.js.map} +1 -1
  77. package/dist/{chunk-HLCGZGPA.mjs → chunk-TWR6P5WG.mjs} +11 -7
  78. package/dist/chunk-TWR6P5WG.mjs.map +1 -0
  79. package/dist/{chunk-73F3SN5O.mjs → chunk-UVE4XY5Y.mjs} +23 -8
  80. package/dist/chunk-UVE4XY5Y.mjs.map +1 -0
  81. package/dist/{chunk-LZ5ZGQEX.mjs → chunk-UYH6NWKB.mjs} +2 -2
  82. package/dist/{chunk-Z6TBQQE5.js → chunk-V6DNVROD.js} +4 -4
  83. package/dist/chunk-V6DNVROD.js.map +1 -0
  84. package/dist/{chunk-Q5JRBGWO.mjs → chunk-VELPHITE.mjs} +2 -2
  85. package/dist/chunk-VELPHITE.mjs.map +1 -0
  86. package/dist/{chunk-HDI4L2DD.js → chunk-VZF43NDM.js} +17 -5
  87. package/dist/chunk-VZF43NDM.js.map +1 -0
  88. package/dist/{chunk-62T7RKU3.mjs → chunk-W57QXOHJ.mjs} +188 -105
  89. package/dist/chunk-W57QXOHJ.mjs.map +1 -0
  90. package/dist/{chunk-PYMUBJQX.js → chunk-X4RMS365.js} +3 -3
  91. package/dist/chunk-X4RMS365.js.map +1 -0
  92. package/dist/{chunk-Y35SM7TO.mjs → chunk-XQO3EG4J.mjs} +4 -4
  93. package/dist/chunk-XQO3EG4J.mjs.map +1 -0
  94. package/dist/{chunk-QHWKLZUC.js → chunk-XSNGD5US.js} +14 -10
  95. package/dist/chunk-XSNGD5US.js.map +1 -0
  96. package/dist/{chunk-A2DDWXMS.mjs → chunk-Y45HQET7.mjs} +12 -5
  97. package/dist/chunk-Y45HQET7.mjs.map +1 -0
  98. package/dist/{chunk-WB6KJX4N.js → chunk-ZG5MS2TO.js} +4 -2
  99. package/dist/chunk-ZG5MS2TO.js.map +1 -0
  100. package/dist/crypto-compare-service/crypto-compare.js +2 -2
  101. package/dist/crypto-compare-service/crypto-compare.mjs +1 -1
  102. package/dist/crypto-compare-service/index.js +2 -2
  103. package/dist/crypto-compare-service/index.mjs +1 -1
  104. package/dist/index.js +21 -19
  105. package/dist/index.mjs +21 -19
  106. package/dist/token-prices-service/codefi-v2.js +2 -2
  107. package/dist/token-prices-service/codefi-v2.mjs +1 -1
  108. package/dist/token-prices-service/index.js +2 -2
  109. package/dist/token-prices-service/index.mjs +1 -1
  110. package/dist/token-service.js +3 -3
  111. package/dist/token-service.mjs +2 -2
  112. package/dist/tsconfig.build.tsbuildinfo +1 -1
  113. package/dist/types/AccountTrackerController.d.ts +13 -12
  114. package/dist/types/AccountTrackerController.d.ts.map +1 -1
  115. package/dist/types/AssetsContractController.d.ts.map +1 -1
  116. package/dist/types/CurrencyRateController.d.ts.map +1 -1
  117. package/dist/types/NftController.d.ts +4 -5
  118. package/dist/types/NftController.d.ts.map +1 -1
  119. package/dist/types/NftDetectionController.d.ts +7 -18
  120. package/dist/types/NftDetectionController.d.ts.map +1 -1
  121. package/dist/types/RatesController/RatesController.d.ts.map +1 -1
  122. package/dist/types/TokenBalancesController.d.ts.map +1 -1
  123. package/dist/types/TokenDetectionController.d.ts.map +1 -1
  124. package/dist/types/TokenListController.d.ts.map +1 -1
  125. package/dist/types/TokenRatesController.d.ts +72 -65
  126. package/dist/types/TokenRatesController.d.ts.map +1 -1
  127. package/dist/types/TokensController.d.ts.map +1 -1
  128. package/dist/types/assetsUtil.d.ts.map +1 -1
  129. package/dist/types/crypto-compare-service/crypto-compare.d.ts.map +1 -1
  130. package/dist/types/index.d.ts +2 -2
  131. package/dist/types/index.d.ts.map +1 -1
  132. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts +0 -1
  133. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -1
  134. package/dist/types/token-prices-service/codefi-v2.d.ts +1 -1
  135. package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -1
  136. package/dist/types/token-service.d.ts.map +1 -1
  137. package/package.json +16 -16
  138. package/dist/chunk-4AC3X2U5.js.map +0 -1
  139. package/dist/chunk-543CC74T.mjs +0 -253
  140. package/dist/chunk-543CC74T.mjs.map +0 -1
  141. package/dist/chunk-5W5OO2Q5.mjs.map +0 -1
  142. package/dist/chunk-62T7RKU3.mjs.map +0 -1
  143. package/dist/chunk-65PB33TE.mjs.map +0 -1
  144. package/dist/chunk-73F3SN5O.mjs.map +0 -1
  145. package/dist/chunk-A2DDWXMS.mjs.map +0 -1
  146. package/dist/chunk-B5YVX5IO.mjs.map +0 -1
  147. package/dist/chunk-B6W4CQOR.mjs.map +0 -1
  148. package/dist/chunk-CGLUTXI7.js.map +0 -1
  149. package/dist/chunk-CNKVITJO.mjs.map +0 -1
  150. package/dist/chunk-E4ECCGJV.mjs.map +0 -1
  151. package/dist/chunk-GU53EI7A.js.map +0 -1
  152. package/dist/chunk-HDI4L2DD.js.map +0 -1
  153. package/dist/chunk-HLCGZGPA.mjs.map +0 -1
  154. package/dist/chunk-JUI3XNEF.js.map +0 -1
  155. package/dist/chunk-MR6EF4B7.mjs.map +0 -1
  156. package/dist/chunk-NEXY7SE2.js.map +0 -1
  157. package/dist/chunk-PYMUBJQX.js.map +0 -1
  158. package/dist/chunk-Q5JRBGWO.mjs.map +0 -1
  159. package/dist/chunk-QFDTOEYR.js +0 -253
  160. package/dist/chunk-QFDTOEYR.js.map +0 -1
  161. package/dist/chunk-QHWKLZUC.js.map +0 -1
  162. package/dist/chunk-UEDNQBJN.js.map +0 -1
  163. package/dist/chunk-WB6KJX4N.js.map +0 -1
  164. package/dist/chunk-Y35SM7TO.mjs.map +0 -1
  165. package/dist/chunk-YIFA2HXH.js.map +0 -1
  166. package/dist/chunk-Z6TBQQE5.js.map +0 -1
  167. /package/dist/{chunk-D3K5MPMW.mjs.map → chunk-56O7BVZV.mjs.map} +0 -0
  168. /package/dist/{chunk-B5YY22QQ.js.map → chunk-6PPM4ETZ.js.map} +0 -0
  169. /package/dist/{chunk-BOTVAG4A.js.map → chunk-JBF4XEGR.js.map} +0 -0
  170. /package/dist/{chunk-ASA5RLBY.mjs.map → chunk-JEIAMJGS.mjs.map} +0 -0
  171. /package/dist/{chunk-U3DJJN4X.js.map → chunk-LBJTMJFA.js.map} +0 -0
  172. /package/dist/{chunk-LZ5ZGQEX.mjs.map → chunk-UYH6NWKB.mjs.map} +0 -0
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  ZERO_ADDRESS
3
- } from "./chunk-Y35SM7TO.mjs";
3
+ } from "./chunk-XQO3EG4J.mjs";
4
4
  import {
5
5
  fetchExchangeRate
6
- } from "./chunk-CNKVITJO.mjs";
6
+ } from "./chunk-JTXPJ6TK.mjs";
7
7
  import {
8
8
  TOKEN_PRICES_BATCH_SIZE,
9
9
  reduceInBatchesSerially
10
- } from "./chunk-Q5JRBGWO.mjs";
10
+ } from "./chunk-VELPHITE.mjs";
11
11
  import {
12
12
  __privateAdd,
13
13
  __privateGet,
@@ -22,9 +22,11 @@ import {
22
22
  FALL_BACK_VS_CURRENCY,
23
23
  toHex
24
24
  } from "@metamask/controller-utils";
25
- import { StaticIntervalPollingControllerV1 } from "@metamask/polling-controller";
25
+ import { StaticIntervalPollingController } from "@metamask/polling-controller";
26
26
  import { createDeferredPromise } from "@metamask/utils";
27
27
  import { isEqual } from "lodash";
28
+ var DEFAULT_INTERVAL = 18e4;
29
+ var controllerName = "TokenRatesController";
28
30
  async function getCurrencyConversionRate({
29
31
  from,
30
32
  to
@@ -44,38 +46,42 @@ async function getCurrencyConversionRate({
44
46
  throw error;
45
47
  }
46
48
  }
47
- var _pollState, _tokenPricesService, _inProcessExchangeRateUpdates, _getTokenAddresses, getTokenAddresses_fn, _stopPoll, stopPoll_fn, _poll, poll_fn, _fetchAndMapExchangeRates, fetchAndMapExchangeRates_fn, _fetchAndMapExchangeRatesForSupportedNativeCurrency, fetchAndMapExchangeRatesForSupportedNativeCurrency_fn, _fetchAndMapExchangeRatesForUnsupportedNativeCurrency, fetchAndMapExchangeRatesForUnsupportedNativeCurrency_fn;
48
- var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
49
+ var tokenRatesControllerMetadata = {
50
+ marketData: { persist: true, anonymous: false }
51
+ };
52
+ var getDefaultTokenRatesControllerState = () => {
53
+ return {
54
+ marketData: {}
55
+ };
56
+ };
57
+ var _handle, _pollState, _tokenPricesService, _inProcessExchangeRateUpdates, _selectedAddress, _disabled, _chainId, _ticker, _interval, _allTokens, _allDetectedTokens, _subscribeToPreferencesStateChange, subscribeToPreferencesStateChange_fn, _subscribeToTokensStateChange, subscribeToTokensStateChange_fn, _subscribeToNetworkStateChange, subscribeToNetworkStateChange_fn, _getTokenAddresses, getTokenAddresses_fn, _getSelectedAddress, getSelectedAddress_fn, _getChainIdAndTicker, getChainIdAndTicker_fn, _getTokensControllerState, getTokensControllerState_fn, _stopPoll, stopPoll_fn, _poll, poll_fn, _fetchAndMapExchangeRates, fetchAndMapExchangeRates_fn, _fetchAndMapExchangeRatesForSupportedNativeCurrency, fetchAndMapExchangeRatesForSupportedNativeCurrency_fn, _fetchAndMapExchangeRatesForUnsupportedNativeCurrency, fetchAndMapExchangeRatesForUnsupportedNativeCurrency_fn;
58
+ var TokenRatesController = class extends StaticIntervalPollingController {
49
59
  /**
50
60
  * Creates a TokenRatesController instance.
51
61
  *
52
62
  * @param options - The controller options.
53
63
  * @param options.interval - The polling interval in ms
54
- * @param options.threshold - The duration in ms before metadata fetched from CoinGecko is considered stale
55
- * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
56
- * @param options.chainId - The chain ID of the current network.
57
- * @param options.ticker - The ticker for the current network.
58
- * @param options.selectedAddress - The current selected address.
59
- * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
60
- * @param options.onTokensStateChange - Allows subscribing to token controller state changes.
61
- * @param options.onNetworkStateChange - Allows subscribing to network state changes.
62
- * @param options.tokenPricesService - An object in charge of retrieving token prices.
63
- * @param config - Initial options used to configure this controller.
64
- * @param state - Initial state to set on this controller.
64
+ * @param options.disabled - Boolean to track if network requests are blocked
65
+ * @param options.tokenPricesService - An object in charge of retrieving token price
66
+ * @param options.messenger - The controller messenger instance for communication
67
+ * @param options.state - Initial state to set on this controller
65
68
  */
66
69
  constructor({
67
- interval = 3 * 60 * 1e3,
68
- threshold = 6 * 60 * 60 * 1e3,
69
- getNetworkClientById,
70
- chainId: initialChainId,
71
- ticker: initialTicker,
72
- selectedAddress: initialSelectedAddress,
73
- onPreferencesStateChange,
74
- onTokensStateChange,
75
- onNetworkStateChange,
76
- tokenPricesService
77
- }, config, state) {
78
- super(config, state);
70
+ interval = DEFAULT_INTERVAL,
71
+ disabled = false,
72
+ tokenPricesService,
73
+ messenger,
74
+ state
75
+ }) {
76
+ super({
77
+ name: controllerName,
78
+ messenger,
79
+ state: { ...getDefaultTokenRatesControllerState(), ...state },
80
+ metadata: tokenRatesControllerMetadata
81
+ });
82
+ __privateAdd(this, _subscribeToPreferencesStateChange);
83
+ __privateAdd(this, _subscribeToTokensStateChange);
84
+ __privateAdd(this, _subscribeToNetworkStateChange);
79
85
  /**
80
86
  * Get the user's tokens for the given chain.
81
87
  *
@@ -83,6 +89,9 @@ var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
83
89
  * @returns The list of tokens addresses for the current chain
84
90
  */
85
91
  __privateAdd(this, _getTokenAddresses);
92
+ __privateAdd(this, _getSelectedAddress);
93
+ __privateAdd(this, _getChainIdAndTicker);
94
+ __privateAdd(this, _getTokensControllerState);
86
95
  /**
87
96
  * Clear the active polling timer, if present.
88
97
  */
@@ -138,63 +147,43 @@ var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
138
147
  * native currency.
139
148
  */
140
149
  __privateAdd(this, _fetchAndMapExchangeRatesForUnsupportedNativeCurrency);
150
+ __privateAdd(this, _handle, void 0);
141
151
  __privateAdd(this, _pollState, "Inactive" /* Inactive */);
142
152
  __privateAdd(this, _tokenPricesService, void 0);
143
153
  __privateAdd(this, _inProcessExchangeRateUpdates, {});
144
- /**
145
- * Name of this controller used during composition
146
- */
147
- this.name = "TokenRatesController";
148
- this.defaultConfig = {
149
- interval,
150
- threshold,
151
- disabled: false,
152
- nativeCurrency: initialTicker,
153
- chainId: initialChainId,
154
- selectedAddress: initialSelectedAddress,
155
- allTokens: {},
156
- // TODO: initialize these correctly, maybe as part of BaseControllerV2 migration
157
- allDetectedTokens: {}
158
- };
159
- this.defaultState = {
160
- marketData: {}
161
- };
162
- this.initialize();
154
+ __privateAdd(this, _selectedAddress, void 0);
155
+ __privateAdd(this, _disabled, void 0);
156
+ __privateAdd(this, _chainId, void 0);
157
+ __privateAdd(this, _ticker, void 0);
158
+ __privateAdd(this, _interval, void 0);
159
+ __privateAdd(this, _allTokens, void 0);
160
+ __privateAdd(this, _allDetectedTokens, void 0);
163
161
  this.setIntervalLength(interval);
164
- this.getNetworkClientById = getNetworkClientById;
165
162
  __privateSet(this, _tokenPricesService, tokenPricesService);
166
- if (config?.disabled) {
167
- this.configure({ disabled: true }, false, false);
168
- }
169
- onPreferencesStateChange(async ({ selectedAddress }) => {
170
- if (this.config.selectedAddress !== selectedAddress) {
171
- this.configure({ selectedAddress });
172
- if (__privateGet(this, _pollState) === "Active" /* Active */) {
173
- await this.updateExchangeRates();
174
- }
175
- }
176
- });
177
- onTokensStateChange(async ({ allTokens, allDetectedTokens }) => {
178
- const previousTokenAddresses = __privateMethod(this, _getTokenAddresses, getTokenAddresses_fn).call(this, this.config.chainId);
179
- this.configure({ allTokens, allDetectedTokens });
180
- const newTokenAddresses = __privateMethod(this, _getTokenAddresses, getTokenAddresses_fn).call(this, this.config.chainId);
181
- if (!isEqual(previousTokenAddresses, newTokenAddresses) && __privateGet(this, _pollState) === "Active" /* Active */) {
182
- await this.updateExchangeRates();
183
- }
184
- });
185
- onNetworkStateChange(async ({ selectedNetworkClientId }) => {
186
- const selectedNetworkClient = getNetworkClientById(
187
- selectedNetworkClientId
188
- );
189
- const { chainId, ticker } = selectedNetworkClient.configuration;
190
- if (this.config.chainId !== chainId || this.config.nativeCurrency !== ticker) {
191
- this.update({ ...this.defaultState });
192
- this.configure({ chainId, nativeCurrency: ticker });
193
- if (__privateGet(this, _pollState) === "Active" /* Active */) {
194
- await this.updateExchangeRates();
195
- }
196
- }
197
- });
163
+ __privateSet(this, _disabled, disabled);
164
+ __privateSet(this, _interval, interval);
165
+ const { chainId: currentChainId, ticker: currentTicker } = __privateMethod(this, _getChainIdAndTicker, getChainIdAndTicker_fn).call(this);
166
+ __privateSet(this, _chainId, currentChainId);
167
+ __privateSet(this, _ticker, currentTicker);
168
+ __privateSet(this, _selectedAddress, __privateMethod(this, _getSelectedAddress, getSelectedAddress_fn).call(this));
169
+ const { allTokens, allDetectedTokens } = __privateMethod(this, _getTokensControllerState, getTokensControllerState_fn).call(this);
170
+ __privateSet(this, _allTokens, allTokens);
171
+ __privateSet(this, _allDetectedTokens, allDetectedTokens);
172
+ __privateMethod(this, _subscribeToPreferencesStateChange, subscribeToPreferencesStateChange_fn).call(this);
173
+ __privateMethod(this, _subscribeToTokensStateChange, subscribeToTokensStateChange_fn).call(this);
174
+ __privateMethod(this, _subscribeToNetworkStateChange, subscribeToNetworkStateChange_fn).call(this);
175
+ }
176
+ /**
177
+ * Allows controller to make active and passive polling requests
178
+ */
179
+ enable() {
180
+ __privateSet(this, _disabled, false);
181
+ }
182
+ /**
183
+ * Blocks controller from making network calls
184
+ */
185
+ disable() {
186
+ __privateSet(this, _disabled, true);
198
187
  }
199
188
  /**
200
189
  * Start (or restart) polling.
@@ -215,10 +204,9 @@ var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
215
204
  * Updates exchange rates for all tokens.
216
205
  */
217
206
  async updateExchangeRates() {
218
- const { chainId, nativeCurrency } = this.config;
219
207
  await this.updateExchangeRatesByChainId({
220
- chainId,
221
- nativeCurrency
208
+ chainId: __privateGet(this, _chainId),
209
+ nativeCurrency: __privateGet(this, _ticker)
222
210
  });
223
211
  }
224
212
  /**
@@ -232,7 +220,7 @@ var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
232
220
  chainId,
233
221
  nativeCurrency
234
222
  }) {
235
- if (this.disabled) {
223
+ if (__privateGet(this, _disabled)) {
236
224
  return;
237
225
  }
238
226
  const tokenAddresses = __privateMethod(this, _getTokenAddresses, getTokenAddresses_fn).call(this, chainId);
@@ -258,8 +246,8 @@ var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
258
246
  ...contractInformations ?? {}
259
247
  }
260
248
  };
261
- this.update({
262
- marketData
249
+ this.update((state) => {
250
+ state.marketData = marketData;
263
251
  });
264
252
  updateSucceeded();
265
253
  } catch (error) {
@@ -276,21 +264,96 @@ var TokenRatesController = class extends StaticIntervalPollingControllerV1 {
276
264
  * @returns The controller state.
277
265
  */
278
266
  async _executePoll(networkClientId) {
279
- const networkClient = this.getNetworkClientById(networkClientId);
267
+ const networkClient = this.messagingSystem.call(
268
+ "NetworkController:getNetworkClientById",
269
+ networkClientId
270
+ );
280
271
  await this.updateExchangeRatesByChainId({
281
272
  chainId: networkClient.configuration.chainId,
282
273
  nativeCurrency: networkClient.configuration.ticker
283
274
  });
284
275
  }
285
276
  };
277
+ _handle = new WeakMap();
286
278
  _pollState = new WeakMap();
287
279
  _tokenPricesService = new WeakMap();
288
280
  _inProcessExchangeRateUpdates = new WeakMap();
281
+ _selectedAddress = new WeakMap();
282
+ _disabled = new WeakMap();
283
+ _chainId = new WeakMap();
284
+ _ticker = new WeakMap();
285
+ _interval = new WeakMap();
286
+ _allTokens = new WeakMap();
287
+ _allDetectedTokens = new WeakMap();
288
+ _subscribeToPreferencesStateChange = new WeakSet();
289
+ subscribeToPreferencesStateChange_fn = function() {
290
+ this.messagingSystem.subscribe(
291
+ "PreferencesController:stateChange",
292
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
293
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
294
+ async (selectedAddress) => {
295
+ if (__privateGet(this, _selectedAddress) !== selectedAddress) {
296
+ __privateSet(this, _selectedAddress, selectedAddress);
297
+ if (__privateGet(this, _pollState) === "Active" /* Active */) {
298
+ await this.updateExchangeRates();
299
+ }
300
+ }
301
+ },
302
+ ({ selectedAddress }) => {
303
+ return selectedAddress;
304
+ }
305
+ );
306
+ };
307
+ _subscribeToTokensStateChange = new WeakSet();
308
+ subscribeToTokensStateChange_fn = function() {
309
+ this.messagingSystem.subscribe(
310
+ "TokensController:stateChange",
311
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
312
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
313
+ async ({ allTokens, allDetectedTokens }) => {
314
+ const previousTokenAddresses = __privateMethod(this, _getTokenAddresses, getTokenAddresses_fn).call(this, __privateGet(this, _chainId));
315
+ __privateSet(this, _allTokens, allTokens);
316
+ __privateSet(this, _allDetectedTokens, allDetectedTokens);
317
+ const newTokenAddresses = __privateMethod(this, _getTokenAddresses, getTokenAddresses_fn).call(this, __privateGet(this, _chainId));
318
+ if (!isEqual(previousTokenAddresses, newTokenAddresses) && __privateGet(this, _pollState) === "Active" /* Active */) {
319
+ await this.updateExchangeRates();
320
+ }
321
+ },
322
+ ({ allTokens, allDetectedTokens }) => {
323
+ return { allTokens, allDetectedTokens };
324
+ }
325
+ );
326
+ };
327
+ _subscribeToNetworkStateChange = new WeakSet();
328
+ subscribeToNetworkStateChange_fn = function() {
329
+ this.messagingSystem.subscribe(
330
+ "NetworkController:stateChange",
331
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
332
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
333
+ async ({ selectedNetworkClientId }) => {
334
+ const {
335
+ configuration: { chainId, ticker }
336
+ } = this.messagingSystem.call(
337
+ "NetworkController:getNetworkClientById",
338
+ selectedNetworkClientId
339
+ );
340
+ if (__privateGet(this, _chainId) !== chainId || __privateGet(this, _ticker) !== ticker) {
341
+ this.update((state) => {
342
+ state.marketData = {};
343
+ });
344
+ __privateSet(this, _chainId, chainId);
345
+ __privateSet(this, _ticker, ticker);
346
+ if (__privateGet(this, _pollState) === "Active" /* Active */) {
347
+ await this.updateExchangeRates();
348
+ }
349
+ }
350
+ }
351
+ );
352
+ };
289
353
  _getTokenAddresses = new WeakSet();
290
354
  getTokenAddresses_fn = function(chainId) {
291
- const { allTokens, allDetectedTokens } = this.config;
292
- const tokens = allTokens[chainId]?.[this.config.selectedAddress] || [];
293
- const detectedTokens = allDetectedTokens[chainId]?.[this.config.selectedAddress] || [];
355
+ const tokens = __privateGet(this, _allTokens)[chainId]?.[__privateGet(this, _selectedAddress)] || [];
356
+ const detectedTokens = __privateGet(this, _allDetectedTokens)[chainId]?.[__privateGet(this, _selectedAddress)] || [];
294
357
  return [
295
358
  ...new Set(
296
359
  [...tokens, ...detectedTokens].map(
@@ -299,18 +362,49 @@ getTokenAddresses_fn = function(chainId) {
299
362
  )
300
363
  ].sort();
301
364
  };
365
+ _getSelectedAddress = new WeakSet();
366
+ getSelectedAddress_fn = function() {
367
+ const { selectedAddress } = this.messagingSystem.call(
368
+ "PreferencesController:getState"
369
+ );
370
+ return selectedAddress;
371
+ };
372
+ _getChainIdAndTicker = new WeakSet();
373
+ getChainIdAndTicker_fn = function() {
374
+ const { selectedNetworkClientId } = this.messagingSystem.call(
375
+ "NetworkController:getState"
376
+ );
377
+ const networkClient = this.messagingSystem.call(
378
+ "NetworkController:getNetworkClientById",
379
+ selectedNetworkClientId
380
+ );
381
+ return {
382
+ chainId: networkClient.configuration.chainId,
383
+ ticker: networkClient.configuration.ticker
384
+ };
385
+ };
386
+ _getTokensControllerState = new WeakSet();
387
+ getTokensControllerState_fn = function() {
388
+ const { allTokens, allDetectedTokens } = this.messagingSystem.call(
389
+ "TokensController:getState"
390
+ );
391
+ return {
392
+ allTokens,
393
+ allDetectedTokens
394
+ };
395
+ };
302
396
  _stopPoll = new WeakSet();
303
397
  stopPoll_fn = function() {
304
- if (this.handle) {
305
- clearTimeout(this.handle);
398
+ if (__privateGet(this, _handle)) {
399
+ clearTimeout(__privateGet(this, _handle));
306
400
  }
307
401
  };
308
402
  _poll = new WeakSet();
309
403
  poll_fn = async function() {
310
404
  await safelyExecute(() => this.updateExchangeRates());
311
- this.handle = setTimeout(() => {
405
+ __privateSet(this, _handle, setTimeout(() => {
312
406
  __privateMethod(this, _poll, poll_fn).call(this);
313
- }, this.config.interval);
407
+ }, __privateGet(this, _interval)));
314
408
  };
315
409
  _fetchAndMapExchangeRates = new WeakSet();
316
410
  fetchAndMapExchangeRates_fn = async function({
@@ -380,7 +474,7 @@ fetchAndMapExchangeRatesForSupportedNativeCurrency_fn = async function({
380
474
  (obj, [tokenAddress, token]) => {
381
475
  obj = {
382
476
  ...obj,
383
- [tokenAddress.toLowerCase()]: { ...token }
477
+ [tokenAddress]: { ...token }
384
478
  };
385
479
  return obj;
386
480
  },
@@ -398,7 +492,7 @@ fetchAndMapExchangeRatesForUnsupportedNativeCurrency_fn = async function({
398
492
  ] = await Promise.all([
399
493
  __privateMethod(this, _fetchAndMapExchangeRatesForSupportedNativeCurrency, fetchAndMapExchangeRatesForSupportedNativeCurrency_fn).call(this, {
400
494
  tokenAddresses,
401
- chainId: this.config.chainId,
495
+ chainId: __privateGet(this, _chainId),
402
496
  nativeCurrency: FALL_BACK_VS_CURRENCY
403
497
  }),
404
498
  getCurrencyConversionRate({
@@ -416,7 +510,7 @@ fetchAndMapExchangeRatesForUnsupportedNativeCurrency_fn = async function({
416
510
  ...acc,
417
511
  [tokenAddress]: {
418
512
  ...token,
419
- value: token.value ? token.value * fallbackCurrencyToNativeCurrencyConversionRate : void 0
513
+ price: token.price ? token.price * fallbackCurrencyToNativeCurrencyConversionRate : void 0
420
514
  }
421
515
  };
422
516
  return acc;
@@ -426,7 +520,9 @@ fetchAndMapExchangeRatesForUnsupportedNativeCurrency_fn = async function({
426
520
  var TokenRatesController_default = TokenRatesController;
427
521
 
428
522
  export {
523
+ controllerName,
524
+ getDefaultTokenRatesControllerState,
429
525
  TokenRatesController,
430
526
  TokenRatesController_default
431
527
  };
432
- //# sourceMappingURL=chunk-E4ECCGJV.mjs.map
528
+ //# sourceMappingURL=chunk-P3O5CVAH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/TokenRatesController.ts"],"sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n safelyExecute,\n toChecksumHexAddress,\n FALL_BACK_VS_CURRENCY,\n toHex,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport { reduceInBatchesSerially, TOKEN_PRICES_BATCH_SIZE } from './assetsUtil';\nimport { fetchExchangeRate as fetchNativeCurrencyExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\nimport { ZERO_ADDRESS } from './token-prices-service/codefi-v2';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n TokensControllerState,\n} from './TokensController';\n\n/**\n * @type Token\n *\n * Token representation\n * @property address - Hex address of the token contract\n * @property decimals - Number of decimals the token uses\n * @property symbol - Symbol of the token\n * @property aggregators - An array containing the token's aggregators\n * @property image - Image of the token, url or bit32 image\n * @property hasBalanceError - 'true' if there is an error while updating the token balance\n * @property isERC721 - 'true' if the token is a ERC721 token\n * @property name - Name of the token\n */\nexport type Token = {\n address: string;\n decimals: number;\n symbol: string;\n aggregators?: string[];\n image?: string;\n hasBalanceError?: boolean;\n isERC721?: boolean;\n name?: string;\n};\n\nconst DEFAULT_INTERVAL = 180000;\n\nexport type ContractExchangeRates = {\n [address: string]: number | undefined;\n};\n\ntype MarketDataDetails = {\n tokenAddress: `0x${string}`;\n currency: string;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\n\n/**\n * Represents a mapping of token contract addresses to their market data.\n */\nexport type ContractMarketData = Record<Hex, MarketDataDetails>;\n\nenum PollState {\n Active = 'Active',\n Inactive = 'Inactive',\n}\n\n/**\n * The external actions available to the {@link TokenRatesController}.\n */\nexport type AllowedActions =\n | TokensControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | PreferencesControllerGetStateAction;\n\n/**\n * The external events available to the {@link TokenRatesController}.\n */\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\n/**\n * The name of the {@link TokenRatesController}.\n */\nexport const controllerName = 'TokenRatesController';\n\n/**\n * @type TokenRatesState\n *\n * Token rates controller state\n * @property marketData - Market data for tokens, keyed by chain ID and then token contract address.\n */\nexport type TokenRatesControllerState = {\n marketData: Record<Hex, Record<Hex, MarketDataDetails>>;\n};\n\n/**\n * The action that can be performed to get the state of the {@link TokenRatesController}.\n */\nexport type TokenRatesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenRatesControllerState\n>;\n\n/**\n * The actions that can be performed using the {@link TokenRatesController}.\n */\nexport type TokenRatesControllerActions = TokenRatesControllerGetStateAction;\n\n/**\n * The event that {@link TokenRatesController} can emit.\n */\nexport type TokenRatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n TokenRatesControllerState\n>;\n\n/**\n * The events that {@link TokenRatesController} can emit.\n */\nexport type TokenRatesControllerEvents = TokenRatesControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link TokenRatesController} for communication.\n */\nexport type TokenRatesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenRatesControllerActions | AllowedActions,\n TokenRatesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Uses the CryptoCompare API to fetch the exchange rate between one currency\n * and another, i.e., the multiplier to apply the amount of one currency in\n * order to convert it to another.\n *\n * @param args - The arguments to this function.\n * @param args.from - The currency to convert from.\n * @param args.to - The currency to convert to.\n * @returns The exchange rate between `fromCurrency` to `toCurrency` if one\n * exists, or null if one does not.\n */\nasync function getCurrencyConversionRate({\n from,\n to,\n}: {\n from: string;\n to: string;\n}) {\n const includeUSDRate = false;\n try {\n const result = await fetchNativeCurrencyExchangeRate(\n to,\n from,\n includeUSDRate,\n );\n return result.conversionRate;\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n ) {\n return null;\n }\n throw error;\n }\n}\n\nconst tokenRatesControllerMetadata = {\n marketData: { persist: true, anonymous: false },\n};\n\n/**\n * Get the default {@link TokenRatesController} state.\n *\n * @returns The default {@link TokenRatesController} state.\n */\nexport const getDefaultTokenRatesControllerState =\n (): TokenRatesControllerState => {\n return {\n marketData: {},\n };\n };\n\n/**\n * Controller that passively polls on a set interval for token-to-fiat exchange rates\n * for tokens stored in the TokensController\n */\nexport class TokenRatesController extends StaticIntervalPollingController<\n typeof controllerName,\n TokenRatesControllerState,\n TokenRatesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #pollState = PollState.Inactive;\n\n #tokenPricesService: AbstractTokenPricesService;\n\n #inProcessExchangeRateUpdates: Record<`${Hex}:${string}`, Promise<void>> = {};\n\n #selectedAddress: string;\n\n #disabled: boolean;\n\n #chainId: Hex;\n\n #ticker: string;\n\n #interval: number;\n\n #allTokens: TokensControllerState['allTokens'];\n\n #allDetectedTokens: TokensControllerState['allDetectedTokens'];\n\n /**\n * Creates a TokenRatesController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The polling interval in ms\n * @param options.disabled - Boolean to track if network requests are blocked\n * @param options.tokenPricesService - An object in charge of retrieving token price\n * @param options.messenger - The controller messenger instance for communication\n * @param options.state - Initial state to set on this controller\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n disabled = false,\n tokenPricesService,\n messenger,\n state,\n }: {\n interval?: number;\n disabled?: boolean;\n tokenPricesService: AbstractTokenPricesService;\n messenger: TokenRatesControllerMessenger;\n state?: Partial<TokenRatesControllerState>;\n }) {\n super({\n name: controllerName,\n messenger,\n state: { ...getDefaultTokenRatesControllerState(), ...state },\n metadata: tokenRatesControllerMetadata,\n });\n\n this.setIntervalLength(interval);\n this.#tokenPricesService = tokenPricesService;\n this.#disabled = disabled;\n this.#interval = interval;\n\n const { chainId: currentChainId, ticker: currentTicker } =\n this.#getChainIdAndTicker();\n this.#chainId = currentChainId;\n this.#ticker = currentTicker;\n\n this.#selectedAddress = this.#getSelectedAddress();\n\n const { allTokens, allDetectedTokens } = this.#getTokensControllerState();\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n\n this.#subscribeToPreferencesStateChange();\n\n this.#subscribeToTokensStateChange();\n\n this.#subscribeToNetworkStateChange();\n }\n\n #subscribeToPreferencesStateChange() {\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (selectedAddress: string) => {\n if (this.#selectedAddress !== selectedAddress) {\n this.#selectedAddress = selectedAddress;\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n },\n ({ selectedAddress }) => {\n return selectedAddress;\n },\n );\n }\n\n #subscribeToTokensStateChange() {\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ allTokens, allDetectedTokens }) => {\n const previousTokenAddresses = this.#getTokenAddresses(this.#chainId);\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n\n const newTokenAddresses = this.#getTokenAddresses(this.#chainId);\n if (\n !isEqual(previousTokenAddresses, newTokenAddresses) &&\n this.#pollState === PollState.Active\n ) {\n await this.updateExchangeRates();\n }\n },\n ({ allTokens, allDetectedTokens }) => {\n return { allTokens, allDetectedTokens };\n },\n );\n }\n\n #subscribeToNetworkStateChange() {\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ selectedNetworkClientId }) => {\n const {\n configuration: { chainId, ticker },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n\n if (this.#chainId !== chainId || this.#ticker !== ticker) {\n this.update((state) => {\n state.marketData = {};\n });\n this.#chainId = chainId;\n this.#ticker = ticker;\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n },\n );\n }\n\n /**\n * Get the user's tokens for the given chain.\n *\n * @param chainId - The chain ID.\n * @returns The list of tokens addresses for the current chain\n */\n #getTokenAddresses(chainId: Hex): Hex[] {\n const tokens = this.#allTokens[chainId]?.[this.#selectedAddress] || [];\n const detectedTokens =\n this.#allDetectedTokens[chainId]?.[this.#selectedAddress] || [];\n\n return [\n ...new Set(\n [...tokens, ...detectedTokens].map((token) =>\n toHex(toChecksumHexAddress(token.address)),\n ),\n ),\n ].sort();\n }\n\n /**\n * Allows controller to make active and passive polling requests\n */\n enable(): void {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from making network calls\n */\n disable(): void {\n this.#disabled = true;\n }\n\n /**\n * Start (or restart) polling.\n */\n async start() {\n this.#stopPoll();\n this.#pollState = PollState.Active;\n await this.#poll();\n }\n\n /**\n * Stop polling.\n */\n stop() {\n this.#stopPoll();\n this.#pollState = PollState.Inactive;\n }\n\n #getSelectedAddress(): string {\n const { selectedAddress } = this.messagingSystem.call(\n 'PreferencesController:getState',\n );\n\n return selectedAddress;\n }\n\n #getChainIdAndTicker(): {\n chainId: Hex;\n ticker: string;\n } {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return {\n chainId: networkClient.configuration.chainId,\n ticker: networkClient.configuration.ticker,\n };\n }\n\n #getTokensControllerState(): {\n allTokens: TokensControllerState['allTokens'];\n allDetectedTokens: TokensControllerState['allDetectedTokens'];\n } {\n const { allTokens, allDetectedTokens } = this.messagingSystem.call(\n 'TokensController:getState',\n );\n\n return {\n allTokens,\n allDetectedTokens,\n };\n }\n\n /**\n * Clear the active polling timer, if present.\n */\n #stopPoll() {\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n }\n\n /**\n * Poll for exchange rate updates.\n */\n async #poll() {\n await safelyExecute(() => this.updateExchangeRates());\n\n // Poll using recursive `setTimeout` instead of `setInterval` so that\n // requests don't stack if they take longer than the polling interval\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();\n }, this.#interval);\n }\n\n /**\n * Updates exchange rates for all tokens.\n */\n async updateExchangeRates() {\n await this.updateExchangeRatesByChainId({\n chainId: this.#chainId,\n nativeCurrency: this.#ticker,\n });\n }\n\n /**\n * Updates exchange rates for all tokens.\n *\n * @param options - The options to fetch exchange rates.\n * @param options.chainId - The chain ID.\n * @param options.nativeCurrency - The ticker for the chain.\n */\n async updateExchangeRatesByChainId({\n chainId,\n nativeCurrency,\n }: {\n chainId: Hex;\n nativeCurrency: string;\n }) {\n if (this.#disabled) {\n return;\n }\n\n const tokenAddresses = this.#getTokenAddresses(chainId);\n\n const updateKey: `${Hex}:${string}` = `${chainId}:${nativeCurrency}`;\n if (updateKey in this.#inProcessExchangeRateUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessExchangeRateUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessExchangeRateUpdates[updateKey] = inProgressUpdate;\n\n try {\n const contractInformations = await this.#fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n\n const marketData = {\n [chainId]: {\n ...(contractInformations ?? {}),\n },\n };\n\n this.update((state) => {\n state.marketData = marketData;\n });\n updateSucceeded();\n } catch (error: unknown) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessExchangeRateUpdates[updateKey];\n }\n }\n\n /**\n * Uses the token prices service to retrieve exchange rates for tokens in a\n * particular currency.\n *\n * If the price API does not support the given chain ID, returns an empty\n * object.\n *\n * If the price API does not support the given currency, retrieves exchange\n * rates in a known currency instead, then converts those rates using the\n * exchange rate between the known currency and desired currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * exchange rates.\n * @returns A map from token address to its exchange rate in the native\n * currency, or an empty map if no exchange rates can be obtained for the\n * chain ID.\n */\n async #fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n if (!this.#tokenPricesService.validateChainIdSupported(chainId)) {\n return tokenAddresses.reduce((obj, tokenAddress) => {\n obj = {\n ...obj,\n [tokenAddress]: undefined,\n };\n\n return obj;\n }, {});\n }\n\n if (this.#tokenPricesService.validateCurrencySupported(nativeCurrency)) {\n return await this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n }\n\n return await this.#fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n });\n }\n\n /**\n * Updates token rates for the given networkClientId\n *\n * @param networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n await this.updateExchangeRatesByChainId({\n chainId: networkClient.configuration.chainId,\n nativeCurrency: networkClient.configuration.ticker,\n });\n }\n\n /**\n * Retrieves prices in the given currency for the given tokens on the given\n * chain. Ensures that token addresses are checksum addresses.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n let contractNativeInformations;\n const tokenPricesByTokenAddress = await reduceInBatchesSerially<\n Hex,\n Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>\n >({\n values: [...tokenAddresses].sort(),\n batchSize: TOKEN_PRICES_BATCH_SIZE,\n eachBatch: async (allTokenPricesByTokenAddress, batch) => {\n const tokenPricesByTokenAddressForBatch =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n contractNativeInformations = tokenPricesByTokenAddress;\n\n // fetch for native token\n if (tokenAddresses.length === 0) {\n const contractNativeInformationsNative =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: [],\n chainId,\n currency: nativeCurrency,\n });\n\n contractNativeInformations = {\n [ZERO_ADDRESS]: {\n currency: nativeCurrency,\n ...contractNativeInformationsNative[ZERO_ADDRESS],\n },\n };\n }\n return Object.entries(contractNativeInformations).reduce(\n (obj, [tokenAddress, token]) => {\n obj = {\n ...obj,\n [tokenAddress]: { ...token },\n };\n\n return obj;\n },\n {},\n );\n }\n\n /**\n * If the price API does not support a given native currency, then we need to\n * convert it to a fallback currency and feed that currency into the price\n * API, then convert the prices to our desired native currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n const [\n contractExchangeInformations,\n fallbackCurrencyToNativeCurrencyConversionRate,\n ] = await Promise.all([\n this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId: this.#chainId,\n nativeCurrency: FALL_BACK_VS_CURRENCY,\n }),\n getCurrencyConversionRate({\n from: FALL_BACK_VS_CURRENCY,\n to: nativeCurrency,\n }),\n ]);\n\n if (fallbackCurrencyToNativeCurrencyConversionRate === null) {\n return {};\n }\n\n const updatedContractExchangeRates = Object.entries(\n contractExchangeInformations,\n ).reduce((acc, [tokenAddress, token]) => {\n acc = {\n ...acc,\n [tokenAddress]: {\n ...token,\n price: token.price\n ? token.price * fallbackCurrencyToNativeCurrencyConversionRate\n : undefined,\n },\n };\n return acc;\n }, {});\n\n return updatedContractExchangeRates;\n }\n}\n\nexport default TokenRatesController;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,uCAAuC;AAKhD,SAAS,6BAAuC;AAChD,SAAS,eAAe;AAoCxB,IAAM,mBAAmB;AA2DlB,IAAM,iBAAiB;AA4D9B,eAAe,0BAA0B;AAAA,EACvC;AAAA,EACA;AACF,GAGG;AACD,QAAM,iBAAiB;AACvB,MAAI;AACF,UAAM,SAAS,MAAM;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO,OAAO;AAAA,EAChB,SAAS,OAAO;AACd,QACE,iBAAiB,SACjB,MAAM,QAAQ,SAAS,0CAA0C,GACjE;AACA,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACF;AAEA,IAAM,+BAA+B;AAAA,EACnC,YAAY,EAAE,SAAS,MAAM,WAAW,MAAM;AAChD;AAOO,IAAM,sCACX,MAAiC;AAC/B,SAAO;AAAA,IACL,YAAY,CAAC;AAAA,EACf;AACF;AA1NF;AAgOO,IAAM,uBAAN,cAAmC,gCAIxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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,QACH,OAAO,MAAM,QACT,MAAM,QAAQ,iDACd;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;AAGF,IAAO,+BAAQ;","names":[]}
@@ -1,17 +1,17 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkB5YY22QQjs = require('./chunk-B5YY22QQ.js');
3
+ var _chunk6PPM4ETZjs = require('./chunk-6PPM4ETZ.js');
4
4
 
5
5
 
6
- var _chunkBOTVAG4Ajs = require('./chunk-BOTVAG4A.js');
6
+ var _chunkJBF4XEGRjs = require('./chunk-JBF4XEGR.js');
7
7
 
8
8
 
9
9
 
10
- var _chunkPYMUBJQXjs = require('./chunk-PYMUBJQX.js');
10
+ var _chunkX4RMS365js = require('./chunk-X4RMS365.js');
11
11
 
12
12
 
13
13
 
14
- var _chunkNEXY7SE2js = require('./chunk-NEXY7SE2.js');
14
+ var _chunkNYVA7ZTQjs = require('./chunk-NYVA7ZTQ.js');
15
15
 
16
16
 
17
17
 
@@ -107,7 +107,8 @@ var TokensController = class extends _basecontroller.BaseController {
107
107
  * Handles the event when the network changes.
108
108
  *
109
109
  * @param networkState - The changed network state.
110
- * @param networkState.providerConfig - RPC URL and network name provider settings of the currently connected network
110
+ * @param networkState.selectedNetworkClientId - The ID of the currently
111
+ * selected network client.
111
112
  */
112
113
  _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _onNetworkDidChange);
113
114
  /**
@@ -242,12 +243,12 @@ var TokensController = class extends _basecontroller.BaseController {
242
243
  address,
243
244
  symbol,
244
245
  decimals,
245
- image: image || _chunkNEXY7SE2js.formatIconUrlWithProxy.call(void 0, {
246
+ image: image || _chunkNYVA7ZTQjs.formatIconUrlWithProxy.call(void 0, {
246
247
  chainId: currentChainId,
247
248
  tokenAddress: address
248
249
  }),
249
250
  isERC721,
250
- aggregators: _chunkNEXY7SE2js.formatAggregatorNames.call(void 0, tokenMetadata?.aggregators || []),
251
+ aggregators: _chunkNYVA7ZTQjs.formatAggregatorNames.call(void 0, tokenMetadata?.aggregators || []),
251
252
  name
252
253
  };
253
254
  const previousIndex = newTokens.findIndex(
@@ -512,21 +513,25 @@ var TokensController = class extends _basecontroller.BaseController {
512
513
  }
513
514
  if (await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _detectIsERC721, detectIsERC721_fn).call(this, asset.address, networkClientId)) {
514
515
  throw _rpcerrors.rpcErrors.invalidParams(
516
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
517
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
515
518
  `Contract ${asset.address} must match type ${type}, but was detected as ${_controllerutils.ERC721}`
516
519
  );
517
520
  }
518
521
  const provider = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getProvider, getProvider_fn).call(this, networkClientId);
519
522
  const isErc1155 = await _controllerutils.safelyExecute.call(void 0,
520
- () => new (0, _chunkBOTVAG4Ajs.ERC1155Standard)(provider).contractSupportsBase1155Interface(
523
+ () => new (0, _chunkJBF4XEGRjs.ERC1155Standard)(provider).contractSupportsBase1155Interface(
521
524
  asset.address
522
525
  )
523
526
  );
524
527
  if (isErc1155) {
525
528
  throw _rpcerrors.rpcErrors.invalidParams(
529
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
530
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
526
531
  `Contract ${asset.address} must match type ${type}, but was detected as ${_controllerutils.ERC1155}`
527
532
  );
528
533
  }
529
- const erc20 = new (0, _chunkB5YY22QQjs.ERC20Standard)(provider);
534
+ const erc20 = new (0, _chunk6PPM4ETZjs.ERC20Standard)(provider);
530
535
  const [contractName, contractSymbol, contractDecimals] = await Promise.all([
531
536
  _controllerutils.safelyExecute.call(void 0, () => erc20.getTokenName(asset.address)),
532
537
  _controllerutils.safelyExecute.call(void 0, () => erc20.getTokenSymbol(asset.address)),
@@ -540,6 +545,8 @@ var TokensController = class extends _basecontroller.BaseController {
540
545
  }
541
546
  if (contractSymbol !== void 0 && asset.symbol !== void 0 && asset.symbol.toUpperCase() !== contractSymbol.toUpperCase()) {
542
547
  throw _rpcerrors.rpcErrors.invalidParams(
548
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
549
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
543
550
  `The symbol in the request (${asset.symbol}) does not match the symbol in the contract (${contractSymbol})`
544
551
  );
545
552
  }
@@ -559,6 +566,8 @@ var TokensController = class extends _basecontroller.BaseController {
559
566
  }
560
567
  if (contractDecimals !== void 0 && asset.decimals !== void 0 && String(asset.decimals) !== contractDecimals) {
561
568
  throw _rpcerrors.rpcErrors.invalidParams(
569
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
570
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
562
571
  `The decimals in the request (${asset.decimals}) do not match the decimals in the contract (${contractDecimals})`
563
572
  );
564
573
  }
@@ -566,6 +575,8 @@ var TokensController = class extends _basecontroller.BaseController {
566
575
  const decimalsNum = parseInt(decimalsStr, 10);
567
576
  if (!Number.isInteger(decimalsNum) || decimalsNum > 36 || decimalsNum < 0) {
568
577
  throw _rpcerrors.rpcErrors.invalidParams(
578
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
579
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
569
580
  `Invalid decimals "${decimalsStr}": must be an integer 0 <= 36`
570
581
  );
571
582
  }
@@ -605,9 +616,13 @@ _selectedAddress = new WeakMap();
605
616
  _provider = new WeakMap();
606
617
  _abortController = new WeakMap();
607
618
  _onNetworkDidChange = new WeakSet();
608
- onNetworkDidChange_fn = function({ providerConfig }) {
619
+ onNetworkDidChange_fn = function({ selectedNetworkClientId }) {
620
+ const selectedNetworkClient = this.messagingSystem.call(
621
+ "NetworkController:getNetworkClientById",
622
+ selectedNetworkClientId
623
+ );
609
624
  const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;
610
- const { chainId } = providerConfig;
625
+ const { chainId } = selectedNetworkClient.configuration;
611
626
  _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _abortController).abort();
612
627
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _abortController, new AbortController());
613
628
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _chainId, chainId);
@@ -630,14 +645,14 @@ onPreferenceControllerStateChange_fn = function({ selectedAddress }) {
630
645
  _fetchTokenMetadata = new WeakSet();
631
646
  fetchTokenMetadata_fn = async function(tokenAddress) {
632
647
  try {
633
- const token = await _chunkPYMUBJQXjs.fetchTokenMetadata.call(void 0,
648
+ const token = await _chunkX4RMS365js.fetchTokenMetadata.call(void 0,
634
649
  _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _chainId),
635
650
  tokenAddress,
636
651
  _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _abortController).signal
637
652
  );
638
653
  return token;
639
654
  } catch (error) {
640
- if (error instanceof Error && error.message.includes(_chunkPYMUBJQXjs.TOKEN_METADATA_NO_SUPPORT_ERROR)) {
655
+ if (error instanceof Error && error.message.includes(_chunkX4RMS365js.TOKEN_METADATA_NO_SUPPORT_ERROR)) {
641
656
  return void 0;
642
657
  }
643
658
  throw error;
@@ -768,4 +783,4 @@ var TokensController_default = TokensController;
768
783
 
769
784
 
770
785
  exports.getDefaultTokensState = getDefaultTokensState; exports.TokensController = TokensController; exports.TokensController_default = TokensController_default;
771
- //# sourceMappingURL=chunk-4AC3X2U5.js.map
786
+ //# sourceMappingURL=chunk-RJBYLTY5.js.map