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

Clear cache on cache serialization problem or wrong version + handle … #316

Merged
merged 1 commit into from
Jun 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { fetchRewardTokens } from 'src/services/quest.service';
import { arrayDistinctBy } from 'src/utils/array.util';
import { getTokenInfo } from 'src/utils/contract.util';
import { GUpx } from 'src/utils/style.util';
import { Logger } from 'src/utils/logger';
import { includesCaseInsensitive } from 'src/utils/string.util';
import { isAddress } from 'src/utils/web3.utils';
import styled from 'styled-components';
Expand Down Expand Up @@ -197,7 +196,7 @@ function AmountFieldInput({
error,
}: Props) {
const isMountedRef = useIsMountedRef();
const { networkId } = getNetwork();
const { networkId, name } = getNetwork();
const [tokens, setTokens] = useState<TokenModel[]>([]);
const [searchTerm, setSearchTerm] = useState<string>();
const [amount, setAmount] = useState<number | undefined>(value?.parsedAmount);
Expand All @@ -206,6 +205,7 @@ function AmountFieldInput({
const [_hasFocused, _setHasFocused] = useState<boolean>();
const tokenInputId = tokenEditable ? id : `token-${id}`; // Handle label for
const amountInputId = !tokenEditable ? id : `amount-${id}`; // Handle label for
const [errorState, setErrorState] = useState<string | false | undefined>(error);

// Needed since the access of state in event handlers is not working
const hasFocusedRef = React.useRef(_hasFocused);
Expand All @@ -225,15 +225,22 @@ function AmountFieldInput({
}, [isEdit, tokenEditable, token]);

useEffect(() => {
if (availableTokens.length && _hasFocused) {
const handleSearch = async () => {
if (searchTerm && isAddress(searchTerm)) {
setTokens([]);
getTokenInfo(searchTerm)
.then((tokenInfo) => {
if (typeof tokenInfo !== 'string')
if (tokenInfo && isMountedRef.current) setTokens([tokenInfo]);
})
.catch(Logger.exception);
let tokenInfo;
try {
tokenInfo = await getTokenInfo(searchTerm);
} catch {
tokenInfo = null;
}
if (isMountedRef.current) {
if (tokenInfo) {
setTokens([tokenInfo]);
} else {
setErrorState(`No token found with this address on ${name}`);
}
}
} else {
setTokens(
availableTokens.filter(
Expand All @@ -242,6 +249,9 @@ function AmountFieldInput({
),
);
}
};
if (availableTokens.length && _hasFocused) {
handleSearch();
}
}, [searchTerm, availableTokens, _hasFocused]);

Expand All @@ -267,6 +277,7 @@ function AmountFieldInput({
const networkDefaultTokens =
Object.values<TokenModel>(TOKENS[networkId]).filter((x) => !!x.token) ?? [];
const questsUsedTokens = await fetchRewardTokens();

if (isMountedRef.current) {
setAvailableTokens(
arrayDistinctBy([...networkDefaultTokens, ...questsUsedTokens], (x) => x.token),
Expand Down Expand Up @@ -404,7 +415,7 @@ function AmountFieldInput({
wide={wide}
compact={compact}
direction={!!amountLabel || !!tokenLabel ? 'column' : 'row'}
error={error}
error={errorState}
className={!isEdit ? 'fit-content' : ''}
>
{reversed ? [tokenField, amountField] : [amountField, tokenField]}
Expand Down
11 changes: 8 additions & 3 deletions packages/react-app/src/components/wallet-balance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function WalletBallance({ askedTokenAmount, setIsEnoughBalance, isLoading
const [isEnoughBalance, _setIsEnoughBalance] = useState(true);
const { currentTheme } = useThemeContext();
const isMountedRef = useIsMountedRef();
const [error, setError] = useState<string>();

useEffect(() => {
if (askedTokenAmount?.token && askedTokenAmount.token.token !== tokenBalance?.token.token) {
Expand All @@ -61,13 +62,17 @@ export function WalletBallance({ askedTokenAmount, setIsEnoughBalance, isLoading
setTokenBalance(undefined);
const balance = (await getBalanceOf({ ..._token }, walletAddress)) ?? undefined;
if (isMountedRef.current) {
setTokenBalance(balance);
if (balance) {
setTokenBalance(balance);
} else {
setError('Token not found');
}
}
};

return (
<WrapperStyled theme={currentTheme} isEnoughBalance={isEnoughBalance}>
{askedTokenAmount?.token && askedTokenAmount !== null ? (
{askedTokenAmount?.token && askedTokenAmount !== null && !error ? (
<AmountFieldInput
isLoading={!tokenBalance || isLoading}
id={`balance-${tokenBalance?.token.symbol}`}
Expand All @@ -84,7 +89,7 @@ export function WalletBallance({ askedTokenAmount, setIsEnoughBalance, isLoading
compact
isLoading={isLoading}
>
<i>No token selected</i>
<i>{error ?? 'No token selected'}</i>
</FieldInput>
)}
</WrapperStyled>
Expand Down
24 changes: 17 additions & 7 deletions packages/react-app/src/services/cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { ONE_HOUR_IN_MS } from 'src/utils/date.utils';
import { Logger } from 'src/utils/logger';
import { fetchRoutePairWithStable } from './uniswap.service';

const cacheVersion = 1;

let cacheMap: Map<
string,
Map<string, { value: any; expirationMs?: number } | null>
Expand Down Expand Up @@ -112,21 +114,29 @@ function reviver(key: string, value: any) {

function saveCacheAsync() {
const { networkId } = getNetwork();
localStorage.setItem(`cache-${networkId}`, JSON.stringify(cacheMap, replacer));
localStorage.setItem(`cache-${networkId}`, JSON.stringify({ cacheVersion, cacheMap }, replacer));
}

function retrieveCache() {
const { networkId } = getNetwork();
const cacheId = `cache-${networkId}`;
try {
const { networkId } = getNetwork();
const cacheJson = localStorage.getItem(`cache-${networkId}`);
const cacheJson = localStorage.getItem(cacheId);
if (cacheJson) {
const map = JSON.parse(cacheJson, reviver) as Map<string, Map<string, any>>;
if (map.size > 0) {
return map;
const result = JSON.parse(cacheJson, reviver) as {
cacheVersion: number;
map: Map<string, Map<string, any>>;
};
if (result.cacheVersion !== cacheVersion) {
Logger.debug('Cache version mismatch, clearing cache');
localStorage.removeItem(cacheId);
} else if (result.map.size > 0) {
return result.map;
}
}
} catch (error) {
Logger.debug('Error retrieving cache from storage', error);
Logger.debug('Error retrieving cache from storage, clearing cache', error);
localStorage.removeItem(cacheId);
}
return new Map<string, Map<string, any>>();
}
7 changes: 5 additions & 2 deletions packages/react-app/src/services/quest.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -562,8 +562,11 @@ export async function getBalanceOf(
price === undefined ? undefined : parsedAmount * fromBigNumber(price, tokenInfo.decimals),
};
}
} catch (error) {
Logger.exception(error);
} catch (error: any) {
Logger.exception(
error,
`Failed to fetch balance of ${(token as any).token ? (token as any).token : token}`,
);
}
return null;
}
Expand Down