From 2af0de47d12969b7828b6ebb2d0117e32bd5b95e Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Thu, 16 Dec 2021 04:32:16 +0800 Subject: [PATCH 1/4] refactor: network settings --- .../components/AddCollectibleDialog/index.tsx | 4 +- .../components/Persona/PersonaSetup.tsx | 3 +- .../Persona/UnconnectedPersonaLine.tsx | 3 +- packages/mask/shared/index.ts | 1 + packages/mask/shared/types.ts | 8 + .../InjectedComponents/CommentBox.tsx | 4 +- .../src/components/shared/InjectedDialog.tsx | 7 +- .../Personas/components/ProfileList/index.tsx | 2 +- .../src/plugins/Collectible/apis/rarible.ts | 21 ++- .../ITO/SNSAdaptor/CompositionDialog.tsx | 4 +- .../mask/src/plugins/ITO/SNSAdaptor/ITO.tsx | 8 +- .../SNSAdaptor/components/TokenCard.tsx | 11 +- .../SNSAdaptor/NftRedPacketHistoryList.tsx | 6 +- .../SNSAdaptor/RedPacketCreateNew.tsx | 4 +- .../hooks/useNftRedPacketHistory.ts | 4 +- .../RedPacket/Worker/apis/nftRedpacket.ts | 25 +-- .../src/plugins/RedPacket/Worker/services.ts | 4 +- .../Trader/SNSAdaptor/trader/Trader.tsx | 11 +- .../Wallet/SNSAdaptor/SelectTokenDialog.tsx | 4 +- .../mask/src/plugins/Wallet/services/chain.ts | 142 ++++++++++-------- .../Wallet/services/transaction/database.ts | 3 +- .../Wallet/services/transaction/watcher.ts | 8 +- .../Wallet/services/wallet/database/token.ts | 22 +-- packages/mask/src/plugins/Wallet/settings.ts | 20 ++- packages/mask/src/settings/createSettings.ts | 20 ++- packages/mask/src/settings/settings.ts | 52 ++++--- .../browser-action/index.ts | 9 +- .../facebook.com/base.ts | 8 +- .../facebook.com/utils/resolveFacebookLink.ts | 4 +- .../instagram.com/base.ts | 8 +- .../social-network-adaptor/minds.com/base.ts | 6 +- .../twitter.com/base.ts | 6 +- packages/mask/src/social-network/ui.ts | 4 +- .../hooks/useERC721TokenDetailedOwnerList.ts | 1 + packages/web3-shared/evm/types/index.ts | 9 +- packages/web3-shared/evm/utils/token.ts | 1 + 36 files changed, 276 insertions(+), 181 deletions(-) create mode 100644 packages/mask/shared/types.ts diff --git a/packages/dashboard/src/pages/Wallets/components/AddCollectibleDialog/index.tsx b/packages/dashboard/src/pages/Wallets/components/AddCollectibleDialog/index.tsx index 05e0a75d6da2..486e95bed87f 100644 --- a/packages/dashboard/src/pages/Wallets/components/AddCollectibleDialog/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/AddCollectibleDialog/index.tsx @@ -4,6 +4,7 @@ import { Box, Button, DialogActions, DialogContent } from '@mui/material' import { EthereumTokenType, isSameAddress, + useChainId, useERC721ContractDetailed, useERC721TokenDetailedCallback, useWallet, @@ -32,6 +33,7 @@ enum FormErrorType { export const AddCollectibleDialog = memo(({ open, onClose }) => { const wallet = useWallet() + const chainId = useChainId() const [address, setAddress] = useState('') const { value: contractDetailed, loading: contractDetailLoading } = useERC721ContractDetailed(address) const [tokenId, setTokenId, erc721TokenDetailedCallback] = useERC721TokenDetailedCallback(contractDetailed) @@ -39,7 +41,7 @@ export const AddCollectibleDialog = memo(({ open, onC const onSubmit = useCallback(async () => { if (contractDetailLoading || !wallet) return - const tokenInDB = await PluginServices.Wallet.getToken(EthereumTokenType.ERC721, address, tokenId) + const tokenInDB = await PluginServices.Wallet.getToken(chainId, EthereumTokenType.ERC721, address, tokenId) if (tokenInDB) throw new Error(FormErrorType.Added) const tokenDetailed = await erc721TokenDetailedCallback() diff --git a/packages/dashboard/stories/components/Persona/PersonaSetup.tsx b/packages/dashboard/stories/components/Persona/PersonaSetup.tsx index d60f7e862412..8c592d4c697c 100644 --- a/packages/dashboard/stories/components/Persona/PersonaSetup.tsx +++ b/packages/dashboard/stories/components/Persona/PersonaSetup.tsx @@ -1,6 +1,7 @@ import { story } from '@masknet/storybook-shared' import { PersonaSetup as C } from '../../../src/pages/Personas/components/PersonaSetup' import { action } from '@storybook/addon-actions' +import { SocialNetworkID } from '../../../../mask/shared' const { meta, of } = story(C) @@ -10,7 +11,7 @@ export default meta({ export const PersonaSetup = of({ args: { - networkIdentifier: 'twitter.com', + networkIdentifier: SocialNetworkID.Twitter, onConnect: action('onConnect'), }, }) diff --git a/packages/dashboard/stories/components/Persona/UnconnectedPersonaLine.tsx b/packages/dashboard/stories/components/Persona/UnconnectedPersonaLine.tsx index fdd994d098a7..43570c50bd86 100644 --- a/packages/dashboard/stories/components/Persona/UnconnectedPersonaLine.tsx +++ b/packages/dashboard/stories/components/Persona/UnconnectedPersonaLine.tsx @@ -1,6 +1,7 @@ import { story } from '@masknet/storybook-shared' import { UnconnectedPersonaLine as C } from '../../../src/pages/Personas/components/PersonaLine' import { action } from '@storybook/addon-actions' +import { SocialNetworkID } from '../../../../mask/shared' const { meta, of } = story(C) @@ -10,7 +11,7 @@ export default meta({ export const UnconnectedPersonaLine = of({ args: { - networkIdentifier: 'twitter', + networkIdentifier: SocialNetworkID.Twitter, onConnect: action('onConnect'), }, }) diff --git a/packages/mask/shared/index.ts b/packages/mask/shared/index.ts index c2f14c48a9b4..0924c1cd9ba3 100644 --- a/packages/mask/shared/index.ts +++ b/packages/mask/shared/index.ts @@ -1,4 +1,5 @@ export * from './messages' +export * from './types' export * from './flags' export { InMemoryStorages, PersistentStorages } from './kv-storage' export * from './helpers/download' diff --git a/packages/mask/shared/types.ts b/packages/mask/shared/types.ts new file mode 100644 index 000000000000..2ed3ee773040 --- /dev/null +++ b/packages/mask/shared/types.ts @@ -0,0 +1,8 @@ +export enum SocialNetworkID { + Dashboard = 'localhost.dashboard', + BrowserAction = 'localhost.browser_action', + Twitter = 'twitter.com', + Facebook = 'facebook.com', + Minds = 'minds.com', + Instagram = 'instagram.com', +} diff --git a/packages/mask/src/components/InjectedComponents/CommentBox.tsx b/packages/mask/src/components/InjectedComponents/CommentBox.tsx index 9cd9d1e170b6..f03a23a33cd4 100644 --- a/packages/mask/src/components/InjectedComponents/CommentBox.tsx +++ b/packages/mask/src/components/InjectedComponents/CommentBox.tsx @@ -2,7 +2,7 @@ import { makeStyles } from '@masknet/theme' import { InputBase, Box } from '@mui/material' import { useI18N } from '../../utils' import { activatedSocialNetworkUI } from '../../social-network' -import { MINDS_ID } from '../../social-network-adaptor/minds.com/base' +import { SocialNetworkID } from '../../../shared' interface StyleProps { snsId: string @@ -13,7 +13,7 @@ const useStyles = makeStyles()((theme, { snsId }) => ({ flex: 1, fontSize: 13, background: '#3a3b3c', - width: snsId === MINDS_ID ? '96%' : '100%', + width: snsId === SocialNetworkID.Minds ? '96%' : '100%', height: 34, borderRadius: 20, padding: '2px 1em', diff --git a/packages/mask/src/components/shared/InjectedDialog.tsx b/packages/mask/src/components/shared/InjectedDialog.tsx index 736f932f3940..82a54a317045 100644 --- a/packages/mask/src/components/shared/InjectedDialog.tsx +++ b/packages/mask/src/components/shared/InjectedDialog.tsx @@ -20,8 +20,7 @@ import { isDashboardPage } from '@masknet/shared-base' import { useI18N, usePortalShadowRoot } from '../../utils' import { DialogDismissIconUI } from '../InjectedComponents/DialogDismissIcon' import { activatedSocialNetworkUI } from '../../social-network' -import { MINDS_ID } from '../../social-network-adaptor/minds.com/base' -import { FACEBOOK_ID } from '../../social-network-adaptor/facebook.com/base' +import { SocialNetworkID } from '../../../shared' interface StyleProps { snsId: string @@ -41,7 +40,9 @@ const useStyles = makeStyles()((theme, { snsId }) => ({ color: theme.palette.text.primary, }, paper: { - ...(snsId === MINDS_ID || snsId === FACEBOOK_ID ? { width: 'auto', backgroundImage: 'none' } : {}), + ...(snsId === SocialNetworkID.Minds || snsId === SocialNetworkID.Facebook + ? { width: 'auto', backgroundImage: 'none' } + : {}), }, })) diff --git a/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx b/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx index 5c3c50d9f984..d7ba1a99ce7e 100644 --- a/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx +++ b/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx @@ -69,7 +69,7 @@ export const ProfileList = memo(() => { const definedSocialNetworks = compact( [...definedSocialNetworkUIs.values()].map(({ networkIdentifier }) => { - if (networkIdentifier === 'localhost') return null + if (networkIdentifier.includes('localhost')) return null return networkIdentifier }), ) diff --git a/packages/mask/src/plugins/Collectible/apis/rarible.ts b/packages/mask/src/plugins/Collectible/apis/rarible.ts index dfbfc4083160..3fd1e85488e3 100644 --- a/packages/mask/src/plugins/Collectible/apis/rarible.ts +++ b/packages/mask/src/plugins/Collectible/apis/rarible.ts @@ -1,4 +1,5 @@ -import { RaribleChainURL, RaribleMainnetURL } from '../constants' +import urlcat from 'urlcat' +import type { ChainId } from '@masknet/web3-shared-evm' import { compact } from 'lodash-unified' import { OrderSide } from 'opensea-js/lib/types' import stringify from 'json-stable-stringify' @@ -10,10 +11,10 @@ import { RaribleOfferResponse, RaribleProfileResponse, } from '../types' +import { RaribleChainURL, RaribleMainnetURL } from '../constants' import { toRaribleImage } from '../helpers' import { resolveRaribleUserNetwork } from '../pipes' import { currentChainIdSettings } from '../../Wallet/settings' -import urlcat from 'urlcat' async function fetchFromRarible(root: string, subPath: string, config = {} as RequestInit) { const response = await ( @@ -54,7 +55,11 @@ export async function getNFTItem(tokenAddress: string, tokenId: string) { return assetResponse } -export async function getOffersFromRarible(tokenAddress: string, tokenId: string) { +export async function getOffersFromRarible( + chainId: ChainId.Mainnet | ChainId.Ropsten, + tokenAddress: string, + tokenId: string, +) { const orders = await fetchFromRarible( RaribleMainnetURL, `items/${tokenAddress}:${tokenId}/offers`, @@ -67,7 +72,6 @@ export async function getOffersFromRarible(tokenAddress: string, tokenId: string }, ) const profiles = await getProfilesFromRarible(orders.map((item) => item.maker)) - const chainId = currentChainIdSettings.value return orders.map((order) => { const ownerInfo = profiles.find((owner) => owner.id === order.maker) return { @@ -107,10 +111,15 @@ export async function getListingsFromRarible(tokenAddress: string, tokenId: stri }) } -export async function getOrderFromRarible(tokenAddress: string, tokenId: string, side: OrderSide) { +export async function getOrderFromRarible( + chainId: ChainId.Mainnet | ChainId.Ropsten, + tokenAddress: string, + tokenId: string, + side: OrderSide, +) { switch (side) { case OrderSide.Buy: - return getOffersFromRarible(tokenAddress, tokenId) + return getOffersFromRarible(chainId, tokenAddress, tokenId) case OrderSide.Sell: return getListingsFromRarible(tokenAddress, tokenId) default: diff --git a/packages/mask/src/plugins/ITO/SNSAdaptor/CompositionDialog.tsx b/packages/mask/src/plugins/ITO/SNSAdaptor/CompositionDialog.tsx index b05d14993f78..caaaf8a4dd63 100644 --- a/packages/mask/src/plugins/ITO/SNSAdaptor/CompositionDialog.tsx +++ b/packages/mask/src/plugins/ITO/SNSAdaptor/CompositionDialog.tsx @@ -19,8 +19,8 @@ import { ConfirmDialog } from './ConfirmDialog' import { WalletMessages } from '../../Wallet/messages' import { omit, set } from 'lodash-unified' import { useCompositionContext } from '../../../components/CompositionDialog/CompositionContext' -import { MINDS_ID } from '../../../social-network-adaptor/minds.com/base' import { activatedSocialNetworkUI } from '../../../social-network' +import { SocialNetworkID } from '../../../../shared' interface StyleProps { snsId: string @@ -28,7 +28,7 @@ interface StyleProps { const useStyles = makeStyles()((theme, { snsId }) => ({ content: { - ...(snsId === MINDS_ID ? { minWidth: 600 } : {}), + ...(snsId === SocialNetworkID.Minds ? { minWidth: 600 } : {}), position: 'relative', paddingTop: 50, }, diff --git a/packages/mask/src/plugins/ITO/SNSAdaptor/ITO.tsx b/packages/mask/src/plugins/ITO/SNSAdaptor/ITO.tsx index c6e67d29169c..cd4886e79d37 100644 --- a/packages/mask/src/plugins/ITO/SNSAdaptor/ITO.tsx +++ b/packages/mask/src/plugins/ITO/SNSAdaptor/ITO.tsx @@ -41,9 +41,9 @@ import { StyledLinearProgress } from './StyledLinearProgress' import { SwapGuide, SwapStatus } from './SwapGuide' import urlcat from 'urlcat' import { startCase } from 'lodash-unified' -import { FACEBOOK_ID } from '../../../social-network-adaptor/facebook.com/base' import { isFacebook } from '../../../social-network-adaptor/facebook.com/base' import { isTwitter } from '../../../social-network-adaptor/twitter.com/base' +import { SocialNetworkID } from '../../../../shared' export interface IconProps { size?: number @@ -77,8 +77,8 @@ const useStyles = makeStyles()((theme, props) => ({ display: 'flex', justifyContent: 'space-between', alignItems: 'end', - width: props.snsId === FACEBOOK_ID ? '98%' : '100%', - maxWidth: props.snsId === FACEBOOK_ID ? 'auto' : 470, + width: props.snsId === SocialNetworkID.Facebook ? '98%' : '100%', + maxWidth: props.snsId === SocialNetworkID.Facebook ? 'auto' : 470, }, title: { fontSize: props.titleLength! > 31 ? '1.3rem' : '1.6rem', @@ -124,7 +124,7 @@ const useStyles = makeStyles()((theme, props) => ({ footer: { position: 'absolute', width: '90%', - maxWidth: props.snsId === FACEBOOK_ID ? 'auto' : 470, + maxWidth: props.snsId === SocialNetworkID.Facebook ? 'auto' : 470, bottom: theme.spacing(2), display: 'flex', justifyContent: 'space-between', diff --git a/packages/mask/src/plugins/MaskBox/SNSAdaptor/components/TokenCard.tsx b/packages/mask/src/plugins/MaskBox/SNSAdaptor/components/TokenCard.tsx index 74a501d5f1b1..ad973fd44181 100644 --- a/packages/mask/src/plugins/MaskBox/SNSAdaptor/components/TokenCard.tsx +++ b/packages/mask/src/plugins/MaskBox/SNSAdaptor/components/TokenCard.tsx @@ -1,7 +1,12 @@ +import { memo } from 'react' import { makeStyles } from '@masknet/theme' -import { ERC721ContractDetailed, NonFungibleAssetProvider, useERC721TokenDetailed } from '@masknet/web3-shared-evm' import { Typography } from '@mui/material' -import { memo } from 'react' +import { + ChainId, + ERC721ContractDetailed, + NonFungibleAssetProvider, + useERC721TokenDetailed, +} from '@masknet/web3-shared-evm' import { CollectibleCard } from '../../../../extension/options-page/DashboardComponents/CollectibleList/CollectibleCard' const useStyles = makeStyles()((theme) => ({ @@ -27,6 +32,8 @@ export const TokenCard = memo((props: TokenCardProps) => { const { classes } = useStyles() const { value: tokenDetailed = { + // TODO: read from currentChainIdSettings + chainId: ChainId.Mainnet, tokenId, contractDetailed, info: {}, diff --git a/packages/mask/src/plugins/RedPacket/SNSAdaptor/NftRedPacketHistoryList.tsx b/packages/mask/src/plugins/RedPacket/SNSAdaptor/NftRedPacketHistoryList.tsx index d9eec9bb36b9..10ba3a049c5b 100644 --- a/packages/mask/src/plugins/RedPacket/SNSAdaptor/NftRedPacketHistoryList.tsx +++ b/packages/mask/src/plugins/RedPacket/SNSAdaptor/NftRedPacketHistoryList.tsx @@ -1,9 +1,9 @@ +import { useRef, useState } from 'react' +import classNames from 'classnames' import { useScrollBottomEvent } from '@masknet/shared' import { makeStyles } from '@masknet/theme' -import classNames from 'classnames' import { ERC721ContractDetailed, useAccount, useChainId } from '@masknet/web3-shared-evm' import { List, Popper, Typography } from '@mui/material' -import { useRef, useState } from 'react' import type { NftRedPacketHistory } from '../types' import { useNftRedPacketHistory } from './hooks/useNftRedPacketHistory' import { NftRedPacketHistoryItem } from './NftRedPacketHistoryItem' @@ -77,7 +77,7 @@ export function NftRedPacketHistoryList({ onSend }: Props) { const { t } = useI18N() const account = useAccount() const chainId = useChainId() - const { histories, fetchMore, loading } = useNftRedPacketHistory(account, chainId) + const { histories, fetchMore, loading } = useNftRedPacketHistory(chainId, account) const containerRef = useRef(null) const [popperText, setPopperText] = useState('') const [anchorEl, setAnchorEl] = useState(null) diff --git a/packages/mask/src/plugins/RedPacket/SNSAdaptor/RedPacketCreateNew.tsx b/packages/mask/src/plugins/RedPacket/SNSAdaptor/RedPacketCreateNew.tsx index a557e734a134..2c2bb4988133 100644 --- a/packages/mask/src/plugins/RedPacket/SNSAdaptor/RedPacketCreateNew.tsx +++ b/packages/mask/src/plugins/RedPacket/SNSAdaptor/RedPacketCreateNew.tsx @@ -3,10 +3,10 @@ import { RedPacketFormProps, RedPacketERC20Form } from './RedPacketERC20Form' import { RedPacketERC721Form } from './RedPacketERC721Form' import AbstractTab, { AbstractTabProps } from '../../../components/shared/AbstractTab' import { useI18N } from '../../../utils' -import { MINDS_ID } from '../../../social-network-adaptor/minds.com/base' import { activatedSocialNetworkUI } from '../../../social-network' import { IconURLs } from './IconURL' +import { SocialNetworkID } from '../../../../shared' interface StyleProps { snsId: string @@ -21,7 +21,7 @@ const useStyles = makeStyles()((theme, { snsId }) => ({ tabs: { height: 36, minHeight: 36, - margin: `0 ${snsId === MINDS_ID ? '12px' : 'auto'}`, + margin: `0 ${snsId === SocialNetworkID.Minds ? '12px' : 'auto'}`, borderRadius: 4, backgroundColor: theme.palette.background.default, '& .Mui-selected': { diff --git a/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useNftRedPacketHistory.ts b/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useNftRedPacketHistory.ts index 6ab1b69674bc..edfcf63d2742 100644 --- a/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useNftRedPacketHistory.ts +++ b/packages/mask/src/plugins/RedPacket/SNSAdaptor/hooks/useNftRedPacketHistory.ts @@ -3,13 +3,13 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { RedPacketRPC } from '../../messages' import type { NftRedPacketHistory } from '../../types' -export function useNftRedPacketHistory(address: string, chainId: ChainId) { +export function useNftRedPacketHistory(chainId: ChainId, address: string) { const [allHistories, setAllHistories] = useState([]) const pageRef = useRef(1) const [loading, setLoading] = useState(false) const getHistories = useCallback(async () => { - const histories = await RedPacketRPC.getNftRedPacketHistory(address, chainId, pageRef.current) + const histories = await RedPacketRPC.getNftRedPacketHistory(chainId, address, pageRef.current) setLoading(false) if (histories.length) { pageRef.current += 1 diff --git a/packages/mask/src/plugins/RedPacket/Worker/apis/nftRedpacket.ts b/packages/mask/src/plugins/RedPacket/Worker/apis/nftRedpacket.ts index ca93128a0483..15413e676d67 100644 --- a/packages/mask/src/plugins/RedPacket/Worker/apis/nftRedpacket.ts +++ b/packages/mask/src/plugins/RedPacket/Worker/apis/nftRedpacket.ts @@ -1,8 +1,7 @@ -import { EthereumTokenType, getChainName, getNftRedPacketConstants } from '@masknet/web3-shared-evm' +import { ChainId, EthereumTokenType, getChainName, getNftRedPacketConstants } from '@masknet/web3-shared-evm' import stringify from 'json-stable-stringify' import { first, pick } from 'lodash-unified' import { tokenIntoMask } from '../../../ITO/SNSAdaptor/helpers' -import { currentChainIdSettings } from '../../../Wallet/settings' import type { NftRedPacketHistory, NftRedPacketJSONPayload, @@ -62,8 +61,8 @@ const RED_PACKET_FIELDS = ` } ` -async function fetchFromNFTRedPacketSubgraph(query: string) { - const subgraphURL = getNftRedPacketConstants(currentChainIdSettings.value).SUBGRAPH_URL +async function fetchFromNFTRedPacketSubgraph(chainId: ChainId, query: string) { + const subgraphURL = getNftRedPacketConstants(chainId).SUBGRAPH_URL if (!subgraphURL) return null const response = await fetch(subgraphURL, { method: 'POST', @@ -76,20 +75,25 @@ async function fetchFromNFTRedPacketSubgraph(query: string) { return data } -export async function getNftRedPacketTxid(rpid: string) { - const data = await fetchFromNFTRedPacketSubgraph<{ redPackets: NftRedPacketSubgraphOutMask[] }>(` +export async function getNftRedPacketTxid(chainId: ChainId, rpid: string) { + const data = await fetchFromNFTRedPacketSubgraph<{ redPackets: NftRedPacketSubgraphOutMask[] }>( + chainId, + ` { nftredPackets (where: { rpid: "${rpid.toLowerCase()}" }) { ${RED_PACKET_FIELDS} } } - `) + `, + ) return first(data?.redPackets)?.txid } const PAGE_SIZE = 5 -export async function getNftRedPacketHistory(address: string, page: number) { - const data = await fetchFromNFTRedPacketSubgraph<{ nftredPackets: NftRedPacketSubgraphOutMask[] }>(` +export async function getNftRedPacketHistory(chainId: ChainId, address: string, page: number) { + const data = await fetchFromNFTRedPacketSubgraph<{ nftredPackets: NftRedPacketSubgraphOutMask[] }>( + chainId, + ` { nftredPackets ( where: { creator: "${address.toLowerCase()}" }, @@ -101,7 +105,8 @@ export async function getNftRedPacketHistory(address: string, page: number) { ${RED_PACKET_FIELDS} } } - `) + `, + ) if (!data?.nftredPackets) return [] return data.nftredPackets.map((x) => { const nftRedPacketSubgraphInMask = { diff --git a/packages/mask/src/plugins/RedPacket/Worker/services.ts b/packages/mask/src/plugins/RedPacket/Worker/services.ts index 5522926e6dc7..cd28b15a8a18 100644 --- a/packages/mask/src/plugins/RedPacket/Worker/services.ts +++ b/packages/mask/src/plugins/RedPacket/Worker/services.ts @@ -49,8 +49,8 @@ export async function getRedPacketHistory(address: string, chainId: ChainId, end //#endregion } -export async function getNftRedPacketHistory(address: string, chainId: ChainId, page: number) { - const histories = await subgraph.getNftRedPacketHistory(address, page) +export async function getNftRedPacketHistory(chainId: ChainId, address: string, page: number) { + const histories = await subgraph.getNftRedPacketHistory(chainId, address, page) const historiesWithPassword = [] for (const history of histories) { const record = await nftDb.getRedPacketNft(history.txid) diff --git a/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Trader.tsx b/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Trader.tsx index 61e377c27180..5965841b87c9 100644 --- a/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Trader.tsx +++ b/packages/mask/src/plugins/Trader/SNSAdaptor/trader/Trader.tsx @@ -193,20 +193,15 @@ export function Trader(props: TraderProps) { } if (chainId && currentProvider && currentAccount) { - const cacheBalance = currentBalancesSettings.value[currentProvider]?.[chainId] + let balance = currentBalancesSettings.value[chainId] - let balance: string - - if (cacheBalance) balance = cacheBalance - else { + if (!balance) { balance = await Services.Ethereum.getBalance(currentAccount, { chainId: chainId, providerType: currentProvider, }) await WalletRPC.updateBalances({ - [currentProvider]: { - [chainId]: balance, - }, + [chainId]: balance, }) } diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectTokenDialog.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectTokenDialog.tsx index 86ffc1816e4a..2074cf990dce 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectTokenDialog.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectTokenDialog.tsx @@ -9,8 +9,8 @@ import { WalletMessages } from '../../Wallet/messages' import { useI18N } from '../../../utils' import { ERC20TokenList, ERC20TokenListProps, useRemoteControlledDialog } from '@masknet/shared' import { delay } from '@masknet/shared-base' -import { MINDS_ID } from '../../../social-network-adaptor/minds.com/base' import { activatedSocialNetworkUI } from '../../../social-network' +import { SocialNetworkID } from '../../../../shared' interface StyleProps { snsId: string @@ -19,7 +19,7 @@ interface StyleProps { const useStyles = makeStyles()((theme, { snsId, isDashboard }) => ({ content: { - ...(snsId === MINDS_ID ? { minWidth: 552 } : {}), + ...(snsId === SocialNetworkID.Minds ? { minWidth: 552 } : {}), padding: theme.spacing(3), paddingTop: isDashboard ? 0 : theme.spacing(2.8), }, diff --git a/packages/mask/src/plugins/Wallet/services/chain.ts b/packages/mask/src/plugins/Wallet/services/chain.ts index bd4d0593997c..41c2299cfec8 100644 --- a/packages/mask/src/plugins/Wallet/services/chain.ts +++ b/packages/mask/src/plugins/Wallet/services/chain.ts @@ -1,38 +1,35 @@ -import { throttle } from 'lodash-unified' -import { BalanceOfChains, ProviderType } from '@masknet/web3-shared-evm' +import { uniq, throttle } from 'lodash-unified' +import { BalanceOfChains, BlockNumberOfChains, ProviderType } from '@masknet/web3-shared-evm' import { pollingTask } from '@masknet/shared-base' import { getBalance, getBlockNumber, resetAllNonce } from '../../../extension/background-script/EthereumService' import { startEffects } from '../../../../utils-pure' import { UPDATE_CHAIN_STATE_DELAY } from '../constants' -import { - currentMaskWalletAccountSettings, - currentAccountSettings, - currentBalanceSettings, - currentBlockNumberSettings, - currentChainIdSettings, - currentMaskWalletBalanceSettings, - currentMaskWalletChainIdSettings, - currentProviderSettings, - currentBalancesSettings, -} from '../settings' +import { currentBlockNumbersSettings, currentBalancesSettings } from '../settings' +import { currentChainIdSettings, currentAccountSettings, currentProviderSettings } from '../../../settings/settings' let beats = 0 const { run } = startEffects(import.meta.webpackHot) -export async function kickToUpdateChainState() { - beats += 1 +const currentChainIds = [...Object.values(currentChainIdSettings)] +const currentAccounts = [...Object.values(currentAccountSettings)] +const currentProviders = [...Object.values(currentProviderSettings)] + +export async function updateBalances(updates: BalanceOfChains) { + currentBalancesSettings.value = { + ...currentBalancesSettings.value, + ...updates, + } } -export async function updateBalances(data: BalanceOfChains) { - const balancesOfChains = { ...currentBalancesSettings.value } - for (const [key, value] of Object.entries(data)) { - balancesOfChains[key] = { - ...balancesOfChains[key], - ...value, - } +export async function updateBlockNumbers(updates: BlockNumberOfChains) { + currentBlockNumbersSettings.value = { + ...currentBlockNumbersSettings.value, + ...updates, } +} - currentBalancesSettings.value = balancesOfChains +export async function kickToUpdateChainState() { + beats += 1 } export async function updateChainState() { @@ -44,29 +41,57 @@ export async function updateChainState() { // update chain state try { - ;[currentBlockNumberSettings.value, currentBalanceSettings.value, currentMaskWalletBalanceSettings.value] = - await Promise.all([ - getBlockNumber(), - currentAccountSettings.value - ? getBalance(currentAccountSettings.value, { - chainId: currentChainIdSettings.value, - providerType: currentProviderSettings.value, - }).then((value) => { - updateBalances({ - [currentProviderSettings.value]: { - [currentChainIdSettings.value]: value, - }, - }) - return value - }) - : currentBalanceSettings.value, - currentMaskWalletAccountSettings.value - ? getBalance(currentMaskWalletAccountSettings.value, { - chainId: currentMaskWalletChainIdSettings.value, - providerType: ProviderType.MaskWallet, - }) - : currentMaskWalletBalanceSettings.value, - ]) + const chainIds = currentChainIds.map((x) => x.value) + const accounts = currentAccounts.map((x) => x.value) + const providers = currentProviders.map((x) => x.value) + const overrides = chainIds.map((_, index) => ({ + chainId: chainIds[index], + provider: providers[index], + })) + + // TODO: + // reduce rpc requests + const allSettled = await Promise.allSettled( + chainIds.map(async (_, index) => { + const [balance, blockNumber] = await Promise.all([ + getBalance(accounts[index], overrides[index]), + getBlockNumber(overrides[index]), + ]) + return { + chainId: chainIds[index], + provider: providers[index], + balance, + blockNumber, + } + }), + ) + + const { balances, blockNumbers } = allSettled.reduce( + ( + updates: { + balances: BalanceOfChains + blockNumbers: BlockNumberOfChains + }, + result, + ) => { + if (result.status === 'rejected') return updates + const { chainId, balance, blockNumber } = result.value + return { + balances: { + ...updates.balances, + [chainId]: balance, + }, + blockNumbers: { + ...updates.blockNumbers, + [chainId]: blockNumber, + }, + } + }, + { balances: {}, blockNumbers: {} }, + ) + + currentBalancesSettings.value = balances + currentBlockNumbersSettings.value = blockNumbers } catch { // do nothing } finally { @@ -99,19 +124,16 @@ run(() => { }) // revalidate chain state if the chainId of current provider was changed -run(() => - currentChainIdSettings.addListener(() => { - updateChainStateThrottled() - if (currentProviderSettings.value === ProviderType.MaskWallet) resetAllNonce() - }), -) -run(() => - currentMaskWalletChainIdSettings.addListener(() => { - updateChainStateThrottled() - resetAllNonce() - }), -) +currentChainIds.forEach((settings, index) => { + run(() => + settings.addListener(() => { + updateChainStateThrottled() + if (currentProviders[index].value === ProviderType.MaskWallet) resetAllNonce() + }), + ) +}) // revalidate chain state if the current wallet was changed -run(() => currentAccountSettings.addListener(() => updateChainStateThrottled())) -run(() => currentMaskWalletAccountSettings.addListener(() => updateChainStateThrottled())) +currentAccounts.forEach((settings) => { + run(() => settings.addListener(() => updateChainStateThrottled())) +}) diff --git a/packages/mask/src/plugins/Wallet/services/transaction/database.ts b/packages/mask/src/plugins/Wallet/services/transaction/database.ts index 55be91511440..6871beb5d8ef 100644 --- a/packages/mask/src/plugins/Wallet/services/transaction/database.ts +++ b/packages/mask/src/plugins/Wallet/services/transaction/database.ts @@ -2,7 +2,6 @@ import { uniqBy } from 'lodash-unified' import type { JsonRpcPayload } from 'web3-core-helpers' import { WalletMessages } from '@masknet/plugin-wallet' import { ChainId, formatEthereumAddress } from '@masknet/web3-shared-evm' -import { currentChainIdSettings } from '../../settings' import { PluginDB } from '../../database/Plugin.db' export const MAX_RECENT_TRANSACTIONS_SIZE = 20 @@ -90,7 +89,7 @@ export async function removeRecentTransaction(chainId: ChainId, address: string, await PluginDB.add({ type: 'recent-transactions', id: recordId, - chainId: currentChainIdSettings.value, + chainId, address: formatEthereumAddress(address), transactions: chunk.transactions.filter((x) => x.hash !== hash), createdAt: chunk.createdAt, diff --git a/packages/mask/src/plugins/Wallet/services/transaction/watcher.ts b/packages/mask/src/plugins/Wallet/services/transaction/watcher.ts index c4cd509f363c..9a665a75b418 100644 --- a/packages/mask/src/plugins/Wallet/services/transaction/watcher.ts +++ b/packages/mask/src/plugins/Wallet/services/transaction/watcher.ts @@ -4,7 +4,6 @@ import { ChainId, TransactionStateType } from '@masknet/web3-shared-evm' import * as EthereumService from '../../../../extension/background-script/EthereumService' import * as progress from './progress' import * as helpers from './helpers' -import { currentChainIdSettings } from '../../settings' let timer: NodeJS.Timer | null = null const WATCHED_TRANSACTION_CHECK_DELAY = 15 * 1000 // 15s @@ -51,13 +50,12 @@ async function getTransactionReceipt(chainId: ChainId, hash: string) { } } -async function checkReceipt() { +async function checkReceipt(chainId: ChainId) { if (timer !== null) { clearTimeout(timer) timer = null } - const chainId = currentChainIdSettings.value const map = getTransactionMap(chainId) const transactions = [...map.entries()].sort(([, a], [, z]) => z.at - a.at) const watchedTransactions = transactions.slice(0, WATCHED_TRANSACTIONS_SIZE) @@ -78,7 +76,7 @@ async function checkReceipt() { if (checkResult.every((x) => x.status === 'fulfilled' && x.value)) return if (timer !== null) clearTimeout(timer) - timer = setTimeout(checkReceipt, WATCHED_TRANSACTION_CHECK_DELAY) + timer = setTimeout(() => checkReceipt(chainId), WATCHED_TRANSACTION_CHECK_DELAY) } export async function getReceipt(chainId: ChainId, hash: string) { @@ -93,7 +91,7 @@ export async function watchTransaction(chainId: ChainId, hash: string) { receipt: getTransactionReceipt(chainId, hash), }) } - if (timer === null) timer = setTimeout(checkReceipt, WATCHED_TRANSACTION_CHECK_DELAY) + if (timer === null) timer = setTimeout(() => checkReceipt(chainId), WATCHED_TRANSACTION_CHECK_DELAY) } export function unwatchTransaction(chainId: ChainId, hash: string) { diff --git a/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts b/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts index c1d7494b126f..354d8b650b66 100644 --- a/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts +++ b/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts @@ -1,5 +1,6 @@ import { omit } from 'lodash-unified' import { + ChainId, ERC1155TokenDetailed, ERC20TokenDetailed, ERC721TokenDetailed, @@ -10,7 +11,6 @@ import { unreachable } from '@dimensiondev/kit' import { WalletMessages } from '@masknet/plugin-wallet' import { PluginDB } from '../../../database/Plugin.db' import { asyncIteratorToArray } from '../../../../../utils' -import { currentChainIdSettings } from '../../../settings' import type { ERC20TokenRecord, ERC721TokenRecord, ERC1155TokenRecord } from '../type' import * as walletDB from './wallet' @@ -20,8 +20,8 @@ type DatabaseTokenRecord = ERC20TokenRecord | ERC721TokenRecord | ERC1155TokenRe const MAX_TOKEN_COUNT = 49 -function getRecordId(address: string, tokenId?: string) { - const recordId = `${currentChainIdSettings.value}_${address}` +function getRecordId(chainId: ChainId, address: string, tokenId?: string) { + const recordId = `${chainId}_${address}` return tokenId ? `${recordId}_${tokenId}` : recordId } @@ -86,12 +86,12 @@ function TokenRecordOutDatabase(type: DatabaseTokenType, token: DatabaseTokenRec } } -export async function hasToken(type: DatabaseTokenType, address: string, tokenId?: string) { - return PluginDB.has(getDatabaseType(type), getRecordId(address, tokenId)) +export async function hasToken(chainId: ChainId, type: DatabaseTokenType, address: string, tokenId?: string) { + return PluginDB.has(getDatabaseType(type), getRecordId(chainId, address, tokenId)) } -export async function getToken(type: DatabaseTokenType, address: string, tokenId?: string) { - return PluginDB.get(getDatabaseType(type), getRecordId(address, tokenId)) +export async function getToken(chainId: ChainId, type: DatabaseTokenType, address: string, tokenId?: string) { + return PluginDB.get(getDatabaseType(type), getRecordId(chainId, address, tokenId)) } export async function getTokens(type: DatabaseTokenType) { @@ -123,12 +123,12 @@ export async function addToken(token: DatabaseTokenDetailed) { const type = getTokenType(token) const tokenId = getTokenId(token) const address = getTokenAddress(token) - if (await hasToken(type, address)) throw new Error(`Token ${address} already exists.`) + if (await hasToken(token.chainId, type, address)) throw new Error(`Token ${address} already exists.`) const now = new Date() // @ts-ignore await PluginDB.add({ ...token, - id: getRecordId(address, tokenId), + id: getRecordId(token.chainId, address, tokenId), type: getDatabaseType(type), createdAt: now, updatedAt: now, @@ -140,8 +140,8 @@ export async function removeToken(token: DatabaseTokenDetailed) { const type = getTokenType(token) const tokenId = getTokenId(token) const address = getTokenAddress(token) - if (!(await hasToken(type, address, tokenId))) throw new Error(`Failed to remove token ${address}.`) - await PluginDB.remove(getDatabaseType(type), getRecordId(address, tokenId)) + if (!(await hasToken(token.chainId, type, address, tokenId))) throw new Error(`Failed to remove token ${address}.`) + await PluginDB.remove(getDatabaseType(type), getRecordId(token.chainId, address, tokenId)) getEventMessage(type).sendToAll() } diff --git a/packages/mask/src/plugins/Wallet/settings.ts b/packages/mask/src/plugins/Wallet/settings.ts index 2198147cf8c1..66abfa5f67d2 100644 --- a/packages/mask/src/plugins/Wallet/settings.ts +++ b/packages/mask/src/plugins/Wallet/settings.ts @@ -10,6 +10,7 @@ import { ProviderType, LockStatus, BalanceOfChains, + BlockNumberOfChains, } from '@masknet/web3-shared-evm' import { PLUGIN_IDENTIFIER } from './constants' import { isEqual } from 'lodash-unified' @@ -60,6 +61,11 @@ export const currentAccountSettings = createGlobalSettings(`${PLUGIN_IDE primary: () => 'DO NOT DISPLAY IT IN UI', }) +export const currentChainIdSettings = createGlobalSettings(`${PLUGIN_IDENTIFIER}+chainId`, ChainId.Mainnet, { + primary: () => i18n.t('settings_choose_eth_network'), + secondary: () => 'This only affects the built-in wallet.', +}) + export const currentNetworkSettings = createGlobalSettings( `${PLUGIN_IDENTIFIER}+selectedWalletNetwork`, NetworkType.Ethereum, @@ -94,15 +100,19 @@ export const currentNonFungibleAssetDataProviderSettings = createGlobalSettings< }, ) -export const currentChainIdSettings = createGlobalSettings(`${PLUGIN_IDENTIFIER}+chainId`, ChainId.Mainnet, { - primary: () => i18n.t('settings_choose_eth_network'), - secondary: () => 'This only affects the built-in wallet.', -}) - export const currentBlockNumberSettings = createGlobalSettings(`${PLUGIN_IDENTIFIER}+blockNumber`, 0, { primary: () => 'DO NOT DISPLAY IT IN UI', }) +export const currentBlockNumbersSettings = createGlobalSettings( + `${PLUGIN_IDENTIFIER}+blockNumbers`, + {}, + { + primary: () => 'DO NOT DISPLAY IT IN UI', + }, + (a, b) => isEqual(a, b), +) + export const currentBalanceSettings = createGlobalSettings(`${PLUGIN_IDENTIFIER}+balance`, '0', { primary: () => 'DO NOT DISPLAY IT IN UI', }) diff --git a/packages/mask/src/settings/createSettings.ts b/packages/mask/src/settings/createSettings.ts index 5e9e0174430f..e2f8536dea0b 100644 --- a/packages/mask/src/settings/createSettings.ts +++ b/packages/mask/src/settings/createSettings.ts @@ -2,6 +2,8 @@ import { ValueRef, isEnvironment, Environment } from '@dimensiondev/holoflows-ki import Services from '../extension/service' import { MaskMessages } from '../utils/messages' import { defer } from '@masknet/shared-base' +import { getEnumAsArray } from '@dimensiondev/kit' +import { SocialNetworkID } from '../../shared/types' export interface SettingsTexts { primary: () => string @@ -99,17 +101,29 @@ export function createGlobalSettings( return settings } -export interface NetworkSettings { +export interface SocialNetworkSettings { [networkKey: string]: ValueRef & { ready: boolean; readyPromise: Promise } } -export function createNetworkSettings(settingsKey: string, defaultValue: T) { - const cached: NetworkSettings = {} +export function createSocialNetworkSettings( + settingsKey: string, + defaultValue: T, +) { + const cached: SocialNetworkSettings = {} + + // setup inital value + getEnumAsArray(SocialNetworkID).forEach(({ value }) => { + cached[value] = createInternalSettings(`${value}+${settingsKey}`, defaultValue) + }) + + // sync by remote updates MaskMessages.events.createNetworkSettingsReady.on((networkKey) => { if (networkKey.startsWith('plugin:') || settingsKey === 'pluginsEnabled') return if (!(networkKey in cached)) cached[networkKey] = createInternalSettings(`${networkKey}+${settingsKey}`, defaultValue) }) + + // get or set by local updates return new Proxy(cached, { get(target, networkKey: string) { if (!(networkKey in target)) { diff --git a/packages/mask/src/settings/settings.ts b/packages/mask/src/settings/settings.ts index cc0501082e52..0ce1c9ad21e9 100644 --- a/packages/mask/src/settings/settings.ts +++ b/packages/mask/src/settings/settings.ts @@ -1,10 +1,11 @@ -import { createGlobalSettings, createNetworkSettings, NetworkSettings } from './createSettings' +import { createGlobalSettings, createSocialNetworkSettings, SocialNetworkSettings } from './createSettings' import { i18n } from '../../shared-ui/locales_legacy' import { LaunchPage } from './types' import { Appearance } from '@masknet/theme' import { LanguageOptions } from '@masknet/public-api' import { Identifier, ProfileIdentifier } from '@masknet/shared-base' import { PLUGIN_ID } from '../plugins/EVM/constants' +import { ChainId, NetworkType, ProviderType } from '@masknet/web3-shared-evm' /** * Does the debug mode on @@ -43,28 +44,21 @@ export const pluginIDSettings = createGlobalSettings('pluginID', PLUGIN_ //#endregion //#region network setting +export const currentSelectedIdentity: SocialNetworkSettings = createSocialNetworkSettings( + 'currentSelectedIdentity', + '', +) -/** - * Expected Usage:export const currentImagePayloadStatus = createNetworkSettings('currentImagePayloadStatus') - * - * Work around the issue: - * https://github.com/microsoft/TypeScript/issues/42873 - * https://github.com/microsoft/TypeScript/issues/30858 - * - * References: - * PluginGitcoinMessages: packages/mask/src/plugins/Gitcoin/messages.ts - * PluginTraderMessages: packages/mask/src/plugins/Trader/messages.ts - * PluginTransakMessages: packages/mask/src/plugins/Transak/messages.ts - */ -export const currentImagePayloadStatus: NetworkSettings = createNetworkSettings('currentImagePayloadStatus', '') -export const currentSelectedIdentity: NetworkSettings = createNetworkSettings('currentSelectedIdentity', '') export function getCurrentSelectedIdentity(network: string) { return Identifier.fromString(currentSelectedIdentity[network].value, ProfileIdentifier).unwrapOr( ProfileIdentifier.unknown, ) } -export const currentSetupGuideStatus: NetworkSettings = createNetworkSettings('currentSetupGuideStatus', '') -export const userGuideStatus: NetworkSettings = createNetworkSettings('userGuideStatus', '') +export const currentSetupGuideStatus: SocialNetworkSettings = createSocialNetworkSettings( + 'currentSetupGuideStatus', + '', +) +export const userGuideStatus: SocialNetworkSettings = createSocialNetworkSettings('userGuideStatus', '') // This is a misuse of concept "NetworkSettings" as "namespaced settings" // The refactor is tracked in https://github.com/DimensionDev/Maskbook/issues/1884 /** @@ -73,7 +67,29 @@ export const userGuideStatus: NetworkSettings = createNetworkSettings('u * use `useActivatedPluginsSNSAdaptor().find((x) => x.ID === PLUGIN_ID)` or * `useActivatedPluginsDashboard().find((x) => x.ID === PLUGIN_ID)` instead */ -export const currentPluginEnabledStatus: NetworkSettings = createNetworkSettings('pluginsEnabled', true) +export const currentPluginEnabledStatus: SocialNetworkSettings = createSocialNetworkSettings( + 'pluginsEnabled', + true, +) +//#endregion + +//#region web3 network settings +export const currentAccountSettings: SocialNetworkSettings = createSocialNetworkSettings( + 'currentAccountSettings', + '', +) +export const currentChainIdSettings: SocialNetworkSettings = createSocialNetworkSettings( + 'currentChainIdSettings', + ChainId.Mainnet, +) +export const currentNetworkSettings: SocialNetworkSettings = createSocialNetworkSettings( + 'currentNetworkSettings', + NetworkType.Ethereum, +) +export const currentProviderSettings: SocialNetworkSettings = createSocialNetworkSettings( + 'currentProviderSettings', + ProviderType.MaskWallet, +) //#endregion export const launchPageSettings = createGlobalSettings('launchPage', LaunchPage.dashboard, { diff --git a/packages/mask/src/social-network-adaptor/browser-action/index.ts b/packages/mask/src/social-network-adaptor/browser-action/index.ts index 8245c74a4e6d..b22ebbdfb1b3 100644 --- a/packages/mask/src/social-network-adaptor/browser-action/index.ts +++ b/packages/mask/src/social-network-adaptor/browser-action/index.ts @@ -1,9 +1,10 @@ -import { defineSocialNetworkUI, definedSocialNetworkUIs, SocialNetworkUI, SocialNetwork } from '../../social-network' -import { isEnvironment, Environment, ValueRef } from '@dimensiondev/holoflows-kit' import { IdentifierMap } from '@masknet/shared-base' +import { isEnvironment, Environment, ValueRef } from '@dimensiondev/holoflows-kit' +import { SocialNetworkID } from '../../../shared' +import { defineSocialNetworkUI, definedSocialNetworkUIs, SocialNetworkUI, SocialNetwork } from '../../social-network' const base: SocialNetwork.Base = { - networkIdentifier: 'localhost', + networkIdentifier: SocialNetworkID.BrowserAction, name: '', declarativePermissions: { origins: [] }, shouldActivate(location) { @@ -35,7 +36,7 @@ const define: SocialNetworkUI.Definition = { if (activeTab === undefined) return state const location = new URL(activeTab.url || globalThis.location.href) for (const ui of definedSocialNetworkUIs.values()) { - if (ui.shouldActivate(location) && ui.networkIdentifier !== 'localhost') { + if (ui.shouldActivate(location) && ui.networkIdentifier !== SocialNetworkID.BrowserAction) { const _ = (await ui.load()).default if (signal.aborted) return state // TODO: heck, this is not what we expected. diff --git a/packages/mask/src/social-network-adaptor/facebook.com/base.ts b/packages/mask/src/social-network-adaptor/facebook.com/base.ts index 6335b60223a9..f754d586d02d 100644 --- a/packages/mask/src/social-network-adaptor/facebook.com/base.ts +++ b/packages/mask/src/social-network-adaptor/facebook.com/base.ts @@ -1,19 +1,19 @@ +import { SocialNetworkID } from '../../../shared' import type { SocialNetwork, SocialNetworkWorker } from '../../social-network/types' const origins = ['https://www.facebook.com/*', 'https://m.facebook.com/*', 'https://facebook.com/*'] -export const FACEBOOK_ID = 'facebook.com' export const facebookBase: SocialNetwork.Base = { - networkIdentifier: FACEBOOK_ID, + networkIdentifier: SocialNetworkID.Facebook, name: 'facebook', declarativePermissions: { origins }, shouldActivate(location) { - return location.hostname.endsWith(FACEBOOK_ID) + return location.hostname.endsWith(SocialNetworkID.Facebook) }, } export function isFacebook(ui: SocialNetwork.Base) { - return ui.networkIdentifier === FACEBOOK_ID + return ui.networkIdentifier === SocialNetworkID.Facebook } export const facebookWorkerBase: SocialNetworkWorker.WorkerBase & SocialNetwork.Base = { diff --git a/packages/mask/src/social-network-adaptor/facebook.com/utils/resolveFacebookLink.ts b/packages/mask/src/social-network-adaptor/facebook.com/utils/resolveFacebookLink.ts index 3acccb7bccd6..39b342fd12b4 100644 --- a/packages/mask/src/social-network-adaptor/facebook.com/utils/resolveFacebookLink.ts +++ b/packages/mask/src/social-network-adaptor/facebook.com/utils/resolveFacebookLink.ts @@ -1,5 +1,5 @@ -import { FACEBOOK_ID } from '../base' +import { SocialNetworkID } from '../../../../shared' export function resolveFacebookLink(link: string, id: string) { - return id === FACEBOOK_ID ? link.replace(/\?fbclid=[\S\s]*#/, '#') : link + return id === SocialNetworkID.Facebook ? link.replace(/\?fbclid=[\S\s]*#/, '#') : link } diff --git a/packages/mask/src/social-network-adaptor/instagram.com/base.ts b/packages/mask/src/social-network-adaptor/instagram.com/base.ts index 4ed98e9b94a3..c05ced62e93a 100644 --- a/packages/mask/src/social-network-adaptor/instagram.com/base.ts +++ b/packages/mask/src/social-network-adaptor/instagram.com/base.ts @@ -1,17 +1,17 @@ +import { SocialNetworkID } from '../../../shared' import type { SocialNetwork, SocialNetworkWorker } from '../../social-network/types' -const id = 'instagram.com' const origins = ['https://www.instagram.com/*', 'https://m.instagram.com/*', 'https://instagram.com/*'] export const instagramBase: SocialNetwork.Base = { - networkIdentifier: id, + networkIdentifier: SocialNetworkID.Instagram, name: 'instagram', declarativePermissions: { origins }, shouldActivate(location) { - return location.host.endsWith(id) + return location.host.endsWith(SocialNetworkID.Instagram) }, notReadyForProduction: true, } export const instagramWorkerBase: SocialNetworkWorker.WorkerBase & SocialNetwork.Base = { ...instagramBase, - gunNetworkHint: id, + gunNetworkHint: SocialNetworkID.Instagram, } diff --git a/packages/mask/src/social-network-adaptor/minds.com/base.ts b/packages/mask/src/social-network-adaptor/minds.com/base.ts index d68eef969776..4ff2943df6cb 100644 --- a/packages/mask/src/social-network-adaptor/minds.com/base.ts +++ b/packages/mask/src/social-network-adaptor/minds.com/base.ts @@ -1,9 +1,9 @@ +import { SocialNetworkID } from '../../../shared' import type { SocialNetwork, SocialNetworkWorker } from '../../social-network/types' -export const MINDS_ID = 'minds.com' const origins = ['https://www.minds.com/*', 'https://minds.com/*', 'https://cdn.minds.com/*'] export const mindsBase: SocialNetwork.Base = { - networkIdentifier: MINDS_ID, + networkIdentifier: SocialNetworkID.Minds, name: 'minds', declarativePermissions: { origins }, shouldActivate(location) { @@ -12,7 +12,7 @@ export const mindsBase: SocialNetwork.Base = { } export function isMinds(ui: SocialNetwork.Base) { - return ui.networkIdentifier === MINDS_ID + return ui.networkIdentifier === SocialNetworkID.Minds } export const mindsWorkerBase: SocialNetworkWorker.WorkerBase & SocialNetwork.Base = { diff --git a/packages/mask/src/social-network-adaptor/twitter.com/base.ts b/packages/mask/src/social-network-adaptor/twitter.com/base.ts index a85a61db85cd..6823edf349d4 100644 --- a/packages/mask/src/social-network-adaptor/twitter.com/base.ts +++ b/packages/mask/src/social-network-adaptor/twitter.com/base.ts @@ -1,9 +1,9 @@ +import { SocialNetworkID } from '../../../shared' import type { SocialNetwork, SocialNetworkWorker } from '../../social-network/types' -const id = 'twitter.com' const origins = ['https://mobile.twitter.com/*', 'https://twitter.com/*'] export const twitterBase: SocialNetwork.Base = { - networkIdentifier: id, + networkIdentifier: SocialNetworkID.Twitter, name: 'twitter', declarativePermissions: { origins }, shouldActivate(location) { @@ -12,7 +12,7 @@ export const twitterBase: SocialNetwork.Base = { } export function isTwitter(ui: SocialNetwork.Base) { - return ui.networkIdentifier === id + return ui.networkIdentifier === SocialNetworkID.Twitter } export const twitterWorkerBase: SocialNetworkWorker.WorkerBase & SocialNetwork.Base = { diff --git a/packages/mask/src/social-network/ui.ts b/packages/mask/src/social-network/ui.ts index 63da5ca7f99d..81c471d04729 100644 --- a/packages/mask/src/social-network/ui.ts +++ b/packages/mask/src/social-network/ui.ts @@ -2,7 +2,7 @@ import '../utils/debug/general' import '../utils/debug/ui' import Services from '../extension/service' import { untilDomLoaded } from '../utils/dom' -import { Flags } from '../../shared' +import { Flags, SocialNetworkID } from '../../shared' import i18nNextInstance from '../../shared-ui/locales_legacy' import type { SocialNetworkUI } from './types' import { managedStateCreator } from './utils' @@ -31,7 +31,7 @@ export let activatedSocialNetworkUI: SocialNetworkUI.Definition = { throw new Error() }, injection: {}, - networkIdentifier: 'localhost', + networkIdentifier: SocialNetworkID.Dashboard, name: '', shouldActivate: () => false, utils: { createPostContext: null! }, diff --git a/packages/web3-shared/evm/hooks/useERC721TokenDetailedOwnerList.ts b/packages/web3-shared/evm/hooks/useERC721TokenDetailedOwnerList.ts index 8299d431d993..fafc4e639a3f 100644 --- a/packages/web3-shared/evm/hooks/useERC721TokenDetailedOwnerList.ts +++ b/packages/web3-shared/evm/hooks/useERC721TokenDetailedOwnerList.ts @@ -140,6 +140,7 @@ export async function getERC721TokenDetailedOwnerListFromOpensea( return assets.map( (asset): ERC721TokenDetailed => ({ + chainId, tokenId: asset.token_id, contractDetailed: contractDetailed ?? { type: EthereumTokenType.ERC721, diff --git a/packages/web3-shared/evm/types/index.ts b/packages/web3-shared/evm/types/index.ts index d7afb2cac29a..3f7e3170de5d 100644 --- a/packages/web3-shared/evm/types/index.ts +++ b/packages/web3-shared/evm/types/index.ts @@ -29,9 +29,11 @@ export interface BalanceOfChainRecord { } export interface BalanceOfChains { - [provider: string]: { - [chainId: number]: string - } + [chainId: string]: string +} + +export interface BlockNumberOfChains { + [chainId: string]: number } // bigint is not in our list. iOS doesn't support that. @@ -170,6 +172,7 @@ export interface ERC721TokenDetailed { tokenId: string info: ERC721TokenInfo contractDetailed: ERC721ContractDetailed + chainId: ChainId } export interface ERC721TokenRecordInDatabase extends ERC721TokenDetailed { diff --git a/packages/web3-shared/evm/utils/token.ts b/packages/web3-shared/evm/utils/token.ts index c113aeed509e..2596c3c6684b 100644 --- a/packages/web3-shared/evm/utils/token.ts +++ b/packages/web3-shared/evm/utils/token.ts @@ -80,6 +80,7 @@ export function createERC721Token( contractDetailed, info, tokenId, + chainId: contractDetailed.chainId, } } From 8be18937b84f689cbb2865fb8a2632e097b58bbf Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 17 Dec 2021 15:15:17 +0800 Subject: [PATCH 2/4] refactor: make code simpler --- .../Trader/SNSAdaptor/trader/TraderDialog.tsx | 14 +++++--------- .../mask/src/plugins/Wallet/services/account.ts | 11 ----------- packages/mask/src/plugins/Wallet/services/chain.ts | 2 +- 3 files changed, 6 insertions(+), 21 deletions(-) diff --git a/packages/mask/src/plugins/Trader/SNSAdaptor/trader/TraderDialog.tsx b/packages/mask/src/plugins/Trader/SNSAdaptor/trader/TraderDialog.tsx index d602c5b8b09a..4cbd14bc31bd 100644 --- a/packages/mask/src/plugins/Trader/SNSAdaptor/trader/TraderDialog.tsx +++ b/packages/mask/src/plugins/Trader/SNSAdaptor/trader/TraderDialog.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' -import { ChainId, getChainIdFromNetworkType, useChainId, useChainIdValid } from '@masknet/web3-shared-evm' +import { useUpdateEffect } from 'react-use' +import { ChainId, getChainIdFromNetworkType, NetworkType, useChainId, useChainIdValid } from '@masknet/web3-shared-evm' import { DialogContent } from '@mui/material' import { InjectedDialog } from '../../../../components/shared/InjectedDialog' import { useRemoteControlledDialog } from '@masknet/shared' @@ -11,9 +12,8 @@ import { useI18N } from '../../../../utils' import { makeStyles, MaskColorVar } from '@masknet/theme' import { WalletStatusBox } from '../../../../components/shared/WalletStatusBox' import { NetworkTab } from '../../../../components/shared/NetworkTab' -import { useAsync, useUpdateEffect } from 'react-use' -import { WalletRPC } from '../../../Wallet/messages' import { isDashboardPage } from '@masknet/shared-base' +import { getEnumAsArray } from '@dimensiondev/kit' const useStyles = makeStyles<{ isDashboard: boolean }>()((theme, { isDashboard }) => ({ walletStatusBox: { @@ -68,8 +68,8 @@ interface TraderDialogProps { } export function TraderDialog({ open, onClose }: TraderDialogProps) { - const isDashboard = isDashboardPage() const { t } = useI18N() + const isDashboard = isDashboardPage() const { classes } = useStyles({ isDashboard }) const currentChainId = useChainId() const chainIdValid = useChainIdValid() @@ -82,11 +82,7 @@ export function TraderDialog({ open, onClose }: TraderDialogProps) { if (ev?.traderProps) setTraderProps(ev.traderProps) }, ) - - const { value: chains } = useAsync(async () => { - const networks = await WalletRPC.getSupportedNetworks() - return networks.map((network) => getChainIdFromNetworkType(network)) - }, []) + const chains = getEnumAsArray(NetworkType).map(({ value }) => getChainIdFromNetworkType(value)) useEffect(() => { if (!chainIdValid) closeDialog() diff --git a/packages/mask/src/plugins/Wallet/services/account.ts b/packages/mask/src/plugins/Wallet/services/account.ts index ad3157b894ac..0f91c370bb44 100644 --- a/packages/mask/src/plugins/Wallet/services/account.ts +++ b/packages/mask/src/plugins/Wallet/services/account.ts @@ -18,7 +18,6 @@ import { } from '../settings' import { getWallets, hasWallet, updateWallet } from './wallet' import { hasNativeAPI, nativeAPI } from '../../../utils' -import { Flags } from '../../../../shared' export async function updateAccount( options: { @@ -116,13 +115,3 @@ export async function setDefaultWallet() { providerType: ProviderType.MaskWallet, }) } - -export async function getSupportedNetworks() { - return [ - NetworkType.Ethereum, - Flags.bsc_enabled ? NetworkType.Binance : undefined, - Flags.polygon_enabled ? NetworkType.Polygon : undefined, - Flags.arbitrum_enabled ? NetworkType.Arbitrum : undefined, - Flags.xdai_enabled ? NetworkType.xDai : undefined, - ].filter(Boolean) as NetworkType[] -} diff --git a/packages/mask/src/plugins/Wallet/services/chain.ts b/packages/mask/src/plugins/Wallet/services/chain.ts index 41c2299cfec8..f8959bce07d7 100644 --- a/packages/mask/src/plugins/Wallet/services/chain.ts +++ b/packages/mask/src/plugins/Wallet/services/chain.ts @@ -1,4 +1,4 @@ -import { uniq, throttle } from 'lodash-unified' +import { throttle } from 'lodash-unified' import { BalanceOfChains, BlockNumberOfChains, ProviderType } from '@masknet/web3-shared-evm' import { pollingTask } from '@masknet/shared-base' import { getBalance, getBlockNumber, resetAllNonce } from '../../../extension/background-script/EthereumService' From e40af75de50670954652923fd38b2ef09256a36e Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 17 Dec 2021 17:07:55 +0800 Subject: [PATCH 3/4] chore: wip --- .../Personas/components/ProfileList/index.tsx | 2 +- .../src/plugins/Collectible/apis/rarible.ts | 45 +++++++++---------- .../Wallet/services/wallet/database/token.ts | 11 ++--- .../plugins/Wallet/services/wallet/index.ts | 2 +- packages/mask/src/settings/createSettings.ts | 2 +- 5 files changed, 29 insertions(+), 33 deletions(-) diff --git a/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx b/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx index d7ba1a99ce7e..7187d633ae1e 100644 --- a/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx +++ b/packages/mask/src/extension/popups/pages/Personas/components/ProfileList/index.tsx @@ -69,7 +69,7 @@ export const ProfileList = memo(() => { const definedSocialNetworks = compact( [...definedSocialNetworkUIs.values()].map(({ networkIdentifier }) => { - if (networkIdentifier.includes('localhost')) return null + if (networkIdentifier.startsWith('localhost')) return null return networkIdentifier }), ) diff --git a/packages/mask/src/plugins/Collectible/apis/rarible.ts b/packages/mask/src/plugins/Collectible/apis/rarible.ts index 3fd1e85488e3..475250ad8222 100644 --- a/packages/mask/src/plugins/Collectible/apis/rarible.ts +++ b/packages/mask/src/plugins/Collectible/apis/rarible.ts @@ -1,5 +1,5 @@ import urlcat from 'urlcat' -import type { ChainId } from '@masknet/web3-shared-evm' +import { ChainId } from '@masknet/web3-shared-evm' import { compact } from 'lodash-unified' import { OrderSide } from 'opensea-js/lib/types' import stringify from 'json-stable-stringify' @@ -14,7 +14,6 @@ import { import { RaribleChainURL, RaribleMainnetURL } from '../constants' import { toRaribleImage } from '../helpers' import { resolveRaribleUserNetwork } from '../pipes' -import { currentChainIdSettings } from '../../Wallet/settings' async function fetchFromRarible(root: string, subPath: string, config = {} as RequestInit) { const response = await ( @@ -27,7 +26,8 @@ async function fetchFromRarible(root: string, subPath: string, config = {} as return response as T } -export async function getProfilesFromRarible(addresses: (string | undefined)[]) { +export async function getProfilesFromRarible(chainId: ChainId, addresses: (string | undefined)[]) { + if (chainId !== ChainId.Mainnet) return [] return fetchFromRarible(RaribleMainnetURL, 'profiles/list', { method: 'POST', body: stringify(addresses), @@ -37,7 +37,8 @@ export async function getProfilesFromRarible(addresses: (string | undefined)[]) }) } -export async function getNFTItem(tokenAddress: string, tokenId: string) { +export async function getNFTItem(chainId: ChainId, tokenAddress: string, tokenId: string) { + if (chainId !== ChainId.Mainnet) return [] const assetResponse = await fetchFromRarible( RaribleChainURL, urlcat('/v0.1/nft/items/:tokenAddress::tokenId', { @@ -55,11 +56,8 @@ export async function getNFTItem(tokenAddress: string, tokenId: string) { return assetResponse } -export async function getOffersFromRarible( - chainId: ChainId.Mainnet | ChainId.Ropsten, - tokenAddress: string, - tokenId: string, -) { +export async function getOffersFromRarible(chainId: ChainId, tokenAddress: string, tokenId: string) { + if (chainId !== ChainId.Mainnet) return [] const orders = await fetchFromRarible( RaribleMainnetURL, `items/${tokenAddress}:${tokenId}/offers`, @@ -89,11 +87,14 @@ export async function getOffersFromRarible( }) } -export async function getListingsFromRarible(tokenAddress: string, tokenId: string) { +export async function getListingsFromRarible(chainId: ChainId, tokenAddress: string, tokenId: string) { + if (chainId !== ChainId.Mainnet) return [] const assets = await fetchFromRarible(RaribleMainnetURL, `items/${tokenAddress}:${tokenId}/ownerships`) const listings = assets.filter((x) => x.selling) - const profiles = await getProfilesFromRarible(listings.map((x) => x.owner)) - const chainId = currentChainIdSettings.value + const profiles = await getProfilesFromRarible( + chainId, + listings.map((x) => x.owner), + ) return listings.map((asset) => { const ownerInfo = profiles.find((owner) => owner.id === asset.owner) return { @@ -111,24 +112,20 @@ export async function getListingsFromRarible(tokenAddress: string, tokenId: stri }) } -export async function getOrderFromRarible( - chainId: ChainId.Mainnet | ChainId.Ropsten, - tokenAddress: string, - tokenId: string, - side: OrderSide, -) { +export async function getOrderFromRarible(chainId: ChainId, tokenAddress: string, tokenId: string, side: OrderSide) { + if (chainId !== ChainId.Mainnet) return [] switch (side) { case OrderSide.Buy: return getOffersFromRarible(chainId, tokenAddress, tokenId) case OrderSide.Sell: - return getListingsFromRarible(tokenAddress, tokenId) + return getListingsFromRarible(chainId, tokenAddress, tokenId) default: return [] } } -export async function getHistoryFromRarible(tokenAddress: string, tokenId: string) { - let histories = await fetchFromRarible(RaribleMainnetURL, `activity`, { +export async function getHistoryFromRarible(chainId: ChainId, tokenAddress: string, tokenId: string) { + const result = await fetchFromRarible(RaribleMainnetURL, `activity`, { method: 'POST', body: stringify({ // types: ['BID', 'BURN', 'BUY', 'CANCEL', 'CANCEL_BID', 'ORDER', 'MINT', 'TRANSFER', 'SALE'], @@ -144,11 +141,9 @@ export async function getHistoryFromRarible(tokenAddress: string, tokenId: strin }, }) - if (histories.length) { - histories = histories.filter((x) => Object.values(RaribleEventType).includes(x['@type'])) - } - + const histories = result.length ? result.filter((x) => Object.values(RaribleEventType).includes(x['@type'])) : [] const profiles = await getProfilesFromRarible( + chainId, compact([ ...histories.map((history) => history.owner), ...histories.map((history) => history.buyer), diff --git a/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts b/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts index 354d8b650b66..42f4cab56a31 100644 --- a/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts +++ b/packages/mask/src/plugins/Wallet/services/wallet/database/token.ts @@ -94,26 +94,27 @@ export async function getToken(chainId: ChainId, type: DatabaseTokenType, addres return PluginDB.get(getDatabaseType(type), getRecordId(chainId, address, tokenId)) } -export async function getTokens(type: DatabaseTokenType) { +export async function getTokens(chainId: ChainId, type: DatabaseTokenType) { const tokens = await asyncIteratorToArray(PluginDB.iterate(getDatabaseType(type))) return tokens .map((x) => x.value) + .filter((y) => y.chainId === chainId) .sort((a, z) => z.createdAt.getTime() - a.createdAt.getTime()) .slice(0, MAX_TOKEN_COUNT) .map((x) => TokenRecordOutDatabase(type, x) as T) } -export async function getTokensCount(type: DatabaseTokenType) { - return (await getTokens(type)).length +export async function getTokensCount(chainId: ChainId, type: DatabaseTokenType) { + return (await getTokens(chainId, type)).length } -export async function getTokensPaged(type: DatabaseTokenType, index: number, count: number) { +export async function getTokensByPagination(chainId: ChainId, type: DatabaseTokenType, index: number, count: number) { let read = 0 const records: DatabaseTokenRecord[] = [] for await (const { value: record } of PluginDB.iterate(getDatabaseType(type))) { if (read > (index + 1) * count) break if (read < index * count) continue - records.push(record) + if (record.chainId === chainId) records.push(record) read += 1 } return records.map((x) => TokenRecordOutDatabase(type, x)) diff --git a/packages/mask/src/plugins/Wallet/services/wallet/index.ts b/packages/mask/src/plugins/Wallet/services/wallet/index.ts index 2a052e64cb6a..3370afe871f1 100644 --- a/packages/mask/src/plugins/Wallet/services/wallet/index.ts +++ b/packages/mask/src/plugins/Wallet/services/wallet/index.ts @@ -25,7 +25,7 @@ export { getToken, getTokens, getTokensCount, - getTokensPaged, + getTokensByPagination, hasToken, addToken, removeToken, diff --git a/packages/mask/src/settings/createSettings.ts b/packages/mask/src/settings/createSettings.ts index e2f8536dea0b..0bd31d83939d 100644 --- a/packages/mask/src/settings/createSettings.ts +++ b/packages/mask/src/settings/createSettings.ts @@ -111,7 +111,7 @@ export function createSocialNetworkSettings = {} - // setup inital value + // setup initial value getEnumAsArray(SocialNetworkID).forEach(({ value }) => { cached[value] = createInternalSettings(`${value}+${settingsKey}`, defaultValue) }) From 552268928ee944899149ae88b3682210bf3670e5 Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Mon, 20 Dec 2021 16:29:28 +0800 Subject: [PATCH 4/4] chore: wip --- .../popups/components/NetworkSelector/index.tsx | 10 ++++------ .../popups/pages/Wallet/ContractInteraction/index.tsx | 6 +++--- .../extension/popups/pages/Wallet/GasSetting/index.tsx | 6 ++---- .../popups/pages/Wallet/ReplaceTransaction/index.tsx | 5 ++--- .../extension/popups/pages/Wallet/Transfer/index.tsx | 7 +++---- 5 files changed, 14 insertions(+), 20 deletions(-) diff --git a/packages/mask/src/extension/popups/components/NetworkSelector/index.tsx b/packages/mask/src/extension/popups/components/NetworkSelector/index.tsx index 093886514540..8e823bc29b01 100644 --- a/packages/mask/src/extension/popups/components/NetworkSelector/index.tsx +++ b/packages/mask/src/extension/popups/components/NetworkSelector/index.tsx @@ -2,14 +2,12 @@ import { memo, useCallback } from 'react' import { Box, MenuItem, Typography } from '@mui/material' import { makeStyles } from '@masknet/theme' import { Flags } from '../../../../../shared' -import { ChainId, ProviderType, useAccount } from '@masknet/web3-shared-evm' +import { ChainId, ProviderType, useAccount, useChainId, useProviderType } from '@masknet/web3-shared-evm' import { getRegisteredWeb3Networks, NetworkPluginID, Web3Plugin } from '@masknet/plugin-infra' import { currentMaskWalletAccountSettings, - currentMaskWalletChainIdSettings, - currentProviderSettings, } from '../../../../plugins/Wallet/settings' -import { ChainIcon, useMenu, useValueRef, WalletIcon } from '@masknet/shared' +import { ChainIcon, useMenu, WalletIcon } from '@masknet/shared' import { ArrowDownRound } from '@masknet/icons' import { WalletRPC } from '../../../../plugins/Wallet/messages' @@ -49,8 +47,8 @@ const useStyles = makeStyles()((theme) => ({ export const NetworkSelector = memo(() => { const networks = getRegisteredWeb3Networks() const account = useAccount() - const currentChainId = useValueRef(currentMaskWalletChainIdSettings) - const currentProvider = useValueRef(currentProviderSettings) + const currentChainId = useChainId() + const currentProvider = useProviderType() const onChainChange = useCallback( async (chainId: ChainId) => { if (currentProvider === ProviderType.MaskWallet) { diff --git a/packages/mask/src/extension/popups/pages/Wallet/ContractInteraction/index.tsx b/packages/mask/src/extension/popups/pages/Wallet/ContractInteraction/index.tsx index 75298e83442c..f793d8f1b7ea 100644 --- a/packages/mask/src/extension/popups/pages/Wallet/ContractInteraction/index.tsx +++ b/packages/mask/src/extension/popups/pages/Wallet/ContractInteraction/index.tsx @@ -15,8 +15,9 @@ import { useChainId, useERC20TokenDetailed, useNativeTokenDetailed, + useNetworkType, } from '@masknet/web3-shared-evm' -import { FormattedBalance, FormattedCurrency, TokenIcon, useValueRef } from '@masknet/shared' +import { FormattedBalance, FormattedCurrency, TokenIcon, } from '@masknet/shared' import { Link, Typography } from '@mui/material' import { useI18N } from '../../../../../utils' import { PopupRoutes } from '@masknet/shared-base' @@ -24,7 +25,6 @@ import { LoadingButton } from '@mui/lab' import { unreachable } from '@dimensiondev/kit' import { WalletRPC } from '../../../../../plugins/Wallet/messages' import Services from '../../../../service' -import { currentNetworkSettings } from '../../../../../plugins/Wallet/settings' import BigNumber from 'bignumber.js' import { useNativeTokenPrice, useTokenPrice } from '../../../../../plugins/Wallet/hooks/useTokenPrice' import { LoadingPlaceholder } from '../../../components/LoadingPlaceholder' @@ -136,7 +136,7 @@ const ContractInteraction = memo(() => { const location = useLocation() const history = useHistory() const chainId = useChainId() - const networkType = useValueRef(currentNetworkSettings) + const networkType = useNetworkType() const [transferError, setTransferError] = useState(false) const { value: request, loading: requestLoading } = useUnconfirmedRequest() diff --git a/packages/mask/src/extension/popups/pages/Wallet/GasSetting/index.tsx b/packages/mask/src/extension/popups/pages/Wallet/GasSetting/index.tsx index 6fb1d0e13b08..cb3b2cc30f86 100644 --- a/packages/mask/src/extension/popups/pages/Wallet/GasSetting/index.tsx +++ b/packages/mask/src/extension/popups/pages/Wallet/GasSetting/index.tsx @@ -1,12 +1,10 @@ import { memo } from 'react' import { makeStyles } from '@masknet/theme' import { Typography } from '@mui/material' -import { useValueRef } from '@masknet/shared' -import { NetworkType } from '@masknet/web3-shared-evm' +import { NetworkType, useNetworkType } from '@masknet/web3-shared-evm' import { useI18N } from '../../../../../utils' import { GasSetting1559 } from './GasSetting1559' import { Prior1559GasSetting } from './Prior1559GasSetting' -import { currentNetworkSettings } from '../../../../../plugins/Wallet/settings' const useStyles = makeStyles()(() => ({ container: { @@ -30,7 +28,7 @@ const useStyles = makeStyles()(() => ({ const GasSetting = memo(() => { const { t } = useI18N() const { classes } = useStyles() - const networkType = useValueRef(currentNetworkSettings) + const networkType = useNetworkType() return (
{t('popups_wallet_gas_fee_settings')} diff --git a/packages/mask/src/extension/popups/pages/Wallet/ReplaceTransaction/index.tsx b/packages/mask/src/extension/popups/pages/Wallet/ReplaceTransaction/index.tsx index 0861d2598eb1..cf861b3c60ca 100644 --- a/packages/mask/src/extension/popups/pages/Wallet/ReplaceTransaction/index.tsx +++ b/packages/mask/src/extension/popups/pages/Wallet/ReplaceTransaction/index.tsx @@ -12,9 +12,8 @@ import { getChainIdFromNetworkType, isEIP1559Supported, useNativeTokenDetailed, + useNetworkType, } from '@masknet/web3-shared-evm' -import { useValueRef } from '@masknet/shared' -import { currentNetworkSettings } from '../../../../../plugins/Wallet/settings' import BigNumber from 'bignumber.js' import { useI18N } from '../../../../../utils' import { hexToNumber, toHex } from 'web3-utils' @@ -79,7 +78,7 @@ const ReplaceTransaction = memo(() => { const { value: nativeToken } = useNativeTokenDetailed() const nativeTokenPrice = useNativeTokenPrice(nativeToken?.chainId) - const networkType = useValueRef(currentNetworkSettings) + const networkType = useNetworkType() const is1559 = isEIP1559Supported(getChainIdFromNetworkType(networkType)) const schema = useMemo(() => { diff --git a/packages/mask/src/extension/popups/pages/Wallet/Transfer/index.tsx b/packages/mask/src/extension/popups/pages/Wallet/Transfer/index.tsx index 05729160830d..927ffa99af88 100644 --- a/packages/mask/src/extension/popups/pages/Wallet/Transfer/index.tsx +++ b/packages/mask/src/extension/popups/pages/Wallet/Transfer/index.tsx @@ -1,11 +1,10 @@ import { memo, useMemo, useState } from 'react' import { makeStyles } from '@masknet/theme' -import { formatBalance, NetworkType, ProviderType, useWallets } from '@masknet/web3-shared-evm' +import { formatBalance, NetworkType, ProviderType, useNetworkType, useWallets } from '@masknet/web3-shared-evm' import { MenuItem, Typography } from '@mui/material' -import { FormattedBalance, TokenIcon, useMenu, useValueRef } from '@masknet/shared' +import { FormattedBalance, TokenIcon, useMenu } from '@masknet/shared' import { useContainer } from 'unstated-next' import { WalletContext } from '../hooks/useWalletContext' -import { currentNetworkSettings } from '../../../../../plugins/Wallet/settings' import { Transfer1559 } from './Transfer1559' import { Prior1559Transfer } from './Prior1559Transfer' @@ -26,7 +25,7 @@ const useStyles = makeStyles()({ const Transfer = memo(() => { const { classes } = useStyles() - const networkType = useValueRef(currentNetworkSettings) + const networkType = useNetworkType() const wallets = useWallets(ProviderType.MaskWallet) const { assets, currentToken } = useContainer(WalletContext) const [selectedAsset, setSelectedAsset] = useState(currentToken)