Skip to content

Commit

Permalink
fix: max button should return full amount
Browse files Browse the repository at this point in the history
  • Loading branch information
chybisov committed May 22, 2023
1 parent 4638a6e commit 64e0592
Show file tree
Hide file tree
Showing 10 changed files with 35 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useTokenAddressBalance } from '../../hooks';
import type { SwapFormTypeProps } from '../../providers';
import { SwapFormKeyHelper } from '../../providers';
import { formatTokenPrice } from '../../utils';
import { formatTokenAmount, formatTokenPrice } from '../../utils';

export const FormPriceHelperText: React.FC<SwapFormTypeProps> = ({
formType,
Expand Down Expand Up @@ -59,7 +59,7 @@ export const FormPriceHelperText: React.FC<SwapFormTypeProps> = ({
pl={0.25}
>
{`/ ${t(`format.number`, {
value: token?.amount,
value: formatTokenAmount(token?.amount),
})}`}
</Typography>
) : null}
Expand Down
6 changes: 3 additions & 3 deletions packages/widget/src/components/SwapInput/SwapInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';
import type { SwapFormTypeProps } from '../../providers';
import { SwapFormKeyHelper, useWidgetConfig } from '../../providers';
import { DisabledUI } from '../../types';
import { formatAmount } from '../../utils';
import { formatInputAmount } from '../../utils';
import { Card, CardTitle } from '../Card';
import { FitInputText } from './FitInputText';
import { FormPriceHelperText } from './FormPriceHelperText';
Expand All @@ -32,15 +32,15 @@ export const SwapInput: React.FC<SwapFormTypeProps & BoxProps> = ({
event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => {
const { value } = event.target;
const formattedAmount = formatAmount(value, true);
const formattedAmount = formatInputAmount(value, true);
onChange(formattedAmount);
};

const handleBlur = (
event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => {
const { value } = event.target;
const formattedAmount = formatAmount(value);
const formattedAmount = formatInputAmount(value);
onChange(formattedAmount);
onBlur();
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const SwapInputEndAdornment = ({ formType }: SwapFormTypeProps) => {

const handleMax = () => {
const chain = getChainById(chainId);
let maxAmount;
let maxAmount = token?.amount;
if (
chain?.nativeToken.address === tokenAddress &&
data?.available &&
Expand All @@ -45,13 +45,9 @@ export const SwapInputEndAdornment = ({ formType }: SwapFormTypeProps) => {
}
}

setValue(
SwapFormKeyHelper.getAmountKey(formType),
maxAmount || token?.amount || '',
{
shouldTouch: true,
},
);
setValue(SwapFormKeyHelper.getAmountKey(formType), maxAmount || '', {
shouldTouch: true,
});
};

return (
Expand Down
8 changes: 6 additions & 2 deletions packages/widget/src/components/TokenList/TokenListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import {
} from '@mui/material';
import { memo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { formatTokenPrice, shortenAddress } from '../../utils';
import {
formatTokenAmount,
formatTokenPrice,
shortenAddress,
} from '../../utils';
import { LinkButton, ListItem, ListItemButton } from './TokenList.style';
import type { TokenListItemButtonProps, TokenListItemProps } from './types';

Expand Down Expand Up @@ -141,7 +145,7 @@ export const TokenListItemButton: React.FC<TokenListItemButtonProps> = ({
{Number(token.amount) ? (
<Typography variant="body1" noWrap>
{t('format.number', {
value: token.amount,
value: formatTokenAmount(token.amount),
})}
</Typography>
) : null}
Expand Down
9 changes: 4 additions & 5 deletions packages/widget/src/hooks/useTokenBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { Token, TokenAmount } from '@lifi/sdk';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useMemo } from 'react';
import { useWallet } from '../providers';
import { formatTokenAmount } from '../utils';
import { useGetTokenBalancesWithRetry } from './useGetTokenBalancesWithRetry';

const defaultRefetchInterval = 30_000;
Expand Down Expand Up @@ -48,9 +47,9 @@ export const useTokenBalance = (token?: Token, accountAddress?: string) => {
const cachedTokenAmount =
queryClient.getQueryData<TokenAmount>(tokenBalanceQueryKey);

const formattedAmount = formatTokenAmount(tokenBalances[0].amount);
const tokenAmount = tokenBalances[0].amount;

if (cachedTokenAmount?.amount !== formattedAmount) {
if (cachedTokenAmount?.amount !== tokenAmount) {
queryClient.setQueryDefaults(tokenBalanceQueryKey, {
refetchInterval: defaultRefetchInterval,
staleTime: defaultRefetchInterval,
Expand All @@ -67,7 +66,7 @@ export const useTokenBalance = (token?: Token, accountAddress?: string) => {
);
clonedData[index] = {
...clonedData[index],
amount: formattedAmount,
amount: tokenAmount,
};
return clonedData;
}
Expand All @@ -76,7 +75,7 @@ export const useTokenBalance = (token?: Token, accountAddress?: string) => {

return {
...tokenBalances[0],
amount: formattedAmount,
amount: tokenAmount,
} as TokenAmount;
},
{
Expand Down
9 changes: 3 additions & 6 deletions packages/widget/src/hooks/useTokenBalances.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useQuery } from '@tanstack/react-query';
import { useLiFi, useWallet } from '../providers';
import type { TokenAmount } from '../types';
import { formatTokenAmount } from '../utils';
import { useFeaturedTokens } from './useFeaturedTokens';
import { useTokens } from './useTokens';

Expand Down Expand Up @@ -39,11 +38,9 @@ export const useTokenBalances = (selectedChainId?: number) => {
parseFloat(a.amount ?? '0') * parseFloat(a.priceUSD ?? '0');

const formattedTokens = (
(tokenBalances.length === 0 ? tokens : tokenBalances) as TokenAmount[]
).map((token) => {
token.amount = formatTokenAmount(token.amount);
return token;
});
tokenBalances.length === 0 ? tokens : tokenBalances
) as TokenAmount[];

const result = [
...formattedTokens
.filter(
Expand Down
4 changes: 2 additions & 2 deletions packages/widget/src/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@
"inProgress": "in progress",
"insurance": {
"bridgeExploits": "Bridge malfunctions, hacks or exploits",
"insure": "Insure <strong>{{amount}} {{tokenSymbol}}</strong> in transit.",
"insured": "You've insured <strong>{{amount}} {{tokenSymbol}}</strong> in transit:",
"insure": "Insure <strong>{{amount, number(maximumFractionDigits: 9)}} {{tokenSymbol}}</strong> in transit.",
"insured": "You've insured <strong>{{amount, number(maximumFractionDigits: 9)}} {{tokenSymbol}}</strong> in transit:",
"slippageError": "Error in slippage for tokens received"
},
"info": {
Expand Down
6 changes: 3 additions & 3 deletions packages/widget/src/pages/SwapPage/StatusBottomSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export const StatusBottomSheet: React.FC<RouteExecution> = ({
: t('swap.success.title.swapSuccessful');
if (token) {
primaryMessage = t('swap.success.message.swapSuccessful', {
amount: token.amount,
amount: formatTokenAmount(token.amount),
tokenSymbol: token.symbol,
chainName: getChainById(token.chainId)?.name,
walletAddress: shortenAddress(route.toAddress),
Expand All @@ -125,7 +125,7 @@ export const StatusBottomSheet: React.FC<RouteExecution> = ({
});
if (token) {
secondaryMessage = t('swap.success.message.swapSuccessful', {
amount: token.amount,
amount: formatTokenAmount(token.amount),
tokenSymbol: token.symbol,
chainName: getChainById(token.chainId)?.name,
walletAddress: shortenAddress(route.toAddress),
Expand All @@ -142,7 +142,7 @@ export const StatusBottomSheet: React.FC<RouteExecution> = ({
});
if (token) {
secondaryMessage = t('swap.success.message.swapSuccessful', {
amount: token.amount,
amount: formatTokenAmount(token.amount),
tokenSymbol: token.symbol,
chainName: getChainById(token.chainId)?.name,
walletAddress: shortenAddress(route.toAddress),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ChainKey } from '@lifi/sdk';
import { getChainByKey } from '@lifi/sdk';
import { createContext, useContext, useId, useMemo } from 'react';
import { setDefaultSettings } from '../../stores';
import { formatAmount } from '../../utils';
import { formatInputAmount } from '../../utils';
import type { WidgetContextProps, WidgetProviderProps } from './types';

const initialContext: WidgetContextProps = {
Expand Down Expand Up @@ -81,7 +81,7 @@ export const WidgetProvider: React.FC<
fromAmount:
typeof searchParams.fromAmount === 'string' &&
!isNaN(parseFloat(searchParams.fromAmount))
? formatAmount(searchParams.fromAmount)
? formatInputAmount(searchParams.fromAmount)
: fromAmount,
elementId,
integrator,
Expand Down
19 changes: 6 additions & 13 deletions packages/widget/src/utils/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ export const formatTokenAmount = (
decimalPlaces++;
}

return Big(
parseFloat(Big(parsedAmount).toFixed(decimalPlaces + 1, 0)),
).toString();
return Big(parsedAmount).toFixed(decimalPlaces + 1, 0);
};

export const formatSlippage = (
Expand Down Expand Up @@ -61,8 +59,8 @@ export const formatSlippage = (
return parsedSlippage.toString();
};

export const formatAmount = (
amount: string = '',
export const formatInputAmount = (
amount: string,
returnInitial: boolean = false,
) => {
if (!amount) {
Expand All @@ -76,20 +74,15 @@ export const formatAmount = (
if (isNaN(Number(formattedAmount)) && !isNaN(parsedAmount)) {
return parsedAmount.toString();
}
if (isNaN(parsedAmount)) {
return '';
}
if (parsedAmount < 0) {
return Math.abs(parsedAmount).toString();
}
try {
if (returnInitial && Big(formattedAmount)) {
const absFormattedAmount = Big(formattedAmount).abs();
if (returnInitial) {
return formattedAmount;
}
return absFormattedAmount.toString();
} catch {
return '';
}
return Big(parsedAmount).toString();
};

export const formatTokenPrice = (amount?: string, price?: string) => {
Expand Down

0 comments on commit 64e0592

Please sign in to comment.