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

TW-1148 Update SWR module #1019

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
"@typescript-eslint/parser": "^5.43.0",
"@vespaiach/axios-fetch-adapter": "^0.3.1",
"assert": "1.5.0",
"async-mutex": "^0.4.0",
"async-retry": "1.3.3",
"autoprefixer": "10.4.2",
"axios": "0.26.1",
Expand Down Expand Up @@ -175,7 +176,7 @@
"rxjs": "^7.5.6",
"scryptsy": "2.1.0",
"stream-browserify": "3.0.0",
"swr": "1.3.0",
"swr": "^2.2.4",
keshan3262 marked this conversation as resolved.
Show resolved Hide resolved
"tailwindcss": "2.2.19",
"terser-webpack-plugin": "5.3.6",
"three": "^0.151.2",
Expand Down
2 changes: 1 addition & 1 deletion src/app/ConfirmPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ const ConfirmDAppForm: FC = () => {
return pageId;
}, [loc.search]);

const { data } = useRetryableSWR<TempleDAppPayload>([id], getDAppPayload, {
const { data } = useRetryableSWR<TempleDAppPayload>(id, getDAppPayload, {
suspense: true,
shouldRetryOnError: false,
revalidateOnFocus: false,
Expand Down
2 changes: 1 addition & 1 deletion src/app/a11y/AwaitFonts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const AwaitFonts: FC<AwaitFontsProps> = ({ name, weights, className, children })

export default AwaitFonts;

async function awaitFonts(name: string, weights: number[], className: string) {
async function awaitFonts([name, weights, className]: [string, number[], string]) {
try {
const fonts = weights.map(weight => new FontFaceObserver(name, { weight }));
await Promise.all(fonts.map(font => font.load()));
Expand Down
4 changes: 2 additions & 2 deletions src/app/pages/AddAsset/AddAsset.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { FC, ReactNode, useCallback, useEffect, useRef, useMemo } from 'r
import classNames from 'clsx';
import { FormContextValues, useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { useSWRConfig } from 'swr';
import { useSWRConfig, unstable_serialize } from 'swr';
import { useDebouncedCallback } from 'use-debounce';

import { Alert, FormField, FormSubmitButton, NoSpaceField } from 'app/atoms';
Expand Down Expand Up @@ -228,7 +228,7 @@ const Form: FC = () => {
Repo.toAccountTokenKey(chainId, accountPkh, tokenSlug)
);

swrCache.delete(getBalanceSWRKey(tezos, tokenSlug, accountPkh));
swrCache.delete(unstable_serialize(getBalanceSWRKey(tezos, tokenSlug, accountPkh)));

formAnalytics.trackSubmitSuccess();

Expand Down
8 changes: 4 additions & 4 deletions src/app/pages/Buy/Crypto/Exolix/steps/InitialStep.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,10 @@ const InitialStep: FC<Props> = ({ exchangeData, setExchangeData, setStep, isErro
const { data: ratesData } = useSWR(['exolix/api/rate', coinFrom, coinTo, amount], () =>
queryExchange({
coinFrom: coinFrom.code,
coinFromNetwork: coinFrom.network!.code,
coinFromNetwork: coinFrom.network.code,
amount: amount ?? 0,
coinTo: coinTo.code,
coinToNetwork: coinTo!.network.code
coinToNetwork: coinTo.network.code
})
);

Expand All @@ -103,10 +103,10 @@ const InitialStep: FC<Props> = ({ exchangeData, setExchangeData, setStep, isErro

const { toAmount: maxCoinFromAmount } = await queryExchange({
coinFrom: coinTo.code,
coinFromNetwork: coinTo.network!.code,
coinFromNetwork: coinTo.network.code,
amount: maxCoinToAmount,
coinTo: coinFrom.code,
coinToNetwork: coinFrom.network!.code
coinToNetwork: coinFrom.network.code
});

setMaxAmountFetched(maxCoinFromAmount);
Expand Down
4 changes: 2 additions & 2 deletions src/app/pages/Home/OtherComponents/BakingSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const BakingSection = memo(() => {
};

const getBakingHistory = useCallback(
async (_k: string, accountPkh: string) => {
async ([, accountPkh, , chainId]: [string, string, string | nullish, string | nullish]) => {
if (!isKnownChainId(chainId!)) {
return [];
}
Expand All @@ -97,7 +97,7 @@ const BakingSection = memo(() => {
})) || []
);
},
[chainId]
[]
);
const { data: bakingHistory, isValidating: loadingBakingHistory } = useRetryableSWR(
['baking-history', acc.publicKeyHash, myBakerPkh, chainId],
Expand Down
13 changes: 6 additions & 7 deletions src/app/pages/ImportAccount/ManagedKTForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,11 @@ export const ManagedKTForm: FC = () => {
const [error, setError] = useState<ReactNode>(null);

const queryKey = useMemo(
() =>
[
'get-accounts-contracts',
chainId,
...accounts.filter(({ type }) => type !== TempleAccountType.ManagedKT).map(({ publicKeyHash }) => publicKeyHash)
] as string[],
() => [
'get-accounts-contracts',
chainId!,
...accounts.filter(({ type }) => type !== TempleAccountType.ManagedKT).map(({ publicKeyHash }) => publicKeyHash)
],
[accounts, chainId]
);
const { data: usersContracts = [] } = useRetryableSWR(queryKey, getUsersContracts, {});
Expand Down Expand Up @@ -224,7 +223,7 @@ export const ManagedKTForm: FC = () => {
);
};

const getUsersContracts = async (_k: string, chainId: string, ...accounts: string[]) => {
const getUsersContracts = async ([, chainId, ...accounts]: string[]) => {
if (!isKnownChainId(chainId)) {
return [];
}
Expand Down
11 changes: 2 additions & 9 deletions src/app/pages/ImportAccount/WatchOnlyForm.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { FC, ReactNode, useCallback, useMemo, useRef, useState } from 'react';

import { useForm, Controller } from 'react-hook-form';
import useSWR from 'swr';

import { Alert, FormSubmitButton, NoSpaceField } from 'app/atoms';
import { useFormAnalytics } from 'lib/analytics';
import { T, t } from 'lib/i18n';
import { useTempleClient, useTezos, useTezosDomainsClient, validateDelegate } from 'lib/temple/front';
import { useTezosAddressByDomainName } from 'lib/temple/front/tzdns';
import { isAddressValid, isKTAddress } from 'lib/temple/helpers';
import { delay } from 'lib/utils';

Expand All @@ -32,14 +32,7 @@ export const WatchOnlyForm: FC = () => {

const addressValue = watch('address');

const domainAddressFactory = useCallback(
(_k: string, _checksum: string, address: string) => domainsClient.resolver.resolveNameToAddress(address),
[domainsClient]
);
const { data: resolvedAddress } = useSWR(['tzdns-address', tezos.checksum, addressValue], domainAddressFactory, {
shouldRetryOnError: false,
revalidateOnFocus: false
});
const { data: resolvedAddress } = useTezosAddressByDomainName(addressValue);

const finalAddress = useMemo(
() => (resolvedAddress && resolvedAddress !== null ? resolvedAddress : addressValue),
Expand Down
20 changes: 5 additions & 15 deletions src/app/pages/Receive/Receive.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React, { FC, memo, useCallback, useEffect } from 'react';
import React, { FC, memo, useEffect } from 'react';

import classNames from 'clsx';
import { QRCode } from 'react-qr-svg';
import useSWR from 'swr';

import { FormField } from 'app/atoms';
import { ReactComponent as CopyIcon } from 'app/icons/copy.svg';
Expand All @@ -13,7 +12,8 @@ import PageLayout from 'app/layouts/PageLayout';
import ViewsSwitcher, { ViewsSwitcherProps } from 'app/templates/ViewsSwitcher/ViewsSwitcher';
import { setTestID } from 'lib/analytics';
import { T, t } from 'lib/i18n';
import { useAccount, useTezos, useTezosDomainsClient } from 'lib/temple/front';
import { useAccount, useTezosDomainsClient } from 'lib/temple/front';
import { useTezosDomainNameByAddress } from 'lib/temple/front/tzdns';
import { useSafeState } from 'lib/ui/hooks';
import useCopyToClipboard from 'lib/ui/useCopyToClipboard';

Expand All @@ -35,23 +35,13 @@ const ADDRESS_FIELD_VIEWS = [

const Receive: FC = () => {
const account = useAccount();
const tezos = useTezos();
const { resolver: domainsResolver, isSupported } = useTezosDomainsClient();
const { isSupported } = useTezosDomainsClient();
const address = account.publicKeyHash;

const { fieldRef, copy, copied } = useCopyToClipboard();
const [activeView, setActiveView] = useSafeState(ADDRESS_FIELD_VIEWS[1]);

const resolveDomainReverseName = useCallback(
(_k: string, pkh: string) => domainsResolver.resolveAddressToName(pkh),
[domainsResolver]
);

const { data: reverseName } = useSWR(
() => ['tzdns-reverse-name', address, tezos.checksum],
resolveDomainReverseName,
{ shouldRetryOnError: false, revalidateOnFocus: false }
);
const { data: reverseName } = useTezosDomainNameByAddress(address);

useEffect(() => {
if (!isSupported) {
Expand Down
17 changes: 3 additions & 14 deletions src/app/templates/AddressChip.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React, { FC, useCallback } from 'react';

import classNames from 'clsx';
import useSWR from 'swr';

import { Button, HashChip } from 'app/atoms';
import { ReactComponent as GlobeIcon } from 'app/icons/globe.svg';
import { ReactComponent as HashIcon } from 'app/icons/hash.svg';
import { TestIDProps } from 'lib/analytics';
import { useTezos, useTezosDomainsClient, useStorage } from 'lib/temple/front';
import { useStorage } from 'lib/temple/front';
import { useTezosDomainNameByAddress } from 'lib/temple/front/tzdns';

type Props = TestIDProps & {
pkh: string;
Expand All @@ -19,18 +19,7 @@ type Props = TestIDProps & {
const TZDNS_MODE_ON_STORAGE_KEY = 'domain-displayed';

const AddressChip: FC<Props> = ({ pkh, className, small, modeSwitch, ...rest }) => {
const tezos = useTezos();
const { resolver: domainsResolver } = useTezosDomainsClient();

const resolveDomainReverseName = useCallback(
(_k: string, pkh: string) => domainsResolver.resolveAddressToName(pkh),
[domainsResolver]
);

const { data: tzdnsName } = useSWR(() => ['pkh-tzdns-name', pkh, tezos.checksum], resolveDomainReverseName, {
shouldRetryOnError: false,
revalidateOnFocus: false
});
const { data: tzdnsName } = useTezosDomainNameByAddress(pkh);

const [domainDisplayed, setDomainDisplayed] = useStorage(TZDNS_MODE_ON_STORAGE_KEY, false);

Expand Down
10 changes: 2 additions & 8 deletions src/app/templates/DelegateForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
useTezosDomainsClient,
validateDelegate
} from 'lib/temple/front';
import { useTezosAddressByDomainName } from 'lib/temple/front/tzdns';
import { hasManager, isAddressValid, isKTAddress, mutezToTz, tzToMutez } from 'lib/temple/helpers';
import { TempleAccountType } from 'lib/temple/types';
import { useSafeState } from 'lib/ui/hooks';
Expand Down Expand Up @@ -92,14 +93,7 @@ const DelegateForm: FC = () => {
() => toValue && isDomainNameValid(toValue, domainsClient),
[toValue, domainsClient]
);
const domainAddressFactory = useCallback(
(_k: string, _checksum: string, value: string) => domainsClient.resolver.resolveNameToAddress(value),
[domainsClient]
);
const { data: resolvedAddress } = useSWR(['tzdns-address', tezos.checksum, toValue], domainAddressFactory, {
shouldRetryOnError: false,
revalidateOnFocus: false
});
const { data: resolvedAddress } = useTezosAddressByDomainName(toValue);

const toFieldRef = useRef<HTMLTextAreaElement>(null);

Expand Down
2 changes: 1 addition & 1 deletion src/app/templates/InternalConfirmation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const InternalConfirmation: FC<InternalConfiramtionProps> = ({ payload, onConfir
if (tzToMutez(tezBalance).isLessThanOrEqualTo(totalTransactionCost)) {
dispatch(setOnRampPossibilityAction(true));
}
}, [tezBalance, totalTransactionCost]);
}, [dispatch, tezBalance, totalTransactionCost]);

const signPayloadFormats: ViewsSwitcherItemProps[] = useMemo(() => {
if (payload.type === 'operations') {
Expand Down
12 changes: 3 additions & 9 deletions src/app/templates/SendForm/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
useFilteredContacts,
validateRecipient
} from 'lib/temple/front';
import { useTezosAddressByDomainName } from 'lib/temple/front/tzdns';
import { hasManager, isAddressValid, isKTAddress, mutezToTz, tzToMutez } from 'lib/temple/helpers';
import { TempleAccountType, TempleAccount, TempleNetworkType } from 'lib/temple/types';
import { useSafeState } from 'lib/ui/hooks';
Expand Down Expand Up @@ -129,7 +130,7 @@ export const Form: FC<FormProps> = ({ assetSlug, setOperation, onAddContactReque
const amount = new BigNumber(getValues().amount);
setValue(
'amount',
(newShouldUseFiat ? amount.multipliedBy(assetPrice!) : amount.div(assetPrice!)).toFormat(
(newShouldUseFiat ? amount.multipliedBy(assetPrice) : amount.div(assetPrice)).toFormat(
newShouldUseFiat ? 2 : 6,
BigNumber.ROUND_FLOOR,
{
Expand Down Expand Up @@ -164,14 +165,7 @@ export const Form: FC<FormProps> = ({ assetSlug, setOperation, onAddContactReque
[toValue, domainsClient]
);

const domainAddressFactory = useCallback(
(_k: string, _checksum: string, address: string) => domainsClient.resolver.resolveNameToAddress(address),
[domainsClient]
);
const { data: resolvedAddress } = useSWR(['tzdns-address', tezos.checksum, toValue], domainAddressFactory, {
shouldRetryOnError: false,
revalidateOnFocus: false
});
const { data: resolvedAddress } = useTezosAddressByDomainName(toValue);

const toFilled = useMemo(
() => (resolvedAddress ? toFilledWithDomain : toFilledWithAddress),
Expand Down
23 changes: 7 additions & 16 deletions src/lib/i18n/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,23 +37,14 @@ export async function init() {
const saved = getSavedLocale();

if (saved) {
const native = getNativeLocale();
keshan3262 marked this conversation as resolved.
Show resolved Hide resolved

await Promise.all([
// Fetch target locale messages if needed
(async () => {
if (!areLocalesEqual(saved, native)) {
refetched.target = await fetchLocaleMessages(saved);
}
})(),
// Fetch fallback locale messages if needed
(async () => {
const deflt = getDefaultLocale();
if (!areLocalesEqual(deflt, native) && !areLocalesEqual(deflt, saved)) {
refetched.fallback = await fetchLocaleMessages(deflt);
}
})()
const deflt = getDefaultLocale();
const [newTargetLocale, newFallbackLocale] = await Promise.all([
!areLocalesEqual(saved, deflt) ? fetchLocaleMessages(saved) : null,
fetchLocaleMessages(deflt)
]);

refetched.target = newTargetLocale;
refetched.fallback = newFallbackLocale;
}

fetchedLocaleMessages = refetched;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/temple/front/assets.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useCallback, useMemo } from 'react';

import { isDefined } from '@rnw-community/shared';
import { ScopedMutator } from 'swr/dist/types';
import { ScopedMutator } from 'swr/_internal';

import { useTokensMetadataSelector } from 'app/store/tokens-metadata/selectors';
import { isTezAsset, TEMPLE_TOKEN_SLUG } from 'lib/assets';
Expand Down
8 changes: 7 additions & 1 deletion src/lib/temple/front/balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { useCallback, useMemo } from 'react';
import BigNumber from 'bignumber.js';

import { fetchBalance } from 'lib/balances';
import { TOKENS_SYNC_INTERVAL } from 'lib/fixed-times';
import { useAssetMetadata } from 'lib/metadata';
import { useRetryableSWR } from 'lib/swr';
import { michelEncoder, loadFastRpcClient } from 'lib/temple/helpers';
import { useInterval } from 'lib/ui/hooks';

import { useTezos, ReactiveTezosToolkit } from './ready';

Expand Down Expand Up @@ -37,12 +39,16 @@ export function useBalance(assetSlug: string, address: string, opts: UseBalanceO

const displayed = opts.displayed ?? true;

return useRetryableSWR(displayed ? getBalanceSWRKey(tezos, assetSlug, address) : null, fetchBalanceLocal, {
const result = useRetryableSWR(displayed ? getBalanceSWRKey(tezos, assetSlug, address) : null, fetchBalanceLocal, {
suspense: opts.suspense ?? true,
revalidateOnFocus: false,
dedupingInterval: 20_000,
fallbackData: opts.initial
});

useInterval(() => displayed && result.mutate(), TOKENS_SYNC_INTERVAL, [displayed], false);

return result;
keshan3262 marked this conversation as resolved.
Show resolved Hide resolved
}

export function getBalanceSWRKey(tezos: ReactiveTezosToolkit, assetSlug: string, address: string) {
Expand Down
2 changes: 1 addition & 1 deletion src/lib/temple/front/sync-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCallback, useState } from 'react';

import constate from 'constate';
import { useSWRConfig } from 'swr';
import { ScopedMutator } from 'swr/dist/types';
import { ScopedMutator } from 'swr/_internal';

import { fetchWhitelistTokenSlugs } from 'lib/apis/temple';
import { TzktAccountToken, fetchTzktTokens } from 'lib/apis/tzkt';
Expand Down
Loading