@lifi/widget 1.18.1 → 1.18.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AppRoutes.js +7 -3
- package/cjs/AppRoutes.js +7 -3
- package/cjs/components/BottomSheet/BottomSheet.js +2 -0
- package/cjs/components/ChainSelect/ChainSelect.js +1 -1
- package/cjs/components/Header/WalletHeader.js +1 -3
- package/cjs/components/SendToWallet/SendToWallet.js +1 -1
- package/cjs/components/SendToWallet/SendToWalletButton.js +9 -1
- package/cjs/components/SwapInput/FormPriceHelperText.js +1 -1
- package/cjs/components/SwapInput/SwapInputAdornment.js +1 -1
- package/cjs/components/SwapRouteCard/SwapRouteCard.js +4 -4
- package/cjs/components/SwapRouteCard/SwapRouteCardSkeleton.js +1 -1
- package/cjs/components/SwapRouteCard/types.d.ts +3 -2
- package/cjs/components/SwapRoutes/SwapRoutesExpanded.js +9 -5
- package/cjs/config/version.d.ts +1 -1
- package/cjs/config/version.js +1 -1
- package/cjs/hooks/index.d.ts +1 -1
- package/cjs/hooks/index.js +1 -1
- package/cjs/hooks/useGasSufficiency.js +10 -11
- package/cjs/hooks/useScrollableContainer.d.ts +0 -1
- package/cjs/hooks/useScrollableContainer.js +1 -15
- package/cjs/hooks/useTokenAddressBalance.d.ts +5 -0
- package/cjs/hooks/useTokenAddressBalance.js +19 -0
- package/cjs/hooks/useTokenBalance.d.ts +7 -3
- package/cjs/hooks/useTokenBalance.js +87 -9
- package/cjs/hooks/useTokenBalances.d.ts +1 -1
- package/cjs/hooks/useTokenBalances.js +1 -4
- package/cjs/i18n/en/translation.json +1 -1
- package/cjs/pages/SelectTokenPage/SelectTokenPage.js +1 -11
- package/cjs/pages/SwapPage/StatusBottomSheet.js +19 -6
- package/cjs/utils/index.d.ts +1 -0
- package/cjs/utils/index.js +1 -0
- package/cjs/utils/wallet.d.ts +1 -0
- package/cjs/utils/wallet.js +7 -0
- package/components/BottomSheet/BottomSheet.js +2 -0
- package/components/ChainSelect/ChainSelect.js +2 -2
- package/components/Header/WalletHeader.js +2 -4
- package/components/SendToWallet/SendToWallet.js +1 -1
- package/components/SendToWallet/SendToWalletButton.js +10 -2
- package/components/SwapInput/FormPriceHelperText.js +2 -2
- package/components/SwapInput/SwapInputAdornment.js +2 -2
- package/components/SwapRouteCard/SwapRouteCard.js +4 -4
- package/components/SwapRouteCard/SwapRouteCardSkeleton.js +1 -1
- package/components/SwapRouteCard/types.d.ts +3 -2
- package/components/SwapRoutes/SwapRoutesExpanded.js +9 -5
- package/config/version.d.ts +1 -1
- package/config/version.js +1 -1
- package/hooks/index.d.ts +1 -1
- package/hooks/index.js +1 -1
- package/hooks/useGasSufficiency.js +11 -12
- package/hooks/useScrollableContainer.d.ts +0 -1
- package/hooks/useScrollableContainer.js +0 -13
- package/hooks/useTokenAddressBalance.d.ts +5 -0
- package/hooks/useTokenAddressBalance.js +15 -0
- package/hooks/useTokenBalance.d.ts +7 -3
- package/hooks/useTokenBalance.js +88 -10
- package/hooks/useTokenBalances.d.ts +1 -1
- package/hooks/useTokenBalances.js +1 -4
- package/i18n/en/translation.json +1 -1
- package/package.json +5 -5
- package/pages/SelectTokenPage/SelectTokenPage.js +2 -12
- package/pages/SwapPage/StatusBottomSheet.js +19 -6
- package/tsconfig.cjs.tsbuildinfo +1 -1
- package/utils/index.d.ts +1 -0
- package/utils/index.js +1 -0
- package/utils/wallet.d.ts +1 -0
- package/utils/wallet.js +3 -0
- package/cjs/components/SwapButton/ButtonTooltip.d.ts +0 -5
- package/cjs/components/SwapButton/ButtonTooltip.js +0 -7
- package/cjs/hooks/useContentHeight.d.ts +0 -1
- package/cjs/hooks/useContentHeight.js +0 -27
- package/components/SwapButton/ButtonTooltip.d.ts +0 -5
- package/components/SwapButton/ButtonTooltip.js +0 -3
- package/hooks/useContentHeight.d.ts +0 -1
- package/hooks/useContentHeight.js +0 -23
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.StatusBottomSheet = void 0;
|
|
4
4
|
const jsx_runtime_1 = require("react/jsx-runtime");
|
|
5
|
+
/* eslint-disable consistent-return */
|
|
5
6
|
const icons_material_1 = require("@mui/icons-material");
|
|
6
7
|
const material_1 = require("@mui/material");
|
|
7
8
|
const react_1 = require("react");
|
|
@@ -11,17 +12,18 @@ const BottomSheet_1 = require("../../components/BottomSheet");
|
|
|
11
12
|
const Token_1 = require("../../components/Token");
|
|
12
13
|
const hooks_1 = require("../../hooks");
|
|
13
14
|
const providers_1 = require("../../providers");
|
|
15
|
+
const utils_1 = require("../../utils");
|
|
14
16
|
const StatusBottomSheet_style_1 = require("./StatusBottomSheet.style");
|
|
15
17
|
const StatusBottomSheet = ({ status, route, }) => {
|
|
16
18
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
17
19
|
const { t } = (0, react_i18next_1.useTranslation)();
|
|
18
|
-
const { navigateBack } = (0, hooks_1.useNavigateBack)();
|
|
20
|
+
const { navigateBack, navigate } = (0, hooks_1.useNavigateBack)();
|
|
19
21
|
const ref = (0, react_1.useRef)(null);
|
|
20
22
|
const { getChainById } = (0, hooks_1.useChains)();
|
|
21
|
-
const { token, refetch
|
|
23
|
+
const { token, refetch, refetchNewBalance, refetchAllBalances } = (0, hooks_1.useTokenBalance)(route.toToken, route.toAddress);
|
|
22
24
|
const { setValue } = (0, react_hook_form_1.useFormContext)();
|
|
23
25
|
const clearFromAmount = () => {
|
|
24
|
-
|
|
26
|
+
refetchAllBalances();
|
|
25
27
|
setValue(providers_1.SwapFormKey.FromAmount, '');
|
|
26
28
|
};
|
|
27
29
|
const handleDone = () => {
|
|
@@ -33,6 +35,13 @@ const StatusBottomSheet = ({ status, route, }) => {
|
|
|
33
35
|
clearFromAmount();
|
|
34
36
|
(_a = ref.current) === null || _a === void 0 ? void 0 : _a.closeDrawer();
|
|
35
37
|
};
|
|
38
|
+
const handleSeeDetails = () => {
|
|
39
|
+
handleClose();
|
|
40
|
+
navigate(utils_1.navigationRoutes.swapDetails, {
|
|
41
|
+
state: { routeId: route.id },
|
|
42
|
+
replace: true,
|
|
43
|
+
});
|
|
44
|
+
};
|
|
36
45
|
let title;
|
|
37
46
|
let message;
|
|
38
47
|
switch (status) {
|
|
@@ -42,6 +51,7 @@ const StatusBottomSheet = ({ status, route, }) => {
|
|
|
42
51
|
amount: token === null || token === void 0 ? void 0 : token.amount,
|
|
43
52
|
tokenSymbol: token === null || token === void 0 ? void 0 : token.symbol,
|
|
44
53
|
chainName: (_a = getChainById(route.toChainId)) === null || _a === void 0 ? void 0 : _a.name,
|
|
54
|
+
walletAddress: (0, utils_1.shortenWalletAddress)(route.toAddress),
|
|
45
55
|
});
|
|
46
56
|
break;
|
|
47
57
|
case 'error': {
|
|
@@ -62,10 +72,13 @@ const StatusBottomSheet = ({ status, route, }) => {
|
|
|
62
72
|
var _a, _b;
|
|
63
73
|
if ((status === 'success' || status === 'error') &&
|
|
64
74
|
!((_a = ref.current) === null || _a === void 0 ? void 0 : _a.isOpen())) {
|
|
65
|
-
|
|
75
|
+
if (status === 'success') {
|
|
76
|
+
refetchNewBalance();
|
|
77
|
+
refetch();
|
|
78
|
+
}
|
|
66
79
|
(_b = ref.current) === null || _b === void 0 ? void 0 : _b.openDrawer();
|
|
67
80
|
}
|
|
68
|
-
}, [
|
|
69
|
-
return ((0, jsx_runtime_1.jsx)(BottomSheet_1.BottomSheet, Object.assign({ ref: ref }, { children: (0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ p: 3 }, { children: [(0, jsx_runtime_1.jsxs)(StatusBottomSheet_style_1.IconContainer, { children: [(0, jsx_runtime_1.jsxs)(StatusBottomSheet_style_1.IconCircle, Object.assign({ status: status, mb: 1 }, { children: [status === 'idle' ? ((0, jsx_runtime_1.jsx)(icons_material_1.Info, { color: "primary", sx: StatusBottomSheet_style_1.iconStyles })) : null, status === 'success' ? ((0, jsx_runtime_1.jsx)(icons_material_1.Done, { color: "success", sx: StatusBottomSheet_style_1.iconStyles })) : null, status === 'error' ? ((0, jsx_runtime_1.jsx)(icons_material_1.Warning, { color: "error", sx: StatusBottomSheet_style_1.iconStyles })) : null] })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ py: 1, fontSize: 18, fontWeight: 700 }, { children: title })), status === 'success' ? ((0, jsx_runtime_1.jsx)(Token_1.Token, { token: Object.assign(Object.assign({}, route.toToken), { amount: (_g = (_e = (_d = (_c = route.steps.at(-1)) === null || _c === void 0 ? void 0 : _c.execution) === null || _d === void 0 ? void 0 : _d.toAmount) !== null && _e !== void 0 ? _e : (_f = route.steps.at(-1)) === null || _f === void 0 ? void 0 : _f.estimate.toAmount) !== null && _g !== void 0 ? _g : route.toAmount }), py: 1 })) : null] }), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ pt: 2, pb: 1 }, { children: message })), (0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ mt: 2 }, { children: (0, jsx_runtime_1.jsxs)(material_1.Button, Object.assign({ variant: "contained", fullWidth: true, onClick: status === 'success' ? handleDone : handleClose }, { children: [status === 'idle' ? t('button.okay') : null, status === 'success' ? t('button.done') : null, status === 'error' ? t('button.tryAgain') : null] })) })), status === 'success' ? ((0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ mt: 2 }, { children: (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ variant: "outlined", fullWidth: true, onClick:
|
|
81
|
+
}, [refetch, refetchNewBalance, status]);
|
|
82
|
+
return ((0, jsx_runtime_1.jsx)(BottomSheet_1.BottomSheet, Object.assign({ ref: ref }, { children: (0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ p: 3 }, { children: [(0, jsx_runtime_1.jsxs)(StatusBottomSheet_style_1.IconContainer, { children: [(0, jsx_runtime_1.jsxs)(StatusBottomSheet_style_1.IconCircle, Object.assign({ status: status, mb: 1 }, { children: [status === 'idle' ? ((0, jsx_runtime_1.jsx)(icons_material_1.Info, { color: "primary", sx: StatusBottomSheet_style_1.iconStyles })) : null, status === 'success' ? ((0, jsx_runtime_1.jsx)(icons_material_1.Done, { color: "success", sx: StatusBottomSheet_style_1.iconStyles })) : null, status === 'error' ? ((0, jsx_runtime_1.jsx)(icons_material_1.Warning, { color: "error", sx: StatusBottomSheet_style_1.iconStyles })) : null] })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ py: 1, fontSize: 18, fontWeight: 700 }, { children: title })), status === 'success' ? ((0, jsx_runtime_1.jsx)(Token_1.Token, { token: Object.assign(Object.assign({}, route.toToken), { amount: (_g = (_e = (_d = (_c = route.steps.at(-1)) === null || _c === void 0 ? void 0 : _c.execution) === null || _d === void 0 ? void 0 : _d.toAmount) !== null && _e !== void 0 ? _e : (_f = route.steps.at(-1)) === null || _f === void 0 ? void 0 : _f.estimate.toAmount) !== null && _g !== void 0 ? _g : route.toAmount }), py: 1 })) : null] }), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ pt: 2, pb: 1 }, { children: message })), (0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ mt: 2 }, { children: (0, jsx_runtime_1.jsxs)(material_1.Button, Object.assign({ variant: "contained", fullWidth: true, onClick: status === 'success' ? handleDone : handleClose }, { children: [status === 'idle' ? t('button.okay') : null, status === 'success' ? t('button.done') : null, status === 'error' ? t('button.tryAgain') : null] })) })), status === 'success' ? ((0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ mt: 2 }, { children: (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ variant: "outlined", fullWidth: true, onClick: handleSeeDetails }, { children: t('button.seeDetails') })) }))) : null] })) })));
|
|
70
83
|
};
|
|
71
84
|
exports.StatusBottomSheet = StatusBottomSheet;
|
package/cjs/utils/index.d.ts
CHANGED
package/cjs/utils/index.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const shortenWalletAddress: (address?: string) => string | null;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.shortenWalletAddress = void 0;
|
|
4
|
+
const shortenWalletAddress = (address) => address
|
|
5
|
+
? `${address.substring(0, 5)}...${address.substring(address.length - 4)}`
|
|
6
|
+
: null;
|
|
7
|
+
exports.shortenWalletAddress = shortenWalletAddress;
|
|
@@ -8,9 +8,11 @@ export const BottomSheet = forwardRef(({ elementRef, children, open }, ref) => {
|
|
|
8
8
|
const containerElement = useScrollableContainer();
|
|
9
9
|
const openDrawer = useCallback(() => {
|
|
10
10
|
setDrawerOpen(true);
|
|
11
|
+
openRef.current = true;
|
|
11
12
|
}, []);
|
|
12
13
|
const closeDrawer = useCallback(() => {
|
|
13
14
|
setDrawerOpen(false);
|
|
15
|
+
openRef.current = false;
|
|
14
16
|
}, []);
|
|
15
17
|
useImperativeHandle(ref, () => ({
|
|
16
18
|
isOpen: () => openRef.current,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { Avatar, Box, Skeleton, Typography } from '@mui/material';
|
|
2
|
+
import { Avatar, Box, Skeleton, Tooltip, Typography } from '@mui/material';
|
|
3
3
|
import { useWatch } from 'react-hook-form';
|
|
4
4
|
import { useNavigate } from 'react-router-dom';
|
|
5
5
|
import { SwapFormKeyHelper } from '../../providers';
|
|
@@ -22,7 +22,7 @@ export const ChainSelect = ({ formType }) => {
|
|
|
22
22
|
const chainsToHide = ((_a = chains === null || chains === void 0 ? void 0 : chains.length) !== null && _a !== void 0 ? _a : 0) - maxChainToOrder;
|
|
23
23
|
return (_jsxs(ChainContainer, { children: [isLoading
|
|
24
24
|
? Array.from({ length: maxChainToOrder + 1 }).map((_, index) => (_jsx(Skeleton, { variant: "rectangular", width: 56, height: 56, sx: { borderRadius: 1 } }, index)))
|
|
25
|
-
: getChains().map((chain) => (_jsx(ChainCard, Object.assign({ onClick: () => setCurrentChain(chain.id), variant: chainId === chain.id ? 'selected' : 'default' }, { children: _jsx(Avatar, Object.assign({ src: chain.logoURI, alt: chain.key, sx: { width: 40, height: 40 } }, { children: chain.name[0] })) }), chain.id))), chainsToHide > 0 ? (_jsx(ChainCard, Object.assign({ onClick: showAllChains }, { children: _jsx(Box, Object.assign({ sx: {
|
|
25
|
+
: getChains().map((chain) => (_jsx(Tooltip, Object.assign({ title: chain.name, placement: "top", enterDelay: 500, enterNextDelay: 500, arrow: true }, { children: _jsx(ChainCard, Object.assign({ onClick: () => setCurrentChain(chain.id), variant: chainId === chain.id ? 'selected' : 'default' }, { children: _jsx(Avatar, Object.assign({ src: chain.logoURI, alt: chain.key, sx: { width: 40, height: 40 } }, { children: chain.name[0] })) })) }), chain.id))), chainsToHide > 0 ? (_jsx(ChainCard, Object.assign({ onClick: showAllChains }, { children: _jsx(Box, Object.assign({ sx: {
|
|
26
26
|
width: 40,
|
|
27
27
|
height: 40,
|
|
28
28
|
display: 'grid',
|
|
@@ -13,14 +13,12 @@ import { Box, IconButton, Typography } from '@mui/material';
|
|
|
13
13
|
import { useTranslation } from 'react-i18next';
|
|
14
14
|
import { useLocation, useNavigate } from 'react-router-dom';
|
|
15
15
|
import { useWallet, useWidgetConfig } from '../../providers';
|
|
16
|
-
import { navigationRoutes } from '../../utils';
|
|
16
|
+
import { navigationRoutes, shortenWalletAddress } from '../../utils';
|
|
17
17
|
import { HeaderAppBar } from './Header.style';
|
|
18
18
|
export const WalletHeader = () => {
|
|
19
19
|
const { t } = useTranslation();
|
|
20
20
|
const { account, disconnect } = useWallet();
|
|
21
|
-
const walletAddress = account.address
|
|
22
|
-
? `${account.address.substring(0, 7)}...${account.address.substring(account.address.length - 7)}`
|
|
23
|
-
: null;
|
|
21
|
+
const walletAddress = shortenWalletAddress(account.address);
|
|
24
22
|
return (_jsx(HeaderAppBar, Object.assign({ elevation: 0 }, { children: walletAddress ? (_jsxs(_Fragment, { children: [_jsxs(Box, Object.assign({ sx: {
|
|
25
23
|
display: 'flex',
|
|
26
24
|
flex: 1,
|
|
@@ -42,5 +42,5 @@ export const SendToWallet = forwardRef((props, ref) => {
|
|
|
42
42
|
}),
|
|
43
43
|
onBlur: () => trigger(SwapFormKey.ToAddress),
|
|
44
44
|
});
|
|
45
|
-
return (_jsx(Collapse, Object.assign({ timeout: 225, in: showSendToWallet }, { children: _jsxs(Card, Object.assign({}, props, { ref: ref }, { children: [_jsx(CardTitle, { children: t('swap.sendToWallet') }), _jsxs(FormControl, Object.assign({ fullWidth: true, sx: { paddingTop: '6px', paddingBottom: '5px' } }, { children: [_jsx(Input, { ref: inputRef, size: "small", autoComplete: "off", autoCorrect: "off", autoCapitalize: "off", spellCheck: "false", onChange: onChange, onBlur: onBlur, name: name, placeholder: t('swap.walletAddressOrEns') }), _jsx(FormHelperText, Object.assign({ error: !!errors.toAddress }, { children: (_a = errors.toAddress) === null || _a === void 0 ? void 0 : _a.message }))] }))] })) })));
|
|
45
|
+
return (_jsx(Collapse, Object.assign({ timeout: 225, unmountOnExit: true, mountOnEnter: true, in: showSendToWallet }, { children: _jsxs(Card, Object.assign({}, props, { ref: ref }, { children: [_jsx(CardTitle, { children: t('swap.sendToWallet') }), _jsxs(FormControl, Object.assign({ fullWidth: true, sx: { paddingTop: '6px', paddingBottom: '5px' } }, { children: [_jsx(Input, { ref: inputRef, size: "small", autoComplete: "off", autoCorrect: "off", autoCapitalize: "off", spellCheck: "false", onChange: onChange, onBlur: onBlur, name: name, placeholder: t('swap.walletAddressOrEns'), autoFocus: true }), _jsx(FormHelperText, Object.assign({ error: !!errors.toAddress }, { children: (_a = errors.toAddress) === null || _a === void 0 ? void 0 : _a.message }))] }))] })) })));
|
|
46
46
|
});
|
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
2
|
import { WalletOutlined as WalletOutlinedIcon } from '@mui/icons-material';
|
|
3
3
|
import { Button, Tooltip } from '@mui/material';
|
|
4
|
+
import { useFormContext } from 'react-hook-form';
|
|
4
5
|
import { useTranslation } from 'react-i18next';
|
|
5
|
-
import { useWallet } from '../../providers';
|
|
6
|
+
import { SwapFormKey, useWallet } from '../../providers';
|
|
6
7
|
import { useSettings } from '../../stores';
|
|
7
8
|
import { useSendToWalletStore } from './store';
|
|
8
9
|
export const SendToWalletButton = () => {
|
|
9
10
|
const { t } = useTranslation();
|
|
10
11
|
const { account } = useWallet();
|
|
12
|
+
const { setValue } = useFormContext();
|
|
11
13
|
const { showDestinationWallet } = useSettings(['showDestinationWallet']);
|
|
12
14
|
const { showSendToWallet, toggleSendToWallet } = useSendToWalletStore();
|
|
13
15
|
if (!showDestinationWallet || !account.isActive) {
|
|
14
16
|
return null;
|
|
15
17
|
}
|
|
16
|
-
|
|
18
|
+
const handleClick = () => {
|
|
19
|
+
if (showSendToWallet) {
|
|
20
|
+
setValue(SwapFormKey.ToAddress, '');
|
|
21
|
+
}
|
|
22
|
+
toggleSendToWallet();
|
|
23
|
+
};
|
|
24
|
+
return (_jsx(Tooltip, Object.assign({ title: t('swap.sendToWallet'), placement: "bottom-end", enterDelay: 500, enterNextDelay: 500, arrow: true }, { children: _jsx(Button, Object.assign({ variant: showSendToWallet ? 'contained' : 'text', onClick: handleClick, sx: {
|
|
17
25
|
minWidth: 48,
|
|
18
26
|
marginLeft: 1,
|
|
19
27
|
} }, { children: _jsx(WalletOutlinedIcon, {}) })) })));
|
|
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { FormHelperText, Skeleton, Typography } from '@mui/material';
|
|
3
3
|
import { useWatch } from 'react-hook-form';
|
|
4
4
|
import { useTranslation } from 'react-i18next';
|
|
5
|
-
import {
|
|
5
|
+
import { useTokenAddressBalance } from '../../hooks';
|
|
6
6
|
import { SwapFormKeyHelper } from '../../providers';
|
|
7
7
|
import { formatTokenPrice } from '../../utils';
|
|
8
8
|
export const FormPriceHelperText = ({ formType, selected }) => {
|
|
@@ -14,7 +14,7 @@ export const FormPriceHelperText = ({ formType, selected }) => {
|
|
|
14
14
|
SwapFormKeyHelper.getTokenKey(formType),
|
|
15
15
|
],
|
|
16
16
|
});
|
|
17
|
-
const { token, isLoading } =
|
|
17
|
+
const { token, isLoading } = useTokenAddressBalance(chainId, tokenAddress);
|
|
18
18
|
const fromAmountTokenPrice = formatTokenPrice(amount, token === null || token === void 0 ? void 0 : token.priceUSD);
|
|
19
19
|
return (_jsxs(FormHelperText, Object.assign({ component: "div", sx: { display: 'flex', justifyContent: 'space-between', margin: 0 } }, { children: [_jsx(Typography, Object.assign({ color: fromAmountTokenPrice ? 'text.secondary' : 'grey.600', fontWeight: 400, fontSize: 12, marginLeft: selected ? 8 : 2, lineHeight: 1.3334, flex: 1, sx: {
|
|
20
20
|
wordBreak: 'break-word',
|
|
@@ -2,7 +2,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
|
|
|
2
2
|
import { InputAdornment, Skeleton } from '@mui/material';
|
|
3
3
|
import { useFormContext, useWatch } from 'react-hook-form';
|
|
4
4
|
import { useTranslation } from 'react-i18next';
|
|
5
|
-
import {
|
|
5
|
+
import { useTokenAddressBalance } from '../../hooks';
|
|
6
6
|
import { SwapFormKeyHelper } from '../../providers';
|
|
7
7
|
import { Button } from './SwapInputAdornment.style';
|
|
8
8
|
export const SwapInputAdornment = ({ formType }) => {
|
|
@@ -14,7 +14,7 @@ export const SwapInputAdornment = ({ formType }) => {
|
|
|
14
14
|
SwapFormKeyHelper.getTokenKey(formType),
|
|
15
15
|
],
|
|
16
16
|
});
|
|
17
|
-
const { token, isLoading } =
|
|
17
|
+
const { token, isLoading } = useTokenAddressBalance(chainId, tokenAddress);
|
|
18
18
|
const handleMax = () => {
|
|
19
19
|
var _a;
|
|
20
20
|
setValue(SwapFormKeyHelper.getAmountKey(formType), (_a = token === null || token === void 0 ? void 0 : token.amount) !== null && _a !== void 0 ? _a : '');
|
|
@@ -20,18 +20,18 @@ import { Token } from '../Token';
|
|
|
20
20
|
import { IconButton, Label } from './SwapRouteCard.style';
|
|
21
21
|
export const SwapRouteCard = (_a) => {
|
|
22
22
|
var _b;
|
|
23
|
-
var { route, active, variant = 'default' } = _a, other = __rest(_a, ["route", "active", "variant"]);
|
|
23
|
+
var { route, active, variant = 'default', expanded } = _a, other = __rest(_a, ["route", "active", "variant", "expanded"]);
|
|
24
24
|
const { t } = useTranslation();
|
|
25
|
-
const [
|
|
25
|
+
const [cardExpanded, setCardExpanded] = useState(variant === 'default' || expanded);
|
|
26
26
|
const alternativeTag = t(`swap.tags.ALTERNATIVE`);
|
|
27
27
|
const label = ((_b = route.tags) === null || _b === void 0 ? void 0 : _b.length)
|
|
28
28
|
? t(`swap.tags.${route.tags[0]}`)
|
|
29
29
|
: alternativeTag;
|
|
30
30
|
const handleExpand = (e) => {
|
|
31
31
|
e.stopPropagation();
|
|
32
|
-
|
|
32
|
+
setCardExpanded((expanded) => !expanded);
|
|
33
33
|
};
|
|
34
|
-
return (_jsxs(Card, Object.assign({ dense: variant === 'dense', variant: active ? 'selected' : 'default', selectionColor: "secondary", indented: true }, other, { children: [_jsxs(Box, Object.assign({ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2 }, { children: [_jsx(Label, Object.assign({ active: active !== null && active !== void 0 ? active : label !== alternativeTag }, { children: label })), variant === '
|
|
34
|
+
return (_jsxs(Card, Object.assign({ dense: variant === 'dense', variant: active ? 'selected' : 'default', selectionColor: "secondary", indented: true }, other, { children: [_jsxs(Box, Object.assign({ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2 }, { children: [_jsx(Label, Object.assign({ active: active !== null && active !== void 0 ? active : label !== alternativeTag }, { children: label })), variant === 'stretched' ? (_jsx(SwapRouteCardEssentials, { route: route })) : null] })), _jsxs(Box, Object.assign({ display: "flex", justifyContent: "space-between", alignItems: "center" }, { children: [_jsx(Token, { token: Object.assign(Object.assign({}, route.toToken), { amount: route.toAmount }), step: variant === 'stretched' ? route.steps[0] : undefined }), variant === 'stretched' && !expanded ? (_jsx(IconButton, Object.assign({ onClick: handleExpand, size: "small" }, { children: cardExpanded ? _jsx(ExpandLessIcon, {}) : _jsx(ExpandMoreIcon, {}) }))) : null] })), _jsx(Collapse, Object.assign({ mountOnEnter: true, unmountOnExit: true, in: cardExpanded }, { children: route.steps.map((step) => (_jsx(StepActions, { step: step, mt: 2 }, step.id))) })), variant !== 'stretched' ? (_jsx(SwapRouteCardEssentials, { route: route, dense: true })) : null] })));
|
|
35
35
|
};
|
|
36
36
|
export const SwapRouteCardEssentials = ({ route, dense }) => {
|
|
37
37
|
var _a;
|
|
@@ -14,5 +14,5 @@ import { Box, Skeleton } from '@mui/material';
|
|
|
14
14
|
import { Card } from '../Card';
|
|
15
15
|
export const SwapRouteCardSkeleton = (_a) => {
|
|
16
16
|
var { variant } = _a, other = __rest(_a, ["variant"]);
|
|
17
|
-
return (_jsxs(Card, Object.assign({ dense: variant === 'dense', indented: true }, other, { children: [_jsxs(Box, Object.assign({ display: "flex", justifyContent: "space-between", alignItems: "center" }, { children: [_jsx(Skeleton, { variant: "rectangular", width: 118, height: 24, sx: { borderRadius: 0.5 } }), variant === '
|
|
17
|
+
return (_jsxs(Card, Object.assign({ dense: variant === 'dense', indented: true }, other, { children: [_jsxs(Box, Object.assign({ display: "flex", justifyContent: "space-between", alignItems: "center" }, { children: [_jsx(Skeleton, { variant: "rectangular", width: 118, height: 24, sx: { borderRadius: 0.5 } }), variant === 'stretched' ? (_jsxs(Box, Object.assign({ display: "flex" }, { children: [_jsx(Skeleton, { variant: "text", width: 52, height: 24, sx: { marginRight: 2 } }), _jsx(Skeleton, { variant: "text", width: 44, height: 24, sx: { marginRight: 2 } }), _jsx(Skeleton, { variant: "text", width: 32, height: 24 })] }))) : null] })), _jsxs(Box, Object.assign({ mt: 2 }, { children: [_jsxs(Box, Object.assign({ display: "flex", alignItems: "center" }, { children: [_jsx(Box, Object.assign({ mr: 2 }, { children: _jsx(Skeleton, { variant: "circular", width: 32, height: 32 }) })), _jsx(Skeleton, { variant: "text", width: 96, height: 32 })] })), _jsxs(Box, Object.assign({ ml: 6, display: "flex", alignItems: "center" }, { children: [_jsx(Skeleton, { variant: "text", width: 102, height: 16, sx: { borderRadius: 0.5 } }), variant === 'stretched' ? (_jsx(Skeleton, { variant: "text", width: 72, height: 16, sx: { marginLeft: 1 } })) : null] }))] })), variant !== 'stretched' ? (_jsxs(Box, Object.assign({ mt: 2, display: "flex", justifyContent: "space-between" }, { children: [_jsx(Skeleton, { variant: "text", width: 48, height: 24 }), _jsx(Skeleton, { variant: "text", width: 48, height: 24 })] }))) : null] })));
|
|
18
18
|
};
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import type { Route } from '@lifi/sdk';
|
|
2
2
|
export interface SwapRouteCardProps {
|
|
3
3
|
route: Route;
|
|
4
|
-
variant?: 'default' | '
|
|
4
|
+
variant?: 'default' | 'stretched' | 'dense';
|
|
5
5
|
active?: boolean;
|
|
6
|
+
expanded?: boolean;
|
|
6
7
|
}
|
|
7
8
|
export interface SwapRouteCardEssentialsProps {
|
|
8
9
|
route: Route;
|
|
9
10
|
dense?: boolean;
|
|
10
11
|
}
|
|
11
12
|
export interface SwapRouteCardSkeletonProps {
|
|
12
|
-
variant?: 'default' | '
|
|
13
|
+
variant?: 'default' | 'stretched' | 'dense';
|
|
13
14
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { Collapse, Grow, Stack, Typography } from '@mui/material';
|
|
3
|
+
import { useFormState } from 'react-hook-form';
|
|
3
4
|
import { useTranslation } from 'react-i18next';
|
|
4
5
|
import { useLocation, useNavigate } from 'react-router-dom';
|
|
5
6
|
import { useSwapRoutes } from '../../hooks';
|
|
@@ -14,6 +15,7 @@ export const SwapRoutesExpanded = () => {
|
|
|
14
15
|
const { containerStyle } = useWidgetConfig();
|
|
15
16
|
const navigate = useNavigate();
|
|
16
17
|
const { routes, isLoading, isFetching, isFetched, dataUpdatedAt, refetchTime, refetch, } = useSwapRoutes();
|
|
18
|
+
const { isValid, isValidating } = useFormState();
|
|
17
19
|
const setExecutableRoute = useSetExecutableRoute();
|
|
18
20
|
const { pathname } = useLocation();
|
|
19
21
|
const cleanedPathname = pathname.endsWith('/')
|
|
@@ -22,13 +24,15 @@ export const SwapRoutesExpanded = () => {
|
|
|
22
24
|
const path = cleanedPathname.substring(cleanedPathname.lastIndexOf('/') + 1);
|
|
23
25
|
const hasPath = navigationRoutesValues.includes(path);
|
|
24
26
|
const handleRouteClick = (route) => {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
if (isValid && !isValidating) {
|
|
28
|
+
setExecutableRoute(route);
|
|
29
|
+
navigate(navigationRoutes.swapExecution, {
|
|
30
|
+
state: { routeId: route.id },
|
|
31
|
+
});
|
|
32
|
+
}
|
|
29
33
|
};
|
|
30
34
|
const currentRoute = routes === null || routes === void 0 ? void 0 : routes[0];
|
|
31
35
|
const expanded = Boolean(currentRoute || isLoading || isFetching || isFetched) && !hasPath;
|
|
32
36
|
const routeNotFound = !currentRoute && !isLoading && !isFetching && expanded;
|
|
33
|
-
return (_jsx(CollapseContainer, { children: _jsx(Collapse, Object.assign({ appear: true, timeout: 225, in: expanded, orientation: "horizontal" }, { children: _jsx(Grow, Object.assign({ appear: true, timeout: 225, in: expanded }, { children: _jsx(Container, Object.assign({ sx: containerStyle }, { children: _jsxs(ScrollableContainer, { children: [_jsxs(Header, { children: [_jsx(Typography, Object.assign({ fontSize: 18, fontWeight: "700", flex: 1, noWrap: true }, { children: t('swap.routes') })), _jsx(ProgressToNextUpdate, { updatedAt: dataUpdatedAt || new Date().getTime(), timeToUpdate: refetchTime, isLoading: isFetching, onClick: () => refetch(), sx: { marginRight: -1 } })] }), _jsx(Stack, Object.assign({ direction: "column", spacing: 2, flex: 1, paddingX: 3, paddingBottom: 3 }, { children: routeNotFound ? (_jsx(SwapRouteNotFoundCard, {})) : isLoading || isFetching ? (Array.from({ length: 3 }).map((_, index) => (_jsx(SwapRouteCardSkeleton, { variant: "
|
|
37
|
+
return (_jsx(CollapseContainer, { children: _jsx(Collapse, Object.assign({ appear: true, timeout: 225, in: expanded, orientation: "horizontal" }, { children: _jsx(Grow, Object.assign({ appear: true, timeout: 225, in: expanded }, { children: _jsx(Container, Object.assign({ sx: containerStyle }, { children: _jsxs(ScrollableContainer, { children: [_jsxs(Header, { children: [_jsx(Typography, Object.assign({ fontSize: 18, fontWeight: "700", flex: 1, noWrap: true }, { children: t('swap.routes') })), _jsx(ProgressToNextUpdate, { updatedAt: dataUpdatedAt || new Date().getTime(), timeToUpdate: refetchTime, isLoading: isFetching, onClick: () => refetch(), sx: { marginRight: -1 } })] }), _jsx(Stack, Object.assign({ direction: "column", spacing: 2, flex: 1, paddingX: 3, paddingBottom: 3 }, { children: routeNotFound ? (_jsx(SwapRouteNotFoundCard, {})) : isLoading || isFetching ? (Array.from({ length: 3 }).map((_, index) => (_jsx(SwapRouteCardSkeleton, { variant: "stretched" }, index)))) : (routes === null || routes === void 0 ? void 0 : routes.map((route, index) => (_jsx(SwapRouteCard, { route: route, onClick: () => handleRouteClick(route), active: index === 0, variant: "stretched", expanded: (routes === null || routes === void 0 ? void 0 : routes.length) <= 2 }, route.id)))) }))] }) })) })) })) }));
|
|
34
38
|
};
|
package/config/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const name = "@lifi/widget";
|
|
2
|
-
export declare const version = "1.18.
|
|
2
|
+
export declare const version = "1.18.3";
|
package/config/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export const name = '@lifi/widget';
|
|
2
|
-
export const version = '1.18.
|
|
2
|
+
export const version = '1.18.3';
|
package/hooks/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
export * from './useChain';
|
|
2
2
|
export * from './useChains';
|
|
3
|
-
export * from './useContentHeight';
|
|
4
3
|
export * from './useDebouncedWatch';
|
|
5
4
|
export * from './useFeaturedTokens';
|
|
6
5
|
export * from './useGasSufficiency';
|
|
@@ -12,6 +11,7 @@ export * from './useScrollableContainer';
|
|
|
12
11
|
export * from './useSwapRoutes';
|
|
13
12
|
export * from './useTelemetry';
|
|
14
13
|
export * from './useToken';
|
|
14
|
+
export * from './useTokenAddressBalance';
|
|
15
15
|
export * from './useTokenBalance';
|
|
16
16
|
export * from './useTokenBalances';
|
|
17
17
|
export * from './useTokens';
|
package/hooks/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
export * from './useChain';
|
|
2
2
|
export * from './useChains';
|
|
3
|
-
export * from './useContentHeight';
|
|
4
3
|
export * from './useDebouncedWatch';
|
|
5
4
|
export * from './useFeaturedTokens';
|
|
6
5
|
export * from './useGasSufficiency';
|
|
@@ -12,6 +11,7 @@ export * from './useScrollableContainer';
|
|
|
12
11
|
export * from './useSwapRoutes';
|
|
13
12
|
export * from './useTelemetry';
|
|
14
13
|
export * from './useToken';
|
|
14
|
+
export * from './useTokenAddressBalance';
|
|
15
15
|
export * from './useTokenBalance';
|
|
16
16
|
export * from './useTokenBalances';
|
|
17
17
|
export * from './useTokens';
|
|
@@ -10,17 +10,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
import Big from 'big.js';
|
|
11
11
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
|
12
12
|
import { useChains } from '.';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
13
|
+
import { useWallet } from '../providers';
|
|
14
|
+
import { useTokenBalance } from './useTokenBalance';
|
|
15
15
|
export const useGasSufficiency = (route) => {
|
|
16
|
-
const lifi = useLiFi();
|
|
17
16
|
const { account } = useWallet();
|
|
18
17
|
const { getChainById } = useChains();
|
|
19
|
-
const {
|
|
18
|
+
const { token: fromToken, getTokenBalancesWithRetry } = useTokenBalance(route === null || route === void 0 ? void 0 : route.fromToken);
|
|
20
19
|
const [insufficientGas, setInsufficientGas] = useState();
|
|
21
20
|
const checkInsufficientGas = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
|
|
22
21
|
var _a, _b;
|
|
23
|
-
if (!account.
|
|
22
|
+
if (!account.address || !route) {
|
|
24
23
|
setInsufficientGas(undefined);
|
|
25
24
|
return;
|
|
26
25
|
}
|
|
@@ -47,7 +46,7 @@ export const useGasSufficiency = (route) => {
|
|
|
47
46
|
if (route.fromToken.address === ((_a = gasCosts[route.fromChainId]) === null || _a === void 0 ? void 0 : _a.token.address)) {
|
|
48
47
|
gasCosts[route.fromChainId].tokenAmount = (_b = gasCosts[route.fromChainId]) === null || _b === void 0 ? void 0 : _b.gasAmount.plus(Big(route.fromAmount).div(Math.pow(10, route.fromToken.decimals)));
|
|
49
48
|
}
|
|
50
|
-
const tokenBalances = yield
|
|
49
|
+
const tokenBalances = yield getTokenBalancesWithRetry(account.address, Object.values(gasCosts).map((item) => item.token));
|
|
51
50
|
if (!(tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.length)) {
|
|
52
51
|
setInsufficientGas(undefined);
|
|
53
52
|
return;
|
|
@@ -63,22 +62,22 @@ export const useGasSufficiency = (route) => {
|
|
|
63
62
|
const insufficientFromChainGasAmount = insufficientFromChainGas
|
|
64
63
|
? (_f = (_e = gasCosts[chainId].tokenAmount) === null || _e === void 0 ? void 0 : _e.minus(gasTokenBalance)) !== null && _f !== void 0 ? _f : gasCosts[chainId].gasAmount.minus(gasTokenBalance)
|
|
65
64
|
: undefined;
|
|
66
|
-
gasCosts[chainId] = Object.assign(Object.assign({}, gasCosts[chainId]), { insufficient: insufficientFromChainGas, insufficientAmount: insufficientFromChainGasAmount });
|
|
65
|
+
gasCosts[chainId] = Object.assign(Object.assign({}, gasCosts[chainId]), { insufficient: insufficientFromChainGas, insufficientAmount: insufficientFromChainGasAmount === null || insufficientFromChainGasAmount === void 0 ? void 0 : insufficientFromChainGasAmount.round(5, Big.roundUp) });
|
|
67
66
|
}
|
|
68
67
|
});
|
|
69
68
|
const gasCostResult = Object.values(gasCosts).filter((gasCost) => gasCost.insufficient);
|
|
70
69
|
setInsufficientGas(gasCostResult);
|
|
71
|
-
}), [account.address,
|
|
70
|
+
}), [account.address, getChainById, getTokenBalancesWithRetry, route]);
|
|
72
71
|
const insufficientFunds = useMemo(() => {
|
|
73
|
-
var _a
|
|
74
|
-
if (!account.isActive || !
|
|
72
|
+
var _a;
|
|
73
|
+
if (!account.isActive || !fromToken || !route) {
|
|
75
74
|
return false;
|
|
76
75
|
}
|
|
77
|
-
const balance = Big((
|
|
76
|
+
const balance = Big((_a = fromToken === null || fromToken === void 0 ? void 0 : fromToken.amount) !== null && _a !== void 0 ? _a : 0);
|
|
78
77
|
return Big(route.fromAmount)
|
|
79
78
|
.div(Math.pow(10, route.fromToken.decimals))
|
|
80
79
|
.gt(balance);
|
|
81
|
-
}, [account.isActive,
|
|
80
|
+
}, [account.isActive, fromToken, route]);
|
|
82
81
|
useEffect(() => {
|
|
83
82
|
checkInsufficientGas();
|
|
84
83
|
}, [checkInsufficientGas]);
|
|
@@ -9,16 +9,3 @@ export const useScrollableContainer = () => {
|
|
|
9
9
|
}, [containerElement]);
|
|
10
10
|
return containerElement;
|
|
11
11
|
};
|
|
12
|
-
export const useScrollableOverflowHidden = () => {
|
|
13
|
-
useLayoutEffect(() => {
|
|
14
|
-
const element = document.getElementById(ElementId.ScrollableContainer);
|
|
15
|
-
if (element) {
|
|
16
|
-
element.style.overflowY = 'hidden';
|
|
17
|
-
}
|
|
18
|
-
return () => {
|
|
19
|
-
if (element) {
|
|
20
|
-
element.style.overflowY = 'auto';
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
}, []);
|
|
24
|
-
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const useTokenAddressBalance: (chainId?: number, tokenAddress?: string) => {
|
|
2
|
+
token: import("..").Token | undefined;
|
|
3
|
+
isLoading: boolean;
|
|
4
|
+
refetch: <TPageData>(options?: (import("@tanstack/query-core").RefetchOptions & import("@tanstack/query-core").RefetchQueryFilters<TPageData>) | undefined) => Promise<import("@tanstack/query-core").QueryObserverResult<import("..").Token[], unknown>>;
|
|
5
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { useMemo } from 'react';
|
|
2
|
+
import { useTokenBalances } from './useTokenBalances';
|
|
3
|
+
export const useTokenAddressBalance = (chainId, tokenAddress) => {
|
|
4
|
+
const { tokens, tokensWithBalance, isBalanceLoading, refetch } = useTokenBalances(chainId);
|
|
5
|
+
const token = useMemo(() => {
|
|
6
|
+
var _a;
|
|
7
|
+
const token = (_a = (tokensWithBalance !== null && tokensWithBalance !== void 0 ? tokensWithBalance : tokens)) === null || _a === void 0 ? void 0 : _a.find((token) => token.address === tokenAddress && token.chainId === chainId);
|
|
8
|
+
return token;
|
|
9
|
+
}, [chainId, tokenAddress, tokens, tokensWithBalance]);
|
|
10
|
+
return {
|
|
11
|
+
token,
|
|
12
|
+
isLoading: isBalanceLoading,
|
|
13
|
+
refetch,
|
|
14
|
+
};
|
|
15
|
+
};
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import type { Token, TokenAmount } from '@lifi/sdk';
|
|
2
|
+
export declare const useTokenBalance: (token?: Token, accountAddress?: string) => {
|
|
3
|
+
token: TokenAmount | undefined;
|
|
3
4
|
isLoading: boolean;
|
|
4
|
-
refetch: <TPageData>(options?: (import("@tanstack/query
|
|
5
|
+
refetch: <TPageData>(options?: (import("@tanstack/react-query").RefetchOptions & import("@tanstack/react-query").RefetchQueryFilters<TPageData>) | undefined) => Promise<import("@tanstack/react-query").QueryObserverResult<TokenAmount, unknown>>;
|
|
6
|
+
refetchNewBalance: () => void;
|
|
7
|
+
refetchAllBalances: () => void;
|
|
8
|
+
getTokenBalancesWithRetry: (accountAddress: string, tokens: Token[], depth?: number) => Promise<TokenAmount[] | undefined>;
|
|
5
9
|
};
|
package/hooks/useTokenBalance.js
CHANGED
|
@@ -1,15 +1,93 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
11
|
+
import { useCallback, useMemo } from 'react';
|
|
12
|
+
import { useLiFi, useWallet } from '../providers';
|
|
13
|
+
import { formatTokenAmount } from '../utils';
|
|
14
|
+
const defaultRefetchInterval = 60000;
|
|
15
|
+
export const useTokenBalance = (token, accountAddress) => {
|
|
16
|
+
const lifi = useLiFi();
|
|
17
|
+
const { account } = useWallet();
|
|
18
|
+
const queryClient = useQueryClient();
|
|
19
|
+
const walletAddress = accountAddress !== null && accountAddress !== void 0 ? accountAddress : account.address;
|
|
20
|
+
const getTokenBalancesWithRetry = useCallback((accountAddress, tokens, depth = 0) => __awaiter(void 0, void 0, void 0, function* () {
|
|
21
|
+
const tokenBalances = yield lifi.getTokenBalances(accountAddress, tokens);
|
|
22
|
+
if (!tokenBalances.every((token) => token.blockNumber)) {
|
|
23
|
+
if (depth > 5) {
|
|
24
|
+
console.warn('Token balance backoff depth exceeded.');
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
yield new Promise((resolve) => {
|
|
28
|
+
setTimeout(resolve, depth * 100);
|
|
29
|
+
});
|
|
30
|
+
return getTokenBalancesWithRetry(accountAddress, tokens, depth + 1);
|
|
31
|
+
}
|
|
32
|
+
return tokenBalances;
|
|
33
|
+
}), [lifi]);
|
|
34
|
+
const tokenBalanceQueryKey = useMemo(() => ['token-balance', walletAddress, token === null || token === void 0 ? void 0 : token.chainId, token === null || token === void 0 ? void 0 : token.address], [token === null || token === void 0 ? void 0 : token.address, token === null || token === void 0 ? void 0 : token.chainId, walletAddress]);
|
|
35
|
+
const { data, isLoading, refetch } = useQuery(tokenBalanceQueryKey, ({ queryKey: [, accountAddress] }) => __awaiter(void 0, void 0, void 0, function* () {
|
|
6
36
|
var _a;
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
37
|
+
const cachedToken = (_a = queryClient
|
|
38
|
+
.getQueryData([
|
|
39
|
+
'token-balances',
|
|
40
|
+
accountAddress,
|
|
41
|
+
token.chainId,
|
|
42
|
+
])) === null || _a === void 0 ? void 0 : _a.find((t) => t.address === token.address);
|
|
43
|
+
if (cachedToken) {
|
|
44
|
+
return cachedToken;
|
|
45
|
+
}
|
|
46
|
+
const tokenBalances = yield getTokenBalancesWithRetry(accountAddress, [token]);
|
|
47
|
+
if (!(tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.length)) {
|
|
48
|
+
throw Error('Could not get tokens balance.');
|
|
49
|
+
}
|
|
50
|
+
const cachedTokenAmount = queryClient.getQueryData(tokenBalanceQueryKey);
|
|
51
|
+
const formattedAmount = formatTokenAmount(tokenBalances[0].amount);
|
|
52
|
+
if ((cachedTokenAmount === null || cachedTokenAmount === void 0 ? void 0 : cachedTokenAmount.amount) !== formattedAmount) {
|
|
53
|
+
queryClient.setQueryDefaults(tokenBalanceQueryKey, {
|
|
54
|
+
refetchInterval: defaultRefetchInterval,
|
|
55
|
+
staleTime: defaultRefetchInterval,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
queryClient.setQueryData(['token-balances', accountAddress, token.chainId], (data) => {
|
|
59
|
+
if (data) {
|
|
60
|
+
const index = data.findIndex((dataToken) => dataToken.address === token.address);
|
|
61
|
+
data[index] = Object.assign(Object.assign({}, data[index]), { amount: formattedAmount });
|
|
62
|
+
}
|
|
63
|
+
return data;
|
|
64
|
+
});
|
|
65
|
+
return Object.assign(Object.assign({}, tokenBalances[0]), { amount: formattedAmount });
|
|
66
|
+
}), {
|
|
67
|
+
enabled: Boolean(walletAddress && token),
|
|
68
|
+
refetchIntervalInBackground: true,
|
|
69
|
+
refetchInterval: defaultRefetchInterval,
|
|
70
|
+
staleTime: defaultRefetchInterval,
|
|
71
|
+
});
|
|
72
|
+
const refetchAllBalances = () => {
|
|
73
|
+
queryClient.refetchQueries([
|
|
74
|
+
'token-balances',
|
|
75
|
+
token === null || token === void 0 ? void 0 : token.chainId,
|
|
76
|
+
accountAddress,
|
|
77
|
+
]);
|
|
78
|
+
};
|
|
79
|
+
const refetchNewBalance = useCallback(() => {
|
|
80
|
+
queryClient.setQueryDefaults(tokenBalanceQueryKey, {
|
|
81
|
+
refetchInterval: 500,
|
|
82
|
+
staleTime: 500,
|
|
83
|
+
});
|
|
84
|
+
}, [queryClient, tokenBalanceQueryKey]);
|
|
10
85
|
return {
|
|
11
|
-
token,
|
|
12
|
-
isLoading
|
|
86
|
+
token: data,
|
|
87
|
+
isLoading,
|
|
13
88
|
refetch,
|
|
89
|
+
refetchNewBalance,
|
|
90
|
+
refetchAllBalances,
|
|
91
|
+
getTokenBalancesWithRetry,
|
|
14
92
|
};
|
|
15
93
|
};
|
|
@@ -5,5 +5,5 @@ export declare const useTokenBalances: (selectedChainId?: number) => {
|
|
|
5
5
|
featuredTokens: import("@lifi/types").Token[];
|
|
6
6
|
isLoading: boolean;
|
|
7
7
|
isBalanceLoading: boolean;
|
|
8
|
-
refetch: <TPageData>(options?: (import("@tanstack/react-query").RefetchOptions & import("@tanstack/react-query").RefetchQueryFilters<TPageData>) | undefined) => Promise<import("@tanstack/react-query").QueryObserverResult<Token[]
|
|
8
|
+
refetch: <TPageData>(options?: (import("@tanstack/react-query").RefetchOptions & import("@tanstack/react-query").RefetchQueryFilters<TPageData>) | undefined) => Promise<import("@tanstack/react-query").QueryObserverResult<Token[], unknown>>;
|
|
9
9
|
};
|