@metamask/assets-controllers 33.0.0 → 34.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 (59) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/dist/AccountTrackerController.js +2 -2
  3. package/dist/AccountTrackerController.mjs +1 -1
  4. package/dist/TokenBalancesController.js +2 -2
  5. package/dist/TokenBalancesController.mjs +1 -1
  6. package/dist/TokenDetectionController.js +2 -2
  7. package/dist/TokenDetectionController.mjs +1 -1
  8. package/dist/TokenRatesController.js +2 -2
  9. package/dist/TokenRatesController.mjs +1 -1
  10. package/dist/TokensController.js +2 -2
  11. package/dist/TokensController.mjs +1 -1
  12. package/dist/{chunk-RJBYLTY5.js → chunk-2NQRWANM.js} +57 -30
  13. package/dist/chunk-2NQRWANM.js.map +1 -0
  14. package/dist/{chunk-3K3LE2CZ.mjs → chunk-2TSAUGE7.mjs} +30 -19
  15. package/dist/chunk-2TSAUGE7.mjs.map +1 -0
  16. package/dist/{chunk-UVE4XY5Y.mjs → chunk-4JLB5OIJ.mjs} +57 -30
  17. package/dist/chunk-4JLB5OIJ.mjs.map +1 -0
  18. package/dist/{chunk-OEEFNXR7.mjs → chunk-6VQJFTNC.mjs} +4 -4
  19. package/dist/chunk-6VQJFTNC.mjs.map +1 -0
  20. package/dist/{chunk-VZF43NDM.js → chunk-GHKGU6GK.js} +30 -19
  21. package/dist/chunk-GHKGU6GK.js.map +1 -0
  22. package/dist/{chunk-P3O5CVAH.mjs → chunk-GJCTAKK5.mjs} +36 -34
  23. package/dist/chunk-GJCTAKK5.mjs.map +1 -0
  24. package/dist/chunk-HVOIBGYN.js +282 -0
  25. package/dist/chunk-HVOIBGYN.js.map +1 -0
  26. package/dist/{chunk-NWVMFCSC.js → chunk-NHFZIY2K.js} +4 -4
  27. package/dist/chunk-NHFZIY2K.js.map +1 -0
  28. package/dist/{chunk-FGAZXVKS.js → chunk-RPQ737HL.js} +36 -34
  29. package/dist/chunk-RPQ737HL.js.map +1 -0
  30. package/dist/chunk-Z7RMCHD4.mjs +282 -0
  31. package/dist/chunk-Z7RMCHD4.mjs.map +1 -0
  32. package/dist/index.js +6 -6
  33. package/dist/index.mjs +5 -5
  34. package/dist/tsconfig.build.tsbuildinfo +1 -1
  35. package/dist/types/AccountTrackerController.d.ts +50 -66
  36. package/dist/types/AccountTrackerController.d.ts.map +1 -1
  37. package/dist/types/TokenBalancesController.d.ts +2 -2
  38. package/dist/types/TokenBalancesController.d.ts.map +1 -1
  39. package/dist/types/TokenDetectionController.d.ts +4 -6
  40. package/dist/types/TokenDetectionController.d.ts.map +1 -1
  41. package/dist/types/TokenRatesController.d.ts +3 -3
  42. package/dist/types/TokenRatesController.d.ts.map +1 -1
  43. package/dist/types/TokensController.d.ts +4 -6
  44. package/dist/types/TokensController.d.ts.map +1 -1
  45. package/dist/types/index.d.ts +2 -1
  46. package/dist/types/index.d.ts.map +1 -1
  47. package/package.json +2 -2
  48. package/dist/chunk-3K3LE2CZ.mjs.map +0 -1
  49. package/dist/chunk-526TATMH.mjs +0 -254
  50. package/dist/chunk-526TATMH.mjs.map +0 -1
  51. package/dist/chunk-AZ6SRJVI.js +0 -254
  52. package/dist/chunk-AZ6SRJVI.js.map +0 -1
  53. package/dist/chunk-FGAZXVKS.js.map +0 -1
  54. package/dist/chunk-NWVMFCSC.js.map +0 -1
  55. package/dist/chunk-OEEFNXR7.mjs.map +0 -1
  56. package/dist/chunk-P3O5CVAH.mjs.map +0 -1
  57. package/dist/chunk-RJBYLTY5.js.map +0 -1
  58. package/dist/chunk-UVE4XY5Y.mjs.map +0 -1
  59. package/dist/chunk-VZF43NDM.js.map +0 -1
@@ -1,254 +0,0 @@
1
- import {
2
- __privateAdd,
3
- __privateMethod
4
- } from "./chunk-XUI43LEZ.mjs";
5
-
6
- // src/AccountTrackerController.ts
7
- import {
8
- query,
9
- safelyExecuteWithTimeout,
10
- toChecksumHexAddress
11
- } from "@metamask/controller-utils";
12
- import EthQuery from "@metamask/eth-query";
13
- import { StaticIntervalPollingControllerV1 } from "@metamask/polling-controller";
14
- import { assert } from "@metamask/utils";
15
- import { Mutex } from "async-mutex";
16
- import { cloneDeep } from "lodash";
17
- var _getCorrectNetworkClient, getCorrectNetworkClient_fn;
18
- var AccountTrackerController = class extends StaticIntervalPollingControllerV1 {
19
- /**
20
- * Creates an AccountTracker instance.
21
- *
22
- * @param options - The controller options.
23
- * @param options.messenger - The messaging system used to communicate with other controllers.
24
- * @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.
25
- * @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.
26
- * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
27
- * @param config - Initial options used to configure this controller.
28
- * @param state - Initial state to set on this controller.
29
- */
30
- constructor({
31
- messenger,
32
- getMultiAccountBalancesEnabled,
33
- getCurrentChainId,
34
- getNetworkClientById
35
- }, config, state) {
36
- super(config, state);
37
- /**
38
- * Resolves a networkClientId to a network client config
39
- * or globally selected network config if not provided
40
- *
41
- * @param networkClientId - Optional networkClientId to fetch a network client with
42
- * @returns network client config
43
- */
44
- __privateAdd(this, _getCorrectNetworkClient);
45
- this.refreshMutex = new Mutex();
46
- /**
47
- * Name of this controller used during composition
48
- */
49
- this.name = "AccountTrackerController";
50
- /**
51
- * Refreshes the balances of the accounts depending on the multi-account setting.
52
- * If multi-account is disabled, only updates the selected account balance.
53
- * If multi-account is enabled, updates balances for all accounts.
54
- *
55
- * @param networkClientId - Optional networkClientId to fetch a network client with
56
- */
57
- this.refresh = async (networkClientId) => {
58
- const selectedAccount = this.messagingSystem.call(
59
- "AccountsController:getSelectedAccount"
60
- );
61
- const releaseLock = await this.refreshMutex.acquire();
62
- try {
63
- const { chainId, ethQuery } = __privateMethod(this, _getCorrectNetworkClient, getCorrectNetworkClient_fn).call(this, networkClientId);
64
- this.syncAccounts(chainId);
65
- const { accounts, accountsByChainId } = this.state;
66
- const isMultiAccountBalancesEnabled = this.getMultiAccountBalancesEnabled();
67
- const accountsToUpdate = isMultiAccountBalancesEnabled ? Object.keys(accounts) : [toChecksumHexAddress(selectedAccount.address)];
68
- const accountsForChain = { ...accountsByChainId[chainId] };
69
- for (const address of accountsToUpdate) {
70
- const balance = await this.getBalanceFromChain(address, ethQuery);
71
- if (balance) {
72
- accountsForChain[address] = {
73
- balance
74
- };
75
- }
76
- }
77
- this.update({
78
- ...chainId === this.getCurrentChainId() && {
79
- accounts: accountsForChain
80
- },
81
- accountsByChainId: {
82
- ...this.state.accountsByChainId,
83
- [chainId]: accountsForChain
84
- }
85
- });
86
- } finally {
87
- releaseLock();
88
- }
89
- };
90
- this.defaultConfig = {
91
- interval: 1e4
92
- };
93
- this.defaultState = {
94
- accounts: {},
95
- accountsByChainId: {
96
- [getCurrentChainId()]: {}
97
- }
98
- };
99
- this.initialize();
100
- this.messagingSystem = messenger;
101
- this.setIntervalLength(this.config.interval);
102
- this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;
103
- this.getCurrentChainId = getCurrentChainId;
104
- this.getNetworkClientById = getNetworkClientById;
105
- this.poll();
106
- this.messagingSystem.subscribe(
107
- "AccountsController:selectedEvmAccountChange",
108
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
109
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
110
- () => this.refresh()
111
- );
112
- }
113
- syncAccounts(newChainId) {
114
- const accounts = { ...this.state.accounts };
115
- const accountsByChainId = cloneDeep(this.state.accountsByChainId);
116
- const existing = Object.keys(accounts);
117
- if (!accountsByChainId[newChainId]) {
118
- accountsByChainId[newChainId] = {};
119
- existing.forEach((address) => {
120
- accountsByChainId[newChainId][address] = { balance: "0x0" };
121
- });
122
- }
123
- const addresses = Object.values(
124
- this.messagingSystem.call("AccountsController:listAccounts").map(
125
- (internalAccount) => toChecksumHexAddress(internalAccount.address)
126
- )
127
- );
128
- const newAddresses = addresses.filter(
129
- (address) => !existing.includes(address)
130
- );
131
- const oldAddresses = existing.filter(
132
- (address) => !addresses.includes(address)
133
- );
134
- newAddresses.forEach((address) => {
135
- accounts[address] = { balance: "0x0" };
136
- });
137
- Object.keys(accountsByChainId).forEach((chainId) => {
138
- newAddresses.forEach((address) => {
139
- accountsByChainId[chainId][address] = {
140
- balance: "0x0"
141
- };
142
- });
143
- });
144
- oldAddresses.forEach((address) => {
145
- delete accounts[address];
146
- });
147
- Object.keys(accountsByChainId).forEach((chainId) => {
148
- oldAddresses.forEach((address) => {
149
- delete accountsByChainId[chainId][address];
150
- });
151
- });
152
- this.update({ accounts, accountsByChainId });
153
- }
154
- /**
155
- * Sets a new provider.
156
- *
157
- * TODO: Replace this wth a method.
158
- *
159
- * @param provider - Provider used to create a new underlying EthQuery instance.
160
- */
161
- set provider(provider) {
162
- this._provider = provider;
163
- }
164
- get provider() {
165
- throw new Error("Property only used for setting");
166
- }
167
- /**
168
- * Starts a new polling interval.
169
- *
170
- * @param interval - Polling interval trigger a 'refresh'.
171
- */
172
- async poll(interval) {
173
- interval && this.configure({ interval }, false, false);
174
- this.handle && clearTimeout(this.handle);
175
- await this.refresh();
176
- this.handle = setTimeout(() => {
177
- this.poll(this.config.interval);
178
- }, this.config.interval);
179
- }
180
- /**
181
- * Refreshes the balances of the accounts using the networkClientId
182
- *
183
- * @param networkClientId - The network client ID used to get balances.
184
- */
185
- async _executePoll(networkClientId) {
186
- this.refresh(networkClientId);
187
- }
188
- /**
189
- * Fetches the balance of a given address from the blockchain.
190
- *
191
- * @param address - The account address to fetch the balance for.
192
- * @param ethQuery - The EthQuery instance to query getBalnce with.
193
- * @returns A promise that resolves to the balance in a hex string format.
194
- */
195
- async getBalanceFromChain(address, ethQuery) {
196
- return await safelyExecuteWithTimeout(async () => {
197
- assert(ethQuery, "Provider not set.");
198
- return await query(ethQuery, "getBalance", [address]);
199
- });
200
- }
201
- /**
202
- * Sync accounts balances with some additional addresses.
203
- *
204
- * @param addresses - the additional addresses, may be hardware wallet addresses.
205
- * @param networkClientId - Optional networkClientId to fetch a network client with.
206
- * @returns accounts - addresses with synced balance
207
- */
208
- async syncBalanceWithAddresses(addresses, networkClientId) {
209
- const { ethQuery } = __privateMethod(this, _getCorrectNetworkClient, getCorrectNetworkClient_fn).call(this, networkClientId);
210
- return await Promise.all(
211
- addresses.map((address) => {
212
- return safelyExecuteWithTimeout(async () => {
213
- assert(ethQuery, "Provider not set.");
214
- const balance = await query(ethQuery, "getBalance", [address]);
215
- return [address, balance];
216
- });
217
- })
218
- ).then((value) => {
219
- return value.reduce((obj, item) => {
220
- if (!item) {
221
- return obj;
222
- }
223
- const [address, balance] = item;
224
- return {
225
- ...obj,
226
- [address]: {
227
- balance
228
- }
229
- };
230
- }, {});
231
- });
232
- }
233
- };
234
- _getCorrectNetworkClient = new WeakSet();
235
- getCorrectNetworkClient_fn = function(networkClientId) {
236
- if (networkClientId) {
237
- const networkClient = this.getNetworkClientById(networkClientId);
238
- return {
239
- chainId: networkClient.configuration.chainId,
240
- ethQuery: new EthQuery(networkClient.provider)
241
- };
242
- }
243
- return {
244
- chainId: this.getCurrentChainId(),
245
- ethQuery: this._provider ? new EthQuery(this._provider) : void 0
246
- };
247
- };
248
- var AccountTrackerController_default = AccountTrackerController;
249
-
250
- export {
251
- AccountTrackerController,
252
- AccountTrackerController_default
253
- };
254
- //# sourceMappingURL=chunk-526TATMH.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/AccountTrackerController.ts"],"sourcesContent":["import type {\n AccountsControllerSelectedEvmAccountChangeEvent,\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerListAccountsAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type {\n BaseConfig,\n BaseState,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n query,\n safelyExecuteWithTimeout,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type { Provider } from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport { cloneDeep } from 'lodash';\n\nconst controllerName = 'AccountTrackerController';\n\nexport type AllowedActions =\n | AccountsControllerListAccountsAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedEvmAccountChangeEvent\n | AccountsControllerSelectedAccountChangeEvent;\n\nexport type AccountTrackerControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * @type AccountInformation\n *\n * Account information object\n * @property balance - Hex string of an account balancec in wei\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountInformation {\n balance: string;\n}\n\n/**\n * @type AccountTrackerConfig\n *\n * Account tracker controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerConfig extends BaseConfig {\n interval: number;\n provider?: Provider;\n}\n\n/**\n * @type AccountTrackerState\n *\n * Account tracker controller state\n * @property accounts - Map of addresses to account information\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerState extends BaseState {\n accounts: { [address: string]: AccountInformation };\n accountsByChainId: Record<string, { [address: string]: AccountInformation }>;\n}\n\n/**\n * Controller that tracks the network balances for all user accounts.\n */\nexport class AccountTrackerController extends StaticIntervalPollingControllerV1<\n AccountTrackerConfig,\n AccountTrackerState\n> {\n private _provider?: Provider;\n\n private readonly refreshMutex = new Mutex();\n\n private handle?: ReturnType<typeof setTimeout>;\n\n private syncAccounts(newChainId: string) {\n const accounts = { ...this.state.accounts };\n const accountsByChainId = cloneDeep(this.state.accountsByChainId);\n\n const existing = Object.keys(accounts);\n if (!accountsByChainId[newChainId]) {\n accountsByChainId[newChainId] = {};\n existing.forEach((address) => {\n accountsByChainId[newChainId][address] = { balance: '0x0' };\n });\n }\n\n // Note: The address from the preferences controller are checksummed\n // The addresses from the accounts controller are lowercased\n const addresses = Object.values(\n this.messagingSystem\n .call('AccountsController:listAccounts')\n .map((internalAccount) =>\n toChecksumHexAddress(internalAccount.address),\n ),\n );\n const newAddresses = addresses.filter(\n (address) => !existing.includes(address),\n );\n const oldAddresses = existing.filter(\n (address) => !addresses.includes(address),\n );\n newAddresses.forEach((address) => {\n accounts[address] = { balance: '0x0' };\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n newAddresses.forEach((address) => {\n accountsByChainId[chainId][address] = {\n balance: '0x0',\n };\n });\n });\n\n oldAddresses.forEach((address) => {\n delete accounts[address];\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n oldAddresses.forEach((address) => {\n delete accountsByChainId[chainId][address];\n });\n });\n\n this.update({ accounts, accountsByChainId });\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AccountTrackerController' as const;\n\n private readonly getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n\n private readonly getCurrentChainId: () => Hex;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n private readonly messagingSystem: AccountTrackerControllerMessenger;\n\n /**\n * Creates an AccountTracker instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The messaging system used to communicate with other controllers.\n * @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.\n * @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n messenger,\n getMultiAccountBalancesEnabled,\n getCurrentChainId,\n getNetworkClientById,\n }: {\n messenger: AccountTrackerControllerMessenger;\n getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n getCurrentChainId: () => Hex;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AccountTrackerConfig>,\n state?: Partial<AccountTrackerState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: 10000,\n };\n this.defaultState = {\n accounts: {},\n accountsByChainId: {\n [getCurrentChainId()]: {},\n },\n };\n this.initialize();\n this.messagingSystem = messenger;\n this.setIntervalLength(this.config.interval);\n this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;\n this.getCurrentChainId = getCurrentChainId;\n this.getNetworkClientById = getNetworkClientById;\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 this.messagingSystem.subscribe(\n 'AccountsController:selectedEvmAccountChange',\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 () => this.refresh(),\n );\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @param provider - Provider used to create a new underlying EthQuery instance.\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Resolves a networkClientId to a network client config\n * or globally selected network config if not provided\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n * @returns network client config\n */\n #getCorrectNetworkClient(networkClientId?: NetworkClientId): {\n chainId: string;\n ethQuery?: EthQuery;\n } {\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n\n return {\n chainId: networkClient.configuration.chainId,\n ethQuery: new EthQuery(networkClient.provider),\n };\n }\n\n return {\n chainId: this.getCurrentChainId(),\n ethQuery: this._provider ? new EthQuery(this._provider) : undefined,\n };\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval trigger a 'refresh'.\n */\n async poll(interval?: number): Promise<void> {\n interval && this.configure({ interval }, false, false);\n this.handle && clearTimeout(this.handle);\n await this.refresh();\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.config.interval);\n }, this.config.interval);\n }\n\n /**\n * Refreshes the balances of the accounts using the networkClientId\n *\n * @param networkClientId - The network client ID used to get balances.\n */\n async _executePoll(networkClientId: string): Promise<void> {\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.refresh(networkClientId);\n }\n\n /**\n * Refreshes the balances of the accounts depending on the multi-account setting.\n * If multi-account is disabled, only updates the selected account balance.\n * If multi-account is enabled, updates balances for all accounts.\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n */\n refresh = async (networkClientId?: NetworkClientId) => {\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n const releaseLock = await this.refreshMutex.acquire();\n try {\n const { chainId, ethQuery } =\n this.#getCorrectNetworkClient(networkClientId);\n this.syncAccounts(chainId);\n const { accounts, accountsByChainId } = this.state;\n const isMultiAccountBalancesEnabled =\n this.getMultiAccountBalancesEnabled();\n\n const accountsToUpdate = isMultiAccountBalancesEnabled\n ? Object.keys(accounts)\n : [toChecksumHexAddress(selectedAccount.address)];\n\n const accountsForChain = { ...accountsByChainId[chainId] };\n for (const address of accountsToUpdate) {\n const balance = await this.getBalanceFromChain(address, ethQuery);\n if (balance) {\n accountsForChain[address] = {\n balance,\n };\n }\n }\n\n this.update({\n ...(chainId === this.getCurrentChainId() && {\n accounts: accountsForChain,\n }),\n accountsByChainId: {\n ...this.state.accountsByChainId,\n [chainId]: accountsForChain,\n },\n });\n } finally {\n releaseLock();\n }\n };\n\n /**\n * Fetches the balance of a given address from the blockchain.\n *\n * @param address - The account address to fetch the balance for.\n * @param ethQuery - The EthQuery instance to query getBalnce with.\n * @returns A promise that resolves to the balance in a hex string format.\n */\n private async getBalanceFromChain(\n address: string,\n ethQuery?: EthQuery,\n ): Promise<string | undefined> {\n return await safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n return await query(ethQuery, 'getBalance', [address]);\n });\n }\n\n /**\n * Sync accounts balances with some additional addresses.\n *\n * @param addresses - the additional addresses, may be hardware wallet addresses.\n * @param networkClientId - Optional networkClientId to fetch a network client with.\n * @returns accounts - addresses with synced balance\n */\n async syncBalanceWithAddresses(\n addresses: string[],\n networkClientId?: NetworkClientId,\n ): Promise<Record<string, { balance: string }>> {\n const { ethQuery } = this.#getCorrectNetworkClient(networkClientId);\n\n return await Promise.all(\n addresses.map((address): Promise<[string, string] | undefined> => {\n return safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n const balance = await query(ethQuery, 'getBalance', [address]);\n return [address, balance];\n });\n }),\n ).then((value) => {\n return value.reduce((obj, item) => {\n if (!item) {\n return obj;\n }\n\n const [address, balance] = item;\n return {\n ...obj,\n [address]: {\n balance,\n },\n };\n }, {});\n });\n }\n}\n\nexport default AccountTrackerController;\n"],"mappings":";;;;;;AAWA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,cAAc;AAMrB,SAAS,yCAAyC;AAGlD,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,iBAAiB;AA3B1B;AA2FO,IAAM,2BAAN,cAAuC,kCAG5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiFA,YACE;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAMA,QACA,OACA;AACA,UAAM,QAAQ,KAAK;AAmDrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAhJA,SAAiB,eAAe,IAAI,MAAM;AAyD1C;AAAA;AAAA;AAAA,SAAS,OAA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,CAAC,SAAS,OAAO;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAAA,IACH,EAAE,KAAK,CAAC,UAAU;AAChB,aAAO,MAAM,OAAO,CAAC,KAAK,SAAS;AACjC,YAAI,CAAC,MAAM;AACT,iBAAO;AAAA,QACT;AAEA,cAAM,CAAC,SAAS,OAAO,IAAI;AAC3B,eAAO;AAAA,UACL,GAAG;AAAA,UACH,CAAC,OAAO,GAAG;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAAA,MACF,GAAG,CAAC,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AACF;AApJE;AAAA,6BAAwB,SAAC,iBAGvB;AACA,MAAI,iBAAiB;AACnB,UAAM,gBAAgB,KAAK,qBAAqB,eAAe;AAE/D,WAAO;AAAA,MACL,SAAS,cAAc,cAAc;AAAA,MACrC,UAAU,IAAI,SAAS,cAAc,QAAQ;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,KAAK,kBAAkB;AAAA,IAChC,UAAU,KAAK,YAAY,IAAI,SAAS,KAAK,SAAS,IAAI;AAAA,EAC5D;AACF;AAqIF,IAAO,mCAAQ;","names":[]}
@@ -1,254 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
-
3
-
4
- var _chunkZ4BLTVTBjs = require('./chunk-Z4BLTVTB.js');
5
-
6
- // src/AccountTrackerController.ts
7
-
8
-
9
-
10
-
11
- var _controllerutils = require('@metamask/controller-utils');
12
- var _ethquery = require('@metamask/eth-query'); var _ethquery2 = _interopRequireDefault(_ethquery);
13
- var _pollingcontroller = require('@metamask/polling-controller');
14
- var _utils = require('@metamask/utils');
15
- var _asyncmutex = require('async-mutex');
16
- var _lodash = require('lodash');
17
- var _getCorrectNetworkClient, getCorrectNetworkClient_fn;
18
- var AccountTrackerController = class extends _pollingcontroller.StaticIntervalPollingControllerV1 {
19
- /**
20
- * Creates an AccountTracker instance.
21
- *
22
- * @param options - The controller options.
23
- * @param options.messenger - The messaging system used to communicate with other controllers.
24
- * @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.
25
- * @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.
26
- * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
27
- * @param config - Initial options used to configure this controller.
28
- * @param state - Initial state to set on this controller.
29
- */
30
- constructor({
31
- messenger,
32
- getMultiAccountBalancesEnabled,
33
- getCurrentChainId,
34
- getNetworkClientById
35
- }, config, state) {
36
- super(config, state);
37
- /**
38
- * Resolves a networkClientId to a network client config
39
- * or globally selected network config if not provided
40
- *
41
- * @param networkClientId - Optional networkClientId to fetch a network client with
42
- * @returns network client config
43
- */
44
- _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getCorrectNetworkClient);
45
- this.refreshMutex = new (0, _asyncmutex.Mutex)();
46
- /**
47
- * Name of this controller used during composition
48
- */
49
- this.name = "AccountTrackerController";
50
- /**
51
- * Refreshes the balances of the accounts depending on the multi-account setting.
52
- * If multi-account is disabled, only updates the selected account balance.
53
- * If multi-account is enabled, updates balances for all accounts.
54
- *
55
- * @param networkClientId - Optional networkClientId to fetch a network client with
56
- */
57
- this.refresh = async (networkClientId) => {
58
- const selectedAccount = this.messagingSystem.call(
59
- "AccountsController:getSelectedAccount"
60
- );
61
- const releaseLock = await this.refreshMutex.acquire();
62
- try {
63
- const { chainId, ethQuery } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectNetworkClient, getCorrectNetworkClient_fn).call(this, networkClientId);
64
- this.syncAccounts(chainId);
65
- const { accounts, accountsByChainId } = this.state;
66
- const isMultiAccountBalancesEnabled = this.getMultiAccountBalancesEnabled();
67
- const accountsToUpdate = isMultiAccountBalancesEnabled ? Object.keys(accounts) : [_controllerutils.toChecksumHexAddress.call(void 0, selectedAccount.address)];
68
- const accountsForChain = { ...accountsByChainId[chainId] };
69
- for (const address of accountsToUpdate) {
70
- const balance = await this.getBalanceFromChain(address, ethQuery);
71
- if (balance) {
72
- accountsForChain[address] = {
73
- balance
74
- };
75
- }
76
- }
77
- this.update({
78
- ...chainId === this.getCurrentChainId() && {
79
- accounts: accountsForChain
80
- },
81
- accountsByChainId: {
82
- ...this.state.accountsByChainId,
83
- [chainId]: accountsForChain
84
- }
85
- });
86
- } finally {
87
- releaseLock();
88
- }
89
- };
90
- this.defaultConfig = {
91
- interval: 1e4
92
- };
93
- this.defaultState = {
94
- accounts: {},
95
- accountsByChainId: {
96
- [getCurrentChainId()]: {}
97
- }
98
- };
99
- this.initialize();
100
- this.messagingSystem = messenger;
101
- this.setIntervalLength(this.config.interval);
102
- this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;
103
- this.getCurrentChainId = getCurrentChainId;
104
- this.getNetworkClientById = getNetworkClientById;
105
- this.poll();
106
- this.messagingSystem.subscribe(
107
- "AccountsController:selectedEvmAccountChange",
108
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
109
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
110
- () => this.refresh()
111
- );
112
- }
113
- syncAccounts(newChainId) {
114
- const accounts = { ...this.state.accounts };
115
- const accountsByChainId = _lodash.cloneDeep.call(void 0, this.state.accountsByChainId);
116
- const existing = Object.keys(accounts);
117
- if (!accountsByChainId[newChainId]) {
118
- accountsByChainId[newChainId] = {};
119
- existing.forEach((address) => {
120
- accountsByChainId[newChainId][address] = { balance: "0x0" };
121
- });
122
- }
123
- const addresses = Object.values(
124
- this.messagingSystem.call("AccountsController:listAccounts").map(
125
- (internalAccount) => _controllerutils.toChecksumHexAddress.call(void 0, internalAccount.address)
126
- )
127
- );
128
- const newAddresses = addresses.filter(
129
- (address) => !existing.includes(address)
130
- );
131
- const oldAddresses = existing.filter(
132
- (address) => !addresses.includes(address)
133
- );
134
- newAddresses.forEach((address) => {
135
- accounts[address] = { balance: "0x0" };
136
- });
137
- Object.keys(accountsByChainId).forEach((chainId) => {
138
- newAddresses.forEach((address) => {
139
- accountsByChainId[chainId][address] = {
140
- balance: "0x0"
141
- };
142
- });
143
- });
144
- oldAddresses.forEach((address) => {
145
- delete accounts[address];
146
- });
147
- Object.keys(accountsByChainId).forEach((chainId) => {
148
- oldAddresses.forEach((address) => {
149
- delete accountsByChainId[chainId][address];
150
- });
151
- });
152
- this.update({ accounts, accountsByChainId });
153
- }
154
- /**
155
- * Sets a new provider.
156
- *
157
- * TODO: Replace this wth a method.
158
- *
159
- * @param provider - Provider used to create a new underlying EthQuery instance.
160
- */
161
- set provider(provider) {
162
- this._provider = provider;
163
- }
164
- get provider() {
165
- throw new Error("Property only used for setting");
166
- }
167
- /**
168
- * Starts a new polling interval.
169
- *
170
- * @param interval - Polling interval trigger a 'refresh'.
171
- */
172
- async poll(interval) {
173
- interval && this.configure({ interval }, false, false);
174
- this.handle && clearTimeout(this.handle);
175
- await this.refresh();
176
- this.handle = setTimeout(() => {
177
- this.poll(this.config.interval);
178
- }, this.config.interval);
179
- }
180
- /**
181
- * Refreshes the balances of the accounts using the networkClientId
182
- *
183
- * @param networkClientId - The network client ID used to get balances.
184
- */
185
- async _executePoll(networkClientId) {
186
- this.refresh(networkClientId);
187
- }
188
- /**
189
- * Fetches the balance of a given address from the blockchain.
190
- *
191
- * @param address - The account address to fetch the balance for.
192
- * @param ethQuery - The EthQuery instance to query getBalnce with.
193
- * @returns A promise that resolves to the balance in a hex string format.
194
- */
195
- async getBalanceFromChain(address, ethQuery) {
196
- return await _controllerutils.safelyExecuteWithTimeout.call(void 0, async () => {
197
- _utils.assert.call(void 0, ethQuery, "Provider not set.");
198
- return await _controllerutils.query.call(void 0, ethQuery, "getBalance", [address]);
199
- });
200
- }
201
- /**
202
- * Sync accounts balances with some additional addresses.
203
- *
204
- * @param addresses - the additional addresses, may be hardware wallet addresses.
205
- * @param networkClientId - Optional networkClientId to fetch a network client with.
206
- * @returns accounts - addresses with synced balance
207
- */
208
- async syncBalanceWithAddresses(addresses, networkClientId) {
209
- const { ethQuery } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectNetworkClient, getCorrectNetworkClient_fn).call(this, networkClientId);
210
- return await Promise.all(
211
- addresses.map((address) => {
212
- return _controllerutils.safelyExecuteWithTimeout.call(void 0, async () => {
213
- _utils.assert.call(void 0, ethQuery, "Provider not set.");
214
- const balance = await _controllerutils.query.call(void 0, ethQuery, "getBalance", [address]);
215
- return [address, balance];
216
- });
217
- })
218
- ).then((value) => {
219
- return value.reduce((obj, item) => {
220
- if (!item) {
221
- return obj;
222
- }
223
- const [address, balance] = item;
224
- return {
225
- ...obj,
226
- [address]: {
227
- balance
228
- }
229
- };
230
- }, {});
231
- });
232
- }
233
- };
234
- _getCorrectNetworkClient = new WeakSet();
235
- getCorrectNetworkClient_fn = function(networkClientId) {
236
- if (networkClientId) {
237
- const networkClient = this.getNetworkClientById(networkClientId);
238
- return {
239
- chainId: networkClient.configuration.chainId,
240
- ethQuery: new (0, _ethquery2.default)(networkClient.provider)
241
- };
242
- }
243
- return {
244
- chainId: this.getCurrentChainId(),
245
- ethQuery: this._provider ? new (0, _ethquery2.default)(this._provider) : void 0
246
- };
247
- };
248
- var AccountTrackerController_default = AccountTrackerController;
249
-
250
-
251
-
252
-
253
- exports.AccountTrackerController = AccountTrackerController; exports.AccountTrackerController_default = AccountTrackerController_default;
254
- //# sourceMappingURL=chunk-AZ6SRJVI.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/AccountTrackerController.ts"],"names":[],"mappings":";;;;;;AAWA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,cAAc;AAMrB,SAAS,yCAAyC;AAGlD,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,iBAAiB;AA3B1B;AA2FO,IAAM,2BAAN,cAAuC,kCAG5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiFA,YACE;AAAA,IACE;A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WAA8B;AAEnD,WAAO,MAAM,QAAQ;AAAA,MACnB,UAAU,IAAI,CAAC,YAAmD;AAChE,eAAO,yBAAyB,YAAY;AAC1C,iBAAO,UAAU,mBAAmB;AACpC,gBAAM,UAAU,MAAM,MAAM,UAAU,cAAc,CAAC,OAAO,CAAC;AAC7D,iBAAO,CAAC,SAAS,OAAO;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAAA,IACH,EAAE,KAAK,CAAC,UAAU;AAChB,aAAO,MAAM,OAAO,CAAC,KAAK,SAAS;AACjC,YAAI,CAAC,MAAM;AACT,iBAAO;AAAA,QACT;AAEA,cAAM,CAAC,SAAS,OAAO,IAAI;AAC3B,eAAO;AAAA,UACL,GAAG;AAAA,UACH,CAAC,OAAO,GAAG;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAAA,MACF,GAAG,CAAC,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AACF;AApJE;AAAA,6BAAwB,SAAC,iBAGvB;AACA,MAAI,iBAAiB;AACnB,UAAM,gBAAgB,KAAK,qBAAqB,eAAe;AAE/D,WAAO;AAAA,MACL,SAAS,cAAc,cAAc;AAAA,MACrC,UAAU,IAAI,SAAS,cAAc,QAAQ;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,KAAK,kBAAkB;AAAA,IAChC,UAAU,KAAK,YAAY,IAAI,SAAS,KAAK,SAAS,IAAI;AAAA,EAC5D;AACF;AAqIF,IAAO,mCAAQ","sourcesContent":["import type {\n AccountsControllerSelectedEvmAccountChangeEvent,\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerListAccountsAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type {\n BaseConfig,\n BaseState,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n query,\n safelyExecuteWithTimeout,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type { Provider } from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport { cloneDeep } from 'lodash';\n\nconst controllerName = 'AccountTrackerController';\n\nexport type AllowedActions =\n | AccountsControllerListAccountsAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedEvmAccountChangeEvent\n | AccountsControllerSelectedAccountChangeEvent;\n\nexport type AccountTrackerControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * @type AccountInformation\n *\n * Account information object\n * @property balance - Hex string of an account balancec in wei\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountInformation {\n balance: string;\n}\n\n/**\n * @type AccountTrackerConfig\n *\n * Account tracker controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerConfig extends BaseConfig {\n interval: number;\n provider?: Provider;\n}\n\n/**\n * @type AccountTrackerState\n *\n * Account tracker controller state\n * @property accounts - Map of addresses to account information\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerState extends BaseState {\n accounts: { [address: string]: AccountInformation };\n accountsByChainId: Record<string, { [address: string]: AccountInformation }>;\n}\n\n/**\n * Controller that tracks the network balances for all user accounts.\n */\nexport class AccountTrackerController extends StaticIntervalPollingControllerV1<\n AccountTrackerConfig,\n AccountTrackerState\n> {\n private _provider?: Provider;\n\n private readonly refreshMutex = new Mutex();\n\n private handle?: ReturnType<typeof setTimeout>;\n\n private syncAccounts(newChainId: string) {\n const accounts = { ...this.state.accounts };\n const accountsByChainId = cloneDeep(this.state.accountsByChainId);\n\n const existing = Object.keys(accounts);\n if (!accountsByChainId[newChainId]) {\n accountsByChainId[newChainId] = {};\n existing.forEach((address) => {\n accountsByChainId[newChainId][address] = { balance: '0x0' };\n });\n }\n\n // Note: The address from the preferences controller are checksummed\n // The addresses from the accounts controller are lowercased\n const addresses = Object.values(\n this.messagingSystem\n .call('AccountsController:listAccounts')\n .map((internalAccount) =>\n toChecksumHexAddress(internalAccount.address),\n ),\n );\n const newAddresses = addresses.filter(\n (address) => !existing.includes(address),\n );\n const oldAddresses = existing.filter(\n (address) => !addresses.includes(address),\n );\n newAddresses.forEach((address) => {\n accounts[address] = { balance: '0x0' };\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n newAddresses.forEach((address) => {\n accountsByChainId[chainId][address] = {\n balance: '0x0',\n };\n });\n });\n\n oldAddresses.forEach((address) => {\n delete accounts[address];\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n oldAddresses.forEach((address) => {\n delete accountsByChainId[chainId][address];\n });\n });\n\n this.update({ accounts, accountsByChainId });\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AccountTrackerController' as const;\n\n private readonly getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n\n private readonly getCurrentChainId: () => Hex;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n private readonly messagingSystem: AccountTrackerControllerMessenger;\n\n /**\n * Creates an AccountTracker instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The messaging system used to communicate with other controllers.\n * @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.\n * @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n messenger,\n getMultiAccountBalancesEnabled,\n getCurrentChainId,\n getNetworkClientById,\n }: {\n messenger: AccountTrackerControllerMessenger;\n getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n getCurrentChainId: () => Hex;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AccountTrackerConfig>,\n state?: Partial<AccountTrackerState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: 10000,\n };\n this.defaultState = {\n accounts: {},\n accountsByChainId: {\n [getCurrentChainId()]: {},\n },\n };\n this.initialize();\n this.messagingSystem = messenger;\n this.setIntervalLength(this.config.interval);\n this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;\n this.getCurrentChainId = getCurrentChainId;\n this.getNetworkClientById = getNetworkClientById;\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 this.messagingSystem.subscribe(\n 'AccountsController:selectedEvmAccountChange',\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 () => this.refresh(),\n );\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @param provider - Provider used to create a new underlying EthQuery instance.\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Resolves a networkClientId to a network client config\n * or globally selected network config if not provided\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n * @returns network client config\n */\n #getCorrectNetworkClient(networkClientId?: NetworkClientId): {\n chainId: string;\n ethQuery?: EthQuery;\n } {\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n\n return {\n chainId: networkClient.configuration.chainId,\n ethQuery: new EthQuery(networkClient.provider),\n };\n }\n\n return {\n chainId: this.getCurrentChainId(),\n ethQuery: this._provider ? new EthQuery(this._provider) : undefined,\n };\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval trigger a 'refresh'.\n */\n async poll(interval?: number): Promise<void> {\n interval && this.configure({ interval }, false, false);\n this.handle && clearTimeout(this.handle);\n await this.refresh();\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.config.interval);\n }, this.config.interval);\n }\n\n /**\n * Refreshes the balances of the accounts using the networkClientId\n *\n * @param networkClientId - The network client ID used to get balances.\n */\n async _executePoll(networkClientId: string): Promise<void> {\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.refresh(networkClientId);\n }\n\n /**\n * Refreshes the balances of the accounts depending on the multi-account setting.\n * If multi-account is disabled, only updates the selected account balance.\n * If multi-account is enabled, updates balances for all accounts.\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n */\n refresh = async (networkClientId?: NetworkClientId) => {\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n const releaseLock = await this.refreshMutex.acquire();\n try {\n const { chainId, ethQuery } =\n this.#getCorrectNetworkClient(networkClientId);\n this.syncAccounts(chainId);\n const { accounts, accountsByChainId } = this.state;\n const isMultiAccountBalancesEnabled =\n this.getMultiAccountBalancesEnabled();\n\n const accountsToUpdate = isMultiAccountBalancesEnabled\n ? Object.keys(accounts)\n : [toChecksumHexAddress(selectedAccount.address)];\n\n const accountsForChain = { ...accountsByChainId[chainId] };\n for (const address of accountsToUpdate) {\n const balance = await this.getBalanceFromChain(address, ethQuery);\n if (balance) {\n accountsForChain[address] = {\n balance,\n };\n }\n }\n\n this.update({\n ...(chainId === this.getCurrentChainId() && {\n accounts: accountsForChain,\n }),\n accountsByChainId: {\n ...this.state.accountsByChainId,\n [chainId]: accountsForChain,\n },\n });\n } finally {\n releaseLock();\n }\n };\n\n /**\n * Fetches the balance of a given address from the blockchain.\n *\n * @param address - The account address to fetch the balance for.\n * @param ethQuery - The EthQuery instance to query getBalnce with.\n * @returns A promise that resolves to the balance in a hex string format.\n */\n private async getBalanceFromChain(\n address: string,\n ethQuery?: EthQuery,\n ): Promise<string | undefined> {\n return await safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n return await query(ethQuery, 'getBalance', [address]);\n });\n }\n\n /**\n * Sync accounts balances with some additional addresses.\n *\n * @param addresses - the additional addresses, may be hardware wallet addresses.\n * @param networkClientId - Optional networkClientId to fetch a network client with.\n * @returns accounts - addresses with synced balance\n */\n async syncBalanceWithAddresses(\n addresses: string[],\n networkClientId?: NetworkClientId,\n ): Promise<Record<string, { balance: string }>> {\n const { ethQuery } = this.#getCorrectNetworkClient(networkClientId);\n\n return await Promise.all(\n addresses.map((address): Promise<[string, string] | undefined> => {\n return safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n const balance = await query(ethQuery, 'getBalance', [address]);\n return [address, balance];\n });\n }),\n ).then((value) => {\n return value.reduce((obj, item) => {\n if (!item) {\n return obj;\n }\n\n const [address, balance] = item;\n return {\n ...obj,\n [address]: {\n balance,\n },\n };\n }, {});\n });\n }\n}\n\nexport default AccountTrackerController;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/TokenRatesController.ts"],"names":[],"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,SAC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d,gBAAgB;AAAA,IAClB;AAAA,IACA,0BAA0B;AAAA,MACxB,MAAM;AAAA,MACN,IAAI;AAAA,IACN,CAAC;AAAA,EACH,CAAC;AAED,MAAI,mDAAmD,MAAM;AAC3D,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,+BAA+B,OAAO;AAAA,IAC1C;AAAA,EACF,EAAE,OAAO,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM;AACvC,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,CAAC,YAAY,GAAG;AAAA,QACd,GAAG;AAAA,QACH,OAAO,MAAM,QACT,MAAM,QAAQ,iDACd;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;AAGF,IAAO,+BAAQ","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"]}