Skip to content

Commit

Permalink
refactor: hub state
Browse files Browse the repository at this point in the history
  • Loading branch information
guanbinrui committed May 20, 2022
1 parent c767c06 commit f883f2d
Show file tree
Hide file tree
Showing 71 changed files with 1,094 additions and 734 deletions.
12 changes: 12 additions & 0 deletions .i18n-codegen.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,18 @@
"sourceMap": "inline"
}
},
{
"input": "./packages/plugins/DAO/src/locales/en-US.json",
"output": "./packages/plugins/DAO/src/locales/i18n_generated",
"parser": { "type": "i18next", "contextSeparator": "$", "pluralSeparator": "_" },
"generator": {
"type": "i18next/react-hooks",
"hooks": "useI18N",
"namespace": "money.juicebox",
"trans": "Translate",
"sourceMap": "inline"
}
},
{
"input": "./packages/plugins/CyberConnect/src/locales/en-US.json",
"output": "./packages/plugins/CyberConnect/src/locales/i18n_generated",
Expand Down
21 changes: 11 additions & 10 deletions packages/mask/src/extension/background-script/BackupService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ export * from '../../../background/services/backup'
import { assertEnvironment, Environment } from '@dimensiondev/holoflows-kit'
assertEnvironment(Environment.ManifestBackground)

import { ProviderType } from '@masknet/web3-shared-evm'
import {
exportMnemonic,
exportPrivateKey,
Expand Down Expand Up @@ -97,22 +96,24 @@ delegateWalletRestore(async function (backup) {
async function backupAllWallets(): Promise<NormalizedBackup.WalletBackup[]> {
const allSettled = await Promise.allSettled(
(
await getWallets(ProviderType.MaskWallet)
).map(async (wallet) => {
return {
...wallet,
mnemonic: wallet.derivationPath ? await exportMnemonic(wallet.address) : undefined,
privateKey: wallet.derivationPath ? undefined : await exportPrivateKey(wallet.address),
}
}),
await getWallets()
)
.filter((x) => x.storedKeyInfo)
.map(async (wallet) => {
return {
...wallet,
mnemonic: wallet.derivationPath ? await exportMnemonic(wallet.address) : undefined,
privateKey: wallet.derivationPath ? undefined : await exportPrivateKey(wallet.address),
}
}),
)
const wallets_ = allSettled.map((x) => (x.status === 'fulfilled' ? WalletRecordToJSONFormat(x.value) : null))
if (wallets_.some((x) => !x)) throw new Error('Failed to backup wallets.')
return wallets_.filter(isNonNull)
}

async function backupAllLegacyWallets(): Promise<NormalizedBackup.WalletBackup[]> {
const x = await getLegacyWallets(ProviderType.MaskWallet)
const x = await getLegacyWallets()
return x.map(LegacyWalletRecordToJSONFormat)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Button, Typography } from '@mui/material'
import { makeStyles } from '@masknet/theme'
import { WalletIcon, WarningIcon } from '@masknet/icons'
import { useNavigate } from 'react-router-dom'
import { ProviderType, formatEthereumAddress } from '@masknet/web3-shared-evm'
import { formatEthereumAddress } from '@masknet/web3-shared-evm'
import { PopupRoutes } from '@masknet/shared-base'
import { first } from 'lodash-unified'
import { FormattedAddress } from '@masknet/shared'
Expand Down Expand Up @@ -111,7 +111,7 @@ const DeleteWallet = memo(() => {
if (wallet?.address) {
try {
await WalletRPC.removeWallet(wallet.address, password)
const wallets = await WalletRPC.getWallets(ProviderType.MaskWallet)
const wallets = await WalletRPC.getWallets()

const otherWalletAddress = first(wallets)?.address

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { makeStyles } from '@masknet/theme'
import { isLessThan, NetworkPluginID, pow10, TransactionDescriptorType } from '@masknet/web3-shared-base'
import { GasOptionType, isLessThan, NetworkPluginID, pow10, TransactionDescriptorType } from '@masknet/web3-shared-base'
import { memo, useEffect, useMemo, useState } from 'react'
import { useI18N } from '../../../../../utils'
import { useAsync, useAsyncFn, useUpdateEffect } from 'react-use'
Expand All @@ -23,7 +23,7 @@ import { isEmpty } from 'lodash-unified'
import { useNavigate } from 'react-router-dom'
import { PopupRoutes } from '@masknet/shared-base'
import { toHex } from 'web3-utils'
import { useChainId, useNativeToken, useNativeTokenPrice, useWeb3, useWeb3State } from '@masknet/plugin-infra/web3'
import { useChainId, useGasOptions, useNativeToken, useNativeTokenPrice, useWeb3 } from '@masknet/plugin-infra/web3'

const useStyles = makeStyles()((theme) => ({
options: {
Expand Down Expand Up @@ -99,7 +99,7 @@ export const Prior1559GasSetting = memo(() => {
const { t } = useI18N()
const { classes } = useStyles()
const web3 = useWeb3(NetworkPluginID.PLUGIN_EVM)
const { GasOptions } = useWeb3State(NetworkPluginID.PLUGIN_EVM)
const { value: gasOptions_ } = useGasOptions(NetworkPluginID.PLUGIN_EVM)
const chainId = useChainId(NetworkPluginID.PLUGIN_EVM)
const { value, loading: getValueLoading } = useUnconfirmedRequest()
const [getGasLimitError, setGetGasLimitError] = useState(false)
Expand All @@ -111,15 +111,13 @@ export const Prior1559GasSetting = memo(() => {
})

// #region Get gas options from debank
const { value: gasOptions } = useAsync(async () => {
const gasOptions = await GasOptions?.getGasOptions?.(chainId)
if (!gasOptions) return null
const gasOptions = useMemo(() => {
return {
slow: gasOptions.slow.suggestedMaxFeePerGas,
standard: gasOptions.normal.suggestedMaxFeePerGas,
fast: gasOptions.fast.suggestedMaxFeePerGas,
slow: gasOptions_?.[GasOptionType.SLOW].suggestedMaxFeePerGas ?? 0,
standard: gasOptions_?.[GasOptionType.NORMAL].suggestedMaxFeePerGas ?? 0,
fast: gasOptions_?.[GasOptionType.FAST].suggestedMaxFeePerGas ?? 0,
}
}, [chainId])
}, [chainId, gasOptions_])
// #endregion

const options = useMemo(
Expand All @@ -128,15 +126,15 @@ export const Prior1559GasSetting = memo(() => {
? [
{
title: t('popups_wallet_gas_fee_settings_low'),
gasPrice: gasOptions?.slow ?? 0,
gasPrice: gasOptions.slow,
},
{
title: t('popups_wallet_gas_fee_settings_medium'),
gasPrice: gasOptions?.standard ?? 0,
gasPrice: gasOptions.standard,
},
{
title: t('popups_wallet_gas_fee_settings_high'),
gasPrice: gasOptions?.fast ?? 0,
gasPrice: gasOptions.fast,
},
]
: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
useWallet,
useWeb3State,
useWeb3Connection,
useGasOptions,
} from '@masknet/plugin-infra/web3'
import { AccountItem } from './AccountItem'
import { TransferAddressError } from '../type'
Expand Down Expand Up @@ -194,7 +195,7 @@ export const Transfer1559 = memo<Transfer1559Props>(({ selectedAsset, openAssetM
const chainId = useChainId(NetworkPluginID.PLUGIN_EVM)
const network = useNetworkType(NetworkPluginID.PLUGIN_EVM)
const connection = useWeb3Connection(NetworkPluginID.PLUGIN_EVM)
const { Others, GasOptions } = useWeb3State(NetworkPluginID.PLUGIN_EVM)
const { Others } = useWeb3State(NetworkPluginID.PLUGIN_EVM)
const { value: nativeToken } = useFungibleToken(NetworkPluginID.PLUGIN_EVM)

const navigate = useNavigate()
Expand All @@ -206,7 +207,9 @@ export const Transfer1559 = memo<Transfer1559Props>(({ selectedAsset, openAssetM
chainId: nativeToken?.chainId,
})

const { value: estimateGasFees } = useAsync(async () => GasOptions?.getGasOptions?.(chainId), [chainId])
const { value: estimateGasFees } = useGasOptions(NetworkPluginID.PLUGIN_EVM, {
chainId,
})

const schema = useMemo(() => {
return zod
Expand Down
10 changes: 6 additions & 4 deletions packages/mask/src/plugins/Pets/hooks/useNfts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import {
NonFungibleTokenContract,
transform,
FungibleAsset,
Constant,
Constants,
} from '@masknet/web3-shared-base'
import { resolveIPFSLink, Constant, ChainId, SchemaType } from '@masknet/web3-shared-evm'
import { resolveIPFSLink, ChainId, SchemaType } from '@masknet/web3-shared-evm'
import { cloneDeep, findLastIndex } from 'lodash-unified'
import { delay } from '@dimensiondev/kit'
import type { User, FilterContract } from '../types'
Expand Down Expand Up @@ -64,7 +66,7 @@ export function useNFTs(user: User | undefined, configNFTs: Record<string, Const
return nfts
}

export function useNFTsExtra(configNFTs: Record<string, Constant> | undefined) {
export function useNFTsExtra(configNFTs: Record<string, Constants> | undefined) {
const initContracts = useInitNFTs(configNFTs)
const [retry, setRetry] = useState(0)
const chainId = useChainId(NetworkPluginID.PLUGIN_EVM)
Expand All @@ -74,15 +76,15 @@ export function useNFTsExtra(configNFTs: Record<string, Constant> | undefined) {
if (retry > 2) return
let requests = []
if (!extra.length) {
requests = initContracts.map((nft) => OpenSea.getContract(nft.contract, chainId))
requests = initContracts.map((nft) => OpenSea.getContract(nft.contract, { chainId }))
} else {
// openSea api request should not immediately
await delay(3000)
requests = extra.map((nft, index) => {
if (nft.symbol && nft.name !== 'Unknown Token') {
return Promise.resolve(nft)
}
return OpenSea.getContract(initContracts[index].contract, chainId)
return OpenSea.getContract(initContracts[index].contract, { chainId })
})
}
const lists: NonFungibleTokenContract<ChainId, SchemaType>[] = await Promise.all(requests)
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/plugins/Pets/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Constant } from '@masknet/web3-shared-base'
import type { ERC721TokenInfo } from '@masknet/web3-shared-evm'
import type { Constant } from '@masknet/web3-shared-evm/constants/utils'

export interface PetsDialogEvent {
open: boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ import { toHex } from 'web3-utils'
import BigNumber from 'bignumber.js'
import ActionButton from '../../../../extension/options-page/DashboardComponents/ActionButton'
import { isDashboardPage } from '@masknet/shared-base'
import { useChainId, useFungibleToken, useNativeTokenPrice, useWeb3State } from '@masknet/plugin-infra/web3'
import { NetworkPluginID } from '@masknet/web3-shared-base'
import {
useChainId,
useFungibleToken,
useGasOptions,
useNativeTokenPrice,
useWeb3State,
} from '@masknet/plugin-infra/web3'
import { GasOptionType, NetworkPluginID } from '@masknet/web3-shared-base'

const useStyles = makeStyles<{ isDashboard: boolean }>()((theme, { isDashboard }) => ({
container: {
Expand Down Expand Up @@ -111,35 +117,32 @@ interface GasPrior1559SettingsProps {
export const GasPrior1559Settings = memo<GasPrior1559SettingsProps>(
({ onCancel, onSave: onSave_, gasConfig, onSaveSlippage }) => {
const chainId = useChainId(NetworkPluginID.PLUGIN_EVM)
const { GasOptions } = useWeb3State(NetworkPluginID.PLUGIN_EVM)
const { value: gasOptions_ } = useGasOptions(NetworkPluginID.PLUGIN_EVM)
const isDashboard = isDashboardPage()
const { classes } = useStyles({ isDashboard })
const { t } = useI18N()
const [selected, setOption] = useState<number>(1)
const [customGasPrice, setCustomGasPrice] = useState('0')

// #region Get gas options from debank
const { value: gasOptions } = useAsync(async () => {
const response = await GasOptions?.getGasOptions?.(chainId)
if (!response) return { slow: 0, normal: 0, fast: 0 }

const gasOptions = useMemo(() => {
return {
slow: response.slow.suggestedMaxFeePerGas,
normal: response.normal.suggestedMaxFeePerGas,
fast: response.fast.suggestedMaxFeePerGas,
slow: gasOptions_?.[GasOptionType.SLOW].suggestedMaxFeePerGas ?? 0,
standard: gasOptions_?.[GasOptionType.NORMAL].suggestedMaxFeePerGas ?? 0,
fast: gasOptions_?.[GasOptionType.FAST].suggestedMaxFeePerGas ?? 0,
}
}, [chainId])
}, [chainId, gasOptions_])
// #endregion

const options = useMemo(
() => [
{
title: t('plugin_trader_gas_setting_standard'),
gasPrice: gasOptions?.normal ?? 0,
gasPrice: gasOptions?.standard,
},
{
title: t('plugin_trader_gas_setting_fast'),
gasPrice: gasOptions?.fast ?? 0,
gasPrice: gasOptions?.fast,
},
{
title: t('plugin_trader_gas_setting_custom'),
Expand All @@ -166,7 +169,7 @@ export const GasPrior1559Settings = memo<GasPrior1559SettingsProps>(
useUpdateEffect(() => {
if (!(gasConfig?.gasPrice && gasOptions)) return
const gasPrice = new BigNumber(gasConfig.gasPrice)
if (gasPrice.isEqualTo(gasOptions.normal)) setOption(0)
if (gasPrice.isEqualTo(gasOptions.standard)) setOption(0)
else if (gasPrice.isEqualTo(gasOptions.fast)) setOption(1)
else {
setCustomGasPrice(formatWeiToGwei(gasPrice).toString())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import { useState } from 'react'
import { useAsync } from 'react-use'
import { GasOptionConfig, formatGweiToWei, ChainId } from '@masknet/web3-shared-evm'
import { useWeb3State } from '@masknet/plugin-infra/web3'
import { NetworkPluginID } from '@masknet/web3-shared-base'
import { useGasOptions } from '@masknet/plugin-infra/web3'
import { GasOptionType, NetworkPluginID } from '@masknet/web3-shared-base'

// TODO: support multiple chain
export function useGasConfig(chainId: ChainId) {
const [gasConfig, setGasConfig] = useState<GasOptionConfig | undefined>()
const { GasOptions } = useWeb3State(NetworkPluginID.PLUGIN_EVM)
const { value: gasOptions_ } = useGasOptions(NetworkPluginID.PLUGIN_EVM)
const { value: gasPrice } = useAsync(async () => {
try {
const response = await GasOptions?.getGasOptions?.(chainId)
const maxFeePerGas = formatGweiToWei(response?.normal?.suggestedMaxFeePerGas ?? 0).toFixed(0)
const maxPriorityFeePerGas = formatGweiToWei(response?.normal?.suggestedMaxPriorityFeePerGas ?? 0).toFixed(
0,
)
const maxFeePerGas = formatGweiToWei(
gasOptions_?.[GasOptionType.NORMAL]?.suggestedMaxFeePerGas ?? 0,
).toFixed(0)
const maxPriorityFeePerGas = formatGweiToWei(
gasOptions_?.[GasOptionType.NORMAL]?.suggestedMaxPriorityFeePerGas ?? 0,
).toFixed(0)

setGasConfig({
maxFeePerGas,
Expand All @@ -25,7 +26,7 @@ export function useGasConfig(chainId: ChainId) {
setGasConfig(undefined)
return
}
}, [chainId])
}, [chainId, gasOptions_])

return { gasPrice, gasConfig, setGasConfig }
}
12 changes: 5 additions & 7 deletions packages/mask/src/plugins/Wallet/services/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { toBuffer } from 'ethereumjs-util'
import { personalSign, signTypedData as signTypedData_, SignTypedDataVersion } from '@metamask/eth-sig-util'
import { encodeText } from '@dimensiondev/kit'
import { isSameAddress } from '@masknet/web3-shared-base'
import { Transaction, formatEthereumAddress, ProviderType } from '@masknet/web3-shared-evm'
import type { Transaction, formatEthereumAddress, ProviderType } from '@masknet/web3-shared-evm'
import { api } from '@dimensiondev/mask-wallet-core/proto'
import { MAX_DERIVE_COUNT, HD_PATH_WITHOUT_INDEX_ETHEREUM } from '@masknet/plugin-wallet'
import * as sdk from './maskwallet'
Expand All @@ -32,22 +32,20 @@ export { isLocked, lockWallet, unlockWallet } from './locker'

export async function getWallet(address?: string) {
if (hasNativeAPI) {
const wallets = await getWallets(ProviderType.MaskWallet)
const wallets = await getWallets()
return wallets.find((x) => isSameAddress(x.address, address))
}
return database.getWallet(address)
}

export async function getWallets(providerType?: ProviderType): Promise<
export async function getWallets(): Promise<
(Omit<WalletRecord, 'type'> & {
configurable: boolean
hasStoredKeyInfo: boolean
hasDerivationPath: boolean
})[]
> {
// if (hasNativeAPI) {
// if (providerType && providerType !== ProviderType.MaskWallet) return []

// // read wallet from rpc
// const accounts = await EVM_RPC.getAccounts()
// const address = first(accounts) ?? ''
Expand All @@ -68,7 +66,7 @@ export async function getWallets(providerType?: ProviderType): Promise<
// },
// ]
// }
return database.getWallets(providerType)
return database.getWallets()
}

export function createMnemonicWords() {
Expand All @@ -79,7 +77,7 @@ export async function getWalletPrimary() {
if (hasNativeAPI) return null
return (
first(
(await database.getWallets(ProviderType.MaskWallet))
(await database.getWallets())
.filter((x) => x.storedKeyInfo?.type === api.StoredKeyType.Mnemonic)
.sort((a, z) => a.createdAt.getTime() - z.createdAt.getTime()),
) ?? null
Expand Down
Loading

0 comments on commit f883f2d

Please sign in to comment.