From fa7d96bb72e2bc4094f16dfc931e356e4420f37d Mon Sep 17 00:00:00 2001 From: Brian Bergeron Date: Tue, 29 Oct 2024 14:03:38 -0700 Subject: [PATCH] only fetch on chains whose tokens updated --- .../src/TokenRatesController.ts | 74 ++++++++++--------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/packages/assets-controllers/src/TokenRatesController.ts b/packages/assets-controllers/src/TokenRatesController.ts index beebbd91bd..7c1e807ca6 100644 --- a/packages/assets-controllers/src/TokenRatesController.ts +++ b/packages/assets-controllers/src/TokenRatesController.ts @@ -20,7 +20,6 @@ import type { NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerStateChangeEvent, - NetworkControllerActions, } from '@metamask/network-controller'; import { StaticIntervalPollingController } from '@metamask/polling-controller'; import { createDeferredPromise, type Hex } from '@metamask/utils'; @@ -315,41 +314,46 @@ export class TokenRatesController extends StaticIntervalPollingController { - if ( - !this.#disabled && - (!isEqual(this.#allTokens, allTokens) || - !isEqual(this.#allDetectedTokens, allDetectedTokens)) - ) { - this.#allTokens = allTokens; - this.#allDetectedTokens = allDetectedTokens; - - const chainIds = [ - ...new Set([ - ...Object.keys(allTokens), - ...Object.keys(allDetectedTokens), - ]), - ]; - - const { networkConfigurationsByChainId } = this.messagingSystem.call( - 'NetworkController:getState', - ); - - // TODO: This could be smarter and determine which specific chains - // the tokens changed on. For now, it refreshes prices on all chains. - await Promise.allSettled( - chainIds.map(async (chainId) => { - const nativeCurrency = - networkConfigurationsByChainId[chainId as Hex]?.nativeCurrency; - - if (nativeCurrency) { - await this.updateExchangeRatesByChainId({ - chainId: chainId as Hex, - nativeCurrency, - }); - } - }), - ); + if (this.#disabled) { + return; } + + const chainIds = [ + ...new Set([ + ...Object.keys(allTokens), + ...Object.keys(allDetectedTokens), + ]), + ] as Hex[]; + + const chainIdsToUpdate = chainIds.filter( + (chainId) => + !isEqual(this.#allTokens[chainId], allTokens[chainId]) || + !isEqual( + this.#allDetectedTokens[chainId], + allDetectedTokens[chainId], + ), + ); + + const { networkConfigurationsByChainId } = this.messagingSystem.call( + 'NetworkController:getState', + ); + + await Promise.allSettled( + chainIdsToUpdate.map(async (chainId) => { + const nativeCurrency = + networkConfigurationsByChainId[chainId as Hex]?.nativeCurrency; + + if (nativeCurrency) { + await this.updateExchangeRatesByChainId({ + chainId: chainId as Hex, + nativeCurrency, + }); + } + }), + ); + + this.#allTokens = allTokens; + this.#allDetectedTokens = allDetectedTokens; }, ({ allTokens, allDetectedTokens }) => { return { allTokens, allDetectedTokens };