diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/index.tsx index bdae6c7ac30a..4d3a0e074628 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/index.tsx @@ -15,7 +15,7 @@ import { import { useDashboardI18N } from '../../../../locales' import { ChangeNetworkTip } from './ChangeNetworkTip' import { getTokenUSDValue } from '../../utils/getTokenUSDValue' -import { pow10 } from '@masknet/web3-shared-base' +import { pow10, toFixed } from '@masknet/web3-shared-base' const useStyles = makeStyles()((theme) => ({ icon: { @@ -101,9 +101,7 @@ export const FungibleTokenTableRow = memo(({ asset, onSend, - - {new BigNumber(Utils?.formatBalance?.(asset.balance, asset.token.decimals) ?? '').toFixed(6)} - + {toFixed(Utils?.formatBalance?.(asset.balance, asset.token.decimals) ?? '', 6)} diff --git a/packages/dashboard/src/pages/Wallets/hooks/useGasConfig.ts b/packages/dashboard/src/pages/Wallets/hooks/useGasConfig.ts index 52ad8791284b..96ca12c33e33 100644 --- a/packages/dashboard/src/pages/Wallets/hooks/useGasConfig.ts +++ b/packages/dashboard/src/pages/Wallets/hooks/useGasConfig.ts @@ -1,15 +1,11 @@ import { useEffect, useMemo, useState } from 'react' -import { toHex, toWei } from 'web3-utils' +import { toHex } from 'web3-utils' import BigNumber from 'bignumber.js' import { formatGweiToWei, GasOption, isEIP1559Supported, useChainId, useGasPrice } from '@masknet/web3-shared-evm' import { useRemoteControlledDialog } from '@masknet/shared' import { WalletMessages } from '@masknet/plugin-wallet' import { useGasOptions } from '../../../hooks/useGasOptions' -function gweiToWei(gwei: number | string) { - return toWei(new BigNumber(gwei).toFixed(9), 'gwei') -} - export const useGasConfig = (gasLimit: number, minGasLimit: number) => { const chainId = useChainId() diff --git a/packages/mask/src/extension/popups/pages/Wallet/GasSetting/GasSetting1559.tsx b/packages/mask/src/extension/popups/pages/Wallet/GasSetting/GasSetting1559.tsx index 481da3c42819..a72d630a7ad0 100644 --- a/packages/mask/src/extension/popups/pages/Wallet/GasSetting/GasSetting1559.tsx +++ b/packages/mask/src/extension/popups/pages/Wallet/GasSetting/GasSetting1559.tsx @@ -31,6 +31,7 @@ import { isLessThanOrEqualTo, isPositive, multipliedBy, + toFixed, } from '@masknet/web3-shared-base' const useStyles = makeStyles()((theme) => ({ @@ -241,12 +242,9 @@ export const GasSetting1559 = memo(() => { if (value?.computedPayload._tx.maxFeePerGas && value?.computedPayload._tx.maxPriorityFeePerGas) { setValue( 'maxPriorityFeePerGas', - fromWei(new BigNumber(value.computedPayload._tx.maxPriorityFeePerGas).toString(), 'gwei'), - ) - setValue( - 'maxFeePerGas', - fromWei(new BigNumber(value.computedPayload._tx.maxFeePerGas).toFixed(), 'gwei'), + fromWei(toFixed(value.computedPayload._tx.maxPriorityFeePerGas), 'gwei'), ) + setValue('maxFeePerGas', fromWei(toFixed(value.computedPayload._tx.maxFeePerGas), 'gwei')) } else { setOption(1) } @@ -345,7 +343,7 @@ export const GasSetting1559 = memo(() => { className={selected === index ? classes.selected : undefined}> {title} - {new BigNumber(content?.suggestedMaxFeePerGas ?? 0).toFixed(2)} + {toFixed(content?.suggestedMaxFeePerGas, 2)} {t('wallet_transfer_gwei')} diff --git a/packages/mask/src/plugins/CryptoartAI/hooks/usePlaceBidCallback.ts b/packages/mask/src/plugins/CryptoartAI/hooks/usePlaceBidCallback.ts index 57bcc9939e9b..f31d5f64a5a5 100644 --- a/packages/mask/src/plugins/CryptoartAI/hooks/usePlaceBidCallback.ts +++ b/packages/mask/src/plugins/CryptoartAI/hooks/usePlaceBidCallback.ts @@ -1,5 +1,4 @@ import { useCallback } from 'react' -import BigNumber from 'bignumber.js' import { ZERO_ADDRESS, TransactionEventType, @@ -10,6 +9,7 @@ import { } from '@masknet/web3-shared-evm' import type { NonPayableTx } from '@masknet/web3-contracts/types/types' import { useCryptoArtAI_Contract } from './useCryptoArtAI_Contract' +import { toFixed } from '@masknet/web3-shared-base' export function usePlaceBidCallback(is24Auction: boolean, editionNumber: string) { const account = useAccount() @@ -40,13 +40,13 @@ export function usePlaceBidCallback(is24Auction: boolean, editionNumber: string) // estimate gas and compose transaction const config = { from: account, - value: new BigNumber(priceInWei).toFixed(), + value: toFixed(priceInWei), gas: !is24Auction ? await artistAcceptingBidsV2_contract?.methods .placeBid(editionNumber) .estimateGas({ from: account, - value: new BigNumber(priceInWei).toFixed(), + value: toFixed(priceInWei), }) .catch((error) => { setPlaceBidState({ @@ -59,7 +59,7 @@ export function usePlaceBidCallback(is24Auction: boolean, editionNumber: string) .placeBid(editionNumber, ZERO_ADDRESS) .estimateGas({ from: account, - value: new BigNumber(priceInWei).toFixed(), + value: toFixed(priceInWei), }) .catch((error) => { setPlaceBidState({ diff --git a/packages/mask/src/plugins/CryptoartAI/hooks/usePurchaseCallback.ts b/packages/mask/src/plugins/CryptoartAI/hooks/usePurchaseCallback.ts index 6f7e9c26feb0..6255c2f66e74 100644 --- a/packages/mask/src/plugins/CryptoartAI/hooks/usePurchaseCallback.ts +++ b/packages/mask/src/plugins/CryptoartAI/hooks/usePurchaseCallback.ts @@ -1,5 +1,4 @@ import { useCallback } from 'react' -import BigNumber from 'bignumber.js' import type { NonPayableTx } from '@masknet/web3-contracts/types/types' import { TransactionEventType, @@ -9,6 +8,7 @@ import { useChainId, } from '@masknet/web3-shared-evm' import { useCryptoArtAI_Contract } from './useCryptoArtAI_Contract' +import { toFixed } from '@masknet/web3-shared-base' export function usePurchaseCallback(editionNumber: string, priceInWei: number) { const account = useAccount() @@ -32,12 +32,12 @@ export function usePurchaseCallback(editionNumber: string, priceInWei: number) { // estimate gas and compose transaction const config = { from: account, - value: new BigNumber(priceInWei).toFixed(), + value: toFixed(priceInWei), gas: await knownOriginDigitalAssetV2_contract.methods .purchase(editionNumber) .estimateGas({ from: account, - value: new BigNumber(priceInWei).toFixed(), + value: toFixed(priceInWei), }) .catch((error) => { setPurchaseState({ diff --git a/packages/mask/src/plugins/Gitcoin/hooks/useDonateCallback.ts b/packages/mask/src/plugins/Gitcoin/hooks/useDonateCallback.ts index ca2929aadb6f..dbd671e85aa0 100644 --- a/packages/mask/src/plugins/Gitcoin/hooks/useDonateCallback.ts +++ b/packages/mask/src/plugins/Gitcoin/hooks/useDonateCallback.ts @@ -1,4 +1,5 @@ import type { PayableTx } from '@masknet/web3-contracts/types/types' +import { toFixed } from '@masknet/web3-shared-base' import { EthereumTokenType, FungibleTokenDetailed, @@ -60,7 +61,7 @@ export function useDonateCallback(address: string, amount: string, token?: Fungi }) // estimate gas and compose transaction - const value = new BigNumber(token.type === EthereumTokenType.Native ? amount : 0).toFixed() + const value = toFixed(token.type === EthereumTokenType.Native ? amount : 0) const config = { from: account, gas: await bulkCheckoutContract.methods diff --git a/packages/mask/src/plugins/GoodGhosting/UI/GameStatsView.tsx b/packages/mask/src/plugins/GoodGhosting/UI/GameStatsView.tsx index 8730687cb024..f28555074d68 100644 --- a/packages/mask/src/plugins/GoodGhosting/UI/GameStatsView.tsx +++ b/packages/mask/src/plugins/GoodGhosting/UI/GameStatsView.tsx @@ -4,10 +4,10 @@ import { makeStyles } from '@masknet/theme' import type { AsyncStateRetry } from 'react-use/lib/useAsyncRetry' import type { GameAssets, GoodGhostingInfo, LendingPoolData, Player } from '../types' import { CircularDataDisplay } from './CircularDataDisplay' -import BigNumber from 'bignumber.js' import { useGameToken, useRewardToken } from '../hooks/usePoolData' import { useI18N } from '../../../utils' import { getGameFinancialData, getPlayerStandings, getReadableInterval } from '../utils' +import { toFixed } from '@masknet/web3-shared-base' const useStyles = makeStyles()((theme) => ({ infoRow: { @@ -153,7 +153,7 @@ export function GameStatsView(props: GameStatsViewProps) {
@@ -164,7 +164,7 @@ export function GameStatsView(props: GameStatsViewProps) {
diff --git a/packages/mask/src/plugins/ITO/SNSAdaptor/hooks/useSwapCallback.ts b/packages/mask/src/plugins/ITO/SNSAdaptor/hooks/useSwapCallback.ts index abf4e9a2c972..6fb7a13ffb29 100644 --- a/packages/mask/src/plugins/ITO/SNSAdaptor/hooks/useSwapCallback.ts +++ b/packages/mask/src/plugins/ITO/SNSAdaptor/hooks/useSwapCallback.ts @@ -15,8 +15,7 @@ import { isSameAddress, useITOConstants, } from '@masknet/web3-shared-evm' -import { isPositive, isZero } from '@masknet/web3-shared-base' -import BigNumber from 'bignumber.js' +import { isPositive, isZero, toFixed } from '@masknet/web3-shared-base' import { useCallback } from 'react' import type { TransactionReceipt } from 'web3-core' import Web3Utils from 'web3-utils' @@ -167,7 +166,7 @@ export function useSwapCallback( ] as Parameters // estimate gas and compose transaction - const value = new BigNumber(token.type === EthereumTokenType.Native ? total : '0').toFixed() + const value = toFixed(token.type === EthereumTokenType.Native ? total : 0) const config = { from: account, gas: isQualificationHasLucky diff --git a/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useCreateCallback.tsx b/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useCreateCallback.tsx index 4ebff03860d5..15946fe3aadc 100644 --- a/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useCreateCallback.tsx +++ b/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useCreateCallback.tsx @@ -1,4 +1,3 @@ -import BigNumber from 'bignumber.js' import { omit } from 'lodash-unified' import { useCallback, useRef, useState } from 'react' import { useAsync } from 'react-use' @@ -17,7 +16,7 @@ import { useTokenConstants, useTransactionState, } from '@masknet/web3-shared-evm' -import { isLessThan } from '@masknet/web3-shared-base' +import { isLessThan, toFixed } from '@masknet/web3-shared-base' import { useRedPacketContract } from './useRedPacketContract' export interface RedPacketSettings { @@ -104,7 +103,7 @@ export function useCreateParams(redPacketSettings: RedPacketSettings | undefined const params = Object.values(omit(paramsObj, ['token'])) as MethodParameters let gasError = null as Error | null - const value = new BigNumber(paramsObj.token?.type === EthereumTokenType.Native ? total : '0').toFixed() + const value = toFixed(paramsObj.token?.type === EthereumTokenType.Native ? total : 0) const gas = await (redPacketContract as HappyRedPacketV4).methods .create_red_packet(...params) @@ -157,7 +156,7 @@ export function useCreateCallback(redPacketSettings: RedPacketSettings, version: }) // estimate gas and compose transaction - const value = new BigNumber(token.type === EthereumTokenType.Native ? paramsObj.total : '0').toFixed() + const value = toFixed(token.type === EthereumTokenType.Native ? paramsObj.total : 0) const config = { from: account, value, diff --git a/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Gas1559Settings.tsx b/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Gas1559Settings.tsx index 7fbc1c5c3c20..5b5aa168ccfa 100644 --- a/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Gas1559Settings.tsx +++ b/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Gas1559Settings.tsx @@ -14,7 +14,14 @@ import { ExpandMore } from '@mui/icons-material' import { fromWei, toHex } from 'web3-utils' import { isEmpty } from 'lodash-unified' import ActionButton from '../../../../extension/options-page/DashboardComponents/ActionButton' -import { isGreaterThan, isLessThan, isLessThanOrEqualTo, isPositive, multipliedBy } from '@masknet/web3-shared-base' +import { + isGreaterThan, + isLessThan, + isLessThanOrEqualTo, + isPositive, + multipliedBy, + toFixed, +} from '@masknet/web3-shared-base' import { isDashboardPage } from '@masknet/shared-base' const useStyles = makeStyles<{ isDashboard: boolean }>()((theme, { isDashboard }) => ({ @@ -237,8 +244,8 @@ export const Gas1559Settings = memo(({ onCancel, onSave: o useEffect(() => { if (selected === null) return const { content } = options[selected] - setValue('maxPriorityFeePerGas', new BigNumber(content?.suggestedMaxPriorityFeePerGas ?? 0).toFixed() ?? '') - setValue('maxFeePerGas', new BigNumber(content?.suggestedMaxFeePerGas ?? 0).toFixed() ?? '') + setValue('maxPriorityFeePerGas', toFixed(content?.suggestedMaxPriorityFeePerGas)) + setValue('maxFeePerGas', toFixed(content?.suggestedMaxFeePerGas)) }, [selected, setValue, options]) //#endregion diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/GasSettingDialog/GasSetting1559.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/GasSettingDialog/GasSetting1559.tsx index 8d8bd0c44759..1ebd10041bef 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/GasSettingDialog/GasSetting1559.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/GasSettingDialog/GasSetting1559.tsx @@ -22,6 +22,7 @@ import { isLessThanOrEqualTo, isPositive, multipliedBy, + toFixed, } from '@masknet/web3-shared-base' const HIGH_FEE_WARNING_MULTIPLIER = 1.5 @@ -191,7 +192,7 @@ export const GasSetting1559: FC = memo( className={selectedGasOption === gasOption ? classes.selected : undefined}> {title} - {new BigNumber(content?.suggestedMaxFeePerGas ?? 0).toFixed(2)} + {toFixed(content?.suggestedMaxFeePerGas, 2)} Gwei diff --git a/packages/mask/src/plugins/Wallet/services/assets.ts b/packages/mask/src/plugins/Wallet/services/assets.ts index c23b3edc208c..5df91424e8d0 100644 --- a/packages/mask/src/plugins/Wallet/services/assets.ts +++ b/packages/mask/src/plugins/Wallet/services/assets.ts @@ -1,5 +1,5 @@ import { unreachable } from '@dimensiondev/kit' -import { leftShift, multipliedBy, rightShift } from '@masknet/web3-shared-base' +import { leftShift, multipliedBy, rightShift, toFixed } from '@masknet/web3-shared-base' import { Asset, ChainId, @@ -163,7 +163,7 @@ function formatAssetsFromDebank(data: WalletTokenRecord[], network?: NetworkType ), balance: rightShift(y.amount, y.decimals).toFixed(), price: { - [CurrencyType.USD]: new BigNumber(y.price ?? 0).toFixed(), + [CurrencyType.USD]: toFixed(y.price), }, value: { [CurrencyType.USD]: multipliedBy(y.price ?? 0, y.amount).toFixed(), diff --git a/packages/mask/src/plugins/dHEDGE/hooks/useInvestCallback.ts b/packages/mask/src/plugins/dHEDGE/hooks/useInvestCallback.ts index 1d413a05b9f9..ab5f0b2a58dd 100644 --- a/packages/mask/src/plugins/dHEDGE/hooks/useInvestCallback.ts +++ b/packages/mask/src/plugins/dHEDGE/hooks/useInvestCallback.ts @@ -1,5 +1,4 @@ import { useCallback } from 'react' -import BigNumber from 'bignumber.js' import { FungibleTokenDetailed, EthereumTokenType, @@ -10,6 +9,7 @@ import { } from '@masknet/web3-shared-evm' import { useDHedgePoolV1Contract, useDHedgePoolV2Contract } from '../contracts/useDHedgePool' import { Pool, PoolType } from '../types' +import { toFixed } from '@masknet/web3-shared-base' /** * A callback for invest dhedge pool @@ -40,7 +40,7 @@ export function useInvestCallback(pool: Pool | undefined, amount: string, token? // step 1: estimate gas const config = { from: account, - value: new BigNumber(token.type === EthereumTokenType.Native ? amount : 0).toFixed(), + value: toFixed(token.type === EthereumTokenType.Native ? amount : 0), } const deposit = () => { diff --git a/packages/plugins/Flow/src/UI/Web3State/index.ts b/packages/plugins/Flow/src/UI/Web3State/index.ts index 48ae5c34b1c5..6e22d68f829c 100644 --- a/packages/plugins/Flow/src/UI/Web3State/index.ts +++ b/packages/plugins/Flow/src/UI/Web3State/index.ts @@ -1,4 +1,3 @@ -import BigNumber from 'bignumber.js' import type { Web3Plugin } from '@masknet/plugin-infra' import { NetworkType, @@ -11,6 +10,7 @@ import { createConstantSubscription, mapSubscription } from '@masknet/shared-bas import { getStorage, StorageDefaultValue } from '../../storage' import { formatAddress } from '../../helpers' import { getFungibleAssets } from '../../apis' +import { toFixed } from '@masknet/web3-shared-base' function createSubscriptionFromChainId(getter: (value: typeof StorageDefaultValue.chainId) => T) { return mapSubscription(getStorage().chainId.subscription, getter) @@ -49,8 +49,8 @@ export function createWeb3State(signal: AbortSignal): Web3Plugin.ObjectCapabilit }, Utils: { formatAddress, - formatBalance: (value) => new BigNumber(value).toFixed(), - formatCurrency: (value) => new BigNumber(value).toFixed(), + formatBalance: toFixed, + formatCurrency: toFixed, isChainIdValid: () => true, diff --git a/packages/plugins/Solana/src/UI/Web3State/index.ts b/packages/plugins/Solana/src/UI/Web3State/index.ts index 92ea8098cbb0..bea02126b0bc 100644 --- a/packages/plugins/Solana/src/UI/Web3State/index.ts +++ b/packages/plugins/Solana/src/UI/Web3State/index.ts @@ -1,5 +1,6 @@ import type { Web3Plugin } from '@masknet/plugin-infra' import { createConstantSubscription, mapSubscription } from '@masknet/shared-base' +import { toFixed } from '@masknet/web3-shared-base' import { ChainId, NetworkType, @@ -8,7 +9,6 @@ import { resolveBlockLinkOnExplorer, resolveTransactionLinkOnExplorer, } from '@masknet/web3-shared-solana' -import BigNumber from 'bignumber.js' import { getFungibleAssets, getNonFungibleAssets } from '../../apis' import { formatAddress } from '../../helpers' import { getStorage, StorageDefaultValue } from '../../storage' @@ -49,8 +49,8 @@ export function createWeb3State(signal: AbortSignal): Web3Plugin.ObjectCapabilit }, Utils: { formatAddress, - formatBalance: (value) => new BigNumber(value).toFixed(), - formatCurrency: (value) => new BigNumber(value).toFixed(), + formatBalance: toFixed, + formatCurrency: toFixed, isChainIdValid: () => true, diff --git a/packages/web3-providers/src/debank/format.ts b/packages/web3-providers/src/debank/format.ts index cca95cbff9f7..2be6bc09e113 100644 --- a/packages/web3-providers/src/debank/format.ts +++ b/packages/web3-providers/src/debank/format.ts @@ -1,8 +1,7 @@ -import BigNumber from 'bignumber.js' import type { WalletTokenRecord } from './type' import { ChainId, createNativeToken, getChainIdFromName } from '@masknet/web3-shared-evm' import { CurrencyType, TokenType, Web3Plugin } from '@masknet/plugin-infra' -import { multipliedBy, rightShift } from '@masknet/web3-shared-base' +import { multipliedBy, rightShift, toFixed } from '@masknet/web3-shared-base' import DeBank from '@masknet/web3-constants/evm/debank.json' type Asset = Web3Plugin.Asset @@ -31,7 +30,7 @@ export function formatAssets(data: WalletTokenRecord[]): Asset[] { }, balance: rightShift(y.amount, y.decimals).toFixed(), price: { - [CurrencyType.USD]: new BigNumber(y.price ?? 0).toFixed(), + [CurrencyType.USD]: toFixed(y.price), }, value: { [CurrencyType.USD]: multipliedBy(y.price ?? 0, y.amount).toFixed(), diff --git a/packages/web3-shared/base/utils/number.ts b/packages/web3-shared/base/utils/number.ts index e33743a7c16f..cae948297267 100644 --- a/packages/web3-shared/base/utils/number.ts +++ b/packages/web3-shared/base/utils/number.ts @@ -62,3 +62,10 @@ export function leftShift(n: BigNumber.Value, m: number | undefined | null) { export function dividedBy(a: BigNumber.Value, b: BigNumber.Value) { return new BigNumber(a).dividedBy(b) } + +export function toFixed(value: BigNumber.Value | undefined): string +export function toFixed(value: BigNumber.Value | undefined, decimalPlaces: number): string +export function toFixed(value: BigNumber.Value = 0, decimalPlaces?: number) { + const n = new BigNumber(value) + return decimalPlaces ? n.toFixed(decimalPlaces) : n.toFixed() +} diff --git a/packages/web3-shared/evm/hooks/useERC20TokenApproveCallback.ts b/packages/web3-shared/evm/hooks/useERC20TokenApproveCallback.ts index d4a459813758..346b49771765 100644 --- a/packages/web3-shared/evm/hooks/useERC20TokenApproveCallback.ts +++ b/packages/web3-shared/evm/hooks/useERC20TokenApproveCallback.ts @@ -1,5 +1,4 @@ import { useCallback, useMemo } from 'react' -import BigNumber from 'bignumber.js' import { once } from 'lodash-unified' import type { NonPayableTx } from '@masknet/web3-contracts/types/types' import { TransactionStateType, TransactionEventType } from '../types' @@ -8,9 +7,9 @@ import { useAccount } from './useAccount' import { useERC20TokenAllowance } from './useERC20TokenAllowance' import { useERC20TokenBalance } from './useERC20TokenBalance' import { useTransactionState } from './useTransactionState' -import { isLessThan } from '@masknet/web3-shared-base' +import { isLessThan, toFixed } from '@masknet/web3-shared-base' -const MaxUint256 = new BigNumber('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff').toFixed() +const MaxUint256 = toFixed('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff') export enum ApproveStateType { UNKNOWN = 0,