Skip to content

Commit

Permalink
fix: gas limit stuff (#11494)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack-Works committed Mar 15, 2024
1 parent b1ecf09 commit c9089f2
Show file tree
Hide file tree
Showing 25 changed files with 135 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
EnhanceableSite,
} from '@masknet/shared-base'
import { queryPersonasDB } from '../../database/persona/web.js'
import { getPluginDefine } from '@masknet/plugin-infra'
import { unreachable } from '@masknet/kit'

function create<T>(settings: ValueRefWithReady<T>) {
async function get() {
Expand Down Expand Up @@ -49,6 +51,18 @@ export async function setCurrentPersonaIdentifier(x?: PersonaIdentifier) {
export async function getPluginMinimalModeEnabled(id: string): Promise<BooleanPreference> {
return getCurrentPluginMinimalMode(id)
}
/**
* Return a resolved result of getPluginMinimalModeEnabled.
* If getPluginMinimalModeEnabled(id) returns BooleanPreference.Default,
* this function will resolve it to true or false based on the plugin default.
*/
export async function getPluginMinimalModeEnabledResolved(id: string): Promise<boolean> {
const result = getCurrentPluginMinimalMode(id)
if (result === BooleanPreference.True) return true
if (result === BooleanPreference.False) return false
if (result === BooleanPreference.Default) return !!getPluginDefine(id)?.inMinimalModeByDefault
unreachable(result)
}
export async function setPluginMinimalModeEnabled(id: string, enabled: boolean) {
setCurrentPluginMinimalMode(id, enabled ? BooleanPreference.True : BooleanPreference.False)

Expand Down
10 changes: 5 additions & 5 deletions packages/mask/popups/components/GasSettingMenu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ export const GasSettingMenu = memo<GasSettingMenuProps>(function GasSettingMenu(
const [, chainDefaultGasLimit] = useGasLimitRange(NetworkPluginID.PLUGIN_EVM, { chainId })
const gasLimit = gasConfig?.gas || defaultGasLimit || chainDefaultGasLimit

const [gasOptionType, setGasOptionType] = useState<GasOptionType | undefined>(
gasConfig?.gasOptionType ?? GasOptionType.SLOW,
)
const [gasOptionType = gasConfig?.gasOptionType ?? GasOptionType.SLOW, setGasOptionType] = useState<
GasOptionType | undefined
>()

const handleChange = useCallback(
(config: GasConfig, type?: GasOptionType) => {
(config: GasConfig, type: GasOptionType) => {
setGasOptionType(type)
setGasConfig(config)
onChange?.(config)
Expand All @@ -75,7 +75,7 @@ export const GasSettingMenu = memo<GasSettingMenuProps>(function GasSettingMenu(
paymentToken,
)

const { data: gasOptions } = useGasOptions()
const { data: gasOptions } = useGasOptions(NetworkPluginID.PLUGIN_EVM, { chainId })

{
const isSupport1559 = useChainIdSupport(NetworkPluginID.PLUGIN_EVM, 'EIP1559', chainId)
Expand Down
9 changes: 6 additions & 3 deletions packages/mask/popups/components/TransactionPreview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,17 +152,20 @@ export const TransactionPreview = memo<TransactionPreviewProps>(function Transac
if (isSupport1559) {
if (transaction.computedPayload.maxFeePerGas && transaction.computedPayload.maxPriorityFeePerGas)
return {
gas: transaction.gas || transaction.computedPayload.gas,
gasOptionType: transaction.gasOptionType,
maxFeePerGas: transaction.computedPayload.maxFeePerGas,
maxPriorityFeePerGas: transaction.computedPayload.maxPriorityFeePerGas,
maxFeePerGas: transaction.maxFeePerGas || transaction.computedPayload.maxFeePerGas,
maxPriorityFeePerGas:
transaction.maxPriorityFeePerGas || transaction.computedPayload.maxPriorityFeePerGas,
}
return
}

if (!transaction.computedPayload.gasPrice) return

return {
gasPrice: transaction.computedPayload.gasPrice,
gas: transaction.gas || transaction.computedPayload.gas,
gasPrice: transaction.gasPrice || transaction.computedPayload.gasPrice,
gasOptionType: transaction.gasOptionType,
}
}, [transaction.computedPayload, transaction.gasOptionType, isSupport1559])
Expand Down
14 changes: 8 additions & 6 deletions packages/mask/popups/hooks/useGasOptionsMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ const useStyles = makeStyles()((theme) => ({

export function useGasOptionsMenu(
gasLimit: string | undefined,
callback: (config: GasConfig, type?: GasOptionType) => void,
callback: (config: GasConfig, type: GasOptionType) => void,
paymentToken?: string,
) {
const t = useMaskSharedTrans()
const { classes } = useStyles()
const { data: gasOptions } = useGasOptions()

const { chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { data: gasOptions } = useGasOptions(NetworkPluginID.PLUGIN_EVM, { chainId })

const isSupport1559 = useChainIdSupport(NetworkPluginID.PLUGIN_EVM, 'EIP1559', chainId)

const [customGasConfig, setCustomGasConfig] = useState<GasConfig>()
Expand All @@ -70,20 +70,22 @@ export function useGasOptionsMenu(
maxFeePerGas: result.maxFeePerGas ? formatWeiToGwei(result.maxFeePerGas).toFixed(2) : '',
maxPriorityFeePerGas:
result.maxPriorityFeePerGas ? formatWeiToGwei(result.maxPriorityFeePerGas).toFixed(2) : '',
gasOptionType: GasOptionType.CUSTOM,
})
} else {
setCustomGasConfig({
...result,
gasPrice: formatWeiToGwei(result.gasPrice).toFixed(2),
gasOptionType: GasOptionType.CUSTOM,
})
}
callback(result)
callback(result, GasOptionType.CUSTOM)
}, [chainId, gasLimit, callback, customGasConfig, paymentToken])

const handleClick = useCallback(
(type?: GasOptionType, option?: GasOption) => {
(type: GasOptionType, option: GasOption | undefined) => {
if (!option) return
const config =
const config: GasConfig =
isSupport1559 ?
{
gasOptionType: type,
Expand Down
19 changes: 17 additions & 2 deletions packages/mask/popups/pages/Swap/SwapBox/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { useMemo } from 'react'
import { useLocation } from 'react-router-dom'
import { NetworkPluginID } from '@masknet/shared-base'
import { NetworkPluginID, PluginID } from '@masknet/shared-base'
import { useChainContext, useFungibleToken } from '@masknet/web3-hooks-base'
import { createERC20Token } from '@masknet/web3-shared-evm'
import { Trader } from '@masknet/plugin-trader'
import { shareToTwitterAsPopup } from '@masknet/shared-base-ui'
import { useQuery } from '@tanstack/react-query'
import Services from '#services'

export function SwapBox() {
const location = useLocation()
Expand All @@ -14,6 +16,12 @@ export function SwapBox() {
const name = params.get('name')
const symbol = params.get('symbol')
const decimals = params.get('decimals')
const isTokenSecurityDisabled =
useQuery({
queryKey: ['Services.Settings.getPluginMinimalModeEnabledResolved(PluginID.GoPlusSecurity)'],
queryFn: () => Services.Settings.getPluginMinimalModeEnabledResolved(PluginID.GoPlusSecurity),
networkMode: 'always',
}).data ?? true

const fallbackToken = useMemo(() => {
return createERC20Token(
Expand All @@ -26,5 +34,12 @@ export function SwapBox() {
}, [chainId, address, name, symbol, decimals])
const { data: coin } = useFungibleToken(NetworkPluginID.PLUGIN_EVM, address ?? '', fallbackToken, { chainId })

return <Trader share={shareToTwitterAsPopup} defaultInputCoin={coin} chainId={chainId} />
return (
<Trader
isTokenSecurityEnabled={isTokenSecurityDisabled}
share={shareToTwitterAsPopup}
defaultInputCoin={coin}
chainId={chainId}
/>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ export const GasSetting1559 = memo(() => {
})

const { value, loading: getValueLoading } = useUnconfirmedRequest()
const { data: gasOptions, isPending: getGasOptionsLoading } = useGasOptions(NetworkPluginID.PLUGIN_EVM)
const { data: gasOptions, isPending: getGasOptionsLoading } = useGasOptions(NetworkPluginID.PLUGIN_EVM, {
chainId: nativeToken?.chainId,
})

// #region Gas options
const options = useMemo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ const minGasPriceOfChain: ChainIdOptionalRecord<BigNumber.Value> = {
export const Prior1559GasSetting = memo(() => {
const t = useMaskSharedTrans()
const { classes } = useStyles()
const { data: gasOptions_ } = useGasOptions(NetworkPluginID.PLUGIN_EVM)
const { chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { data: gasOptions_ } = useGasOptions(NetworkPluginID.PLUGIN_EVM, { chainId })
const { value, loading: getValueLoading } = useUnconfirmedRequest()
const navigate = useNavigate()
const [selected, setOption] = useState<number | null>(null)
Expand Down
36 changes: 34 additions & 2 deletions packages/mask/popups/pages/Wallet/Interaction/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
Suspense,
useTransition,
useLayoutEffect,
useCallback,
} from 'react'
import { BigNumber } from 'bignumber.js'
import { useAsyncFn, useLatest } from 'react-use'
Expand Down Expand Up @@ -54,9 +55,11 @@ import {
parseEIP4361Message,
type EIP4361Message,
TransactionDescriptorType,
GasOptionType,
} from '@masknet/web3-shared-base'
import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useInteractionWalletContext } from './InteractionContext.js'
import { produce } from 'immer'

const useStyles = makeStyles()((theme) => ({
left: {
Expand Down Expand Up @@ -412,7 +415,7 @@ const Interaction = memo((props: InteractionProps) => {
: null
return (
<InteractionItem
key={currentMessageIndex}
key={currentRequest.ID}
paymentToken={paymentToken}
setPaymentToken={setPaymentToken}
currentRequest={currentRequest}
Expand Down Expand Up @@ -454,7 +457,36 @@ const InteractionItem = memo((props: InteractionItemProps) => {
)

const [approvedAmount, setApproveAmount] = useState('')
const [gasConfig, setGasConfig] = useState<GasConfig | undefined>()
const [gasConfig, _setGasConfig] = useState<GasConfig | undefined>()
const { Message } = useWeb3State()
const setGasConfig = useCallback(
(gasConfig: GasConfig) => {
_setGasConfig(gasConfig)
Message?.updateMessage(
currentRequest.ID,
produce(currentRequest, (draft) => {
if (gasConfig.gasOptionType) draft.request.options.gasOptionType = gasConfig.gasOptionType
if (gasConfig.gasOptionType === GasOptionType.CUSTOM) {
draft.request.options.gas = gasConfig.gas
if ('gasPrice' in gasConfig) {
if (gasConfig.gasPrice) draft.request.options.gasPrice = gasConfig.gasPrice
} else {
if (gasConfig.maxFeePerGas) draft.request.options.maxFeePerGas = gasConfig.maxFeePerGas
if (gasConfig.maxPriorityFeePerGas)
draft.request.options.maxPriorityFeePerGas = gasConfig.maxPriorityFeePerGas
}
} else if (gasConfig.gasOptionType) {
// remove them to use new default next time.
delete draft.request.options.gas
delete draft.request.options.gasPrice
delete draft.request.options.maxFeePerGas
delete draft.request.options.maxPriorityFeePerGas
}
}),
)
},
[Message],
)

const isSignRequest = signRequest.includes(currentRequest.request.arguments.method)
let isDangerRequest = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import type { ChainId, GasConfig } from '@masknet/web3-shared-evm'
export function useDefaultGasConfig(chainId: ChainId, gasLimit: string): GasConfig | undefined {
const Utils = useWeb3Utils()
const isSupportEIP1559 = Utils.chainResolver.isFeatureSupported(chainId, 'EIP1559')
const { data: gasOptions } = useGasOptions(NetworkPluginID.PLUGIN_EVM, {
chainId,
})
const { data: gasOptions } = useGasOptions(NetworkPluginID.PLUGIN_EVM, { chainId }, true)

const gasOption = gasOptions?.[GasOptionType.SLOW]

Expand Down
5 changes: 5 additions & 0 deletions packages/mask/popups/pages/Wallet/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ export type TransactionDetail = {
computedPayload: Partial<Transaction>
formattedTransaction?: TransactionDescriptor<ChainId, Transaction, TransactionParameter>
transactionContext?: TransactionContext<ChainId, TransactionParameter>

maxFeePerGas?: string
maxPriorityFeePerGas?: string
gasPrice?: string
gas?: string
}

export enum TransferTabType {
Expand Down
11 changes: 5 additions & 6 deletions packages/plugins/Trader/src/SiteAdaptor/trader/TradeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { makeStyles, MaskColorVar } from '@masknet/theme'
import type { Web3Helper } from '@masknet/web3-helpers'
import { type ChainId, type GasConfig, GasEditor, type Transaction } from '@masknet/web3-shared-evm'
import { rightShift, multipliedBy, isZero, ZERO, formatBalance } from '@masknet/web3-shared-base'
import { PluginID, NetworkPluginID, Sniffings } from '@masknet/shared-base'
import { NetworkPluginID, Sniffings } from '@masknet/shared-base'
import { useChainContext, useNetworkContext, useWeb3Utils } from '@masknet/web3-hooks-base'
import type { TraderAPI } from '@masknet/web3-providers/types'
import { InputTokenPanel } from './InputTokenPanel.js'
Expand All @@ -22,7 +22,6 @@ import { AllProviderTradeContext } from '../../trader/useAllProviderTradeContext
import { currentSlippageSettings } from '../../settings.js'
import { PluginTraderMessages } from '../../messages.js'
import { useTraderTrans } from '../../locales/index.js'
import { useActivatedPlugins } from './hooks/useMinimalMaybe.js'

const useStyles = makeStyles()((theme) => {
return {
Expand Down Expand Up @@ -170,6 +169,7 @@ const useStyles = makeStyles()((theme) => {
})

interface AllTradeFormProps extends withClasses<'root'> {
isTokenSecurityEnabled: boolean
inputAmount: string
inputToken?: Web3Helper.FungibleTokenAll
outputToken?: Web3Helper.FungibleTokenAll
Expand Down Expand Up @@ -203,6 +203,7 @@ export const TradeForm = memo<AllTradeFormProps>(
onSwitch,
settings,
gasConfig,
isTokenSecurityEnabled,
...props
}) => {
const maxAmountTrade = useRef<AsyncStateRetry<TraderAPI.TradeInfo> | null>(null)
Expand All @@ -215,8 +216,6 @@ export const TradeForm = memo<AllTradeFormProps>(
const { allTradeComputed } = AllProviderTradeContext.useContainer()
const [isExpand, setExpand] = useState(false)

const isTokenSecurityEnable = !useActivatedPlugins().some((x) => x.ID === PluginID.GoPlusSecurity)

// #region token balance
const inputTokenBalanceAmount = new BigNumber(inputTokenBalance || '0')
// #endregion
Expand Down Expand Up @@ -348,7 +347,7 @@ export const TradeForm = memo<AllTradeFormProps>(
const { value: tokenSecurityInfo, error } = useTokenSecurity(
pluginID === NetworkPluginID.PLUGIN_EVM ? (chainId as ChainId) : undefined,
outputToken?.address.trim(),
isTokenSecurityEnable,
isTokenSecurityEnabled,
)

return (
Expand Down Expand Up @@ -401,7 +400,7 @@ export const TradeForm = memo<AllTradeFormProps>(
}}
/>
<Box marginTop="8px">
{isTokenSecurityEnable && tokenSecurityInfo && !error ?
{isTokenSecurityEnabled && tokenSecurityInfo && !error ?
<TokenSecurityBar tokenSecurity={tokenSecurityInfo} />
: null}
</Box>
Expand Down
3 changes: 3 additions & 0 deletions packages/plugins/Trader/src/SiteAdaptor/trader/Trader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { ConfirmDialog } from './ConfirmDialog.js'
import { Icons } from '@masknet/icons'

export interface TraderProps extends withClasses<'root'> {
isTokenSecurityEnabled: boolean
defaultInputCoin?: Web3Helper.FungibleTokenAll
defaultOutputCoin?: Web3Helper.FungibleTokenAll
chainId?: Web3Helper.ChainIdAll
Expand Down Expand Up @@ -413,6 +414,7 @@ export const Trader = forwardRef<TraderRef, TraderProps>((props: TraderProps, re
return (
<>
<TradeForm
isTokenSecurityEnabled={props.isTokenSecurityEnabled}
isSmartPay={
!!wallet?.owner &&
chainId === smartPayConfig?.smartPayChainId &&
Expand Down Expand Up @@ -454,6 +456,7 @@ export const Trader = forwardRef<TraderRef, TraderProps>((props: TraderProps, re
: null}

<TraderStateBar
isTokenSecurityEnabled={props.isTokenSecurityEnabled}
trades={sortedAllTradeComputed}
inputToken={inputToken}
outputToken={outputToken}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState, useMemo } from 'react'
import { useAsyncFn } from 'react-use'
import { PluginID, NetworkPluginID, CrossIsolationMessages, type TokenType, Sniffings } from '@masknet/shared-base'
import { useActivatedPluginSiteAdaptor } from '@masknet/plugin-infra/content-script'
import { useActivatedPluginSiteAdaptor, useIsMinimalMode } from '@masknet/plugin-infra/content-script'
import {
useChainContext,
useChainIdValid,
Expand Down Expand Up @@ -88,6 +88,7 @@ const useStyles = makeStyles<{ rotate: boolean }>()((theme, { rotate }) => ({
export function TraderDialog(props: { share: ((text: string) => void) | undefined }) {
const tradeRef = useRef<TraderRef>(null)
const traderDefinition = useActivatedPluginSiteAdaptor.visibility.useAnyMode(PluginID.Trader)
const isTokenSecurityEnabled = !useIsMinimalMode(PluginID.GoPlusSecurity)
const { pluginID } = useNetworkContext()
const { chainId, setChainId } = useChainContext()
const Utils = useWeb3Utils()
Expand Down Expand Up @@ -229,6 +230,7 @@ export function TraderDialog(props: { share: ((text: string) => void) | undefine
</div>
<AllProviderTradeContext.Provider>
<Trader
isTokenSecurityEnabled={isTokenSecurityEnabled}
share={props.share}
defaultInputCoin={defaultInputCoin ? inputToken : undefined}
defaultOutputCoin={defaultOutputCoin ? outputToken : undefined}
Expand Down

0 comments on commit c9089f2

Please sign in to comment.