Skip to content

Commit

Permalink
Merge pull request #999 from airswap/fix/metadata-cache
Browse files Browse the repository at this point in the history
Removed metadata all tokens from cache
  • Loading branch information
makkelie-dev authored Dec 9, 2024
2 parents 77f3199 + b45cf09 commit a5b87ce
Show file tree
Hide file tree
Showing 24 changed files with 400 additions and 422 deletions.
1 change: 0 additions & 1 deletion public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"addToTokenSet": "Import",
"balance": "Balance",
"failedToFetchAllowances": "Failed to fetch token allowances",
"failedToFetchAllowancesCta": "Please reload the page",
"tokenBalances": "Token balances",
"unsupportedToken": "Not yet supported"
},
Expand Down
3 changes: 0 additions & 3 deletions src/app/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import gasCostReducer from "../features/gasCost/gasCostSlice";
import indexerReducer from "../features/indexer/indexerSlice";
import makeOtcReducer from "../features/makeOtc/makeOtcSlice";
import metadataReducer from "../features/metadata/metadataSlice";
import { subscribeToSavedTokenChangesForLocalStoragePersisting } from "../features/metadata/metadataSubscriber";
import myOrdersReducer from "../features/myOrders/myOrdersSlice";
import ordersReducer from "../features/orders/ordersSlice";
import quotesReducer from "../features/quotes/quotesSlice";
Expand Down Expand Up @@ -39,8 +38,6 @@ export const store = configureStore({
},
});

subscribeToSavedTokenChangesForLocalStoragePersisting();

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ const InfoSection: FC<ActionButtonsProps> = ({
<StyledInfoHeading>
{t("balances.failedToFetchAllowances")}
</StyledInfoHeading>
<StyledInfoSubHeading>
{t("balances.failedToFetchAllowancesCta")}
</StyledInfoSubHeading>
</Container>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,12 @@ const OrderDetailWidget: FC<OrderDetailWidgetProps> = ({ order }) => {
);
const [orderStatus, isOrderStatusLoading] = useOrderStatus(order);
const [senderToken, isSenderTokenLoading] = useTakerTokenInfo(
order.senderToken
order.senderToken,
order.chainId
);
const [signerToken, isSignerTokenLoading] = useTakerTokenInfo(
order.signerToken
order.signerToken,
order.chainId
);
const isBalanceLoading = useBalanceLoading();
const senderAmount = useFormattedTokenAmount(
Expand Down
1 change: 0 additions & 1 deletion src/components/@widgets/OrderDetailWidget/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export const getFullOrderERC20WarningTranslation = (
if (isAllowancesFailed) {
return {
heading: i18n.t("balances.failedToFetchAllowances"),
subHeading: i18n.t("balances.failedToFetchAllowancesCta"),
};
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,97 +1,66 @@
import { useEffect, useState } from "react";

import { TokenInfo } from "@airswap/utils";
import { Web3Provider } from "@ethersproject/providers";
import { useWeb3React } from "@web3-react/core";

import { useAppDispatch, useAppSelector } from "../../../../app/hooks";
import { getAllTokensFromLocalStorage } from "../../../../features/metadata/metadataApi";
import {
addActiveToken,
addTokenInfo,
fetchUnkownTokens,
} from "../../../../features/metadata/metadataActions";
import {
selectActiveTokenAddresses,
selectAllTokens,
} from "../../../../features/metadata/metadataSlice";
import { selectTakeOtcReducer } from "../../../../features/takeOtc/takeOtcSlice";
import findEthOrTokenByAddress from "../../../../helpers/findEthOrTokenByAddress";
import scrapeToken from "../../../../helpers/scrapeToken";
import useDefaultLibrary from "../../../../hooks/useDefaultLibrary";
import useJsonRpcProvider from "../../../../hooks/useJsonRpcProvider";

// OTC Taker version of useTokenInfo. Look at chainId of the active FullOrderERC20 instead
// of active wallet chainId. This way we don't need to connect a wallet to show order tokens.

const useTakerTokenInfo = (
address: string | null
address: string | null,
chainId: number
): [TokenInfo | null, boolean] => {
const dispatch = useAppDispatch();
const { provider: library } = useWeb3React<Web3Provider>();
const { isActive } = useAppSelector((state) => state.web3);
// Using JsonRpcProvider for unconnected wallets or for wallets connected to a different chain
const library = useJsonRpcProvider(chainId);

const allTokens = useAppSelector(selectAllTokens);
const activeTokenAddresses = useAppSelector(selectActiveTokenAddresses);
const { activeOrder } = useAppSelector(selectTakeOtcReducer);

const [token, setToken] = useState<TokenInfo>();
const [scrapedToken, setScrapedToken] = useState<TokenInfo>();
const [isCallScrapeTokenLoading, setIsCallScrapeTokenLoading] =
useState(false);
const [isCallScrapeTokenSuccess, setIsCallScrapeTokenSuccess] =
useState(false);

useEffect(() => {
if (scrapedToken) {
dispatch(addTokenInfo(scrapedToken));
// Add active token so balance will be fetched
dispatch(addActiveToken(scrapedToken.address));
if (
address &&
allTokens.find((token) => token.address === address) &&
!activeTokenAddresses.includes(address)
) {
// Add as active token so balance and token info will be fetched
dispatch(addActiveToken(address));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scrapedToken]);
}, [address, allTokens]);

useEffect(() => {
if (!activeOrder || !address || !allTokens.length) {
if (!address || !allTokens.length || token || !library) {
return;
}

const chainId = activeOrder.chainId;

// If wallet is not connected the metadata tokens can't be filled yet because it gets chainId from
// the wallet. But in this case we have the chainId from the order already. So we can get tokens from
// localStorage directly so we don't have to wait for the wallet getting connected.

const tokensObject = getAllTokensFromLocalStorage(chainId);

const tokens = [
...allTokens,
...(!isActive ? Object.values(tokensObject) : []),
];

const callScrapeToken = async () => {
setIsCallScrapeTokenLoading(true);

if (library) {
const result = await scrapeToken(address, library);
if (result) {
setScrapedToken(result);
}
setIsCallScrapeTokenSuccess(true);
} else {
setIsCallScrapeTokenSuccess(false);
}
setIsCallScrapeTokenLoading(false);
};

const tokenFromStore = findEthOrTokenByAddress(address, tokens, chainId);
const tokenFromStore = findEthOrTokenByAddress(address, allTokens, chainId);

if (tokenFromStore) {
setToken(tokenFromStore);
} else if (
!tokenFromStore &&
!isCallScrapeTokenLoading &&
!isCallScrapeTokenSuccess
) {
callScrapeToken();
} else {
dispatch(addActiveToken(address));
dispatch(fetchUnkownTokens({ provider: library, tokens: [address] }));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [allTokens, address, activeOrder, isActive]);
}, [address, activeOrder, allTokens.length]);

return [token || scrapedToken || null, isCallScrapeTokenLoading];
return [token || null, false];
};

export default useTakerTokenInfo;
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import { UserTokenPair } from "../../../../features/userSettings/userSettingsSli
export default function getTokenOrFallback(
token: string | undefined,
pairedToken: string | undefined,
userToken: UserTokenPair["tokenTo"] | UserTokenPair["tokenFrom"],
pairedUserToken: UserTokenPair["tokenTo"] | UserTokenPair["tokenFrom"],
defaultTokenAddress: string | null,
defaultPairedTokenAddress: string | null,
customTokens: string[]
defaultPairedTokenAddress: string | null
): string | null {
if (token) {
return token;
Expand All @@ -18,11 +16,6 @@ export default function getTokenOrFallback(
return null;
}

// Else get the user token from store (if it's not a custom token)
if (userToken && !customTokens.includes(userToken)) {
return userToken;
}

// Check if the paired token is not already the default token address
if (pairedUserToken === defaultTokenAddress) {
return defaultPairedTokenAddress;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useMemo } from "react";

import { useAppSelector } from "../../../../app/hooks";
import nativeCurrency from "../../../../constants/nativeCurrency";
import { selectCustomTokenAddresses } from "../../../../features/metadata/metadataSlice";
import { selectUserTokens } from "../../../../features/userSettings/userSettingsSlice";
import useTokenAddress from "../../../../hooks/useTokenAddress";
import getTokenOrFallback from "../helpers/getTokenOrFallback";
Expand All @@ -15,7 +14,6 @@ const useTokenOrFallback = (
isFrom?: boolean
): string | null => {
const userTokens = useAppSelector(selectUserTokens);
const customTokens = useAppSelector(selectCustomTokenAddresses);
const { chainId } = useAppSelector((state) => state.web3);

const defaultBaseTokenAddress = useTokenAddress("USDT");
Expand All @@ -25,11 +23,9 @@ const useTokenOrFallback = (
return getTokenOrFallback(
isFrom ? tokenFrom : tokenTo,
isFrom ? tokenTo : tokenFrom,
isFrom ? userTokens.tokenFrom : userTokens.tokenTo,
isFrom ? userTokens.tokenTo : userTokens.tokenFrom,
isFrom ? defaultBaseTokenAddress : defaultQuoteTokenAddress,
isFrom ? defaultQuoteTokenAddress : defaultBaseTokenAddress,
customTokens
isFrom ? defaultQuoteTokenAddress : defaultBaseTokenAddress
);
}, [
userTokens,
Expand All @@ -38,7 +34,6 @@ const useTokenOrFallback = (
isFrom,
defaultBaseTokenAddress,
defaultQuoteTokenAddress,
customTokens,
]);
};

Expand Down
10 changes: 1 addition & 9 deletions src/components/TokenList/TokenList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ import nativeCurrency from "../../constants/nativeCurrency";
import { BalancesState } from "../../features/balances/balancesSlice";
import {
addActiveToken,
addCustomToken,
removeActiveToken,
removeCustomToken,
} from "../../features/metadata/metadataSlice";
} from "../../features/metadata/metadataActions";
import useWindowSize from "../../hooks/useWindowSize";
import { OverlayActionButton } from "../ModalOverlay/ModalOverlay.styles";
import { InfoHeading } from "../Typography/Typography";
Expand Down Expand Up @@ -146,12 +144,7 @@ const TokenList = ({
]);

const handleAddToken = async (address: string) => {
const isCustomToken = scrapedToken?.address === address;

if (library && account) {
if (isCustomToken) {
dispatch(addCustomToken(address));
}
await dispatch(addActiveToken(address));

onAfterAddActiveToken && onAfterAddActiveToken(address);
Expand All @@ -161,7 +154,6 @@ const TokenList = ({
const handleRemoveActiveToken = (address: string) => {
if (library) {
dispatch(removeActiveToken(address));
dispatch(removeCustomToken(address));

onAfterRemoveActiveToken && onAfterRemoveActiveToken(address);
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/TokenList/hooks/useScrapeToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { TokenInfo } from "@airswap/utils";
import { Web3Provider } from "@ethersproject/providers";
import { useWeb3React } from "@web3-react/core";

import { addTokenInfo } from "../../../features/metadata/metadataSlice";
import { addUnknownTokenInfo } from "../../../features/metadata/metadataActions";
import scrapeToken from "../../../helpers/scrapeToken";

const useScrapeToken = (
Expand All @@ -19,7 +19,7 @@ const useScrapeToken = (

useEffect(() => {
if (scrapedToken) {
dispatch(addTokenInfo(scrapedToken));
dispatch(addUnknownTokenInfo(scrapedToken));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [scrapedToken]);
Expand Down
14 changes: 11 additions & 3 deletions src/features/balances/balancesHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { useWeb3React } from "@web3-react/core";

import { useAppDispatch, useAppSelector } from "../../app/hooks";
import { TransactionTypes } from "../../types/transactionTypes";
import { fetchUnkownTokens } from "../metadata/metadataActions";
import { selectActiveTokens } from "../metadata/metadataSlice";
import useLatestSucceededTransaction from "../transactions/hooks/useLatestSucceededTransaction";
import {
Expand Down Expand Up @@ -34,8 +33,10 @@ export const useBalances = () => {
if (
activeAccount === account &&
activeChainId === chainId &&
activeTokens.length === activeTokensLength
activeTokens.length <= activeTokensLength
) {
setActiveTokensLength(activeTokens.length);

return;
}

Expand All @@ -46,9 +47,12 @@ export const useBalances = () => {
dispatch(requestActiveTokenBalances({ provider: library }));
dispatch(requestActiveTokenAllowancesSwap({ provider: library }));
dispatch(requestActiveTokenAllowancesWrapper({ provider: library }));
dispatch(fetchUnkownTokens({ provider: library }));
}, [account, chainId, library, activeTokens]);

useEffect(() => {
setActiveTokensLength(activeTokens.length);
}, [account, chainId]);

useEffect(() => {
if (!isActive) {
setActiveAccount(undefined);
Expand All @@ -64,6 +68,10 @@ export const useBalances = () => {

const { type } = latestSuccessfulTransaction;

if (latestSuccessfulTransaction.type === TransactionTypes.order) {
return;
}

if (type === TransactionTypes.order) {
dispatch(requestActiveTokenBalances({ provider: library }));
dispatch(requestActiveTokenAllowancesSwap({ provider: library }));
Expand Down
5 changes: 2 additions & 3 deletions src/features/balances/balancesSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ const getThunk: (
? getWethAddress(chainId)
: undefined;
const activeTokensAddresses = [
...state.metadata.tokens.active,
...state.metadata.tokens.custom,
...state.metadata.activeTokens,
...(wrappedNativeToken ? [wrappedNativeToken] : []),
ADDRESS_ZERO,
];
Expand Down Expand Up @@ -123,7 +122,7 @@ const getThunk: (
// If we're not fetching, definitely continue
if (sliceState.status !== "fetching") return true;
if (sliceState.inFlightFetchTokens) {
const tokensToFetch = getState().metadata.tokens.active;
const tokensToFetch = getState().metadata.activeTokens;
// only fetch if new list is larger.
return tokensToFetch.length > sliceState.inFlightFetchTokens.length;
}
Expand Down
Loading

0 comments on commit a5b87ce

Please sign in to comment.