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

fix: reset input amount and some other issues #11849

Merged
merged 7 commits into from
Oct 11, 2024
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
10 changes: 8 additions & 2 deletions packages/plugins/Trader/src/SiteAdaptor/trader/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Web3Helper } from '@masknet/web3-helpers'
import { formatCompact, leftShift, TokenType } from '@masknet/web3-shared-base'
import { formatCompact, leftShift, TokenType, trimZero } from '@masknet/web3-shared-base'
import type { Token } from '../../types/trader.js'
import { SchemaType } from '@masknet/web3-shared-evm'
import type { RouterListItem } from '@masknet/web3-providers/types'
import { type BigNumber } from 'bignumber.js'
import { BigNumber } from 'bignumber.js'

const MINIMUM_AMOUNT_RE = /((?:Minimum|Maximum) amount is\s+)(\d+)/
export function fixBridgeMessage(message: string, token?: Web3Helper.FungibleTokenAll) {
Expand Down Expand Up @@ -49,3 +49,9 @@ export function formatTokenBalance(raw: BigNumber.Value, decimals = 0) {
: 2,
})
}

export function formatInput(input: string) {
if (!input) return input
const bn = new BigNumber(input)
return bn.isNaN() ? input : trimZero(bn.toFixed(12, 1))
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NetworkPluginID } from '@masknet/shared-base'
import { useAccount, useWeb3Connection } from '@masknet/web3-hooks-base'
import { useERC20TokenAllowance } from '@masknet/web3-hooks-evm'
import { OKX } from '@masknet/web3-providers'
import { isGreaterThan, isZero } from '@masknet/web3-shared-base'
import { isGte, isZero } from '@masknet/web3-shared-base'
import { addGasMargin, ChainId, isNativeTokenAddress } from '@masknet/web3-shared-evm'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useTrade } from '../contexts/TradeProvider.js'
Expand Down Expand Up @@ -54,7 +54,7 @@ export function useApprove() {
approveInfo?.gasPrice,
],
mutationFn: async () => {
if (!approveInfo?.data || !tokenAddress || isGreaterThan(allowance, amount)) return
if (!approveInfo?.data || !tokenAddress || isGte(allowance, amount)) return
const hash = await Web3.sendTransaction({
to: tokenAddress,
// gas provided by API for Arbitrum is too low, let wallet estimate itself
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
multipliedBy,
rightShift,
} from '@masknet/web3-shared-base'
import { type ChainId, formatWeiToEther } from '@masknet/web3-shared-evm'
import { ChainId, formatWeiToEther } from '@masknet/web3-shared-evm'
import { Box, Link as MuiLink, Typography } from '@mui/material'
import { useQueryClient } from '@tanstack/react-query'
import { BigNumber } from 'bignumber.js'
Expand Down Expand Up @@ -248,14 +248,14 @@ export const BridgeConfirm = memo(function BridgeConfirm() {
from: account,
value: transaction.value,
gasPrice: gasConfig.gasPrice ?? transaction.gasPrice,
gas: gas ? multipliedBy(gas, 1.2).toFixed(0) : gas,
gas: fromChainId !== ChainId.Arbitrum && gas ? multipliedBy(gas, 1.2).toFixed(0) : undefined,
maxPriorityFeePerGas:
'maxPriorityFeePerGas' in gasConfig && gasConfig.maxFeePerGas ?
gasConfig.maxFeePerGas
: transaction.maxPriorityFeePerGas,
_disableSnackbar: true,
})
}, [transaction, account, gasConfig, Web3, gas])
}, [transaction, fromChainId, account, gasConfig, Web3, gas])

const [isBridgable, errorMessage] = useBridgable()

Expand Down Expand Up @@ -304,23 +304,32 @@ export const BridgeConfirm = memo(function BridgeConfirm() {
return
}
queryClient.invalidateQueries({ queryKey: ['fungible-token', 'balance'] })
showSnackbar(t`Bridge`, {
message: (
<MuiLink
sx={{ wordBreak: 'break-word' }}
className={classes.link}
color="inherit"
href={Utils.explorerResolver.transactionLink(fromChainId, hash)}
tabIndex={-1}
target="_blank"
rel="noopener noreferrer">
{t`Transaction submitted.`}
<Icons.LinkOut size={16} sx={{ ml: 0.5 }} />
</MuiLink>
),
variant: 'default',
processing: true,
})
const receipt = await Web3.getTransactionReceipt(hash)
if (!receipt?.status) {
showSnackbar(t`Bridge`, {
message: t`Failed to bridge`,
})
} else {
showSnackbar(t`Bridge`, {
message: (
<MuiLink
sx={{ wordBreak: 'break-word' }}
className={classes.link}
color="inherit"
href={Utils.explorerResolver.transactionLink(fromChainId, hash)}
tabIndex={-1}
target="_blank"
rel="noopener noreferrer">
<Typography
color={theme.palette.maskColor.success}
component="span">{t`Transaction submitted.`}</Typography>
<Icons.LinkOut size={16} sx={{ ml: 0.5 }} />
</MuiLink>
),
variant: 'default',
processing: true,
})
}
await addTransaction(account, {
kind: 'bridge',
hash,
Expand Down Expand Up @@ -384,6 +393,7 @@ export const BridgeConfirm = memo(function BridgeConfirm() {
gasConfig.gasPrice,
router,
mode,
Web3,
])

const loading = isSending || isCheckingApprove || isApproving || submitting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
multipliedBy,
rightShift,
} from '@masknet/web3-shared-base'
import { formatWeiToEther } from '@masknet/web3-shared-evm'
import { ChainId, formatWeiToEther } from '@masknet/web3-shared-evm'
import { Box, Link as MuiLink, Typography } from '@mui/material'
import { BigNumber } from 'bignumber.js'
import { memo, useMemo, useState } from 'react'
Expand Down Expand Up @@ -248,14 +248,14 @@ export const Confirm = memo(function Confirm() {
from: account,
value: transaction.value,
gasPrice: gasConfig.gasPrice ?? transaction.gasPrice,
gas: gas ? multipliedBy(gas, 1.2).toFixed(0) : gas,
gas: chainId !== ChainId.Arbitrum && gas ? multipliedBy(gas, 1.2).toFixed(0) : undefined,
maxPriorityFeePerGas:
'maxPriorityFeePerGas' in gasConfig && gasConfig.maxFeePerGas ?
gasConfig.maxFeePerGas
: transaction.maxPriorityFeePerGas,
_disableSnackbar: true,
})
}, [transaction, account, gasConfig, Web3, gas])
}, [transaction, chainId, account, gasConfig, Web3, gas])

const [{ isLoadingApproveInfo, isLoadingSpender, isLoadingAllowance, spender }, approveMutation] = useApprove()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ import {
} from '@masknet/web3-shared-base'
import { isNativeTokenAddress, type ChainId } from '@masknet/web3-shared-evm'
import { Box, Button, Typography } from '@mui/material'
import { useMemo } from 'react'
import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import urlcat from 'urlcat'
import { CoinIcon } from '../../../components/CoinIcon.js'
import { Warning } from '../../../components/Warning.js'
import { RoutePaths } from '../../../constants.js'
import { useGasManagement, useTrade } from '../../contexts/index.js'
import { formatTokenBalance } from '../../helpers.js'
import { formatInput, formatTokenBalance } from '../../helpers.js'
import { useBridgable } from '../../hooks/useBridgable.js'
import { useSupportedChains } from '../../hooks/useSupportedChains.js'
import { useSwappable } from '../../hooks/useSwappable.js'
Expand Down Expand Up @@ -235,6 +235,8 @@ export function TradeView() {
const isLoading = isSwap ? isQuoteLoading : isBridgeQuoteLoading
const swapButtonLabel = isOverSlippage ? t`Swap anyway` : t`Swap`
const bridgeButtonLabel = isOverSlippage ? t`Bridge anyway` : t`Bridge`
// When set to max, swap all amount of the token
const [isMax, setIsMax] = useState(false)
return (
<div className={classes.view}>
<Box className={classes.container}>
Expand All @@ -253,6 +255,7 @@ export function TradeView() {
isSwap && toToken?.address ? [toToken.address] : [],
)
if (picked) {
setInputAmount('')
setFromToken(picked)
if (toChainId !== picked.chainId && isSwap) setToToken(undefined)
}
Expand Down Expand Up @@ -294,9 +297,8 @@ export function TradeView() {
const isNative = isNativeTokenAddress(fromToken.address)
const balance =
isNative ? minus(fromTokenBalance, gasFee) : fromTokenBalance
setInputAmount(
trimZero(leftShift(balance, fromToken.decimals).toFixed(12, 1)),
)
setInputAmount(trimZero(leftShift(balance, fromToken.decimals).toFixed()))
setIsMax(true)
}}>
<Trans>MAX</Trans>
</Button>
Expand All @@ -305,8 +307,9 @@ export function TradeView() {
<input
className={classes.tokenInput}
autoFocus
value={inputAmount}
value={isMax ? formatInput(inputAmount) : inputAmount}
onChange={(e) => {
setIsMax(false)
setInputAmount(e.currentTarget.value)
}}
/>
Expand All @@ -320,6 +323,7 @@ export function TradeView() {
<Box
className={classes.swapButton}
onClick={() => {
setInputAmount('')
setFromToken(toToken)
setToToken(fromToken)
}}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import { useAccount, useNetwork, useWeb3Connection, useWeb3Utils } from '@maskne
import { EVMExplorerResolver, OKX } from '@masknet/web3-providers'
import { dividedBy, formatBalance, formatCompact, leftShift, TransactionStatusType } from '@masknet/web3-shared-base'
import { type ChainId, formatEthereumAddress } from '@masknet/web3-shared-evm'
import { alpha, Box, Button, Typography, Link as MuiLink } from '@mui/material'
import { alpha, Box, Button, Link as MuiLink, Typography } from '@mui/material'
import { skipToken, useQuery } from '@tanstack/react-query'
import { format } from 'date-fns'
import { memo, useMemo, useState } from 'react'
import { memo, useCallback, useMemo, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAsync } from 'react-use'
import urlcat from 'urlcat'
import { formatTime } from '../../../helpers/formatTime.js'
import { CoinIcon } from '../../components/CoinIcon.js'
Expand All @@ -21,10 +22,9 @@ import { RoutePaths } from '../../constants.js'
import { useTransaction } from '../../storage.js'
import { useTrade } from '../contexts/index.js'
import { okxTokenToFungibleToken } from '../helpers.js'
import { useAsync } from 'react-use'
import { useWaitForTransaction } from '../hooks/useWaitForTransaction.js'
import { useGetTransferReceived } from '../hooks/useGetTransferReceived.js'
import { useLeave } from '../hooks/useLeave.js'
import { useWaitForTransaction } from '../hooks/useWaitForTransaction.js'

const useStyles = makeStyles<void, 'leftSideToken' | 'rightSideToken'>()((theme, _, refs) => ({
container: {
Expand Down Expand Up @@ -281,6 +281,17 @@ export const Transaction = memo(function Transaction() {
const waitForTransaction = useWaitForTransaction()
const getReceived = useGetTransferReceived()
const toTxHash = bridgeStatus?.toTxHash

const removePendingParam = useCallback(() => {
setParams(
(params) => {
params.delete('pending')
return params.toString()
},
{ replace: true },
)
}, [setParams])

useAsync(async () => {
if (!isPending || !toChainId || !toTxHash || !toToken) return
const receipt = await waitForTransaction({ chainId: toChainId, hash: toTxHash, confirmationCount: 1 })
Expand All @@ -289,7 +300,6 @@ export const Transaction = memo(function Transaction() {
showSnackbar(t`Bridge`, {
message: t`Failed to bridge`,
})
return
} else {
const received = await getReceived({ hash: toTxHash, account, chainId: toChainId })

Expand All @@ -312,14 +322,8 @@ export const Transaction = memo(function Transaction() {
}
}

setParams(
(params) => {
params.delete('pending')
return params.toString()
},
{ replace: true },
)
}, [isPending, toChainId, toTxHash, toToken])
removePendingParam()
}, [isPending, toChainId, toTxHash, toToken, removePendingParam])

if (!tx)
return (
Expand Down
Loading