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: transaction receipt #11845

Merged
merged 4 commits into from
Oct 10, 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
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ export function useApprove() {

const { data: spenderFromAPI, isPending: isLoadingSpender } = useSpender()
const spender = approveInfo?.dexContractAddress || spenderFromAPI
const { data: allowance = '0', isPending: isLoadingAllowance } = useERC20TokenAllowance(tokenAddress, spender, {
const {
data: allowance = '0',
isPending: isLoadingAllowance,
refetch: refetchAllowance,
} = useERC20TokenAllowance(tokenAddress, spender, {
chainId,
})

Expand Down Expand Up @@ -60,6 +64,7 @@ export function useApprove() {
})
const receipt = await waitForTransaction({ chainId, hash, confirmationCount: 1 })
if (!receipt?.status) throw new Error('Failed to approve')
await refetchAllowance()
return hash
},
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { NetworkPluginID } from '@masknet/shared-base'
import { useWeb3 } from '@masknet/web3-hooks-base'
import type { ChainId } from '@masknet/web3-shared-evm'
import { useWeb3Connection } from '@masknet/web3-hooks-base'
import { BigNumber } from 'bignumber.js'
import { useCallback } from 'react'

/**
* Transfer(address,address,uint256)
*/
const TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
export function useGetTransferReceived(chainId: ChainId) {
const web3 = useWeb3(NetworkPluginID.PLUGIN_EVM, { chainId })
export function useGetTransferReceived() {
const web3 = useWeb3Connection(NetworkPluginID.PLUGIN_EVM)
return useCallback(
async (hash: string, receiver: string) => {
const receipt = await web3?.eth.getTransactionReceipt(hash)
const receiverTopic = `0x000000000000000000000000${receiver.slice(2)}`.toLowerCase()
async ({ hash, account, chainId }: { hash: string; account: string; chainId: number }) => {
const receipt = await web3.getTransactionReceipt(hash, { chainId })
const receiverTopic = `0x000000000000000000000000${account.slice(2)}`.toLowerCase()

const datas = receipt?.logs
.filter((x) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function useWaitForTransaction() {
}
const [receipt, blockNumber] = await Promise.all([
web3.getTransactionReceipt(hash, { chainId }),
web3.getBlockNumber(),
web3.getBlockNumber({ chainId }),
])
if (receipt?.blockNumber && blockNumber - receipt.blockNumber >= confirmationCount) {
resolve(receipt)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Icons } from '@masknet/icons'
import { CopyButton, LoadingStatus, NetworkIcon, PluginWalletStatusBar, ProgressiveText } from '@masknet/shared'
import { NetworkPluginID } from '@masknet/shared-base'
import { ActionButton, LoadingBase, makeStyles, ShadowRootTooltip, useCustomSnackbar } from '@masknet/theme'
import { useAccount, useNativeTokenPrice, useNetwork, useWeb3Connection } from '@masknet/web3-hooks-base'
import { useAccount, useNativeTokenPrice, useNetwork, useWeb3Connection, useWeb3Utils } from '@masknet/web3-hooks-base'
import {
dividedBy,
formatBalance,
Expand All @@ -14,24 +14,25 @@ import {
rightShift,
} from '@masknet/web3-shared-base'
import { type ChainId, formatWeiToEther } from '@masknet/web3-shared-evm'
import { Box, Typography } from '@mui/material'
import { Box, Link as MuiLink, Typography } from '@mui/material'
import { useQueryClient } from '@tanstack/react-query'
import { BigNumber } from 'bignumber.js'
import { memo, useMemo, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useAsyncFn } from 'react-use'
import urlcat from 'urlcat'
import { CoinIcon } from '../../components/CoinIcon.js'
import { Warning } from '../../components/Warning.js'
import { DEFAULT_SLIPPAGE, RoutePaths } from '../../constants.js'
import { addTransaction } from '../../storage.js'
import { useGasManagement, useTrade } from '../contexts/index.js'
import { useBridgeData } from '../hooks/useBridgeData.js'
import { getBridgeLeftSideToken, getBridgeRightSideToken } from '../helpers.js'
import { useApprove } from '../hooks/useApprove.js'
import { useBridgable } from '../hooks/useBridgable.js'
import { useBridgeData } from '../hooks/useBridgeData.js'
import { useLeave } from '../hooks/useLeave.js'
import { useToken } from '../hooks/useToken.js'
import { useTokenPrice } from '../hooks/useTokenPrice.js'
import { CoinIcon } from '../../components/CoinIcon.js'
import { getBridgeLeftSideToken, getBridgeRightSideToken } from '../helpers.js'
import { useLeave } from '../hooks/useLeave.js'
import { useApprove } from '../hooks/useApprove.js'

const useStyles = makeStyles()((theme) => ({
container: {
Expand Down Expand Up @@ -236,6 +237,7 @@ export const BridgeConfirm = memo(function BridgeConfirm() {
</>
: null

const Utils = useWeb3Utils(NetworkPluginID.PLUGIN_EVM)
const Web3 = useWeb3Connection(NetworkPluginID.PLUGIN_EVM, { chainId: fromChainId })
const gas = gasConfig.gas ?? transaction?.gasLimit ?? gasLimit
const [{ loading: isSending }, sendBridge] = useAsyncFn(async () => {
Expand Down Expand Up @@ -281,6 +283,7 @@ export const BridgeConfirm = memo(function BridgeConfirm() {
const showStale = isQuoteStale && !isSending && !isApproving

const leaveRef = useLeave()
const queryClient = useQueryClient()

const [{ loading: submitting }, submit] = useAsyncFn(async () => {
if (!fromToken || !toToken || !transaction?.to || !spender || !bridge) return
Expand All @@ -300,6 +303,24 @@ 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,
})
await addTransaction(account, {
kind: 'bridge',
hash,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { useLiquidityResources } from '../hooks/useLiquidityResources.js'
import { useSwapData } from '../hooks/useSwapData.js'
import { useSwappable } from '../hooks/useSwappable.js'
import { useWaitForTransaction } from '../hooks/useWaitForTransaction.js'
import { useQueryClient } from '@tanstack/react-query'

const useStyles = makeStyles()((theme) => ({
container: {
Expand Down Expand Up @@ -264,9 +265,10 @@ export const Confirm = memo(function Confirm() {

const { showSnackbar } = useCustomSnackbar()
const leaveRef = useLeave()
const queryClient = useQueryClient()
const Utils = useWeb3Utils(NetworkPluginID.PLUGIN_EVM)
const waitForTransaction = useWaitForTransaction()
const getReceived = useGetTransferReceived(chainId)
const getReceived = useGetTransferReceived()

const [{ loading: submitting }, submit] = useAsyncFn(async () => {
if (!fromToken || !toToken || !transaction?.to || !spender) return
Expand All @@ -286,9 +288,10 @@ export const Confirm = memo(function Confirm() {
})
return
}
queryClient.invalidateQueries({ queryKey: ['fungible-token', 'balance'] })
try {
await waitForTransaction({ chainId, hash })
const received = await getReceived(hash, account)
const received = await getReceived({ hash, account, chainId })
if (received && !leaveRef.current) {
showSnackbar(t`Swap`, {
message: (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ export const Transaction = memo(function Transaction() {
const { reset, setFromToken, mode, setToToken } = useTrade()
const { classes, cx, theme } = useStyles()
const navigate = useNavigate()
const [params] = useSearchParams()
const [params, setParams] = useSearchParams()
const hash = params.get('hash')
const rawChainId = params.get('chainId')
const isPending = params.has('pending')
Expand All @@ -263,7 +263,7 @@ export const Transaction = memo(function Transaction() {
const { data: bridgeStatus } = useQuery({
queryKey: ['okx-bridge', 'transaction-status', chainId, hash],
queryFn: hash && tx?.kind === 'bridge' ? () => OKX.getBridgeStatus({ chainId, hash }) : skipToken,
refetchInterval: 60_000,
refetchInterval: 10_000,
})
const detailStatus = bridgeStatus?.detailStatus

Expand All @@ -279,30 +279,47 @@ export const Transaction = memo(function Transaction() {
const leaveRef = useLeave()
const Utils = useWeb3Utils(NetworkPluginID.PLUGIN_EVM)
const waitForTransaction = useWaitForTransaction()
const getReceived = useGetTransferReceived(chainId as ChainId)
const getReceived = useGetTransferReceived()
const toTxHash = bridgeStatus?.toTxHash
useAsync(async () => {
if (!isPending || !chainId || !hash || !toToken) return
await waitForTransaction({ chainId, hash })
const received = await getReceived(hash, account)
if (!isPending || !toChainId || !toTxHash || !toToken) return
const receipt = await waitForTransaction({ chainId: toChainId, hash: toTxHash, confirmationCount: 1 })

if (received && !leaveRef.current) {
if (!receipt.status) {
showSnackbar(t`Bridge`, {
message: (
<MuiLink
className={classes.toastLink}
color="inherit"
href={Utils.explorerResolver.transactionLink(chainId, hash)}
tabIndex={-1}
target="_blank"
rel="noopener noreferrer">
{t`${formatBalance(received, toToken.decimals)} ${toToken.symbol} bridge completed successfully.`}{' '}
<Icons.LinkOut size={16} sx={{ ml: 0.5 }} />
</MuiLink>
),
variant: 'success',
message: t`Failed to bridge`,
})
return
} else {
const received = await getReceived({ hash: toTxHash, account, chainId: toChainId })

if (received && !leaveRef.current) {
showSnackbar(t`Bridge`, {
message: (
<MuiLink
className={classes.toastLink}
color="inherit"
href={Utils.explorerResolver.transactionLink(toChainId, toTxHash)}
tabIndex={-1}
target="_blank"
rel="noopener noreferrer">
{t`${formatBalance(received, toToken.decimals)} ${toToken.symbol} bridge completed successfully.`}{' '}
<Icons.LinkOut size={16} sx={{ ml: 0.5 }} />
</MuiLink>
),
variant: 'success',
})
}
}
}, [isPending, chainId, hash, toToken])

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

if (!tx)
return (
Expand Down
1 change: 1 addition & 0 deletions packages/plugins/Trader/src/locale/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"kPQQEW": "Enter an Amount",
"Citz6F": "Exchange",
"7Bj3x9": "Failed",
"QUBIav": "Failed to bridge",
"2J5wRx": "Failed to get quote information",
"KziH2K": "Fast",
"pG7O41": "Fastest",
Expand Down
Loading