diff --git a/packages/assets-controllers/src/TokenRatesController.test.ts b/packages/assets-controllers/src/TokenRatesController.test.ts index 20b040f75e..e9d40764be 100644 --- a/packages/assets-controllers/src/TokenRatesController.test.ts +++ b/packages/assets-controllers/src/TokenRatesController.test.ts @@ -152,7 +152,7 @@ describe('TokenRatesController', () => { }, async ({ controller, triggerTokensStateChange }) => { const updateExchangeRatesSpy = jest - .spyOn(controller, 'updateExchangeRates') + .spyOn(controller, 'updateExchangeRatesByChainId') .mockResolvedValue(); await controller.start(); triggerTokensStateChange({ @@ -198,7 +198,7 @@ describe('TokenRatesController', () => { }, async ({ controller, triggerTokensStateChange }) => { const updateExchangeRatesSpy = jest - .spyOn(controller, 'updateExchangeRates') + .spyOn(controller, 'updateExchangeRatesByChainId') .mockResolvedValue(); await controller.start(); triggerTokensStateChange({ diff --git a/packages/assets-controllers/src/TokenRatesController.ts b/packages/assets-controllers/src/TokenRatesController.ts index ec2ade5e0b..3e38cb1176 100644 --- a/packages/assets-controllers/src/TokenRatesController.ts +++ b/packages/assets-controllers/src/TokenRatesController.ts @@ -314,17 +314,46 @@ export class TokenRatesController extends StaticIntervalPollingController { - const previousTokenAddresses = this.#getTokenAddresses(this.#chainId); + 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], + ), + ); + this.#allTokens = allTokens; this.#allDetectedTokens = allDetectedTokens; - const newTokenAddresses = this.#getTokenAddresses(this.#chainId); - if ( - !isEqual(previousTokenAddresses, newTokenAddresses) && - this.#pollState === PollState.Active - ) { - await this.updateExchangeRates(); - } + 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, + }); + } + }), + ); }, ({ allTokens, allDetectedTokens }) => { return { allTokens, allDetectedTokens }; @@ -591,6 +620,7 @@ export class TokenRatesController extends StaticIntervalPollingController { @@ -714,7 +747,7 @@ export class TokenRatesController extends StaticIntervalPollingController