Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

index favorites by uniqueId instead of address #5972

Merged
merged 3 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 7 additions & 14 deletions src/hooks/useLoadGlobalLateData.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getWalletBalances, WALLET_BALANCES_FROM_STORAGE } from '@/handlers/localstorage/walletBalances';
import { queryClient } from '@/react-query';
import { AppState } from '@/redux/store';
import { promiseUtils } from '@/utils';
import logger from '@/utils/logger';
import { contactsLoadState } from '@/redux/contacts';
import { imageMetadataCacheLoadState } from '@/redux/imageMetadata';
import { keyboardHeightsLoadState } from '@/redux/keyboardHeight';
import { AppState } from '@/redux/store';
import { transactionSignaturesLoadState } from '@/redux/transactionSignatures';
import { contactsLoadState } from '@/redux/contacts';
import { favoritesQueryKey, refreshFavorites } from '@/resources/favorites';
import { promiseUtils } from '@/utils';
import logger from '@/utils/logger';
import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';

const loadWalletBalanceNamesToCache = () => queryClient.prefetchQuery([WALLET_BALANCES_FROM_STORAGE], getWalletBalances);

Expand All @@ -28,12 +27,6 @@ export default function useLoadGlobalLateData() {
// mainnet eth balances for all wallets
const p2 = loadWalletBalanceNamesToCache();

// favorites
const p3 = queryClient.prefetchQuery({
queryKey: favoritesQueryKey,
queryFn: () => refreshFavorites(),
});

// contacts
const p4 = dispatch(contactsLoadState());

Expand All @@ -46,7 +39,7 @@ export default function useLoadGlobalLateData() {
// tx method names
const p7 = dispatch(transactionSignaturesLoadState());

promises.push(p2, p3, p4, p5, p6, p7);
promises.push(p2, p4, p5, p6, p7);

// @ts-expect-error ts-migrate(2345) FIXME: Argument of type '(Promise<void> | ((dispatch: Dis... Remove this comment to see the full error message
return promiseUtils.PromiseAllWithFails(promises);
Expand Down
100 changes: 67 additions & 33 deletions src/resources/favorites.ts
greg-schrammel marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
import { UniqueId } from '@/__swaps__/types/assets';
import { ChainId } from '@/__swaps__/types/chains';
import { EthereumAddress, NativeCurrencyKeys, RainbowToken } from '@/entities';
import { Network } from '@/networks/types';
import { createQueryKey, queryClient } from '@/react-query';
import { DAI_ADDRESS, ETH_ADDRESS, SOCKS_ADDRESS, WBTC_ADDRESS, WETH_ADDRESS } from '@/references';
import { promiseUtils } from '@/utils';
import ethereumUtils, { getUniqueId } from '@/utils/ethereumUtils';
greg-schrammel marked this conversation as resolved.
Show resolved Hide resolved
import { useQuery } from '@tanstack/react-query';
import { omit } from 'lodash';
import { externalTokenQueryKey, fetchExternalToken } from './assets/externalAssetsQuery';
import { ChainId } from '@/__swaps__/types/chains';
import { promiseUtils } from '@/utils';

export const favoritesQueryKey = createQueryKey('favorites', {}, { persisterVersion: 1 });
export const favoritesQueryKey = createQueryKey('favorites', {}, { persisterVersion: 141224 });
greg-schrammel marked this conversation as resolved.
Show resolved Hide resolved

const DAI_uniqueId = getUniqueId(DAI_ADDRESS, Network.mainnet);
const ETH_uniqueId = getUniqueId(ETH_ADDRESS, Network.mainnet);
const SOCKS_uniqueId = getUniqueId(SOCKS_ADDRESS, Network.mainnet);
const WBTC_uniqueId = getUniqueId(WBTC_ADDRESS, Network.mainnet);

const DEFAULT: Record<EthereumAddress, RainbowToken> = {
[DAI_ADDRESS]: {
const DEFAULT: Record<UniqueId, RainbowToken> = {
[DAI_uniqueId]: {
address: DAI_ADDRESS,
color: '#F0B340',
decimals: 18,
Expand All @@ -23,9 +29,9 @@ const DEFAULT: Record<EthereumAddress, RainbowToken> = {
name: 'Dai',
symbol: 'DAI',
network: Network.mainnet,
uniqueId: DAI_ADDRESS,
uniqueId: DAI_uniqueId,
},
[ETH_ADDRESS]: {
[ETH_uniqueId]: {
address: ETH_ADDRESS,
color: '#25292E',
decimals: 18,
Expand All @@ -35,9 +41,9 @@ const DEFAULT: Record<EthereumAddress, RainbowToken> = {
name: 'Ethereum',
symbol: 'ETH',
network: Network.mainnet,
uniqueId: ETH_ADDRESS,
uniqueId: ETH_uniqueId,
},
[SOCKS_ADDRESS]: {
[SOCKS_uniqueId]: {
address: SOCKS_ADDRESS,
color: '#E15EE5',
decimals: 18,
Expand All @@ -48,9 +54,9 @@ const DEFAULT: Record<EthereumAddress, RainbowToken> = {
name: 'Unisocks',
symbol: 'SOCKS',
network: Network.mainnet,
uniqueId: SOCKS_ADDRESS,
uniqueId: SOCKS_uniqueId,
},
[WBTC_ADDRESS]: {
[WBTC_uniqueId]: {
address: WBTC_ADDRESS,
color: '#FF9900',
decimals: 8,
Expand All @@ -61,16 +67,16 @@ const DEFAULT: Record<EthereumAddress, RainbowToken> = {
name: 'Wrapped Bitcoin',
symbol: 'WBTC',
network: Network.mainnet,
uniqueId: WBTC_ADDRESS,
uniqueId: WBTC_uniqueId,
},
};

/**
* Returns a map of the given `addresses` to their corresponding `RainbowToken` metadata.
*/
async function fetchMetadata(addresses: string[], chainId = ChainId.mainnet) {
const favoritesMetadata: Record<EthereumAddress, RainbowToken> = {};
const newFavoritesMeta: Record<EthereumAddress, RainbowToken> = {};
const favoritesMetadata: Record<UniqueId, RainbowToken> = {};
const newFavoritesMeta: Record<UniqueId, RainbowToken> = {};

const network = ethereumUtils.getNetworkFromChainId(chainId);

Expand All @@ -85,13 +91,14 @@ async function fetchMetadata(addresses: string[], chainId = ChainId.mainnet) {
);

if (externalAsset) {
newFavoritesMeta[address] = {
const uniqueId = getUniqueId(externalAsset?.networks[chainId]?.address, network);
newFavoritesMeta[uniqueId] = {
...externalAsset,
network: ethereumUtils.getNetworkFromChainId(ChainId.mainnet),
network,
address,
networks: externalAsset.networks,
mainnet_address: externalAsset?.networks[ChainId.mainnet]?.address,
uniqueId: getUniqueId(externalAsset?.networks[chainId]?.address, Network.mainnet),
uniqueId,
isVerified: true,
};
}
Expand All @@ -103,32 +110,56 @@ async function fetchMetadata(addresses: string[], chainId = ChainId.mainnet) {
const ethIsFavorited = addresses.includes(ETH_ADDRESS);
const wethIsFavorited = addresses.includes(WETH_ADDRESS);
if (newFavoritesMeta) {
if (newFavoritesMeta[WETH_ADDRESS] && ethIsFavorited) {
const favorite = newFavoritesMeta[WETH_ADDRESS];
newFavoritesMeta[ETH_ADDRESS] = {
const WETH_uniqueId = getUniqueId(WETH_ADDRESS, Network.mainnet);
if (newFavoritesMeta[WETH_uniqueId] && ethIsFavorited) {
const favorite = newFavoritesMeta[WETH_uniqueId];
const uniqueId = getUniqueId(ETH_ADDRESS, Network.mainnet);
newFavoritesMeta[uniqueId] = {
...favorite,
address: ETH_ADDRESS,
name: 'Ethereum',
symbol: 'ETH',
uniqueId: getUniqueId(ETH_ADDRESS, Network.mainnet),
uniqueId,
};
}
Object.entries(newFavoritesMeta).forEach(([address, favorite]) => {
if (address !== WETH_ADDRESS || wethIsFavorited) {
favoritesMetadata[address] = { ...favorite, favorite: true };
Object.entries(newFavoritesMeta).forEach(([uniqueId, favorite]) => {
if (favorite.address !== WETH_ADDRESS || wethIsFavorited) {
favoritesMetadata[uniqueId] = { ...favorite, favorite: true };
}
});
}

return favoritesMetadata;
}

/**
* Refreshes the metadata associated with all favorites.
*/
export async function refreshFavorites() {
const favorites = Object.keys(queryClient.getQueryData(favoritesQueryKey) ?? DEFAULT);
const updatedMetadata = await fetchMetadata(favorites, ChainId.mainnet);
return updatedMetadata;
const favorites = queryClient.getQueryData<Record<UniqueId, RainbowToken>>(favoritesQueryKey) ?? DEFAULT;
greg-schrammel marked this conversation as resolved.
Show resolved Hide resolved

const favoritesByNetwork = Object.values(favorites).reduce(
(favoritesByChain, token) => {
favoritesByChain[token.network] ??= [];
favoritesByChain[token.network].push(token.address);
return favoritesByChain;
},
{} as Record<Network, string[]>
);

const updatedMetadataByNetwork = await Promise.all(
Object.entries(favoritesByNetwork).map(async ([network, networkFavorites]) =>
fetchMetadata(networkFavorites, ethereumUtils.getChainIdFromNetwork(network as Network))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this splits the tokens that don't have a mainnet address to fetchMetadata from their network instead
like the case for degen

)
);

return updatedMetadataByNetwork.reduce(
(updatedMetadata, updatedNetworkMetadata) => ({
...updatedMetadata,
...updatedNetworkMetadata,
}),
{}
);
}

/**
Expand All @@ -139,10 +170,11 @@ export async function refreshFavorites() {
* @param chainId - The chain id of the network to toggle the favorite status of @default ChainId.mainnet
*/
export async function toggleFavorite(address: string, chainId = ChainId.mainnet) {
const favorites = queryClient.getQueryData<Record<EthereumAddress, RainbowToken>>(favoritesQueryKey);
const favorites = queryClient.getQueryData<Record<UniqueId, RainbowToken>>(favoritesQueryKey);
const lowercasedAddress = address.toLowerCase() as EthereumAddress;
if (Object.keys(favorites || {}).includes(lowercasedAddress)) {
queryClient.setQueryData(favoritesQueryKey, omit(favorites, lowercasedAddress));
const uniqueId = getUniqueId(lowercasedAddress, ethereumUtils.getNetworkFromChainId(chainId));
if (Object.keys(favorites || {}).includes(uniqueId)) {
queryClient.setQueryData(favoritesQueryKey, omit(favorites, uniqueId));
} else {
const metadata = await fetchMetadata([lowercasedAddress], chainId);
queryClient.setQueryData(favoritesQueryKey, {
Expand All @@ -159,10 +191,12 @@ export async function toggleFavorite(address: string, chainId = ChainId.mainnet)
*/
export function useFavorites(): {
favorites: string[];
favoritesMetadata: Record<EthereumAddress, RainbowToken>;
favoritesMetadata: Record<UniqueId, RainbowToken>;
} {
const query = useQuery<Record<EthereumAddress, RainbowToken>>(favoritesQueryKey, refreshFavorites, {
staleTime: Infinity,
const query = useQuery({
queryKey: favoritesQueryKey,
queryFn: refreshFavorites,
staleTime: 24 * 60 * 60 * 1000, // 24hrs
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of refetching every time the app loads, refresh once after 24hrs stale

cacheTime: Infinity,
});

Expand Down
Loading