Skip to content

Commit

Permalink
fix: swap and bridge (#11908)
Browse files Browse the repository at this point in the history
* fix: swap and bridge

mf-6474
mf-6475
mf-6476

* fix: run codegen

---------

Co-authored-by: swkatmask <[email protected]>
  • Loading branch information
swkatmask and swkatmask authored Nov 7, 2024
1 parent 308540b commit bf307d8
Show file tree
Hide file tree
Showing 14 changed files with 51 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useMessages } from '@masknet/web3-hooks-base'
export function useMessageGuard() {
const matchInteraction = useMatch(PopupRoutes.ContractInteraction)
const messages = useMessages()
const nonSilentMessages = messages.filter((x) => !x.request.options.silent)

return !matchInteraction && messages.length > 0
return !matchInteraction && nonSilentMessages.length > 0
}
25 changes: 11 additions & 14 deletions packages/plugins/Trader/src/SiteAdaptor/storage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { EMPTY_LIST, type ScopedStorage } from '@masknet/shared-base'
import { useQuery } from '@tanstack/react-query'
import { queryClient } from '@masknet/shared-base-ui'
import { sortBy } from 'lodash-es'
import { useMemo } from 'react'
import { useSubscription } from 'use-subscription'
import type { OkxTransaction } from '../types/trader.js'

export interface StorageOptions {
Expand All @@ -14,18 +16,12 @@ export function setupStorage(initialized: ScopedStorage<StorageOptions>) {
}

export function useTradeHistory(address: string) {
return useQuery({
enabled: storage.storage.transactions.initialized,
queryKey: ['trade-history', address],
refetchOnMount: 'always',
queryFn: async () => {
return storage.storage.transactions.value
},
select(data) {
const addr = address.toLowerCase()
return sortBy(data[addr], (x) => -x.timestamp) || EMPTY_LIST
},
})
const transactions = useSubscription(storage.storage.transactions.subscription)
return useMemo(() => {
if (!storage.storage.transactions.initialized) return null
const addr = address.toLowerCase()
return sortBy(transactions[addr], (x) => -x.timestamp) || EMPTY_LIST
}, [transactions])
}

export async function addTransaction<T extends OkxTransaction>(address: string, transaction: T) {
Expand All @@ -38,6 +34,7 @@ export async function addTransaction<T extends OkxTransaction>(address: string,
...txObject.value,
[addr]: [...transactions, transaction],
})
queryClient.refetchQueries({ queryKey: ['trade-history'] })
}

export async function updateTransaction<T extends OkxTransaction>(
Expand All @@ -61,6 +58,6 @@ export async function updateTransaction<T extends OkxTransaction>(
}

export function useTransaction(address: string, hash: string | null) {
const { data: txes } = useTradeHistory(address)
const txes = useTradeHistory(address)
return hash && txes ? txes.find((x) => x.hash === hash) : null
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ export function useApprove() {
const hash = await Web3.sendTransaction(
{
to: tokenAddress,
// gas provided by API for Arbitrum is too low, let wallet estimate itself
gas: chainId === ChainId.Arbitrum ? undefined : addGasMargin(approveInfo.gasLimit).toFixed(0),
// Add more gas margin for Arbitrum, since gas for Arbitrum that provided by API is too low.
gas: addGasMargin(approveInfo.gasLimit, chainId === ChainId.Arbitrum ? 1 : 0.3),
gasPrice: approveInfo.gasPrice,
data: approveInfo.data,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { msg, Select, Trans } from '@lingui/macro'
import { useLingui } from '@lingui/react'
import { Icons } from '@masknet/icons'
import { CopyButton, LoadingStatus, NetworkIcon, PluginWalletStatusBar, ProgressiveText } from '@masknet/shared'
import { NetworkPluginID, Sniffings } from '@masknet/shared-base'
Expand All @@ -20,7 +21,7 @@ import {
multipliedBy,
rightShift,
} from '@masknet/web3-shared-base'
import { ChainId, formatEthereumAddress, formatWeiToEther } from '@masknet/web3-shared-evm'
import { addGasMargin, ChainId, formatEthereumAddress, 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 All @@ -41,7 +42,6 @@ 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 { useLingui } from '@lingui/react'

const useStyles = makeStyles()((theme) => ({
container: {
Expand Down Expand Up @@ -261,7 +261,7 @@ export const BridgeConfirm = memo(function BridgeConfirm() {
from: account,
value: transaction.value,
gasPrice: gasConfig.gasPrice ?? transaction.gasPrice,
gas: fromChainId !== ChainId.Arbitrum && gas ? multipliedBy(gas, 1.2).toFixed(0) : undefined,
gas: gas ? addGasMargin(gas, fromChainId === ChainId.Arbitrum ? 1 : 0.3) : undefined,
maxPriorityFeePerGas:
'maxPriorityFeePerGas' in gasConfig && gasConfig.maxFeePerGas ?
gasConfig.maxFeePerGas
Expand Down
10 changes: 4 additions & 6 deletions packages/plugins/Trader/src/SiteAdaptor/trader/views/Confirm.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { msg, Select, Trans } from '@lingui/macro'
import { useLingui } from '@lingui/react'
import { Icons } from '@masknet/icons'
import { LoadingStatus, PluginWalletStatusBar, ProgressiveText, TokenIcon } from '@masknet/shared'
import { EMPTY_LIST, NetworkPluginID, Sniffings } from '@masknet/shared-base'
Expand All @@ -10,10 +11,9 @@ import {
formatCompact,
GasOptionType,
leftShift,
multipliedBy,
rightShift,
} from '@masknet/web3-shared-base'
import { ChainId, formatWeiToEther } from '@masknet/web3-shared-evm'
import { addGasMargin, 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 All @@ -33,7 +33,6 @@ 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 { useLingui } from '@lingui/react'

const useStyles = makeStyles()((theme) => ({
container: {
Expand Down Expand Up @@ -253,7 +252,7 @@ export const Confirm = memo(function Confirm() {
from: account,
value: transaction.value,
gasPrice: gasConfig.gasPrice ?? transaction.gasPrice,
gas: chainId !== ChainId.Arbitrum && gas ? multipliedBy(gas, 1.2).toFixed(0) : undefined,
gas: gas ? addGasMargin(gas, chainId === ChainId.Arbitrum ? 1 : 0.3) : undefined,
maxPriorityFeePerGas:
'maxPriorityFeePerGas' in gasConfig && gasConfig.maxFeePerGas ?
gasConfig.maxFeePerGas
Expand All @@ -270,7 +269,6 @@ export const Confirm = memo(function Confirm() {

const isApproving = approveMutation.isPending
const isCheckingApprove = isLoadingApproveInfo || isLoadingSpender || isLoadingAllowance
const showStale = isQuoteStale && !isSending && !isApproving

const leaveRef = useLeave()
const queryClient = useQueryClient()
Expand Down Expand Up @@ -388,8 +386,8 @@ export const Confirm = memo(function Confirm() {
mode,
waitForTransaction,
gasOptions,
approveMutation.mutateAsync,
])
const showStale = isQuoteStale && !isSending && !isApproving && !submitting
const loading = isSending || isCheckingApprove || isApproving || submitting
const disabled = !isSwappable || loading || dexIdsCount === 0

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { t } from '@lingui/macro'
import { Icons } from '@masknet/icons'
import { LoadingStatus, TokenIcon } from '@masknet/shared'
import { EMPTY_LIST, NetworkPluginID } from '@masknet/shared-base'
import { NetworkPluginID } from '@masknet/shared-base'
import { makeStyles } from '@masknet/theme'
import { useAccount, useNetworks } from '@masknet/web3-hooks-base'
import { formatBalance } from '@masknet/web3-shared-base'
Expand Down Expand Up @@ -131,10 +131,10 @@ export function HistoryView() {
const { classes, theme } = useStyles()
const { basePath } = useRuntime()
const address = useAccount(NetworkPluginID.PLUGIN_EVM)
const { data: history = EMPTY_LIST, isLoading } = useTradeHistory(address)
const history = useTradeHistory(address)
const networks = useNetworks(NetworkPluginID.PLUGIN_EVM)

if (isLoading) {
if (!history) {
return (
<div className={classes.statusBox}>
<LoadingStatus />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
trimZero,
} from '@masknet/web3-shared-base'
import { isNativeTokenAddress, type ChainId } from '@masknet/web3-shared-evm'
import { Box, Button, Typography } from '@mui/material'
import { Box, Button, Skeleton, Typography } from '@mui/material'
import { BigNumber } from 'bignumber.js'
import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
Expand Down Expand Up @@ -184,9 +184,13 @@ export function TradeView() {
const toChainId = toToken?.chainId as ChainId
const fromNetwork = networks.find((x) => x.chainId === fromChainId)
const toNetwork = networks.find((x) => x.chainId === toChainId)
const { data: fromTokenBalance } = useFungibleTokenBalance(NetworkPluginID.PLUGIN_EVM, fromToken?.address, {
chainId: fromChainId,
})
const { data: fromTokenBalance, isLoading: isLoadingFromTokenBalance } = useFungibleTokenBalance(
NetworkPluginID.PLUGIN_EVM,
fromToken?.address,
{
chainId: fromChainId,
},
)
const { gasFee } = useGasManagement()
const { data: toTokenBalance } = useFungibleTokenBalance(NetworkPluginID.PLUGIN_EVM, toToken?.address, {
chainId: toChainId,
Expand Down Expand Up @@ -271,7 +275,15 @@ export function TradeView() {
</Box>
<Box flexGrow={1}>
<Box height="100%" position="relative">
{fromTokenBalance ?
{isLoadingFromTokenBalance ?
<Box className={classes.tokenStatus}>
<Icons.Wallet size={16} />
<Skeleton className={classes.balance} width={50} variant="rounded" />
<Button type="button" className={classes.maxButton} disabled>
<Trans>MAX</Trans>
</Button>
</Box>
: fromTokenBalance ?
<Box className={classes.tokenStatus}>
<Icons.Wallet size={16} />
<Typography className={classes.balance}>
Expand Down
1 change: 1 addition & 0 deletions packages/plugins/Trader/src/locale/en-US.po

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/plugins/Trader/src/locale/ja-JP.po

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/plugins/Trader/src/locale/ko-KR.po

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/plugins/Trader/src/locale/zh-CN.po

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/plugins/Trader/src/locale/zh-TW.po

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/web3-providers/src/Web3/EVM/apis/Web3StateAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,7 @@ export async function createEVMState(context: WalletAPI.IOContext): Promise<Web3
transactions: state.Transaction!.transactions!,
}),
})
// Warming up
state.TransactionWatcher
return state
}
4 changes: 2 additions & 2 deletions packages/web3-shared/evm/src/helpers/addGasMargin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BigNumber } from 'bignumber.js'

export function addGasMargin(value: BigNumber.Value, scale = 3000) {
return new BigNumber(value).multipliedBy(new BigNumber(10000).plus(scale)).dividedToIntegerBy(10000)
export function addGasMargin(value: BigNumber.Value, scale = 0.3) {
return new BigNumber(value).multipliedBy(1 + scale).toFixed(0)
}

0 comments on commit bf307d8

Please sign in to comment.