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

feat: Upper limit validation #280

Merged
merged 5 commits into from
Jan 10, 2025
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
5 changes: 5 additions & 0 deletions .release/.changeset/blue-goats-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bnb-chain/canonical-bridge-widget": patch
---

chore: Update confirmation popup amount styling
11 changes: 11 additions & 0 deletions .release/.changeset/pre.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"mode": "pre",
"tag": "alpha",
"initialVersions": {
"@bnb-chain/canonical-bridge-sdk": "0.4.7",
"@bnb-chain/canonical-bridge-widget": "0.5.18"
},
"changesets": [
"blue-goats-shave"
]
}
2 changes: 1 addition & 1 deletion packages/canonical-bridge-sdk/src/shared/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const formatNumber = (
useGrouping = true
) => {
const num = removeAfterDecimals(value, decimals);
return num.toLocaleString('fullwide', {
return Number(num).toLocaleString('fullwide', {
maximumFractionDigits: decimals,
useGrouping,
});
Expand Down
6 changes: 6 additions & 0 deletions packages/canonical-bridge-widget/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @bnb-chain/canonical-bridge-widget

## 0.5.19-alpha.0

### Patch Changes

- chore: Update confirmation popup amount styling

## 0.5.19

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/canonical-bridge-widget/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bnb-chain/canonical-bridge-widget",
"version": "0.5.19",
"version": "0.5.19-alpha.0",
"description": "canonical bridge widget",
"author": "bnb-chain",
"private": false,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export const formatNumber = (value: number, decimals = 18, useGrouping = true) => {
const num = removeAfterDecimals(value, decimals);
return num.toLocaleString('fullwide', {
return Number(num).toLocaleString('fullwide', {
maximumFractionDigits: decimals,
useGrouping,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ export const LayerZeroOption = () => {
? `${formatNumber(
Number(formatUnits(BigInt(estimatedAmount?.['layerZero']), getToDecimals()['layerZero'])),
8,
false,
)}`
: '--';
}, [estimatedAmount, toTokenInfo, sendValue, getToDecimals]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query';
import { useCallback, useEffect } from 'react';
import { IBridgeToken } from '@bnb-chain/canonical-bridge-sdk';

import { useBridgeConfig } from '@/CanonicalBridgeProvider';
import { IBridgeConfig, useBridgeConfig } from '@/CanonicalBridgeProvider';
import { TIME } from '@/core/constants';
import { useAppDispatch, useAppSelector } from '@/modules/store/StoreProvider';
import { setIsLoadingTokenPrices, setTokenPrices } from '@/modules/aggregator/action';
Expand All @@ -21,27 +21,13 @@ interface ITokenPricesResponse {
export function TokenPricesProvider() {
const bridgeConfig = useBridgeConfig();
const dispatch = useAppDispatch();
const { fetchApiTokenPrices } = useTokenPrice();

const { isLoading, data } = useQuery<TokenPricesContextProps>({
staleTime: TIME.MINUTE * 5,
refetchInterval: TIME.MINUTE * 5,
queryKey: ['tokenPrices'],
queryFn: async () => {
const { serverEndpoint } = bridgeConfig.http;

const [cmcRes, llamaRes] = await Promise.allSettled([
axios.get<ITokenPricesResponse>(`${serverEndpoint}/api/token/cmc`),
axios.get<ITokenPricesResponse>(`${serverEndpoint}/api/token/llama`),
]);

const cmcPrices = cmcRes.status === 'fulfilled' ? cmcRes.value.data.data : {};
const llamaPrices = llamaRes.status === 'fulfilled' ? llamaRes.value.data.data : {};

return {
cmcPrices,
llamaPrices,
};
},
queryFn: async () => fetchApiTokenPrices(bridgeConfig),
});

useEffect(() => {
Expand Down Expand Up @@ -85,7 +71,25 @@ export function useTokenPrice() {
[tokenPrices],
);

const fetchApiTokenPrices = useCallback(async (bridgeConfig: IBridgeConfig) => {
const { serverEndpoint } = bridgeConfig.http;

const [cmcRes, llamaRes] = await Promise.allSettled([
axios.get<ITokenPricesResponse>(`${serverEndpoint}/api/token/cmc`),
axios.get<ITokenPricesResponse>(`${serverEndpoint}/api/token/llama`),
]);

const cmcPrices = cmcRes.status === 'fulfilled' ? cmcRes.value.data.data : {};
const llamaPrices = llamaRes.status === 'fulfilled' ? llamaRes.value.data.data : {};

return {
cmcPrices,
llamaPrices,
};
}, []);

return {
getTokenPrice,
fetchApiTokenPrices,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
STARGATE_ENDPOINT,
} from '@/core/constants';
import { useHandleTxFailure } from '@/modules/aggregator/hooks/useHandleTxFailure';
import { usePriceValidation } from '@/modules/transfer/hooks/usePriceValidation';

export const TransferConfirmButton = ({
onClose,
Expand All @@ -49,6 +50,7 @@ export const TransferConfirmButton = ({
const { formatMessage } = useIntl();
const theme = useTheme();
const { colorMode } = useColorMode();
const { validateTokenPrice } = usePriceValidation();

const { address } = useAccount();
const { address: tronAddress, signTransaction } = useTronWallet();
Expand Down Expand Up @@ -104,6 +106,17 @@ export const TransferConfirmButton = ({
}

try {
// Check whether token price exists
const result = await validateTokenPrice({
tokenSymbol: selectedToken.symbol,
tokenAddress: selectedToken.address,
});
if (!result) {
throw new Error(
`Can not get token price from API server: ${sendValue} ${selectedToken.symbol}`,
);
}

setHash(null);
setChosenBridge('');
setIsLoading(true);
Expand Down Expand Up @@ -537,6 +550,7 @@ export const TransferConfirmButton = ({
signMessageAsync,
signTransaction,
handleFailure,
validateTokenPrice,
]);

const isFeeLoading = isLoading || isGlobalFeeLoading || !transferActionInfo || !isTransferable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const FeeSummary = () => {
h={['auto', 'auto', '60px']}
borderRadius={'8px'}
bg={theme.colors[colorMode].background.modal}
className="bccb-widget-transaction-summary-modal-fee-summary"
>
{isGlobalFeeLoading ? (
<Flex flexDir={'column'} gap={'8px'}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Box, Flex, Skeleton, theme, useColorMode } from '@bnb-chain/space';
import { Flex, Skeleton, useColorMode, useTheme } from '@bnb-chain/space';

import { IconImage } from '@/core/components/IconImage';
import { useAppSelector } from '@/modules/store/StoreProvider';
Expand All @@ -9,14 +9,15 @@ export const TokenInfo = ({
chainName,
amount,
tokenSymbol,
isLongText,
}: {
chainIconUrl?: string;
tokenIconUrl?: string;
chainName?: string;
amount?: string;
tokenSymbol?: string;
isLongText: boolean;
}) => {
const { colorMode } = useColorMode();
const isGlobalFeeLoading = useAppSelector((state) => state.transfer.isGlobalFeeLoading);

return (
Expand All @@ -26,6 +27,7 @@ export const TokenInfo = ({
w={'100%'}
alignItems={'center'}
gap={'16px'}
className="bccb-widget-transaction-summary-modal-token-info"
>
<Flex flexShrink={1} flexDir={'row'} alignItems={'center'} gap={'14px'}>
<Flex
Expand All @@ -43,32 +45,65 @@ export const TokenInfo = ({
boxSize="16px"
src={tokenIconUrl}
flexShrink={0}
className="bccb-widget-transaction-summary-modal-token-icon"
/>
<IconImage
boxSize="32px"
src={chainIconUrl}
flexShrink={0}
className="bccb-widget-transaction-summary-modal-chain-icon"
/>
<IconImage boxSize="32px" src={chainIconUrl} flexShrink={0} />
</Flex>
<Box fontSize={'16px'} py={'8px'} fontWeight={700} maxW={'142px'} whiteSpace={'wrap'}>
{chainName}
</Box>
</Flex>
{isGlobalFeeLoading ? (
<Skeleton height="24px" maxW="120px" w={'100%'} borderRadius={'4px'} />
) : (
<Flex
flex={1}
wordBreak={'break-all'}
py={'8px'}
textAlign={'right'}
alignItems={'center'}
justifyContent={'flex-end'}
color={
Number(amount?.replace(' ', '')) < 0
? theme.colors[colorMode].support.danger[3]
: theme.colors[colorMode].support.success[3]
}
flexDir={'column'}
justifyContent={isLongText ? 'flex-start' : 'center'}
whiteSpace={'wrap'}
className="bccb-widget-transaction-summary-modal-chain-name"
>
{amount ?? '--'} {tokenSymbol}
<Flex fontSize={'16px'} fontWeight={700}>
{chainName}
</Flex>
{isLongText && !isGlobalFeeLoading && (
<TokenAmount amount={amount ?? '--'} tokenSymbol={tokenSymbol ?? ''} />
)}
</Flex>
</Flex>
{!isLongText && !isGlobalFeeLoading && (
<TokenAmount amount={amount ?? '--'} tokenSymbol={tokenSymbol ?? ''} />
)}
{isGlobalFeeLoading && (
<Skeleton
className="bccb-widget-transaction-summary-modal-loading-skeleton"
height="24px"
maxW="120px"
w={'100%'}
borderRadius={'4px'}
/>
)}
</Flex>
);
};

const TokenAmount = ({ amount, tokenSymbol }: { amount: string; tokenSymbol: string }) => {
const { colorMode } = useColorMode();
const theme = useTheme();
return (
<Flex
flex={1}
wordBreak={'break-all'}
alignItems={'center'}
justifyContent={'flex-end'}
fontSize={'14px'}
lineHeight={'14px'}
fontWeight={700}
className="bccb-widget-transaction-summary-modal-token-amount"
color={
Number(amount?.replace(' ', '')) < 0
? theme.colors[colorMode].support.danger[3]
: theme.colors[colorMode].support.success[3]
}
>
{amount} {tokenSymbol}
</Flex>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,26 @@ export const TransferSummary = () => {
[toTokenAddress, toChain?.chainType],
);

const isLongFromAmount = useMemo(() => {
if (isBase) return true;
try {
if (sendValue && selectedToken?.symbol) {
return sendValue.length + selectedToken.symbol.length - 1 > 16;
}
} catch {}
return false;
}, [sendValue, selectedToken?.symbol, isBase]);

const isLongToAmount = useMemo(() => {
if (isBase) return true;
try {
if (receiveAmt && toTokenInfo?.symbol) {
return String(receiveAmt).length + toTokenInfo?.symbol.length - 1 > 16;
}
} catch {}
return false;
}, [receiveAmt, toTokenInfo?.symbol, isBase]);

return (
<Flex
flexDir={'column'}
Expand All @@ -55,13 +75,15 @@ export const TransferSummary = () => {
gap={'4px'}
borderRadius={'8px'}
bg={theme.colors[colorMode].background.modal}
className="bccb-widget-transaction-summary-modal-summary-wrapper"
>
<TokenInfo
chainIconUrl={fromChain?.icon}
tokenIconUrl={selectedToken?.icon}
chainName={fromChain?.name}
amount={!!sendValue ? `- ${sendValue}` : ''}
tokenSymbol={selectedToken?.symbol ?? ''}
isLongText={isLongFromAmount || isLongToAmount}
/>
<TransferToIcon
w={'24px'}
Expand All @@ -76,6 +98,7 @@ export const TransferSummary = () => {
chainName={toChain?.name}
amount={!!receiveAmt ? `+ ${receiveAmt}` : ''}
tokenSymbol={toTokenInfo?.symbol ?? ''}
isLongText={isLongFromAmount || isLongToAmount}
/>
<WarningMessage
text={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,20 @@ import { useAppSelector } from '@/modules/store/StoreProvider';
import { useSolanaBalance } from '@/modules/wallet/hooks/useSolanaBalance';
import { MIN_SOL_TO_ENABLED_TX } from '@/core/constants';
import { useIsWalletCompatible } from '@/modules/wallet/hooks/useIsWalletCompatible';
import { useTokenUpperLimit } from '@/modules/aggregator/hooks/useTokenUpperLimit';
import { useBridgeConfig } from '@/index';

export const useInputValidation = () => {
const { data } = useSolanaBalance();
const isWalletCompatible = useIsWalletCompatible();
const {
transfer: { dollarUpperLimit },
} = useBridgeConfig();
const solBalance = Number(data?.formatted);
const fromChain = useAppSelector((state) => state.transfer.fromChain);
const selectedToken = useAppSelector((state) => state.transfer.selectedToken);

const priceInfo = useTokenUpperLimit(selectedToken);
const validateInput = useCallback(
({
balance,
Expand All @@ -39,6 +47,15 @@ export const useInputValidation = () => {
isError: true,
};
}
// Check upper limit
if (priceInfo?.upperLimit && Number(value) >= Number(priceInfo?.upperLimit)) {
return {
text: `Transfer value over $${formatNumber(dollarUpperLimit)} (${formatNumber(
priceInfo.upperLimit,
)} ${selectedToken?.symbol}) or equivalent is not allowed`,
isError: true,
};
}
// check if send amount is greater than token balance
if (!!balance && value > balance) {
return { text: `You have insufficient balance`, isError: true };
Expand Down Expand Up @@ -71,7 +88,14 @@ export const useInputValidation = () => {
console.log(e);
}
},
[fromChain?.chainType, solBalance, isWalletCompatible],
[
fromChain?.chainType,
solBalance,
isWalletCompatible,
priceInfo,
dollarUpperLimit,
selectedToken?.symbol,
],
);

return {
Expand Down
Loading
Loading