Skip to content

Commit

Permalink
only fetch on chains whose tokens updated
Browse files Browse the repository at this point in the history
  • Loading branch information
bergeron committed Oct 29, 2024
1 parent c6d939c commit fa7d96b
Showing 1 changed file with 39 additions and 35 deletions.
74 changes: 39 additions & 35 deletions packages/assets-controllers/src/TokenRatesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -315,41 +314,46 @@ export class TokenRatesController extends StaticIntervalPollingController<TokenR
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-misused-promises
async ({ allTokens, allDetectedTokens }) => {
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 };
Expand Down

0 comments on commit fa7d96b

Please sign in to comment.