From cba3aca208fff65ef15078a629c82c018d09906f Mon Sep 17 00:00:00 2001 From: nuanyang233 Date: Thu, 9 Jun 2022 00:04:32 +0800 Subject: [PATCH 01/14] fix: bugfix for token list sort --- packages/plugin-infra/src/web3/useFungibleAssets.ts | 13 +++++-------- .../shared/src/UI/components/TokenIcon/index.tsx | 4 ++-- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/packages/plugin-infra/src/web3/useFungibleAssets.ts b/packages/plugin-infra/src/web3/useFungibleAssets.ts index 38c872964730..0df4fc0ab474 100644 --- a/packages/plugin-infra/src/web3/useFungibleAssets.ts +++ b/packages/plugin-infra/src/web3/useFungibleAssets.ts @@ -3,10 +3,10 @@ import { asyncIteratorToArray, EMPTY_LIST } from '@masknet/shared-base' import { CurrencyType, currySameAddress, + formatBalance, FungibleAsset, isSameAddress, minus, - multipliedBy, NetworkPluginID, toZero, } from '@masknet/web3-shared-base' @@ -46,14 +46,11 @@ export function useFungibleAssets !isBlockedToken(x)) .sort((a, z) => { - const aBalance = toZero(a.balance) - const zBalance = toZero(z.balance) + const aBalance = toZero(formatBalance(a.balance, a.decimals)) + const zBalance = toZero(formatBalance(z.balance, z.decimals)) - const aPrice = toZero(a.value?.[CurrencyType.USD] ?? '0') - const zPrice = toZero(z.value?.[CurrencyType.USD] ?? '0') - - const aUSD = multipliedBy(aPrice, aBalance) - const zUSD = multipliedBy(zPrice, zBalance) + const aUSD = toZero(a.value?.[CurrencyType.USD] ?? '0') + const zUSD = toZero(z.value?.[CurrencyType.USD] ?? '0') const isNativeTokenA = isSameAddress(a.address, Others?.getNativeTokenAddress(a.chainId)) const isNativeTokenZ = isSameAddress(z.address, Others?.getNativeTokenAddress(z.chainId)) diff --git a/packages/shared/src/UI/components/TokenIcon/index.tsx b/packages/shared/src/UI/components/TokenIcon/index.tsx index b05d08fca76b..44deda13b820 100644 --- a/packages/shared/src/UI/components/TokenIcon/index.tsx +++ b/packages/shared/src/UI/components/TokenIcon/index.tsx @@ -37,7 +37,7 @@ export function TokenIcon(props: TokenIconProps) { }, [chainId, address, logoURL, hub]) const { value: trustedLogoURL } = useImageFailOver(urls, '') - const base64 = useImageBase64(address, trustedLogoURL) + const base64 = useImageBase64(`${address}_${chainId}`, trustedLogoURL) return } @@ -64,7 +64,7 @@ export const TokenIconUI = memo((props) => { src={logoURL} style={{ backgroundColor: logoURL ? undefined : defaultBackgroundColor }} {...AvatarProps}> - {' '} + {name?.slice(0, 1).toUpperCase()} ) }) From b549dace3ee4f831036d6568791723e7c224bda2 Mon Sep 17 00:00:00 2001 From: nuanyang233 Date: Thu, 9 Jun 2022 14:01:42 +0800 Subject: [PATCH 02/14] fix: fetch nft assets from opensea --- packages/plugins/EVM/src/state/Hub/hub.ts | 4 ++-- packages/web3-providers/src/opensea/index.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/plugins/EVM/src/state/Hub/hub.ts b/packages/plugins/EVM/src/state/Hub/hub.ts index ca5d384c09e6..d6ff71f66681 100644 --- a/packages/plugins/EVM/src/state/Hub/hub.ts +++ b/packages/plugins/EVM/src/state/Hub/hub.ts @@ -94,9 +94,9 @@ class Hub implements EVM_Hub { options?: HubOptions | undefined, ): Promise>> { try { - return OpenSea.getTokens(account, options) + return OpenSea.getTokens(account, { chainId: this.chainId, ...options }) } catch { - return NFTScan.getTokens(account, options) + return NFTScan.getTokens(account, { chainId: this.chainId, ...options }) } } getNonFungibleCollections( diff --git a/packages/web3-providers/src/opensea/index.ts b/packages/web3-providers/src/opensea/index.ts index 1f1413a6777d..d0c06db10b14 100644 --- a/packages/web3-providers/src/opensea/index.ts +++ b/packages/web3-providers/src/opensea/index.ts @@ -37,7 +37,7 @@ import { OPENSEA_ACCOUNT_URL, OPENSEA_API_KEY, OPENSEA_API_URL } from './constan import { isProxyENV } from '../helpers' async function fetchFromOpenSea(url: string, chainId: ChainId, apiKey?: string) { - if (![ChainId.Mainnet, ChainId.Rinkeby].includes(chainId)) return + if (![ChainId.Mainnet, ChainId.Rinkeby, ChainId.Matic].includes(chainId)) return try { const response = await fetch(urlcat(OPENSEA_API_URL, url), { From 4c9b8b00f75dce1852283cbeed8975ec68e1b9e5 Mon Sep 17 00:00:00 2001 From: nuanyang233 Date: Thu, 9 Jun 2022 16:37:46 +0800 Subject: [PATCH 03/14] fix: incorrect value --- .../src/UI/components/FungibleTokenList/index.tsx | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/shared/src/UI/components/FungibleTokenList/index.tsx b/packages/shared/src/UI/components/FungibleTokenList/index.tsx index a7d5e403365d..b47601ae272c 100644 --- a/packages/shared/src/UI/components/FungibleTokenList/index.tsx +++ b/packages/shared/src/UI/components/FungibleTokenList/index.tsx @@ -24,7 +24,6 @@ import { FungibleToken, isSameAddress, minus, - multipliedBy, NetworkPluginID, toZero, } from '@masknet/web3-shared-base' @@ -105,17 +104,16 @@ export function FungibleTokenList(props: FungibleToke const isTrustedToken = currySameAddress(trustedFungibleTokens.map((x) => x.address)) const isBlockedToken = currySameAddress(blockedFungibleTokens.map((x) => x.address)) + console.log(filteredFungibleTokens) + console.log(fungibleAssetsTable) return filteredFungibleTokens .filter((x) => !isBlockedToken(x)) .sort((a, z) => { const aBalance = toZero(formatBalance(fungibleTokensBalance[a.address] ?? '0', a.decimals)) const zBalance = toZero(formatBalance(fungibleTokensBalance[z.address] ?? '0', z.decimals)) - const aPrice = toZero(fungibleAssetsTable[a.address]?.value?.[CurrencyType.USD] ?? '0') - const zPrice = toZero(fungibleAssetsTable[z.address]?.value?.[CurrencyType.USD] ?? '0') - - const aUSD = multipliedBy(aPrice, aBalance) - const zUSD = multipliedBy(zPrice, zBalance) + const aUSD = toZero(fungibleAssetsTable[a.address]?.value?.[CurrencyType.USD] ?? '0') + const zUSD = toZero(fungibleAssetsTable[z.address]?.value?.[CurrencyType.USD] ?? '0') const isNativeTokenA = isSameAddress(a.address, Others?.getNativeTokenAddress(a.chainId)) const isNativeTokenZ = isSameAddress(z.address, Others?.getNativeTokenAddress(z.chainId)) From 515a3937d0164e07676cf25757ecf283a719035e Mon Sep 17 00:00:00 2001 From: nuanyang233 Date: Thu, 9 Jun 2022 16:59:29 +0800 Subject: [PATCH 04/14] fix: sort rule for all --- .../components/FungibleTokenTable/index.tsx | 26 ++++++++++++++++--- .../UI/components/FungibleTokenList/index.tsx | 2 -- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx index d0b80f54abf1..c27ad2aeab29 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useEffect } from 'react' +import { memo, useCallback, useEffect, useMemo } from 'react' import { useNavigate } from 'react-router-dom' import BigNumber from 'bignumber.js' import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material' @@ -7,7 +7,7 @@ import { useDashboardI18N } from '../../../../locales' import { EmptyPlaceholder } from '../EmptyPlaceholder' import { LoadingPlaceholder } from '../../../../components/LoadingPlaceholder' import { FungibleTokenTableRow } from '../FungibleTokenTableRow' -import { formatBalance, FungibleAsset, NetworkPluginID } from '@masknet/web3-shared-base' +import { CurrencyType, formatBalance, FungibleAsset, minus, NetworkPluginID, toZero } from '@masknet/web3-shared-base' import { DashboardRoutes, EMPTY_LIST } from '@masknet/shared-base' import { useCurrentWeb3NetworkPluginID, useFungibleAssets, useWeb3State, Web3Helper } from '@masknet/plugin-infra/web3' import { PluginMessages } from '../../../../API' @@ -107,11 +107,31 @@ export const FungibleTokenTable = memo(({ selectedChainId }) => [], ) + const dataSource = useMemo(() => { + const results = fungibleAssets.filter((x) => !selectedChainId || x.chainId === selectedChainId) + + if (!selectedChainId) + return results.sort((a, z) => { + const aUSD = toZero(a.value?.[CurrencyType.USD] ?? '0') + const zUSD = toZero(z.value?.[CurrencyType.USD] ?? '0') + + // token value + if (!aUSD.isEqualTo(zUSD)) return minus(zUSD, aUSD).isPositive() ? 1 : -1 + + // // token balance + // if (!aBalance.isEqualTo(zBalance)) return minus(zBalance, aBalance).isPositive() ? 1 : -1 + + return 0 + }) + + return results + }, [fungibleAssets, selectedChainId]) + return ( !selectedChainId || x.chainId === selectedChainId)} + dataSource={dataSource} onSwap={onSwap} onSend={onSend} /> diff --git a/packages/shared/src/UI/components/FungibleTokenList/index.tsx b/packages/shared/src/UI/components/FungibleTokenList/index.tsx index b47601ae272c..e7dd19ed6ca6 100644 --- a/packages/shared/src/UI/components/FungibleTokenList/index.tsx +++ b/packages/shared/src/UI/components/FungibleTokenList/index.tsx @@ -104,8 +104,6 @@ export function FungibleTokenList(props: FungibleToke const isTrustedToken = currySameAddress(trustedFungibleTokens.map((x) => x.address)) const isBlockedToken = currySameAddress(blockedFungibleTokens.map((x) => x.address)) - console.log(filteredFungibleTokens) - console.log(fungibleAssetsTable) return filteredFungibleTokens .filter((x) => !isBlockedToken(x)) .sort((a, z) => { From 863dce384713cbccba8d37023b84423086bab9ea Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Thu, 9 Jun 2022 17:17:45 +0800 Subject: [PATCH 05/14] fix: value pollution from other chain --- .../Wallets/components/FungibleTokenTable/index.tsx | 9 --------- .../shared/src/UI/components/FungibleTokenList/index.tsx | 4 +++- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx index c27ad2aeab29..c92fface4fd4 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx @@ -68,12 +68,6 @@ export const FungibleTokenTable = memo(({ selectedChainId }) => } = useFungibleAssets(NetworkPluginID.PLUGIN_EVM) const { setDialog: openSwapDialog } = useRemoteControlledDialog(PluginMessages.Swap.swapDialogUpdated) - useEffect(() => { - // PluginMessages.Wallet.events.erc20TokensUpdated.on(() => - // setTimeout(() => setTokenUpdateCount((prev) => prev + 1), 100), - // ) - }, []) - const onSwap = useCallback( ( token: FungibleAsset< @@ -118,9 +112,6 @@ export const FungibleTokenTable = memo(({ selectedChainId }) => // token value if (!aUSD.isEqualTo(zUSD)) return minus(zUSD, aUSD).isPositive() ? 1 : -1 - // // token balance - // if (!aBalance.isEqualTo(zBalance)) return minus(zBalance, aBalance).isPositive() ? 1 : -1 - return 0 }) diff --git a/packages/shared/src/UI/components/FungibleTokenList/index.tsx b/packages/shared/src/UI/components/FungibleTokenList/index.tsx index e7dd19ed6ca6..d5befac872f9 100644 --- a/packages/shared/src/UI/components/FungibleTokenList/index.tsx +++ b/packages/shared/src/UI/components/FungibleTokenList/index.tsx @@ -100,7 +100,9 @@ export function FungibleTokenList(props: FungibleToke const { value: fungibleAssets = EMPTY_LIST, loading: fungibleAssetsLoading } = useFungibleAssets(pluginID) const sortedFungibleTokens = useMemo(() => { - const fungibleAssetsTable = Object.fromEntries(fungibleAssets.map((x) => [x.address, x])) + const fungibleAssetsTable = Object.fromEntries( + fungibleAssets.filter((x) => x.chainId === chainId).map((x) => [x.address, x]), + ) const isTrustedToken = currySameAddress(trustedFungibleTokens.map((x) => x.address)) const isBlockedToken = currySameAddress(blockedFungibleTokens.map((x) => x.address)) From 40c7edae3b7c26d30ba0fb02567604817437043c Mon Sep 17 00:00:00 2001 From: guanbinrui <52657989+guanbinrui@users.noreply.github.com> Date: Fri, 10 Jun 2022 01:42:08 +0800 Subject: [PATCH 06/14] refactor: support derive global network type on hooks (#6457) --- .../components/CollectibleCard/index.tsx | 9 +- .../ChangeNetworkTip.tsx | 6 +- .../Wallets/components/HistoryTable/index.tsx | 4 +- .../components/HistoryTableRow/index.tsx | 2 +- .../components/WalletStateBar/index.tsx | 4 +- .../WalletStateBar/useNetworkSelector.tsx | 8 +- .../dashboard/src/pages/Wallets/index.tsx | 2 +- .../WalletStatusBox/TransactionList.tsx | 2 +- .../shared/WalletStatusBox/index.tsx | 2 +- .../Avatar/Application/NFTListPage.tsx | 2 +- .../plugins/Avatar/SNSAdaptor/NFTAvatar.tsx | 4 +- .../ConnectionProgress.tsx | 2 +- .../SNSAdaptor/ConnectWalletDialog/index.tsx | 2 +- .../SNSAdaptor/SelectNftContractDialog.tsx | 4 +- .../SNSAdaptor/SelectProviderDialog/index.tsx | 7 +- .../SNSAdaptor/TransactionSnackbar/index.tsx | 2 +- packages/mask/src/web3/UI/ChainBoundary.tsx | 6 +- .../plugin-infra/src/web3-helpers/index.ts | 146 +++++++++++++++++- packages/plugin-infra/src/web3/index.ts | 2 - packages/plugin-infra/src/web3/useAccount.ts | 2 +- .../plugin-infra/src/web3/useAccountName.ts | 7 +- packages/plugin-infra/src/web3/useBalance.ts | 9 +- .../plugin-infra/src/web3/useBlockNumber.ts | 9 +- .../src/web3/useBlockTimestamp.ts | 8 +- .../src/web3/useBlockedFungibleTokens.ts | 16 +- .../src/web3/useBlockedNonFungibleTokens.ts | 16 +- .../plugin-infra/src/web3/useChainColor.ts | 4 +- .../src/web3/useChainDescriptor.ts | 5 +- packages/plugin-infra/src/web3/useChainId.ts | 16 +- .../src/web3/useChainIdMainnet.ts | 5 +- .../src/web3/useChainIdSupport.ts | 4 +- .../plugin-infra/src/web3/useChainIdValid.ts | 11 +- .../src/web3/useClearTransactionsCallback.ts | 7 +- .../plugin-infra/src/web3/useFungibleAsset.ts | 18 +-- .../src/web3/useFungibleAssets.ts | 25 ++- .../plugin-infra/src/web3/useFungibleToken.ts | 15 +- .../src/web3/useFungibleTokenBalance.ts | 8 +- .../src/web3/useFungibleTokenPrice.ts | 4 +- .../src/web3/useFungibleTokens.ts | 12 +- .../src/web3/useFungibleTokensBalance.ts | 11 +- .../web3/useFungibleTokensFromTokenList.ts | 20 +-- .../plugin-infra/src/web3/useGasOptions.ts | 13 +- packages/plugin-infra/src/web3/useGasPrice.ts | 5 +- .../plugin-infra/src/web3/useLookupAddress.ts | 7 +- .../plugin-infra/src/web3/useNativeToken.ts | 7 +- .../src/web3/useNativeTokenAddress.ts | 8 +- .../src/web3/useNativeTokenBalance.ts | 10 +- .../src/web3/useNativeTokenPrice.ts | 11 +- .../src/web3/useNetworkDescriptor.ts | 4 +- .../src/web3/useNetworkDescriptors.ts | 6 +- .../plugin-infra/src/web3/useNetworkType.ts | 14 +- .../src/web3/useNonFungibleAsset.ts | 17 +- .../src/web3/useNonFungibleAssets.ts | 28 ++-- .../src/web3/useNonFungibleCollections.ts | 28 ++-- .../src/web3/useNonFungibleToken.ts | 22 +-- .../src/web3/useNonFungibleTokenBalance.ts | 11 +- .../src/web3/useNonFungibleTokenContract.ts | 14 +- .../src/web3/useNonFungibleTokenPrice.ts | 13 +- .../src/web3/useNonFungibleTokens.ts | 25 +-- .../src/web3/useNonFungibleTokensBalance.ts | 12 +- .../web3/useNonFungibleTokensFromTokenList.ts | 20 +-- .../src/web3/useProviderDescriptor.ts | 4 +- .../src/web3/useProviderDescriptors.ts | 6 +- .../plugin-infra/src/web3/useProviderReady.ts | 4 +- .../plugin-infra/src/web3/useProviderType.ts | 11 +- .../src/web3/useRecentTransactions.ts | 24 +-- .../src/web3/useRemoveTransaction.ts | 11 +- .../src/web3/useReverseAddress.ts | 10 +- .../plugin-infra/src/web3/useSchemaType.ts | 15 +- .../src/web3/useSocialAddressList.ts | 6 +- .../src/web3/useSocialAddressListAll.ts | 2 +- .../plugin-infra/src/web3/useSocketOnce.ts | 44 ------ .../plugin-infra/src/web3/useTransactions.ts | 12 +- .../src/web3/useTrustedFungibleTokens.ts | 14 +- .../src/web3/useTrustedNonFungibleTokens.ts | 16 +- packages/plugin-infra/src/web3/useWeb3.ts | 10 +- .../src/web3/useWeb3Connection.ts | 12 +- packages/plugin-infra/src/web3/useWeb3Hub.ts | 16 +- .../plugin-infra/src/web3/useWeb3Provider.ts | 12 +- .../plugin-infra/src/web3/useWeb3State.ts | 4 +- packages/plugin-infra/src/web3/useWeb3UI.ts | 4 +- .../plugin-infra/src/web3/useZeroAddress.ts | 9 +- .../src/SNSAdaptor/components/TabContent.tsx | 4 +- .../EVM/src/state/Connection/connection.ts | 42 +++-- .../state/Connection/providers/MaskWallet.ts | 6 +- packages/plugins/EVM/src/state/Hub/hub.ts | 2 +- packages/plugins/Flow/src/state/Hub/hub.ts | 2 +- packages/plugins/Solana/src/state/Hub/hub.ts | 2 +- .../shared-base/src/utils/asyncIterator.ts | 3 +- .../FungibleTokenList/FungibleTokenItem.tsx | 10 +- .../UI/components/FungibleTokenList/index.tsx | 22 ++- .../NFTCardStyledAssetPlayer/index.tsx | 3 +- .../src/UI/components/TokenIcon/index.tsx | 4 +- packages/shared/src/hooks/index.ts | 1 + .../src/hooks}/useImageChecker.ts | 0 packages/web3-providers/src/debank/index.ts | 6 +- packages/web3-providers/src/types.ts | 8 +- packages/web3-providers/src/zerion/index.ts | 4 +- packages/web3-shared/base/src/specs/index.ts | 4 +- .../web3-shared/base/src/utils/pagination.ts | 2 +- 100 files changed, 513 insertions(+), 581 deletions(-) delete mode 100644 packages/plugin-infra/src/web3/useSocketOnce.ts rename packages/{plugin-infra/src/web3 => shared/src/hooks}/useImageChecker.ts (100%) diff --git a/packages/dashboard/src/pages/Wallets/components/CollectibleCard/index.tsx b/packages/dashboard/src/pages/Wallets/components/CollectibleCard/index.tsx index 7ece8d52e239..4d85e65c54d6 100644 --- a/packages/dashboard/src/pages/Wallets/components/CollectibleCard/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/CollectibleCard/index.tsx @@ -3,7 +3,7 @@ import { useHoverDirty } from 'react-use' import { WalletIcon, NFTCardStyledAssetPlayer } from '@masknet/shared' import { Box, Button, Link, Tooltip, Typography } from '@mui/material' import { makeStyles, MaskColorVar } from '@masknet/theme' -import { NetworkPluginID, NonFungibleAsset } from '@masknet/web3-shared-base' +import { NetworkPluginID } from '@masknet/web3-shared-base' import { CollectiblePlaceholder } from '../CollectiblePlaceHolder' import { useDashboardI18N } from '../../../../locales' import { ChangeNetworkTip } from '../FungibleTokenTableRow/ChangeNetworkTip' @@ -95,10 +95,7 @@ const useStyles = makeStyles()((theme) => ({ })) export interface CollectibleCardProps { - token: NonFungibleAsset< - Web3Helper.Definition[NetworkPluginID]['ChainId'], - Web3Helper.Definition[NetworkPluginID]['SchemaType'] - > + token: Web3Helper.NonFungibleAssetScope<'all'> onSend(): void renderOrder: number } @@ -108,7 +105,7 @@ export const CollectibleCard = memo(({ token, onSend, rend const chainId = useChainId() const { classes } = useStyles() const ref = useRef(null) - const { Others } = useWeb3State<'all'>() + const { Others } = useWeb3State() const [isHoveringTooltip, setHoveringTooltip] = useState(false) const isHovering = useHoverDirty(ref) const networkDescriptor = useNetworkDescriptor(undefined, token.contract?.chainId) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/ChangeNetworkTip.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/ChangeNetworkTip.tsx index 82574e994560..4a80b7869235 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/ChangeNetworkTip.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTableRow/ChangeNetworkTip.tsx @@ -11,9 +11,9 @@ interface ChangeNetworkTipProps { export const ChangeNetworkTip = memo(({ chainId }) => { const t = useDashboardI18N() - const providerDescriptor = useProviderDescriptor<'all'>() - const networkDescriptors = useNetworkDescriptors<'all'>() - const Web3UI = useWeb3UI<'all'>() + const providerDescriptor = useProviderDescriptor() + const networkDescriptors = useNetworkDescriptors() + const Web3UI = useWeb3UI() const { NetworkIconClickBait } = Web3UI.SelectNetworkMenu ?? {} const targetNetwork = networkDescriptors.find((x) => x.chainId === chainId) diff --git a/packages/dashboard/src/pages/Wallets/components/HistoryTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/HistoryTable/index.tsx index fcac5746f8e3..ef547f7f1351 100644 --- a/packages/dashboard/src/pages/Wallets/components/HistoryTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/HistoryTable/index.tsx @@ -64,8 +64,8 @@ export const HistoryTable = memo(({ selectedChainId }) => { onPageChange={setPage} hasNextPage={false} isLoading={loading} - isEmpty={!value?.data?.length} - dataSource={(value?.data ?? EMPTY_LIST) as Array>} + isEmpty={!value?.length} + dataSource={(value ?? EMPTY_LIST) as Array>} selectedChainId={selectedChainId} /> ) diff --git a/packages/dashboard/src/pages/Wallets/components/HistoryTableRow/index.tsx b/packages/dashboard/src/pages/Wallets/components/HistoryTableRow/index.tsx index 8438b546a044..416a6d334353 100644 --- a/packages/dashboard/src/pages/Wallets/components/HistoryTableRow/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/HistoryTableRow/index.tsx @@ -78,7 +78,7 @@ export interface HistoryTableRowUIProps extends HistoryTableRowProps { export const HistoryTableRowUI = memo( ({ transaction, selectedChainId, formattedType, domain }) => { const { classes } = useStyles() - const { Others } = useWeb3State<'all'>() + const { Others } = useWeb3State() return ( diff --git a/packages/dashboard/src/pages/Wallets/components/WalletStateBar/index.tsx b/packages/dashboard/src/pages/Wallets/components/WalletStateBar/index.tsx index 9bd044952bdc..dcc313002756 100644 --- a/packages/dashboard/src/pages/Wallets/components/WalletStateBar/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/WalletStateBar/index.tsx @@ -66,8 +66,8 @@ export const WalletStateBar = memo(() => { const account = useAccount() const wallet = useWallet() - const networkDescriptor = useNetworkDescriptor<'all'>() - const providerDescriptor = useProviderDescriptor<'all'>() + const networkDescriptor = useNetworkDescriptor() + const providerDescriptor = useProviderDescriptor() const pendingTransactions = useRecentTransactions(NetworkPluginID.PLUGIN_EVM, TransactionStatusType.NOT_DEPEND) const { openDialog: openWalletStatusDialog } = useRemoteControlledDialog( diff --git a/packages/dashboard/src/pages/Wallets/components/WalletStateBar/useNetworkSelector.tsx b/packages/dashboard/src/pages/Wallets/components/WalletStateBar/useNetworkSelector.tsx index b0fad555088d..8562da71141b 100644 --- a/packages/dashboard/src/pages/Wallets/components/WalletStateBar/useNetworkSelector.tsx +++ b/packages/dashboard/src/pages/Wallets/components/WalletStateBar/useNetworkSelector.tsx @@ -31,11 +31,11 @@ export const useNetworkSelector = (pluginID?: NetworkPluginID) => { const { classes } = useStyles() const currentChainId = useChainId() - const providerDescriptor = useProviderDescriptor<'all'>() - const networkDescriptors = useNetworkDescriptors<'all'>() - const Web3UI = useWeb3UI<'all'>() + const providerDescriptor = useProviderDescriptor() + const networkDescriptors = useNetworkDescriptors() + const Web3UI = useWeb3UI() const { NetworkIconClickBait } = Web3UI.SelectNetworkMenu ?? {} - const { Connection } = useWeb3State<'all'>(pluginID) + const { Connection } = useWeb3State(pluginID) const onConnect = useCallback( async (chainId: Web3Helper.ChainIdAll) => { diff --git a/packages/dashboard/src/pages/Wallets/index.tsx b/packages/dashboard/src/pages/Wallets/index.tsx index 88879c828593..7189373a3caf 100644 --- a/packages/dashboard/src/pages/Wallets/index.tsx +++ b/packages/dashboard/src/pages/Wallets/index.tsx @@ -46,7 +46,7 @@ function Wallets() { const networks = getRegisteredWeb3Networks() const pluginId = useCurrentWeb3NetworkPluginID() - const networkDescriptor = useNetworkDescriptor<'all'>() + const networkDescriptor = useNetworkDescriptor() const [selectedNetwork, setSelectedNetwork] = useState( networkDescriptor ?? null, ) diff --git a/packages/mask/src/components/shared/WalletStatusBox/TransactionList.tsx b/packages/mask/src/components/shared/WalletStatusBox/TransactionList.tsx index 254a69a9b5c9..dcbda78cfa30 100644 --- a/packages/mask/src/components/shared/WalletStatusBox/TransactionList.tsx +++ b/packages/mask/src/components/shared/WalletStatusBox/TransactionList.tsx @@ -93,7 +93,7 @@ const Transaction: FC = ({ chainId, transaction: tx, onClear = } const web3 = useWeb3() - const { Others } = useWeb3State<'all'>() + const { Others } = useWeb3State() const { value: targetAddress } = useAsync(async () => { return '' diff --git a/packages/mask/src/components/shared/WalletStatusBox/index.tsx b/packages/mask/src/components/shared/WalletStatusBox/index.tsx index 2b86ab2920f4..f8a7f7939476 100644 --- a/packages/mask/src/components/shared/WalletStatusBox/index.tsx +++ b/packages/mask/src/components/shared/WalletStatusBox/index.tsx @@ -105,7 +105,7 @@ export function WalletStatusBox(props: WalletStatusBox) { const providerType = useProviderType() const providerDescriptor = useProviderDescriptor() const networkDescriptor = useNetworkDescriptor() - const { Others } = useWeb3State<'all'>() + const { Others } = useWeb3State() const { value: domain } = useReverseAddress(undefined, account) // #region copy addr to clipboard diff --git a/packages/mask/src/plugins/Avatar/Application/NFTListPage.tsx b/packages/mask/src/plugins/Avatar/Application/NFTListPage.tsx index d8afc8b3dd32..cc997bf84e38 100644 --- a/packages/mask/src/plugins/Avatar/Application/NFTListPage.tsx +++ b/packages/mask/src/plugins/Avatar/Application/NFTListPage.tsx @@ -1,4 +1,4 @@ -import { useImageChecker } from '@masknet/plugin-infra/web3' +import { useImageChecker } from '@masknet/shared' import { makeStyles } from '@masknet/theme' import type { NonFungibleToken } from '@masknet/web3-shared-base' import { ChainId, createERC721Token, SchemaType } from '@masknet/web3-shared-evm' diff --git a/packages/mask/src/plugins/Avatar/SNSAdaptor/NFTAvatar.tsx b/packages/mask/src/plugins/Avatar/SNSAdaptor/NFTAvatar.tsx index 8cbe2d2be27b..2f0cc3fc6afa 100644 --- a/packages/mask/src/plugins/Avatar/SNSAdaptor/NFTAvatar.tsx +++ b/packages/mask/src/plugins/Avatar/SNSAdaptor/NFTAvatar.tsx @@ -8,8 +8,8 @@ import { Box, Button, Skeleton, Typography } from '@mui/material' import { useI18N } from '../../../utils' import { AddNFT } from './AddNFT' import { NFTImage } from './NFTImage' -import { useAccount, useChainId, useImageChecker } from '@masknet/plugin-infra/web3' -import { ReversedAddress } from '@masknet/shared' +import { useAccount, useChainId } from '@masknet/plugin-infra/web3' +import { ReversedAddress, useImageChecker } from '@masknet/shared' import { NetworkPluginID, NonFungibleToken } from '@masknet/web3-shared-base' import { ChainBoundary } from '../../../web3/UI/ChainBoundary' import { useCollectibles } from '../hooks/useCollectibles' diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/ConnectionProgress.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/ConnectionProgress.tsx index 620c1979c5b8..8c7af4f22bff 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/ConnectionProgress.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/ConnectionProgress.tsx @@ -53,7 +53,7 @@ export function ConnectionProgress(props: ConnectionProgressProps) { const { t } = useI18N() const classes = useStylesExtends(useStyles(), props) - const { Others } = useWeb3State<'all'>(pluginID) + const { Others } = useWeb3State(pluginID) const providerDescriptor = useProviderDescriptor(pluginID, providerType) if (!Others) return null diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/index.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/index.tsx index c78ba7df69b9..9a4d73da136a 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/index.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/ConnectWalletDialog/index.tsx @@ -39,7 +39,7 @@ export function ConnectWalletDialog(props: ConnectWalletDialogProps) { ) // #endregion - const { Connection, Others } = useWeb3State<'all'>(pluginID) + const { Connection, Others } = useWeb3State(pluginID) const connection = useAsyncRetry(async () => { if (!open) return true diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectNftContractDialog.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectNftContractDialog.tsx index 2ab0848a93d9..5daa6bd588c3 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectNftContractDialog.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectNftContractDialog.tsx @@ -147,7 +147,9 @@ export function SelectNftContractDialog(props: SelectNftContractDialogProps) { }, [id, setDialog]) // #endregion - const { value: assets = [], loading } = useNonFungibleCollections(NetworkPluginID.PLUGIN_EVM, chainId) + const { value: assets = [], loading } = useNonFungibleCollections(NetworkPluginID.PLUGIN_EVM, { + chainId, + }) const contractList = assets .filter((x) => x.schema_name === WyvernSchemaName.ERC721) diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectProviderDialog/index.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectProviderDialog/index.tsx index 8a7ecf3267c4..1ec251d463fd 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectProviderDialog/index.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/SelectProviderDialog/index.tsx @@ -53,15 +53,14 @@ export function SelectProviderDialog(props: SelectProviderDialogProps) { const networks = getRegisteredWeb3Networks() const providers = getRegisteredWeb3Providers() const pluginID = useValueRef(pluginIDSettings) - const network = useNetworkDescriptor<'all'>() + const network = useNetworkDescriptor() const [undeterminedPluginID, setUndeterminedPluginID] = useState(pluginID) const [undeterminedNetworkID, setUndeterminedNetworkID] = useState(network?.ID) - const Web3State = useWeb3State<'all'>(undeterminedPluginID) + const Web3State = useWeb3State(undeterminedPluginID) const { Others, Provider } = Web3State - const { NetworkIconClickBait, ProviderIconClickBait } = - useWeb3UI<'all'>(undeterminedPluginID).SelectProviderDialog ?? {} + const { NetworkIconClickBait, ProviderIconClickBait } = useWeb3UI(undeterminedPluginID).SelectProviderDialog ?? {} const onNetworkIconClicked = useCallback((network: Web3Helper.NetworkDescriptorAll) => { setUndeterminedPluginID(network.networkSupporterPluginID) diff --git a/packages/mask/src/plugins/Wallet/SNSAdaptor/TransactionSnackbar/index.tsx b/packages/mask/src/plugins/Wallet/SNSAdaptor/TransactionSnackbar/index.tsx index b4e9151c0b14..abaf701a2783 100644 --- a/packages/mask/src/plugins/Wallet/SNSAdaptor/TransactionSnackbar/index.tsx +++ b/packages/mask/src/plugins/Wallet/SNSAdaptor/TransactionSnackbar/index.tsx @@ -27,7 +27,7 @@ export function TransactionSnackbar({ pluginID }: TransactionSnackbarProps) { const chainId = useChainId(pluginID) const [progress, setProgress] = useState() - const { Others, TransactionFormatter, TransactionWatcher } = useWeb3State<'all'>(progress?.pluginID) + const { Others, TransactionFormatter, TransactionWatcher } = useWeb3State(progress?.pluginID) useEffect(() => { const removeListener = TransactionWatcher?.emitter.on('progress', (id, status, transaction) => { diff --git a/packages/mask/src/web3/UI/ChainBoundary.tsx b/packages/mask/src/web3/UI/ChainBoundary.tsx index a554ee6e2468..6c312c469651 100644 --- a/packages/mask/src/web3/UI/ChainBoundary.tsx +++ b/packages/mask/src/web3/UI/ChainBoundary.tsx @@ -71,13 +71,13 @@ export function ChainBoundary(props: ChainBoundaryPro const classes = useStylesExtends(useStyles(), props) const actualPluginID = useCurrentWeb3NetworkPluginID() - const { Others: actualOthers } = useWeb3State<'all'>(actualPluginID) + const { Others: actualOthers } = useWeb3State(actualPluginID) const actualChainId = useChainId(actualPluginID) const actualProviderType = useProviderType(actualPluginID) const actualChainName = actualOthers?.chainResolver.chainName(actualChainId) - const { Others: expectedOthers } = useWeb3State<'all'>(expectedPluginID) - const expectedConnection = useWeb3Connection<'all'>(expectedPluginID) + const { Others: expectedOthers } = useWeb3State(expectedPluginID) + const expectedConnection = useWeb3Connection(expectedPluginID) const expectedAllowTestnet = useAllowTestnet(expectedPluginID) const expectedAccount = useAccount(expectedPluginID) const expectedChainName = expectedOthers?.chainResolver.chainName(expectedChainId) diff --git a/packages/plugin-infra/src/web3-helpers/index.ts b/packages/plugin-infra/src/web3-helpers/index.ts index b1d3e55a1e0d..2e1a10ca3ea6 100644 --- a/packages/plugin-infra/src/web3-helpers/index.ts +++ b/packages/plugin-infra/src/web3-helpers/index.ts @@ -8,6 +8,11 @@ import type { ConnectionState, ProviderDescriptor, ProviderState, + FungibleToken, + NonFungibleToken, + FungibleAsset, + NonFungibleAsset, + RecentTransaction, } from '@masknet/web3-shared-base' import type * as EVM from '@masknet/web3-shared-evm' import type * as Flow from '@masknet/web3-shared-flow' @@ -119,10 +124,9 @@ export declare namespace Web3Helper { Definition[T]['Web3'], Definition[T]['Web3Provider'] > - export type Web3HubOptions< - T extends NetworkPluginID = never, - Indicator extends string | number = number, - > = T extends never ? never : HubOptions + export type Web3HubOptions = T extends never + ? never + : HubOptions export type Web3Hub = T extends never ? never @@ -176,6 +180,12 @@ export declare namespace Web3Helper { Definition[NetworkPluginID]['ProviderType'] > + export type Web3ConnectionOptionsAll = ConnectionOptions< + Definition[NetworkPluginID]['ChainId'], + Definition[NetworkPluginID]['ProviderType'], + Definition[NetworkPluginID]['Transaction'] + > + export type Web3ConnectionAll = Connection< Definition[NetworkPluginID]['ChainId'], Definition[NetworkPluginID]['SchemaType'], @@ -190,6 +200,8 @@ export declare namespace Web3Helper { Definition[NetworkPluginID]['Web3Provider'] > + export type Web3HubOptionsAll = HubOptions + export type Web3HubAll = Hub< Definition[NetworkPluginID]['ChainId'], Definition[NetworkPluginID]['SchemaType'], @@ -219,4 +231,130 @@ export declare namespace Web3Helper { Definition[NetworkPluginID]['ProviderType'], Definition[NetworkPluginID]['NetworkType'] > + + export type Scope = S extends 'all' ? T : F + + export type ChainIdScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' ? Web3Helper.ChainIdAll : Web3Helper.Definition[T]['ChainId'] + export type NetworkTypeScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' ? Web3Helper.NetworkTypeAll : Web3Helper.Definition[T]['NetworkType'] + export type ProviderTypeScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' ? Web3Helper.ProviderTypeAll : Web3Helper.Definition[T]['ProviderType'] + export type SchemaTypeScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' ? Web3Helper.SchemaTypeAll : Web3Helper.Definition[T]['SchemaType'] + export type TransactionScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' ? TransactionAll : Web3Helper.Definition[T]['Transaction'] + export type RecentTransactionScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = RecentTransaction, TransactionScope> + export type FungibleTokenScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = FungibleToken, SchemaTypeScope> + export type NonFungibleTokenScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = NonFungibleToken, SchemaTypeScope> + export type FungibleAssetScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = FungibleAsset, SchemaTypeScope> + export type NonFungibleAssetScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = NonFungibleAsset, SchemaTypeScope> + export type NetworkDescriptorScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? NetworkDescriptorAll + : NetworkDescriptor + export type ProviderDescriptorScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? ProviderDescriptorAll + : ProviderDescriptor + export type Web3Scope = S extends 'all' + ? Web3All + : Definition[T]['Web3'] + export type Web3ProviderScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' ? Web3ProviderAll : Definition[T]['Web3Provider'] + export type Web3StateScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? Web3StateAll + : Web3Plugin.ObjectCapabilities.Capabilities< + Definition[T]['ChainId'], + Definition[T]['SchemaType'], + Definition[T]['ProviderType'], + Definition[T]['NetworkType'], + Definition[T]['Signature'], + Definition[T]['GasOption'], + Definition[T]['Block'], + Definition[T]['Transaction'], + Definition[T]['TransactionReceipt'], + Definition[T]['TransactionDetailed'], + Definition[T]['TransactionSignature'], + Definition[T]['TransactionParameter'], + Definition[T]['Web3'], + Definition[T]['Web3Provider'] + > + export type Web3ConnectionOptionsScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? Web3ConnectionOptionsAll + : ConnectionOptions + export type Web3ConnectionScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? Web3ConnectionAll + : Connection< + Definition[T]['ChainId'], + Definition[T]['SchemaType'], + Definition[T]['ProviderType'], + Definition[T]['Signature'], + Definition[T]['Block'], + Definition[T]['Transaction'], + Definition[T]['TransactionReceipt'], + Definition[T]['TransactionDetailed'], + Definition[T]['TransactionSignature'], + Definition[T]['Web3'], + Definition[T]['Web3Provider'] + > + export type Web3UIScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? Web3UIAll + : Web3Plugin.UI.UI + export type Web3HubOptionsScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + Indicator = number, + > = S extends 'all' ? Web3HubOptionsAll : HubOptions + export type Web3HubScope< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + > = S extends 'all' + ? Web3HubAll + : Hub } + +// S extends 'all' | void = void, T extends NetworkPluginID = NetworkPluginID diff --git a/packages/plugin-infra/src/web3/index.ts b/packages/plugin-infra/src/web3/index.ts index 5bced7295e19..8bc9866e7c71 100644 --- a/packages/plugin-infra/src/web3/index.ts +++ b/packages/plugin-infra/src/web3/index.ts @@ -37,7 +37,6 @@ export * from './useFungibleTokensFromTokenList' export * from './useGasOptionType' export * from './useGasOptions' export * from './useGasPrice' -export * from './useImageChecker' export * from './useLookupAddress' export * from './useNativeToken' export * from './useNativeTokenAddress' @@ -65,7 +64,6 @@ export * from './useRemoveTransaction' export * from './useReverseAddress' export * from './useRiskWarningApproved' export * from './useSchemaType' -export * from './useSocketOnce' export * from './useRecentTransactions' export * from './useTransactions' export * from './useTrustedFungibleTokens' diff --git a/packages/plugin-infra/src/web3/useAccount.ts b/packages/plugin-infra/src/web3/useAccount.ts index 602228038c96..e05a703f017c 100644 --- a/packages/plugin-infra/src/web3/useAccount.ts +++ b/packages/plugin-infra/src/web3/useAccount.ts @@ -5,7 +5,7 @@ import { UNDEFINED } from '../utils/subscription' import { useCurrentWeb3NetworkAccount } from './Context' export function useAccount(pluginID?: T, expectedAccount?: string) { - const { Provider, Others } = useWeb3State(pluginID) + const { Provider, Others } = useWeb3State(pluginID) const currentAccount = useCurrentWeb3NetworkAccount(pluginID) const defaultAccount = useSubscription(Provider?.account ?? UNDEFINED) const account = expectedAccount ?? currentAccount ?? defaultAccount ?? '' diff --git a/packages/plugin-infra/src/web3/useAccountName.ts b/packages/plugin-infra/src/web3/useAccountName.ts index 95f26cb8700f..9527feeb15f1 100644 --- a/packages/plugin-infra/src/web3/useAccountName.ts +++ b/packages/plugin-infra/src/web3/useAccountName.ts @@ -4,12 +4,9 @@ import { useWeb3State } from './useWeb3State' import { useAccount } from './useAccount' import { useWallets } from './useWallets' import { useProviderType } from './useProviderType' -import type { Web3Helper } from '../web3-helpers' export function useAccountName(pluginID?: T, expectedAccount?: string) { - type ProviderName = (providerType: Web3Helper.Definition[T]['ProviderType']) => string - - const { Others } = useWeb3State(pluginID) + const { Others } = useWeb3State(pluginID) const account = useAccount(pluginID, expectedAccount) const providerType = useProviderType(pluginID) const wallets = useWallets(pluginID) @@ -20,6 +17,6 @@ export function useAccountName(pluginID?: T, expected if (wallet?.name) return wallet.name // else use the provider name as the account name - return (Others?.providerResolver.providerName as ProviderName | undefined)?.(providerType) + return Others?.providerResolver.providerName?.(providerType) }, [account, providerType, wallets.map((x) => x.address.toLowerCase()), Others]) } diff --git a/packages/plugin-infra/src/web3/useBalance.ts b/packages/plugin-infra/src/web3/useBalance.ts index 3622cbc08f55..0ad7f40918fc 100644 --- a/packages/plugin-infra/src/web3/useBalance.ts +++ b/packages/plugin-infra/src/web3/useBalance.ts @@ -4,14 +4,15 @@ import type { Web3Helper } from '../web3-helpers' import { useAccount } from './useAccount' import { useWeb3Connection } from './useWeb3Connection' -export function useBalance(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions) { - type GetBalance = (account: string, options?: Web3Helper.Web3ConnectionOptions) => Promise - +export function useBalance( + pluginID?: T, + options?: Web3Helper.Web3ConnectionOptionsScope, +) { const account = useAccount(pluginID, options?.account) const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return '0' - return (connection.getBalance as GetBalance)(account) + return connection.getBalance(account) }, [account, connection]) } diff --git a/packages/plugin-infra/src/web3/useBlockNumber.ts b/packages/plugin-infra/src/web3/useBlockNumber.ts index a34b00150819..5812548d48c2 100644 --- a/packages/plugin-infra/src/web3/useBlockNumber.ts +++ b/packages/plugin-infra/src/web3/useBlockNumber.ts @@ -4,14 +4,15 @@ import type { Web3Helper } from '../web3-helpers' import { useChainId } from './useChainId' import { useWeb3Connection } from './useWeb3Connection' -export function useBlockNumber(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions) { - type GetBlockNumber = (options?: Web3Helper.Web3ConnectionOptions) => Promise - +export function useBlockNumber( + pluginID?: T, + options?: Web3Helper.Web3ConnectionOptionsScope, +) { const chainId = useChainId(pluginID, options?.chainId) const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return 0 - return (connection.getBlockNumber as GetBlockNumber)() + return connection.getBlockNumber() }, [chainId, connection]) } diff --git a/packages/plugin-infra/src/web3/useBlockTimestamp.ts b/packages/plugin-infra/src/web3/useBlockTimestamp.ts index 0151d3a138b9..b92d46f9d564 100644 --- a/packages/plugin-infra/src/web3/useBlockTimestamp.ts +++ b/packages/plugin-infra/src/web3/useBlockTimestamp.ts @@ -4,17 +4,15 @@ import type { Web3Helper } from '../web3-helpers' import { useChainId } from './useChainId' import { useWeb3Connection } from './useWeb3Connection' -export function useBlockTimestamp( +export function useBlockTimestamp( pluginID?: T, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetBlockTimestamp = (options?: Web3Helper.Web3ConnectionOptions) => Promise - const chainId = useChainId(pluginID, options?.chainId) const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return 0 - return (connection.getBlockTimestamp as GetBlockTimestamp)() + return connection.getBlockTimestamp() }, [chainId, connection]) } diff --git a/packages/plugin-infra/src/web3/useBlockedFungibleTokens.ts b/packages/plugin-infra/src/web3/useBlockedFungibleTokens.ts index 2425ab1031f4..298b1e13820c 100644 --- a/packages/plugin-infra/src/web3/useBlockedFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useBlockedFungibleTokens.ts @@ -1,21 +1,17 @@ import { useMemo } from 'react' -import { Subscription, useSubscription } from 'use-subscription' -import type { FungibleToken, NetworkPluginID } from '@masknet/web3-shared-base' +import { useSubscription } from 'use-subscription' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import { EMPTY_ARRAY } from '../utils/subscription' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' -export function useBlockedFungibleTokens( +export function useBlockedFungibleTokens( pluginID?: T, - schemaType?: Web3Helper.Definition[T]['SchemaType'], + schemaType?: Web3Helper.SchemaTypeScope, ) { const { Token } = useWeb3State(pluginID) - const fungibleTokens = useSubscription( - (Token?.blockedFungibleTokens ?? EMPTY_ARRAY) as Subscription< - Array> - >, - ) - return useMemo(() => { + const fungibleTokens = useSubscription(Token?.blockedFungibleTokens ?? EMPTY_ARRAY) + return useMemo>>(() => { return fungibleTokens.length && schemaType ? fungibleTokens.filter((x) => x.schema === schemaType) : fungibleTokens diff --git a/packages/plugin-infra/src/web3/useBlockedNonFungibleTokens.ts b/packages/plugin-infra/src/web3/useBlockedNonFungibleTokens.ts index 8dc00cbf9b5e..8450b96a6b31 100644 --- a/packages/plugin-infra/src/web3/useBlockedNonFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useBlockedNonFungibleTokens.ts @@ -1,21 +1,17 @@ import { useMemo } from 'react' -import { Subscription, useSubscription } from 'use-subscription' -import type { NetworkPluginID, NonFungibleToken } from '@masknet/web3-shared-base' +import { useSubscription } from 'use-subscription' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' import { EMPTY_ARRAY } from '../utils/subscription' -export function useBlockedNonFungibleTokens( +export function useBlockedNonFungibleTokens( pluginID?: T, - schemaType?: Web3Helper.Definition[T]['SchemaType'], + schemaType?: Web3Helper.SchemaTypeScope, ) { const { Token } = useWeb3State(pluginID) - const nonFungibleTokens = useSubscription( - (Token?.blockedNonFungibleTokens ?? EMPTY_ARRAY) as Subscription< - Array> - >, - ) - return useMemo(() => { + const nonFungibleTokens = useSubscription(Token?.blockedNonFungibleTokens ?? EMPTY_ARRAY) + return useMemo>>(() => { return nonFungibleTokens.length && schemaType ? nonFungibleTokens.filter((x) => x.schema === schemaType) : nonFungibleTokens diff --git a/packages/plugin-infra/src/web3/useChainColor.ts b/packages/plugin-infra/src/web3/useChainColor.ts index 6ac3152e6705..2bc830b3341d 100644 --- a/packages/plugin-infra/src/web3/useChainColor.ts +++ b/packages/plugin-infra/src/web3/useChainColor.ts @@ -7,10 +7,8 @@ export function useChainColor( pluginID?: T, expectedChainId?: Web3Helper.Definition[T]['ChainId'], ) { - type ChainColor = (chainId?: Web3Helper.Definition[T]['ChainId']) => string | undefined - const chainId = useChainId(pluginID, expectedChainId) const { Others } = useWeb3State(pluginID) - return (Others?.chainResolver.chainColor as ChainColor | undefined)?.(chainId) ?? 'transparent' + return Others?.chainResolver.chainColor?.(chainId) ?? 'transparent' } diff --git a/packages/plugin-infra/src/web3/useChainDescriptor.ts b/packages/plugin-infra/src/web3/useChainDescriptor.ts index b63f2471e149..45ddb033728c 100644 --- a/packages/plugin-infra/src/web3/useChainDescriptor.ts +++ b/packages/plugin-infra/src/web3/useChainDescriptor.ts @@ -2,10 +2,11 @@ import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useCurrentWeb3NetworkPluginID } from './Context' import { getPluginDefine } from '../manager/store' import { useChainId } from './useChainId' +import type { Web3Helper } from '../web3-helpers' -export function useChainDescriptor( +export function useChainDescriptor( expectedPluginID?: T, - expectedChainId?: ChainId, + expectedChainId?: Web3Helper.Definition[T]['ChainId'], ) { const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) const chainId = useChainId(pluginID) diff --git a/packages/plugin-infra/src/web3/useChainId.ts b/packages/plugin-infra/src/web3/useChainId.ts index ca6df830be41..3aab74837f19 100644 --- a/packages/plugin-infra/src/web3/useChainId.ts +++ b/packages/plugin-infra/src/web3/useChainId.ts @@ -1,4 +1,4 @@ -import { Subscription, useSubscription } from 'use-subscription' +import { useSubscription } from 'use-subscription' import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' @@ -8,15 +8,11 @@ import { useCurrentWeb3NetworkChainId } from './Context' export function useChainId( pluginID?: T, - expectedChainId?: Web3Helper.Definition[T]['ChainId'], + expectedChainId?: Web3Helper.ChainIdScope, ) { - type Result = S extends 'all' ? Web3Helper.ChainIdAll : Web3Helper.Definition[T]['ChainId'] - - const { Provider } = useWeb3State(pluginID) + const { Provider } = useWeb3State(pluginID) const currentChainId = useCurrentWeb3NetworkChainId(pluginID) - const defaultChainId = useDefaultChainId(pluginID) as Web3Helper.Definition[T]['ChainId'] - const actualChainId = useSubscription( - (Provider?.chainId ?? UNDEFINED) as Subscription, - ) - return (expectedChainId ?? currentChainId ?? actualChainId ?? defaultChainId) as Result + const defaultChainId = useDefaultChainId(pluginID) + const actualChainId = useSubscription(Provider?.chainId ?? UNDEFINED) + return (expectedChainId ?? currentChainId ?? actualChainId ?? defaultChainId) as Web3Helper.ChainIdScope } diff --git a/packages/plugin-infra/src/web3/useChainIdMainnet.ts b/packages/plugin-infra/src/web3/useChainIdMainnet.ts index 91dcbe0b32d6..f72f117ba499 100644 --- a/packages/plugin-infra/src/web3/useChainIdMainnet.ts +++ b/packages/plugin-infra/src/web3/useChainIdMainnet.ts @@ -7,10 +7,7 @@ export function useChainIdMainnet( pluginID?: T, expectedChainId?: Web3Helper.Definition[T]['ChainId'], ) { - type IsMainnet = (chainId?: Web3Helper.Definition[T]['ChainId']) => boolean - const chainId = useChainId(pluginID, expectedChainId) const { Others } = useWeb3State(pluginID) - - return (Others?.chainResolver.isMainnet as IsMainnet | undefined)?.(chainId) ?? false + return Others?.chainResolver.isMainnet?.(chainId) ?? false } diff --git a/packages/plugin-infra/src/web3/useChainIdSupport.ts b/packages/plugin-infra/src/web3/useChainIdSupport.ts index aa42923f43f8..5ba1ca4150e5 100644 --- a/packages/plugin-infra/src/web3/useChainIdSupport.ts +++ b/packages/plugin-infra/src/web3/useChainIdSupport.ts @@ -8,10 +8,8 @@ export function useChainIdSupport( expectedChainId?: Web3Helper.Definition[T]['ChainId'], feature?: string, ) { - type IsSupport = (chainId?: Web3Helper.Definition[T]['ChainId'], feature?: string) => boolean - const chainId = useChainId(pluginID, expectedChainId) const { Others } = useWeb3State(pluginID) - return (Others?.chainResolver.isSupport as IsSupport | undefined)?.(chainId, feature) ?? false + return Others?.chainResolver.isSupport?.(chainId, feature) ?? false } diff --git a/packages/plugin-infra/src/web3/useChainIdValid.ts b/packages/plugin-infra/src/web3/useChainIdValid.ts index 1144edb7b01a..6d01c1cdb35a 100644 --- a/packages/plugin-infra/src/web3/useChainIdValid.ts +++ b/packages/plugin-infra/src/web3/useChainIdValid.ts @@ -8,18 +8,9 @@ export function useChainIdValid( pluginID?: T, expectedChainId?: Web3Helper.Definition[T]['ChainId'], ) { - type IsValid = (chainId?: Web3Helper.Definition[T]['ChainId'], testnet?: boolean) => boolean - const chainId = useChainId(pluginID, expectedChainId) const account = useAccount(pluginID) const { Others } = useWeb3State(pluginID) - return ( - (!account || - (Others?.chainResolver.isValid as IsValid | undefined)?.( - chainId, - process.env.NODE_ENV === 'development', - )) ?? - false - ) + return (!account || Others?.chainResolver.isValid?.(chainId, process.env.NODE_ENV === 'development')) ?? false } diff --git a/packages/plugin-infra/src/web3/useClearTransactionsCallback.ts b/packages/plugin-infra/src/web3/useClearTransactionsCallback.ts index 5dd93e393301..e02220dbfaad 100644 --- a/packages/plugin-infra/src/web3/useClearTransactionsCallback.ts +++ b/packages/plugin-infra/src/web3/useClearTransactionsCallback.ts @@ -3,17 +3,14 @@ import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useAccount } from './useAccount' import { useChainId } from './useChainId' import { useWeb3State } from './useWeb3State' -import type { Web3Helper } from '../web3-helpers' - -export function useClearTransactionsCallback(pluginID?: NetworkPluginID) { - type ClearTransactions = (chainId: Web3Helper.Definition[T]['ChainId'], account: string) => Promise +export function useClearTransactionsCallback(pluginID?: T) { const account = useAccount(pluginID) const chainId = useChainId(pluginID) const { Transaction } = useWeb3State(pluginID) return useCallback(async () => { if (!account) return - return (Transaction?.clearTransactions as ClearTransactions | undefined)?.(chainId, account) + return Transaction?.clearTransactions?.(chainId, account) }, [chainId, account, Transaction]) } diff --git a/packages/plugin-infra/src/web3/useFungibleAsset.ts b/packages/plugin-infra/src/web3/useFungibleAsset.ts index 84e60fe69131..2ee3a6f46c10 100644 --- a/packages/plugin-infra/src/web3/useFungibleAsset.ts +++ b/packages/plugin-infra/src/web3/useFungibleAsset.ts @@ -1,23 +1,17 @@ import { useAsyncRetry } from 'react-use' -import { EMPTY_LIST } from '@masknet/shared-base' -import type { FungibleAsset, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3Hub } from './useWeb3Hub' -export function useFungibleAsset( +export function useFungibleAsset( pluginID?: T, address?: string, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetFungibleAsset = ( - address: string, - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise> - const hub = useWeb3Hub(pluginID, options) - return useAsyncRetry(async () => { - if (!address) return EMPTY_LIST - return (hub?.getFungibleAsset as GetFungibleAsset | undefined)?.(address) + return useAsyncRetry | undefined>(async () => { + if (!address) return + return hub?.getFungibleAsset?.(address) }, [address, hub?.getFungibleAsset]) } diff --git a/packages/plugin-infra/src/web3/useFungibleAssets.ts b/packages/plugin-infra/src/web3/useFungibleAssets.ts index 0df4fc0ab474..b70cb63a1d5f 100644 --- a/packages/plugin-infra/src/web3/useFungibleAssets.ts +++ b/packages/plugin-infra/src/web3/useFungibleAssets.ts @@ -4,7 +4,6 @@ import { CurrencyType, currySameAddress, formatBalance, - FungibleAsset, isSameAddress, minus, NetworkPluginID, @@ -18,29 +17,23 @@ import { useWeb3State } from './useWeb3State' import { useTrustedFungibleTokens } from './useTrustedFungibleTokens' import { useBlockedFungibleTokens } from './useBlockedFungibleTokens' -export function useFungibleAssets( - pluginID?: T, - schemaType?: Web3Helper.Definition[T]['SchemaType'], - options?: Web3Helper.Web3HubOptions, -) { - type GetAllFungibleAssets = ( - address: string, - ) => AsyncIterableIterator< - FungibleAsset - > - +export function useFungibleAssets< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + Indicator = number, +>(pluginID?: T, schemaType?: Web3Helper.SchemaTypeScope, options?: Web3Helper.Web3HubOptionsScope) { const account = useAccount(pluginID) - const chainId = useChainId(pluginID) + const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) const trustedTokens = useTrustedFungibleTokens(pluginID) const blockedTokens = useBlockedFungibleTokens(pluginID) - const { Others } = useWeb3State<'all'>(pluginID) + const { Others } = useWeb3State(pluginID) - return useAsyncRetry(async () => { + return useAsyncRetry>>(async () => { if (!account || !hub) return EMPTY_LIST const isTrustedToken = currySameAddress(trustedTokens.map((x) => x.address)) const isBlockedToken = currySameAddress(blockedTokens.map((x) => x.address)) - const assets = await asyncIteratorToArray((hub?.getAllFungibleAssets as GetAllFungibleAssets)(account)) + const assets = await asyncIteratorToArray(hub?.getAllFungibleAssets?.(account)) const filteredAssets = assets.length && schemaType ? assets.filter((x) => x.schema === schemaType) : assets return filteredAssets diff --git a/packages/plugin-infra/src/web3/useFungibleToken.ts b/packages/plugin-infra/src/web3/useFungibleToken.ts index 73a5bcd185e4..727eb8febb4e 100644 --- a/packages/plugin-infra/src/web3/useFungibleToken.ts +++ b/packages/plugin-infra/src/web3/useFungibleToken.ts @@ -1,22 +1,17 @@ -import type { FungibleToken, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import useAsyncRetry from 'react-use/lib/useAsyncRetry' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useFungibleToken( +export function useFungibleToken( pluginID?: T, address?: string, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3HubOptionsScope, ) { - type GetFungibleToken = ( - address: string, - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise> - const connection = useWeb3Connection(pluginID, options) - return useAsyncRetry(async () => { + return useAsyncRetry | undefined>(async () => { if (!connection) return - return (connection?.getFungibleToken as GetFungibleToken)(address ?? '', options) + return (connection?.getFungibleToken)(address ?? '', options) }, [address, connection]) } diff --git a/packages/plugin-infra/src/web3/useFungibleTokenBalance.ts b/packages/plugin-infra/src/web3/useFungibleTokenBalance.ts index 05d3ec18dd43..431964c7f6bf 100644 --- a/packages/plugin-infra/src/web3/useFungibleTokenBalance.ts +++ b/packages/plugin-infra/src/web3/useFungibleTokenBalance.ts @@ -3,17 +3,15 @@ import useAsyncRetry from 'react-use/lib/useAsyncRetry' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useFungibleTokenBalance( +export function useFungibleTokenBalance( pluginID?: T, address?: string, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetFungibleTokenBalance = (address: string, options?: Web3Helper.Web3ConnectionOptions) => Promise - const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return '0' - return (connection.getFungibleTokenBalance as GetFungibleTokenBalance)(address ?? '') + return connection.getFungibleTokenBalance(address ?? '') }, [address, connection]) } diff --git a/packages/plugin-infra/src/web3/useFungibleTokenPrice.ts b/packages/plugin-infra/src/web3/useFungibleTokenPrice.ts index 66e9741aaa98..f9c820caa987 100644 --- a/packages/plugin-infra/src/web3/useFungibleTokenPrice.ts +++ b/packages/plugin-infra/src/web3/useFungibleTokenPrice.ts @@ -9,13 +9,11 @@ export function useFungibleTokenPrice( address?: string, options?: Web3Helper.Web3HubOptions, ) { - type GetFungibleTokenPrice = (chainId: Web3Helper.Definition[T]['ChainId'], address: string) => Promise - const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) return useAsyncRetry(async () => { if (!chainId || !hub) return 0 - return (hub.getFungibleTokenPrice as GetFungibleTokenPrice)(chainId, address ?? '') + return hub.getFungibleTokenPrice?.(chainId, address ?? '') }, [chainId, address, hub]) } diff --git a/packages/plugin-infra/src/web3/useFungibleTokens.ts b/packages/plugin-infra/src/web3/useFungibleTokens.ts index 6e4c48513808..6360f09fb90f 100644 --- a/packages/plugin-infra/src/web3/useFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useFungibleTokens.ts @@ -1,19 +1,17 @@ import { useAsyncRetry } from 'react-use' import { EMPTY_LIST } from '@masknet/shared-base' -import type { FungibleToken, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useFungibleTokens( +export function useFungibleTokens( pluginID?: T, listOfAddress?: string[], - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - const connection = useWeb3Connection(pluginID, options) + const connection = useWeb3Connection(pluginID, options) - return useAsyncRetry< - Array> - >(async () => { + return useAsyncRetry>>(async () => { if (!connection) return EMPTY_LIST return Promise.all(listOfAddress?.map((x) => connection.getFungibleToken(x)) ?? []) }, [connection, listOfAddress?.join()]) diff --git a/packages/plugin-infra/src/web3/useFungibleTokensBalance.ts b/packages/plugin-infra/src/web3/useFungibleTokensBalance.ts index 1b7b2f4fc678..c6255e26f5ac 100644 --- a/packages/plugin-infra/src/web3/useFungibleTokensBalance.ts +++ b/packages/plugin-infra/src/web3/useFungibleTokensBalance.ts @@ -4,20 +4,15 @@ import useAsyncRetry from 'react-use/lib/useAsyncRetry' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useFungibleTokensBalance( +export function useFungibleTokensBalance( pluginID?: T, listOfAddress?: string[], - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetFungibleTokensBalance = ( - listOfAddress: string[], - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise> - const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return EMPTY_OBJECT - return (connection.getFungibleTokensBalance as GetFungibleTokensBalance)(listOfAddress ?? []) + return connection.getFungibleTokensBalance(listOfAddress ?? []) }, [listOfAddress?.join(), connection]) } diff --git a/packages/plugin-infra/src/web3/useFungibleTokensFromTokenList.ts b/packages/plugin-infra/src/web3/useFungibleTokensFromTokenList.ts index eb7879f1571b..03487311c489 100644 --- a/packages/plugin-infra/src/web3/useFungibleTokensFromTokenList.ts +++ b/packages/plugin-infra/src/web3/useFungibleTokensFromTokenList.ts @@ -1,21 +1,17 @@ import { useAsyncRetry } from 'react-use' -import type { FungibleToken, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useChainId } from './useChainId' import { useWeb3Hub } from './useWeb3Hub' -export function useFungibleTokensFromTokenList( - pluginID?: T, - options?: Web3Helper.Web3HubOptions, -) { - type GetFungibleTokens = ( - chainId: Web3Helper.Definition[T]['ChainId'], - ) => Promise>> - - const chainId = useChainId(pluginID) +export function useFungibleTokensFromTokenList< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, +>(pluginID?: T, options?: Web3Helper.Web3HubOptionsScope) { + const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) - return useAsyncRetry(async () => { - return (hub?.getFungibleTokensFromTokenList as GetFungibleTokens | undefined)?.(chainId) + return useAsyncRetry> | undefined>(async () => { + return hub?.getFungibleTokensFromTokenList?.(chainId) }, [chainId, hub]) } diff --git a/packages/plugin-infra/src/web3/useGasOptions.ts b/packages/plugin-infra/src/web3/useGasOptions.ts index b5d544a83a08..1b2e620fbd41 100644 --- a/packages/plugin-infra/src/web3/useGasOptions.ts +++ b/packages/plugin-infra/src/web3/useGasOptions.ts @@ -4,16 +4,15 @@ import type { Web3Helper } from '../web3-helpers' import { useChainId } from './useChainId' import { useWeb3Hub } from './useWeb3Hub' -export function useGasOptions(pluginID?: T, options?: Web3Helper.Web3HubOptions) { - type GetGasOptions = ( - chainId: Web3Helper.Definition[T]['ChainId'], - ) => Promise> - - const chainId = useChainId(pluginID) +export function useGasOptions( + pluginID?: T, + options?: Web3Helper.Web3HubOptionsScope, +) { + const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) return useAsyncRetry(async () => { if (!chainId || !hub) return - return (hub.getGasOptions as GetGasOptions)(chainId) + return hub.getGasOptions?.(chainId) }, [chainId, hub]) } diff --git a/packages/plugin-infra/src/web3/useGasPrice.ts b/packages/plugin-infra/src/web3/useGasPrice.ts index 6ded9d6fdbde..095fcf6cf71b 100644 --- a/packages/plugin-infra/src/web3/useGasPrice.ts +++ b/packages/plugin-infra/src/web3/useGasPrice.ts @@ -3,7 +3,10 @@ import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useGasPrice(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions) { +export function useGasPrice( + pluginID?: T, + options?: Web3Helper.Web3ConnectionOptionsScope, +) { const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return '0' diff --git a/packages/plugin-infra/src/web3/useLookupAddress.ts b/packages/plugin-infra/src/web3/useLookupAddress.ts index d27eea0b02f8..d5945b93ce7f 100644 --- a/packages/plugin-infra/src/web3/useLookupAddress.ts +++ b/packages/plugin-infra/src/web3/useLookupAddress.ts @@ -2,16 +2,13 @@ import { useAsyncRetry } from 'react-use' import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useChainId } from './useChainId' import { useWeb3State } from './useWeb3State' -import type { Web3Helper } from '../web3-helpers' export function useLookupAddress(pluginId?: T, domain?: string) { - type LookupDomain = (chainId: Web3Helper.Definition[T]['ChainId'], domain?: string) => Promise - const chainId = useChainId(pluginId) const { NameService, Others } = useWeb3State(pluginId) return useAsyncRetry(async () => { - if (!chainId || !Others?.isValidDomain?.(domain) || !NameService) return - return (NameService.lookup as LookupDomain)(chainId, domain) + if (!chainId || !domain || !Others?.isValidDomain?.(domain) || !NameService) return + return NameService.lookup?.(chainId, domain) }, [chainId, domain, NameService, Others]) } diff --git a/packages/plugin-infra/src/web3/useNativeToken.ts b/packages/plugin-infra/src/web3/useNativeToken.ts index 7cbf6cd125c9..bbb18b1c43fc 100644 --- a/packages/plugin-infra/src/web3/useNativeToken.ts +++ b/packages/plugin-infra/src/web3/useNativeToken.ts @@ -3,7 +3,10 @@ import type { Web3Helper } from '../web3-helpers' import { useFungibleToken } from './useFungibleToken' import { useNativeTokenAddress } from './useNativeTokenAddress' -export function useNativeToken(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions) { +export function useNativeToken( + pluginID?: T, + options?: Web3Helper.Web3ConnectionOptionsScope, +) { const nativeTokenAddress = useNativeTokenAddress(pluginID, options) - return useFungibleToken(pluginID, nativeTokenAddress, options) + return useFungibleToken(pluginID, nativeTokenAddress, options) } diff --git a/packages/plugin-infra/src/web3/useNativeTokenAddress.ts b/packages/plugin-infra/src/web3/useNativeTokenAddress.ts index a8e6c045687e..89ab188b34b7 100644 --- a/packages/plugin-infra/src/web3/useNativeTokenAddress.ts +++ b/packages/plugin-infra/src/web3/useNativeTokenAddress.ts @@ -2,14 +2,12 @@ import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' -export function useNativeTokenAddress( +export function useNativeTokenAddress( pluginID?: T, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNativeTokenAddress = (chainId?: Web3Helper.Definition[T]['ChainId']) => string - const { Others } = useWeb3State(pluginID) - const nativeTokenAddress = (Others?.getNativeTokenAddress as GetNativeTokenAddress)(options?.chainId) + const nativeTokenAddress = Others?.getNativeTokenAddress?.(options?.chainId) if (!nativeTokenAddress) throw new Error('No native token address.') return nativeTokenAddress diff --git a/packages/plugin-infra/src/web3/useNativeTokenBalance.ts b/packages/plugin-infra/src/web3/useNativeTokenBalance.ts index b91e4f6d7731..370cd70685a7 100644 --- a/packages/plugin-infra/src/web3/useNativeTokenBalance.ts +++ b/packages/plugin-infra/src/web3/useNativeTokenBalance.ts @@ -4,17 +4,17 @@ import type { Web3Helper } from '../web3-helpers' import { useAccount } from './useAccount' import { useWeb3Connection } from './useWeb3Connection' -export function useNativeTokenBalance( +export function useNativeTokenBalance( pluginID?: T, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNativeTokenBalance = (account: string, options?: Web3Helper.Web3ConnectionOptions) => Promise - const account = useAccount(pluginID, options?.account) const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!connection) return '0' - return (connection.getNativeTokenBalance as GetNativeTokenBalance)(account) + return connection.getNativeTokenBalance?.({ + account, + }) }, [account, connection]) } diff --git a/packages/plugin-infra/src/web3/useNativeTokenPrice.ts b/packages/plugin-infra/src/web3/useNativeTokenPrice.ts index a426cd49e927..eef156bf9bc9 100644 --- a/packages/plugin-infra/src/web3/useNativeTokenPrice.ts +++ b/packages/plugin-infra/src/web3/useNativeTokenPrice.ts @@ -5,14 +5,15 @@ import { useChainId } from './useChainId' import { useWeb3Hub } from './useWeb3Hub' import type { Web3Helper } from '../web3-helpers' -export function useNativeTokenPrice(pluginID: T, options?: Web3Helper.Web3HubOptions) { - type GetFungibleTokenPrice = (chainId: Web3Helper.Definition[T]['ChainId'], address: string) => Promise - - const chainId = useChainId(pluginID) +export function useNativeTokenPrice( + pluginID: T, + options?: Web3Helper.Web3HubOptionsScope, +) { + const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) const nativeTokenAddress = useNativeTokenAddress(pluginID, options) return useAsyncRetry(async () => { - return (hub?.getFungibleTokenPrice as GetFungibleTokenPrice)(chainId, nativeTokenAddress) + return hub?.getFungibleTokenPrice?.(chainId, nativeTokenAddress) }, [chainId, nativeTokenAddress, hub]) } diff --git a/packages/plugin-infra/src/web3/useNetworkDescriptor.ts b/packages/plugin-infra/src/web3/useNetworkDescriptor.ts index 9808452f5371..6ae1388c3709 100644 --- a/packages/plugin-infra/src/web3/useNetworkDescriptor.ts +++ b/packages/plugin-infra/src/web3/useNetworkDescriptor.ts @@ -8,12 +8,10 @@ export function useNetworkDescriptor - const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) const networkType = useNetworkType(pluginID) return getPluginDefine(pluginID)?.declareWeb3Networks?.find((x) => [x.chainId, x.type, x.ID].includes(expectedChainIdOrNetworkTypeOrID ?? networkType ?? ''), - ) as Result + ) as Web3Helper.NetworkDescriptorScope } diff --git a/packages/plugin-infra/src/web3/useNetworkDescriptors.ts b/packages/plugin-infra/src/web3/useNetworkDescriptors.ts index 4bf8d6f7b6a9..7aee2eeabaeb 100644 --- a/packages/plugin-infra/src/web3/useNetworkDescriptors.ts +++ b/packages/plugin-infra/src/web3/useNetworkDescriptors.ts @@ -7,8 +7,8 @@ import { useCurrentWeb3NetworkPluginID } from './Context' export function useNetworkDescriptors( expectedPluginID?: T, ) { - type Result = S extends 'all' ? Web3Helper.NetworkDescriptorAll : Web3Helper.Web3NetworkDescriptor - const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) - return (getPluginDefine(pluginID)?.declareWeb3Networks ?? EMPTY_LIST) as Result[] + return (getPluginDefine(pluginID)?.declareWeb3Networks ?? EMPTY_LIST) as Array< + Web3Helper.NetworkDescriptorScope + > } diff --git a/packages/plugin-infra/src/web3/useNetworkType.ts b/packages/plugin-infra/src/web3/useNetworkType.ts index 58bec5774d9a..11779508bc7e 100644 --- a/packages/plugin-infra/src/web3/useNetworkType.ts +++ b/packages/plugin-infra/src/web3/useNetworkType.ts @@ -1,4 +1,4 @@ -import { Subscription, useSubscription } from 'use-subscription' +import { useSubscription } from 'use-subscription' import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' @@ -9,14 +9,10 @@ import { useCurrentWeb3NetworkNetworkType } from './Context' export function useNetworkType( pluginID?: T, ) { - type Result = S extends 'all' ? Web3Helper.NetworkTypeAll : Web3Helper.Definition[T]['NetworkType'] - - const { Provider } = useWeb3State(pluginID) + const { Provider } = useWeb3State(pluginID) const currentNetworkType = useCurrentWeb3NetworkNetworkType(pluginID) - const defaultNetworkType = useDefaultNetworkType(pluginID) as Web3Helper.Definition[T]['NetworkType'] - const networkType = useSubscription( - (Provider?.networkType ?? UNDEFINED) as Subscription, - ) + const defaultNetworkType = useDefaultNetworkType(pluginID) + const networkType = useSubscription(Provider?.networkType ?? UNDEFINED) - return (currentNetworkType ?? networkType ?? defaultNetworkType) as Result + return (currentNetworkType ?? networkType ?? defaultNetworkType) as Web3Helper.NetworkTypeScope } diff --git a/packages/plugin-infra/src/web3/useNonFungibleAsset.ts b/packages/plugin-infra/src/web3/useNonFungibleAsset.ts index 8343638eecf3..95a1583451c3 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleAsset.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleAsset.ts @@ -1,25 +1,20 @@ import { useAsyncRetry } from 'react-use' -import type { NonFungibleAsset, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useAccount } from '../entry-web3' import { useWeb3Hub } from './useWeb3Hub' -export function useNonFungibleAsset( +export function useNonFungibleAsset( pluginID?: T, address?: string, id?: string, - options?: Web3Helper.Web3HubOptions, + options?: Web3Helper.Web3HubOptionsScope, ) { - type GetNonFungibleAsset = ( - address: string, - id: string, - ) => Promise> - - const account = useAccount(pluginID) + const account = useAccount(pluginID, options?.account) const hub = useWeb3Hub(pluginID, options) - return useAsyncRetry(async () => { + return useAsyncRetry | undefined>(async () => { if (!address || !id || !hub) return - return (hub.getNonFungibleAsset as GetNonFungibleAsset)(address, id) + return hub.getNonFungibleAsset?.(address, id) }, [address, account, id, hub]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleAssets.ts b/packages/plugin-infra/src/web3/useNonFungibleAssets.ts index e6ab407a6ed7..b2f1cf7d8fa5 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleAssets.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleAssets.ts @@ -1,27 +1,25 @@ import { useAsyncRetry } from 'react-use' -import { asyncIteratorToArray } from '@masknet/shared-base' -import type { NonFungibleAsset, NetworkPluginID } from '@masknet/web3-shared-base' +import { asyncIteratorToArray, EMPTY_LIST } from '@masknet/shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useAccount } from './useAccount' import { useWeb3Hub } from './useWeb3Hub' -export function useNonFungibleAssets( +export function useNonFungibleAssets< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + Indicator = number, +>( pluginID?: T, - schemaType?: Web3Helper.Definition[T]['SchemaType'], - options?: Web3Helper.Web3HubOptions, + schemaType?: Web3Helper.SchemaTypeScope, + options?: Web3Helper.Web3HubOptionsScope, ) { - type GetAllNonFungibleAssets = ( - address: string, - ) => AsyncIterableIterator< - NonFungibleAsset - > - - const account = useAccount(pluginID) + const account = useAccount(pluginID, options?.account) const hub = useWeb3Hub(pluginID, options) - return useAsyncRetry(async () => { - if (!account || !hub) return [] - const assets = await asyncIteratorToArray((hub.getAllNonFungibleAssets as GetAllNonFungibleAssets)(account)) + return useAsyncRetry> | undefined>(async () => { + if (!account || !hub) return EMPTY_LIST + const assets = await asyncIteratorToArray(hub.getAllNonFungibleAssets?.(account)) return assets.length && schemaType ? assets.filter((x) => x.schema === schemaType) : assets }, [account, schemaType, hub]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleCollections.ts b/packages/plugin-infra/src/web3/useNonFungibleCollections.ts index 31ded7d1bea5..a11d8123e686 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleCollections.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleCollections.ts @@ -1,26 +1,20 @@ import { useAsyncRetry } from 'react-use' import { asyncIteratorToArray } from '@masknet/shared-base' -import type { NonFungibleTokenCollection, NetworkPluginID, HubOptions } from '@masknet/web3-shared-base' +import type { NetworkPluginID, NonFungibleTokenCollection } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useAccount } from './useAccount' import { useWeb3Hub } from './useWeb3Hub' -export function useNonFungibleCollections( - pluginID?: T, - chainId?: Web3Helper.Definition[T]['ChainId'], -) { - type GetAllNonFungibleCollections = ( - address: string, - options?: HubOptions, - ) => AsyncIterableIterator> +export function useNonFungibleCollections< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, + Indicator = number, +>(pluginID?: T, options?: Web3Helper.Web3HubOptionsScope) { + const account = useAccount(pluginID, options?.account) + const hub = useWeb3Hub(pluginID, options) - const account = useAccount(pluginID) - const hub = useWeb3Hub(pluginID) - - return useAsyncRetry(async () => { + return useAsyncRetry>>>(async () => { if (!account || !hub) return [] - return asyncIteratorToArray( - (hub.getAllNonFungibleCollections as GetAllNonFungibleCollections)(account, { chainId }), - ) - }, [account, chainId, hub]) + return asyncIteratorToArray(hub.getAllNonFungibleCollections?.(account)) + }, [account, hub]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleToken.ts b/packages/plugin-infra/src/web3/useNonFungibleToken.ts index 1e005852866f..d4bbe0802745 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleToken.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleToken.ts @@ -1,32 +1,26 @@ -import { NetworkPluginID, NonFungibleToken } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import useAsyncRetry from 'react-use/lib/useAsyncRetry' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' import { useChainId } from './useChainId' import { useAccount } from './useAccount' -export function useNonFungibleToken( +export function useNonFungibleToken( pluginID?: T, address?: string, id?: string, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNonFungibleToken = ( - address: string, - id: string, - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise> - + const chainId = useChainId(pluginID, options?.chainId) + const account = useAccount(pluginID, options?.account) const connection = useWeb3Connection(pluginID, options) - const chainId = useChainId(NetworkPluginID.PLUGIN_EVM) - const account = useAccount(NetworkPluginID.PLUGIN_EVM) - return useAsyncRetry(async () => { + return useAsyncRetry | undefined>(async () => { if (!address || !id || !connection) return - return (connection.getNonFungibleToken as GetNonFungibleToken)(address, id, { + return connection.getNonFungibleToken(address, id, { ...options, account: options?.account ?? account, chainId: options?.chainId ?? chainId, - } as Web3Helper.Web3ConnectionOptions) + }) }, [address, id, connection, chainId, account]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleTokenBalance.ts b/packages/plugin-infra/src/web3/useNonFungibleTokenBalance.ts index dc36f5518bae..bb47bd6f932d 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleTokenBalance.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleTokenBalance.ts @@ -3,20 +3,15 @@ import useAsyncRetry from 'react-use/lib/useAsyncRetry' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useNonFungibleTokenBalance( +export function useNonFungibleTokenBalance( pluginID?: T, address?: string, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNonFungibleTokenBalance = ( - address: string, - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise - const connection = useWeb3Connection(pluginID, options) return useAsyncRetry(async () => { if (!address || !connection) return '0' - return (connection.getNonFungibleTokenBalance as GetNonFungibleTokenBalance)(address) + return connection.getNonFungibleTokenBalance(address) }, [address, connection]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleTokenContract.ts b/packages/plugin-infra/src/web3/useNonFungibleTokenContract.ts index 2d2020f45d7f..056dfea6c1b8 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleTokenContract.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleTokenContract.ts @@ -3,19 +3,17 @@ import type { NetworkPluginID, NonFungibleTokenContract } from '@masknet/web3-sh import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useNonFungibleTokenContract( +export function useNonFungibleTokenContract( pluginID: T, address: string, - options: Web3Helper.Web3ConnectionOptions, + options: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNonFungibleTokenContract = ( - address: string, - options: Web3Helper.Web3ConnectionOptions, - ) => Promise> const connection = useWeb3Connection(pluginID, options) - return useAsyncRetry(async () => { + return useAsyncRetry< + NonFungibleTokenContract, Web3Helper.SchemaTypeScope> | undefined + >(async () => { if (!connection || !address || !options) return - return (connection.getNonFungibleTokenContract as GetNonFungibleTokenContract)(address, options) + return connection.getNonFungibleTokenContract?.(address, options) }, [address, connection, JSON.stringify(options)]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleTokenPrice.ts b/packages/plugin-infra/src/web3/useNonFungibleTokenPrice.ts index 5e956a8c2be6..f812e32e2716 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleTokenPrice.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleTokenPrice.ts @@ -4,23 +4,18 @@ import type { Web3Helper } from '../web3-helpers' import { useChainId } from './useChainId' import { useWeb3Hub } from './useWeb3Hub' -export function useNonFungibleTokenPrice( +export function useNonFungibleTokenPrice( pluginID: T, address?: string, tokenId?: string, - options?: Web3Helper.Web3HubOptions, + options?: Web3Helper.Web3HubOptionsScope, ) { - type GetNonFungibleTokenPrice = ( - chainId: Web3Helper.Definition[T]['ChainId'], - address: string, - tokenId: string, - ) => Promise - const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) return useAsyncRetry(async () => { if (!chainId || !address || !tokenId) return 0 - return (hub?.getNonFungibleTokenPrice as GetNonFungibleTokenPrice)(chainId, address, tokenId) + const price = await hub?.getNonFungibleTokenPrice?.(chainId, address, tokenId) + return price ?? 0 }, [chainId, address, tokenId, hub]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleTokens.ts b/packages/plugin-infra/src/web3/useNonFungibleTokens.ts index 0ccb0f27c98b..9df978e81314 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleTokens.ts @@ -1,34 +1,19 @@ import { useAsyncRetry } from 'react-use' import { EMPTY_LIST } from '@masknet/shared-base' -import type { NonFungibleToken, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useNonFungibleTokens( +export function useNonFungibleTokens( pluginID?: T, // pair: [address, tokenId] listOfPairs?: [string, string], - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNonFungibleToken = ( - address: string, - id: string, - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise< - NonFungibleToken< - Web3Helper.Definition[NetworkPluginID.PLUGIN_EVM]['ChainId'], - Web3Helper.Definition[NetworkPluginID.PLUGIN_EVM]['SchemaType'] - > - > - const connection = useWeb3Connection(pluginID, options) - return useAsyncRetry< - Array> - >(async () => { + return useAsyncRetry>>(async () => { if (!connection) return EMPTY_LIST - return Promise.all( - listOfPairs?.map((x) => (connection.getNonFungibleToken as GetNonFungibleToken)(x[0], x[1], options)) ?? [], - ) + return Promise.all(listOfPairs?.map((x) => connection.getNonFungibleToken(x[0], x[1], options)) ?? []) }, [connection, listOfPairs?.join()]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleTokensBalance.ts b/packages/plugin-infra/src/web3/useNonFungibleTokensBalance.ts index ac9211cf35e8..9b2e7a1485a9 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleTokensBalance.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleTokensBalance.ts @@ -4,20 +4,14 @@ import useAsyncRetry from 'react-use/lib/useAsyncRetry' import type { Web3Helper } from '../web3-helpers' import { useWeb3Connection } from './useWeb3Connection' -export function useNonFungibleTokensBalance( +export function useNonFungibleTokensBalance( pluginID?: T, listOfAddress?: string[], - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetNonFungibleTokensBalance = ( - listOfAddress: string[], - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise> - const connection = useWeb3Connection(pluginID, options) - return useAsyncRetry(async () => { if (!connection) return EMPTY_OBJECT - return (connection.getNonFungibleTokensBalance as GetNonFungibleTokensBalance)(listOfAddress ?? []) + return connection.getNonFungibleTokensBalance(listOfAddress ?? []) }, [listOfAddress?.join(), connection]) } diff --git a/packages/plugin-infra/src/web3/useNonFungibleTokensFromTokenList.ts b/packages/plugin-infra/src/web3/useNonFungibleTokensFromTokenList.ts index a4605a89fd56..6a2840cf435c 100644 --- a/packages/plugin-infra/src/web3/useNonFungibleTokensFromTokenList.ts +++ b/packages/plugin-infra/src/web3/useNonFungibleTokensFromTokenList.ts @@ -1,21 +1,17 @@ import { useAsyncRetry } from 'react-use' -import type { NetworkPluginID, NonFungibleToken } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3Hub } from './useWeb3Hub' import { useChainId } from './useChainId' -export function useNonFungibleTokensFromTokenList( - pluginID?: T, - options?: Web3Helper.Web3HubOptions, -) { - type GetNonFungibleTokens = ( - chainId: Web3Helper.Definition[T]['ChainId'], - ) => Promise>> - - const chainId = useChainId(pluginID) +export function useNonFungibleTokensFromTokenList< + S extends 'all' | void = void, + T extends NetworkPluginID = NetworkPluginID, +>(pluginID?: T, options?: Web3Helper.Web3HubOptionsScope) { + const chainId = useChainId(pluginID, options?.chainId) const hub = useWeb3Hub(pluginID, options) - return useAsyncRetry(async () => { - return (hub?.getNonFungibleTokensFromTokenList as GetNonFungibleTokens | undefined)?.(chainId) + return useAsyncRetry> | undefined>(async () => { + return hub?.getNonFungibleTokensFromTokenList?.(chainId) }, [chainId, hub]) } diff --git a/packages/plugin-infra/src/web3/useProviderDescriptor.ts b/packages/plugin-infra/src/web3/useProviderDescriptor.ts index b35311c76b26..e29ad17793fd 100644 --- a/packages/plugin-infra/src/web3/useProviderDescriptor.ts +++ b/packages/plugin-infra/src/web3/useProviderDescriptor.ts @@ -8,12 +8,10 @@ export function useProviderDescriptor - const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) const providerType = useProviderType(pluginID) return getPluginDefine(pluginID)?.declareWeb3Providers?.find((x) => [x.type, x.ID].includes(expectedProviderTypeOrID ?? providerType ?? ''), - ) as Result + ) as Web3Helper.ProviderDescriptorScope } diff --git a/packages/plugin-infra/src/web3/useProviderDescriptors.ts b/packages/plugin-infra/src/web3/useProviderDescriptors.ts index a0ac9111a4be..5da8b8711d24 100644 --- a/packages/plugin-infra/src/web3/useProviderDescriptors.ts +++ b/packages/plugin-infra/src/web3/useProviderDescriptors.ts @@ -7,8 +7,8 @@ import { useCurrentWeb3NetworkPluginID } from './Context' export function useProviderDescriptors( expectedPluginID?: T, ) { - type Result = S extends 'all' ? Web3Helper.ProviderDescriptorAll : Web3Helper.Web3ProviderDescriptor - const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) - return (getPluginDefine(pluginID)?.declareWeb3Providers ?? EMPTY_LIST) as Result[] + return (getPluginDefine(pluginID)?.declareWeb3Providers ?? EMPTY_LIST) as Array< + Web3Helper.ProviderDescriptorScope + > } diff --git a/packages/plugin-infra/src/web3/useProviderReady.ts b/packages/plugin-infra/src/web3/useProviderReady.ts index 3a75967dd10b..8ce1e19f8eba 100644 --- a/packages/plugin-infra/src/web3/useProviderReady.ts +++ b/packages/plugin-infra/src/web3/useProviderReady.ts @@ -7,12 +7,10 @@ export function useProviderReady( pluginID?: T, providerType?: Web3Helper.Definition[T]['ProviderType'], ) { - type IsReady = (providerType: Web3Helper.Definition[T]['ProviderType']) => boolean - const { Provider } = useWeb3State(pluginID) return useMemo(async () => { if (!providerType || !Provider) return false - return (Provider.isReady as IsReady)(providerType) ?? false + return Provider.isReady?.(providerType) ?? false }, [providerType, Provider]) } diff --git a/packages/plugin-infra/src/web3/useProviderType.ts b/packages/plugin-infra/src/web3/useProviderType.ts index 93f11f5c54bb..315cd34b3b7b 100644 --- a/packages/plugin-infra/src/web3/useProviderType.ts +++ b/packages/plugin-infra/src/web3/useProviderType.ts @@ -1,4 +1,4 @@ -import { Subscription, useSubscription } from 'use-subscription' +import { useSubscription } from 'use-subscription' import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' @@ -8,13 +8,8 @@ import { useCurrentWeb3NetworkProviderType } from './Context' export function useProviderType( pluginID?: T, ) { - type Result = S extends 'all' ? Web3Helper.ProviderTypeAll : Web3Helper.Definition[T]['ProviderType'] - const { Provider } = useWeb3State(pluginID) const currentProviderType = useCurrentWeb3NetworkProviderType(pluginID) - const providerType = useSubscription( - (Provider?.providerType ?? UNDEFINED) as Subscription, - ) - - return (currentProviderType ?? providerType) as Result + const providerType = useSubscription(Provider?.providerType ?? UNDEFINED) + return (currentProviderType ?? providerType) as Web3Helper.ProviderTypeScope } diff --git a/packages/plugin-infra/src/web3/useRecentTransactions.ts b/packages/plugin-infra/src/web3/useRecentTransactions.ts index 9a638b25ed46..623638c86af5 100644 --- a/packages/plugin-infra/src/web3/useRecentTransactions.ts +++ b/packages/plugin-infra/src/web3/useRecentTransactions.ts @@ -1,28 +1,16 @@ import { useMemo } from 'react' -import { Subscription, useSubscription } from 'use-subscription' -import type { - NetworkPluginID, - RecentTransaction, - RecentTransactionComputed, - TransactionStatusType, -} from '@masknet/web3-shared-base' +import { useSubscription } from 'use-subscription' +import type { NetworkPluginID, RecentTransactionComputed, TransactionStatusType } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' import { EMPTY_ARRAY } from '../utils/subscription' export function useRecentTransactions(pluginID?: T, status?: TransactionStatusType) { - type TransactionComputed = RecentTransactionComputed< - Web3Helper.Definition[T]['ChainId'], - Web3Helper.Definition[T]['Transaction'] - > - const { Transaction } = useWeb3State(pluginID) - const transactions = useSubscription( - (Transaction?.transactions ?? EMPTY_ARRAY) as Subscription< - Array> - >, - ) - return useMemo(() => { + const transactions = useSubscription(Transaction?.transactions ?? EMPTY_ARRAY) + return useMemo< + Array> + >(() => { return (status ? transactions.filter((x) => status === x.status) : transactions).map((x) => ({ ...x, _tx: x.candidates[x.indexId], diff --git a/packages/plugin-infra/src/web3/useRemoveTransaction.ts b/packages/plugin-infra/src/web3/useRemoveTransaction.ts index e3ab0151eb0b..f6b1de675720 100644 --- a/packages/plugin-infra/src/web3/useRemoveTransaction.ts +++ b/packages/plugin-infra/src/web3/useRemoveTransaction.ts @@ -3,15 +3,8 @@ import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useAccount } from './useAccount' import { useChainId } from './useChainId' import { useWeb3State } from './useWeb3State' -import type { Web3Helper } from '../web3-helpers' - -export function useRemoveTransactionCallback(pluginID?: NetworkPluginID) { - type RemoveTransactions = ( - chainId: Web3Helper.Definition[T]['ChainId'], - account: string, - id: string, - ) => Promise +export function useRemoveTransactionCallback(pluginID?: T) { const account = useAccount(pluginID) const chainId = useChainId(pluginID) const { Transaction } = useWeb3State(pluginID) @@ -19,7 +12,7 @@ export function useRemoveTransactionCallback(pluginID return useCallback( async (id: string) => { if (!account) return - return (Transaction?.removeTransaction as RemoveTransactions | undefined)?.(chainId, account, id) + return Transaction?.removeTransaction?.(chainId, account, id) }, [chainId, account, Transaction], ) diff --git a/packages/plugin-infra/src/web3/useReverseAddress.ts b/packages/plugin-infra/src/web3/useReverseAddress.ts index 4019b06198f6..31d301425c03 100644 --- a/packages/plugin-infra/src/web3/useReverseAddress.ts +++ b/packages/plugin-infra/src/web3/useReverseAddress.ts @@ -2,19 +2,13 @@ import { useAsyncRetry } from 'react-use' import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useChainId } from './useChainId' import { useWeb3State } from './useWeb3State' -import type { Web3Helper } from '../web3-helpers' export function useReverseAddress(pluginID?: T, address?: string) { - type ReverseAddress = ( - chainId: Web3Helper.Definition[T]['ChainId'], - address?: string, - ) => Promise - const chainId = useChainId(pluginID) const { NameService, Others } = useWeb3State(pluginID) return useAsyncRetry(async () => { - if (!chainId || !Others?.isValidAddress?.(address) || !NameService) return - return (NameService.reverse as ReverseAddress)(chainId, address) + if (!chainId || !address || !Others?.isValidAddress?.(address) || !NameService) return + return NameService.reverse?.(chainId, address) }, [address, chainId, NameService]) } diff --git a/packages/plugin-infra/src/web3/useSchemaType.ts b/packages/plugin-infra/src/web3/useSchemaType.ts index db0434bcca60..af75898e7cad 100644 --- a/packages/plugin-infra/src/web3/useSchemaType.ts +++ b/packages/plugin-infra/src/web3/useSchemaType.ts @@ -2,20 +2,15 @@ import { useAsyncRetry } from 'react-use' import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useWeb3Connection, Web3Helper } from '../entry-web3' -export function useSchemaType( +export function useSchemaType( pluginID?: T, address?: string, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type GetSchemaType = ( - address: string, - options?: Web3Helper.Web3ConnectionOptions, - ) => Promise + const connection = useWeb3Connection(pluginID, options) - const connection = useWeb3Connection(pluginID, options) - - return useAsyncRetry(async () => { + return useAsyncRetry | undefined>(async () => { if (!address) return - return (connection?.getSchemaType as GetSchemaType | undefined)?.(address, options) + return connection?.getSchemaType?.(address, options) }, [address]) } diff --git a/packages/plugin-infra/src/web3/useSocialAddressList.ts b/packages/plugin-infra/src/web3/useSocialAddressList.ts index 65d331ee78bc..7e9ca7b81d8c 100644 --- a/packages/plugin-infra/src/web3/useSocialAddressList.ts +++ b/packages/plugin-infra/src/web3/useSocialAddressList.ts @@ -9,15 +9,13 @@ import { useWeb3State } from './useWeb3State' export function useSocialAddressList( pluginID?: T, identity?: SocialIdentity, - sorter?: (a: SocialAddress, z: SocialAddress) => number, + sorter?: (a: SocialAddress, z: SocialAddress) => number, ) { - type Lookup = (identity: SocialIdentity) => Promise>> - const { IdentityService } = useWeb3State(pluginID) return useAsyncRetry(async () => { if (!identity?.identifier?.userId || !IdentityService?.lookup) return EMPTY_LIST - const listOfAddress = (await (IdentityService.lookup as Lookup)(identity)) ?? EMPTY_LIST + const listOfAddress = (await IdentityService.lookup(identity)) ?? EMPTY_LIST return sorter && listOfAddress.length ? listOfAddress.sort(sorter) : listOfAddress }, [identity?.identifier?.userId, sorter, IdentityService?.lookup]) } diff --git a/packages/plugin-infra/src/web3/useSocialAddressListAll.ts b/packages/plugin-infra/src/web3/useSocialAddressListAll.ts index e205076c7560..88bb6ce5b255 100644 --- a/packages/plugin-infra/src/web3/useSocialAddressListAll.ts +++ b/packages/plugin-infra/src/web3/useSocialAddressListAll.ts @@ -4,7 +4,7 @@ import { NetworkPluginID, SocialAddress, SocialIdentity } from '@masknet/web3-sh import { useWeb3State } from './useWeb3State' /** - * Get all social addresses under a specific network. + * Get all social addresses under of all networks. */ export function useSocialAddressListAll( identity?: SocialIdentity, diff --git a/packages/plugin-infra/src/web3/useSocketOnce.ts b/packages/plugin-infra/src/web3/useSocketOnce.ts deleted file mode 100644 index 62b4fb866bc8..000000000000 --- a/packages/plugin-infra/src/web3/useSocketOnce.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { getWebSocketInstance, PayloadMessage, RequestMessage } from '@masknet/web3-shared-base' -import { useEffect, useState } from 'react' -import { useAsyncRetry } from 'react-use' - -export const useSocketOnce = (message: Omit) => { - const [data, setData] = useState([]) - const [done, setDone] = useState(false) - const [error, setError] = useState() - const { value: ws, retry } = useAsyncRetry(() => getWebSocketInstance(), []) - - useEffect(() => { - if (!ws) return - ws.addEventListener('message', (event: MessageEvent) => { - const { results = [], error } = JSON.parse(event.data) as PayloadMessage - if (error) { - setError(error) - setDone(true) - return - } - if (results.length === 0) { - setDone(true) - return - } - setData((pr) => [...pr, ...results]) - }) - ws.send(JSON.stringify(message)) - - return () => { - ws.close() - } - }, [ws]) - - return { - done, - error, - data, - retry: () => { - setData([]) - setError(undefined) - setDone(false) - retry() - }, - } -} diff --git a/packages/plugin-infra/src/web3/useTransactions.ts b/packages/plugin-infra/src/web3/useTransactions.ts index c142d7079cb7..ac5af44ab1ed 100644 --- a/packages/plugin-infra/src/web3/useTransactions.ts +++ b/packages/plugin-infra/src/web3/useTransactions.ts @@ -1,17 +1,17 @@ -import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useAsyncRetry } from 'react-use' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import { useAccount, useChainId, useWeb3Hub } from '../entry-web3' import type { Web3Helper } from '../web3-helpers' -export function useTransactions( +export function useTransactions( pluginID?: NetworkPluginID, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { const account = useAccount(pluginID) const chainId = useChainId(pluginID) - const hub = useWeb3Hub<'all'>(pluginID, options) + const hub = useWeb3Hub(pluginID, options) - return useAsyncRetry(async () => { + return useAsyncRetry> | undefined>(async () => { return hub?.getTransactions(chainId, account) - }, [account, hub, account, chainId]) + }, [account, chainId, hub]) } diff --git a/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts b/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts index 75e4eae84a6f..88f67afa59d5 100644 --- a/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts @@ -1,21 +1,17 @@ import { useMemo } from 'react' import { Subscription, useSubscription } from 'use-subscription' -import type { FungibleToken, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import { EMPTY_ARRAY } from '../utils/subscription' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' -export function useTrustedFungibleTokens( +export function useTrustedFungibleTokens( pluginID?: T, - schemaType?: Web3Helper.Definition[T]['SchemaType'], + schemaType?: Web3Helper.SchemaTypeScope, ) { const { Token } = useWeb3State(pluginID) - const fungibleTokens = useSubscription( - (Token?.trustedFungibleTokens ?? EMPTY_ARRAY) as Subscription< - Array> - >, - ) - return useMemo(() => { + const fungibleTokens = useSubscription(Token?.trustedFungibleTokens ?? EMPTY_ARRAY) + return useMemo>>(() => { return fungibleTokens.length && schemaType ? fungibleTokens.filter((x) => x.schema === schemaType) : fungibleTokens diff --git a/packages/plugin-infra/src/web3/useTrustedNonFungibleTokens.ts b/packages/plugin-infra/src/web3/useTrustedNonFungibleTokens.ts index 2b7d9cb2ac39..b031d9bd703e 100644 --- a/packages/plugin-infra/src/web3/useTrustedNonFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useTrustedNonFungibleTokens.ts @@ -1,21 +1,17 @@ import { useMemo } from 'react' -import { Subscription, useSubscription } from 'use-subscription' -import type { NetworkPluginID, NonFungibleToken } from '@masknet/web3-shared-base' +import { useSubscription } from 'use-subscription' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' import { EMPTY_ARRAY } from '../utils/subscription' -export function useTrustedNonFungibleTokens( +export function useTrustedNonFungibleTokens( pluginID?: T, - schemaType?: Web3Helper.Definition[T]['SchemaType'], + schemaType?: Web3Helper.SchemaTypeScope, ) { const { Token } = useWeb3State(pluginID) - const nonFungibleTokens = useSubscription( - (Token?.trustedNonFungibleTokens ?? EMPTY_ARRAY) as Subscription< - Array> - >, - ) - return useMemo(() => { + const nonFungibleTokens = useSubscription(Token?.trustedNonFungibleTokens ?? EMPTY_ARRAY) + return useMemo>>(() => { return nonFungibleTokens.length && schemaType ? nonFungibleTokens.filter((x) => x.schema === schemaType) : nonFungibleTokens diff --git a/packages/plugin-infra/src/web3/useWeb3.ts b/packages/plugin-infra/src/web3/useWeb3.ts index 29050a690548..4f601692be93 100644 --- a/packages/plugin-infra/src/web3/useWeb3.ts +++ b/packages/plugin-infra/src/web3/useWeb3.ts @@ -11,23 +11,19 @@ export function useWeb3, ) { - type Result = S extends 'all' ? Web3Helper.Web3All : Web3Helper.Web3 - type GetWeb3 = (options?: Web3Helper.Web3ConnectionOptions) => Promise> - const { Connection } = useWeb3State(pluginID) const chainId = useChainId(pluginID) const account = useAccount(pluginID) const providerType = useProviderType(pluginID) const { value: web3 = null } = useAsyncRetry(async () => { - if (!Connection?.getWeb3) return null - return (Connection.getWeb3 as GetWeb3)({ + return Connection?.getWeb3?.({ account, chainId, providerType, ...options, - } as Web3Helper.Web3ConnectionOptions) + }) }, [account, chainId, providerType, JSON.stringify(options)]) - return web3 as Result + return web3 as Web3Helper.Web3Scope } diff --git a/packages/plugin-infra/src/web3/useWeb3Connection.ts b/packages/plugin-infra/src/web3/useWeb3Connection.ts index 840f654fd769..09d630bb4b79 100644 --- a/packages/plugin-infra/src/web3/useWeb3Connection.ts +++ b/packages/plugin-infra/src/web3/useWeb3Connection.ts @@ -8,25 +8,21 @@ import { useWeb3State } from './useWeb3State' export function useWeb3Connection( pluginID?: T, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type Result = S extends 'all' ? Web3Helper.Web3ConnectionAll : Web3Helper.Web3Connection - type GetConnection = (options?: Web3Helper.Web3ConnectionOptions) => Promise> - const { Connection } = useWeb3State(pluginID) const chainId = useChainId(pluginID) const account = useAccount(pluginID) const providerType = useProviderType(pluginID) const { value: connection = null } = useAsyncRetry(async () => { - if (!Connection?.getConnection) return - return (Connection.getConnection as GetConnection)?.({ + return Connection?.getConnection?.({ account, chainId, providerType, ...options, - } as Web3Helper.Web3ConnectionOptions) + }) }, [account, chainId, providerType, Connection, JSON.stringify(options)]) - return connection as Result + return connection as Web3Helper.Web3ConnectionScope } diff --git a/packages/plugin-infra/src/web3/useWeb3Hub.ts b/packages/plugin-infra/src/web3/useWeb3Hub.ts index 38863c601bdc..c367542be7bf 100644 --- a/packages/plugin-infra/src/web3/useWeb3Hub.ts +++ b/packages/plugin-infra/src/web3/useWeb3Hub.ts @@ -7,23 +7,19 @@ import { useWeb3State } from './useWeb3State' export function useWeb3Hub< S extends 'all' | void = void, T extends NetworkPluginID = NetworkPluginID, - Indicator extends string | number = number, ->(pluginID?: T, options?: Web3Helper.Web3HubOptions) { - type Result = S extends 'all' ? Web3Helper.Web3HubAll : Web3Helper.Web3Hub - type GetHub = (options?: Web3Helper.Web3HubOptions) => Promise - + Indicator = number, +>(pluginID?: T, options?: Web3Helper.Web3HubOptionsScope) { const { Hub } = useWeb3State(pluginID) - const chainId = useChainId(pluginID) const account = useAccount(pluginID) + const chainId = useChainId(pluginID) const { value: hub = null } = useAsyncRetry(async () => { - if (!Hub?.getHub) return - return (Hub.getHub as GetHub)?.({ + return Hub?.getHub?.({ account, chainId, ...options, - } as Web3Helper.Web3HubOptions) + } as Web3Helper.Web3HubOptionsScope) }, [account, chainId, Hub, JSON.stringify(options)]) - return hub as Result + return hub as Web3Helper.Web3HubScope } diff --git a/packages/plugin-infra/src/web3/useWeb3Provider.ts b/packages/plugin-infra/src/web3/useWeb3Provider.ts index 58c9065eac72..494bc99ef199 100644 --- a/packages/plugin-infra/src/web3/useWeb3Provider.ts +++ b/packages/plugin-infra/src/web3/useWeb3Provider.ts @@ -8,25 +8,21 @@ import { useWeb3State } from './useWeb3State' export function useWeb3Provider( pluginID?: T, - options?: Web3Helper.Web3ConnectionOptions, + options?: Web3Helper.Web3ConnectionOptionsScope, ) { - type Result = S extends 'all' ? Web3Helper.Web3ProviderAll : Web3Helper.Web3Provider - type GetWeb3Provider = (options?: Web3Helper.Web3ConnectionOptions) => Promise> - const { Connection } = useWeb3State(pluginID) const chainId = useChainId(pluginID) const account = useAccount(pluginID) const providerType = useProviderType(pluginID) const { value: web3Provider = null } = useAsyncRetry(async () => { - if (!Connection?.getWeb3Provider) return null - return (Connection.getWeb3Provider as GetWeb3Provider)({ + return Connection?.getWeb3Provider?.({ account, chainId, providerType, ...options, - } as Web3Helper.Web3ConnectionOptions) + }) }, [account, chainId, providerType, Connection, JSON.stringify(options)]) - return web3Provider as Result + return web3Provider as Web3Helper.Web3ProviderScope } diff --git a/packages/plugin-infra/src/web3/useWeb3State.ts b/packages/plugin-infra/src/web3/useWeb3State.ts index f272a8213519..3eb89c524052 100644 --- a/packages/plugin-infra/src/web3/useWeb3State.ts +++ b/packages/plugin-infra/src/web3/useWeb3State.ts @@ -6,8 +6,6 @@ import type { Web3Helper } from '../web3-helpers' export function useWeb3State( expectedPluginID?: T, ) { - type Result = S extends 'all' ? Web3Helper.Web3StateAll : Web3Helper.Web3State - const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) as T - return useActivatedPluginWeb3State(pluginID) as Result + return useActivatedPluginWeb3State(pluginID) as Web3Helper.Web3StateScope } diff --git a/packages/plugin-infra/src/web3/useWeb3UI.ts b/packages/plugin-infra/src/web3/useWeb3UI.ts index c9c3e683fc92..77196d9e66f0 100644 --- a/packages/plugin-infra/src/web3/useWeb3UI.ts +++ b/packages/plugin-infra/src/web3/useWeb3UI.ts @@ -6,8 +6,6 @@ import type { Web3Helper } from '../web3-helpers' export function useWeb3UI( expectedPluginID?: T, ) { - type Result = S extends 'all' ? Web3Helper.Web3UIAll : Web3Helper.Web3UI - const pluginID = useCurrentWeb3NetworkPluginID(expectedPluginID) as T - return useActivatedPluginWeb3UI(pluginID) as Result + return useActivatedPluginWeb3UI(pluginID) as Web3Helper.Web3UIScope } diff --git a/packages/plugin-infra/src/web3/useZeroAddress.ts b/packages/plugin-infra/src/web3/useZeroAddress.ts index 8a7126639f4f..7672e824df69 100644 --- a/packages/plugin-infra/src/web3/useZeroAddress.ts +++ b/packages/plugin-infra/src/web3/useZeroAddress.ts @@ -2,9 +2,10 @@ import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useWeb3State } from './useWeb3State' -export function useZeroAddress(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions) { - type GetZeroAddress = (chainId?: Web3Helper.Definition[T]['ChainId']) => string - +export function useZeroAddress( + pluginID?: T, + options?: Web3Helper.Web3ConnectionOptionsScope, +) { const { Others } = useWeb3State(pluginID) - return (Others?.getZeroAddress as GetZeroAddress)(options?.chainId) ?? '' + return Others?.getZeroAddress?.(options?.chainId) ?? '' } diff --git a/packages/plugins/Debugger/src/SNSAdaptor/components/TabContent.tsx b/packages/plugins/Debugger/src/SNSAdaptor/components/TabContent.tsx index 681bc88c37e2..67420b10e87e 100644 --- a/packages/plugins/Debugger/src/SNSAdaptor/components/TabContent.tsx +++ b/packages/plugins/Debugger/src/SNSAdaptor/components/TabContent.tsx @@ -78,8 +78,8 @@ export function TabContent({ identity, socialAddressList }: TabContentProps) { const { NATIVE_TOKEN_ADDRESS } = useTokenConstants() const pluginID = useCurrentWeb3NetworkPluginID() - const { Others } = useWeb3State<'all'>() - const connection = useWeb3Connection<'all'>() + const { Others } = useWeb3State() + const connection = useWeb3Connection() const account = useAccount() const chainId = useChainId() const { value: balance = '0' } = useBalance() diff --git a/packages/plugins/EVM/src/state/Connection/connection.ts b/packages/plugins/EVM/src/state/Connection/connection.ts index b6608a85559c..1439a44d6982 100644 --- a/packages/plugins/EVM/src/state/Connection/connection.ts +++ b/packages/plugins/EVM/src/state/Connection/connection.ts @@ -35,6 +35,7 @@ import { import { Account, ConnectionOptions, + currySameAddress, FungibleToken, isSameAddress, NonFungibleToken, @@ -303,20 +304,35 @@ class Connection implements EVM_Connection { ): Promise> { if (!listOfAddress.length) return {} - const { BALANCE_CHECKER_ADDRESS } = getEthereumConstants(options?.chainId ?? this.chainId) - const contract = await this.getWeb3Contract( - BALANCE_CHECKER_ADDRESS ?? '', - BalanceCheckerABI as AbiItem[], - options, - ) - const result = await contract?.methods.balances([options?.account ?? this.account], listOfAddress).call({ - // cannot check the sender's balance in the same contract - from: undefined, - chainId: numberToHex(options?.chainId ?? this.chainId), - }) + const account = options?.account ?? this.account + const chainId = options?.chainId ?? this.chainId + const { NATIVE_TOKEN_ADDRESS = '' } = getTokenConstants(chainId) + const { BALANCE_CHECKER_ADDRESS } = getEthereumConstants(chainId) + const entities: Array<[string, string]> = [] - if (result?.length !== listOfAddress.length) return {} - return Object.fromEntries(listOfAddress.map<[string, string]>((x, i) => [x, result[i]])) + if (listOfAddress.some(currySameAddress(NATIVE_TOKEN_ADDRESS))) { + entities.push([NATIVE_TOKEN_ADDRESS, await this.getBalance(this.account, options)]) + } + + const listOfNonNativeAddress = listOfAddress.filter((x) => !isSameAddress(NATIVE_TOKEN_ADDRESS, x)) + + if (listOfNonNativeAddress.length) { + const contract = await this.getWeb3Contract( + BALANCE_CHECKER_ADDRESS ?? '', + BalanceCheckerABI as AbiItem[], + options, + ) + const balances = await contract?.methods.balances([account], listOfNonNativeAddress).call({ + // cannot check the sender's balance in the same contract + from: undefined, + chainId: numberToHex(chainId), + }) + + listOfNonNativeAddress.forEach((x, i) => { + entities.push([x, balances?.[i] ?? '0']) + }) + } + return Object.fromEntries(entities) } async getNonFungibleTokensBalance( diff --git a/packages/plugins/EVM/src/state/Connection/providers/MaskWallet.ts b/packages/plugins/EVM/src/state/Connection/providers/MaskWallet.ts index f94dd62015e4..b8ef87153bd1 100644 --- a/packages/plugins/EVM/src/state/Connection/providers/MaskWallet.ts +++ b/packages/plugins/EVM/src/state/Connection/providers/MaskWallet.ts @@ -9,6 +9,8 @@ import { first } from 'lodash-unified' import type { ProviderOptions } from '@masknet/web3-shared-base' export class MaskWalletProvider extends BaseProvider implements EVM_Provider { + private id = 0 + constructor() { super() Web3StateSettings.readyPromise.then(this.addSharedContextListeners.bind(this)) @@ -53,8 +55,10 @@ export class MaskWalletProvider extends BaseProvider implements EVM_Provider { requestArguments: RequestArguments, options?: ProviderOptions, ): Promise { + this.id += 1 + const response = await SharedContextSettings.value.send( - createPayload(0, requestArguments.method, requestArguments.params), + createPayload(this.id, requestArguments.method, requestArguments.params), { chainId: SharedContextSettings.value.chainId.getCurrentValue(), popupsWindow: getSiteType() === ExtensionSite.Dashboard || isEnhanceableSiteType(), diff --git a/packages/plugins/EVM/src/state/Hub/hub.ts b/packages/plugins/EVM/src/state/Hub/hub.ts index d6ff71f66681..ca43cb0d3d3f 100644 --- a/packages/plugins/EVM/src/state/Hub/hub.ts +++ b/packages/plugins/EVM/src/state/Hub/hub.ts @@ -155,7 +155,7 @@ class Hub implements EVM_Hub { chainId: ChainId, account: string, options?: HubOptions | undefined, - ): Promise>> { + ): Promise>> { return DeBank.getTransactions(account, { chainId }) } diff --git a/packages/plugins/Flow/src/state/Hub/hub.ts b/packages/plugins/Flow/src/state/Hub/hub.ts index de5aa0991d18..b72ff27a9983 100644 --- a/packages/plugins/Flow/src/state/Hub/hub.ts +++ b/packages/plugins/Flow/src/state/Hub/hub.ts @@ -129,7 +129,7 @@ class Hub implements FlowHub { chainId: ChainId, account: string, options?: HubOptions | undefined, - ): Promise>> { + ): Promise>> { throw new Error('Method not implemented.') } diff --git a/packages/plugins/Solana/src/state/Hub/hub.ts b/packages/plugins/Solana/src/state/Hub/hub.ts index f61b373c689b..ae650a6a455b 100644 --- a/packages/plugins/Solana/src/state/Hub/hub.ts +++ b/packages/plugins/Solana/src/state/Hub/hub.ts @@ -113,7 +113,7 @@ class Hub implements SolanaHub { chainId: ChainId, account: string, options?: HubOptions | undefined, - ): Promise>> { + ): Promise>> { throw new Error('Method not implemented.') } diff --git a/packages/shared-base/src/utils/asyncIterator.ts b/packages/shared-base/src/utils/asyncIterator.ts index 966162279a58..ce24a94efad0 100644 --- a/packages/shared-base/src/utils/asyncIterator.ts +++ b/packages/shared-base/src/utils/asyncIterator.ts @@ -1,4 +1,5 @@ -export async function asyncIteratorToArray(iterable: AsyncIterable) { +export async function asyncIteratorToArray(iterable?: AsyncIterable) { + if (!iterable) return [] const arr: T[] = [] for await (const x of iterable) arr.push(x) return arr diff --git a/packages/shared/src/UI/components/FungibleTokenList/FungibleTokenItem.tsx b/packages/shared/src/UI/components/FungibleTokenList/FungibleTokenItem.tsx index 30b4dc989c6f..d2205c86c1d8 100644 --- a/packages/shared/src/UI/components/FungibleTokenList/FungibleTokenItem.tsx +++ b/packages/shared/src/UI/components/FungibleTokenList/FungibleTokenItem.tsx @@ -85,7 +85,7 @@ export const getFungibleTokenItem = const { classes } = useStyles() if (!token) return null - const { address, name, symbol, decimals, logoURL } = token + const { chainId, address, name, symbol, decimals, logoURL } = token const { source, balance, selected, loading } = useMemo(() => { return { @@ -140,7 +140,13 @@ export const getFungibleTokenItem = onClick={handleTokenSelect} disabled={selected}> - + (props: FungibleToke const pluginID = useCurrentWeb3NetworkPluginID(props.pluginID) const account = useAccount() const chainId = useChainId(pluginID, props.chainId) - const { Token, Others } = useWeb3State<'all'>() - const { value: fungibleTokens = EMPTY_LIST } = useFungibleTokensFromTokenList() + const { Token, Others } = useWeb3State() + const { value: fungibleTokens = EMPTY_LIST } = useFungibleTokensFromTokenList(undefined, { + chainId, + }) const trustedFungibleTokens = useTrustedFungibleTokens() const blockedFungibleTokens = useBlockedFungibleTokens() - - const nativeToken = useMemo(() => { - return Others?.chainResolver.nativeCurrency(chainId) - }, [chainId]) + const nativeToken = useMemo(() => Others?.chainResolver.nativeCurrency(chainId), [chainId]) const filteredFungibleTokens = useMemo(() => { const allFungibleTokens = uniqBy( @@ -95,9 +94,18 @@ export function FungibleTokenList(props: FungibleToke useFungibleTokensBalance( pluginID, filteredFungibleTokens.map((x) => x.address), + { + chainId, + }, ) - const { value: fungibleAssets = EMPTY_LIST, loading: fungibleAssetsLoading } = useFungibleAssets(pluginID) + const { value: fungibleAssets = EMPTY_LIST, loading: fungibleAssetsLoading } = useFungibleAssets( + pluginID, + undefined, + { + chainId, + }, + ) const sortedFungibleTokens = useMemo(() => { const fungibleAssetsTable = Object.fromEntries( diff --git a/packages/shared/src/UI/components/NFTCardStyledAssetPlayer/index.tsx b/packages/shared/src/UI/components/NFTCardStyledAssetPlayer/index.tsx index 47683b804a6b..16748f8c70c8 100644 --- a/packages/shared/src/UI/components/NFTCardStyledAssetPlayer/index.tsx +++ b/packages/shared/src/UI/components/NFTCardStyledAssetPlayer/index.tsx @@ -2,9 +2,10 @@ import classNames from 'classnames' import { CircularProgress, useTheme } from '@mui/material' import { makeStyles, useStylesExtends } from '@masknet/theme' import { AssetPlayer } from '../AssetPlayer' -import { useImageChecker, useNonFungibleToken, Web3Helper } from '@masknet/plugin-infra/web3' +import { useNonFungibleToken, Web3Helper } from '@masknet/plugin-infra/web3' import type { ChainId } from '@masknet/web3-shared-evm' import { NetworkPluginID } from '@masknet/web3-shared-base' +import { useImageChecker } from '../../../hooks' const useStyles = makeStyles()((theme) => ({ wrapper: { diff --git a/packages/shared/src/UI/components/TokenIcon/index.tsx b/packages/shared/src/UI/components/TokenIcon/index.tsx index 44deda13b820..431fcaaff178 100644 --- a/packages/shared/src/UI/components/TokenIcon/index.tsx +++ b/packages/shared/src/UI/components/TokenIcon/index.tsx @@ -28,8 +28,8 @@ export interface TokenIconProps extends withClasses<'icon'> { export function TokenIcon(props: TokenIconProps) { const { address, logoURL, name, AvatarProps, classes } = props - const chainId = useChainId<'all'>(props.pluginID, props.chainId) - const hub = useWeb3Hub<'all'>(props.pluginID) + const chainId = useChainId(props.pluginID, props.chainId) + const hub = useWeb3Hub(props.pluginID) const { value: urls = EMPTY_LIST } = useAsyncRetry(async () => { const logoURLs = await hub?.getFungibleTokenIconURLs?.(chainId, address) diff --git a/packages/shared/src/hooks/index.ts b/packages/shared/src/hooks/index.ts index 23b1a243a6e8..499f0e697dc4 100644 --- a/packages/shared/src/hooks/index.ts +++ b/packages/shared/src/hooks/index.ts @@ -2,3 +2,4 @@ export * from './useMenu' export * from './useOpenShareTxDialog' export * from './useSnackbarCallback' export * from './useImageFailOver' +export * from './useImageChecker' diff --git a/packages/plugin-infra/src/web3/useImageChecker.ts b/packages/shared/src/hooks/useImageChecker.ts similarity index 100% rename from packages/plugin-infra/src/web3/useImageChecker.ts rename to packages/shared/src/hooks/useImageChecker.ts diff --git a/packages/web3-providers/src/debank/index.ts b/packages/web3-providers/src/debank/index.ts index f5fa3002d7ab..9969cc56a299 100644 --- a/packages/web3-providers/src/debank/index.ts +++ b/packages/web3-providers/src/debank/index.ts @@ -105,14 +105,14 @@ export class DeBankAPI async getTransactions( address: string, { chainId = ChainId.Mainnet }: HubOptions = {}, - ): Promise>> { + ): Promise>> { const { CHAIN_ID = '' } = getDeBankConstants(chainId) - if (!CHAIN_ID) return createPageable([], 0) + if (!CHAIN_ID) return [] const response = await fetch(`${DEBANK_API}/history/list?user_addr=${address.toLowerCase()}&chain=${CHAIN_ID}`) const { data, error_code } = (await response.json()) as HistoryResponse if (error_code !== 0) throw new Error('Fail to load transactions.') - return createPageable(formatTransactions(chainId, data), 0) + return formatTransactions(chainId, data) } } diff --git a/packages/web3-providers/src/types.ts b/packages/web3-providers/src/types.ts index 698518b0b00f..43ba406181e8 100644 --- a/packages/web3-providers/src/types.ts +++ b/packages/web3-providers/src/types.ts @@ -112,11 +112,11 @@ export namespace PriceAPI { } export namespace HistoryAPI { - export interface Provider { + export interface Provider { getTransactions( address: string, options?: HubOptions, - ): Promise, Indicator>> + ): Promise>> } } @@ -127,7 +127,7 @@ export namespace GasOptionAPI { } export namespace FungibleTokenAPI { - export interface Provider { + export interface Provider { getAssets( address: string, options?: HubOptions, @@ -136,7 +136,7 @@ export namespace FungibleTokenAPI { } export namespace NonFungibleTokenAPI { - export interface Provider { + export interface Provider { getAsset?: ( address: string, tokenId: string, diff --git a/packages/web3-providers/src/zerion/index.ts b/packages/web3-providers/src/zerion/index.ts index 7cb52cdf1cf0..5906b93f09f6 100644 --- a/packages/web3-providers/src/zerion/index.ts +++ b/packages/web3-providers/src/zerion/index.ts @@ -136,7 +136,7 @@ export class ZerionAPI async getTransactions( address: string, options?: HubOptions, - ): Promise>> { + ): Promise>> { let result: Array> = [] // xdai-assets is not support const pairs = getEnumAsArray(ChainId).map( @@ -151,6 +151,6 @@ export class ZerionAPI result = [...result, ...formatTransactions(chainId, payload.transactions)] } - return createPageable(result, 0) + return result } } diff --git a/packages/web3-shared/base/src/specs/index.ts b/packages/web3-shared/base/src/specs/index.ts index 2b5f99e4afad..3a14d55d0893 100644 --- a/packages/web3-shared/base/src/specs/index.ts +++ b/packages/web3-shared/base/src/specs/index.ts @@ -667,7 +667,7 @@ export interface Connection< cancelRequest(hash: string, config: Transaction, options?: Web3ConnectionOptions): Promise } -export interface HubOptions { +export interface HubOptions { /** The user account as the API parameter */ account?: string /** The chain id as the API parameter */ @@ -754,7 +754,7 @@ export interface Hub Promise /** Get the most recent transactions */ - getTransactions: (chainId: ChainId, account: string, options?: Web3HubOptions) => Promise>> + getTransactions: (chainId: ChainId, account: string, options?: Web3HubOptions) => Promise>> } export interface SettingsState { diff --git a/packages/web3-shared/base/src/utils/pagination.ts b/packages/web3-shared/base/src/utils/pagination.ts index fdc15c6fe73c..6fda1cd274c4 100644 --- a/packages/web3-shared/base/src/utils/pagination.ts +++ b/packages/web3-shared/base/src/utils/pagination.ts @@ -1,4 +1,4 @@ -export function createPageable( +export function createPageable( data: Item[], indicator: Indicator, nextIndicator?: Indicator, From 8d40875556a85f10b8702fcc8cb18b8dfd8be390 Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 01:44:13 +0800 Subject: [PATCH 07/14] fix: lint errors --- .../src/pages/Wallets/components/FungibleTokenTable/index.tsx | 2 +- packages/plugin-infra/src/web3/useBalance.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx index c92fface4fd4..8ba6fa217b7c 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx @@ -1,4 +1,4 @@ -import { memo, useCallback, useEffect, useMemo } from 'react' +import { memo, useCallback, useMemo } from 'react' import { useNavigate } from 'react-router-dom' import BigNumber from 'bignumber.js' import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material' diff --git a/packages/plugin-infra/src/web3/useBalance.ts b/packages/plugin-infra/src/web3/useBalance.ts index 80de24b40d7d..89d9ad950570 100644 --- a/packages/plugin-infra/src/web3/useBalance.ts +++ b/packages/plugin-infra/src/web3/useBalance.ts @@ -13,6 +13,6 @@ export function useBalance { if (!account || !connection) return '0' - return (connection.getBalance as GetBalance)(account) + return connection.getBalance(account) }, [account, connection]) } From 54a9a6257a845f10d15bb2f3cc5d7158392e96fa Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 01:59:16 +0800 Subject: [PATCH 08/14] fix: hub options --- packages/plugins/EVM/src/state/Hub/hub.ts | 29 ++++++++++++-------- packages/plugins/Flow/src/state/Hub/hub.ts | 12 ++++---- packages/plugins/Solana/src/state/Hub/hub.ts | 10 ++++--- 3 files changed, 31 insertions(+), 20 deletions(-) diff --git a/packages/plugins/EVM/src/state/Hub/hub.ts b/packages/plugins/EVM/src/state/Hub/hub.ts index 73080f89a386..6249c2bfab5e 100644 --- a/packages/plugins/EVM/src/state/Hub/hub.ts +++ b/packages/plugins/EVM/src/state/Hub/hub.ts @@ -44,8 +44,9 @@ class Hub implements EVM_Hub { chainId: ChainId, options?: HubOptions | undefined, ): Promise>> { - const { FUNGIBLE_TOKEN_LISTS = [] } = getTokenListConstants(chainId) - return TokenList.fetchFungibleTokensFromTokenLists(chainId, FUNGIBLE_TOKEN_LISTS) + const expectedChainId = options?.chainId ?? chainId + const { FUNGIBLE_TOKEN_LISTS = [] } = getTokenListConstants(expectedChainId) + return TokenList.fetchFungibleTokensFromTokenLists(expectedChainId, FUNGIBLE_TOKEN_LISTS) } async getNonFungibleTokensFromTokenList( chainId: ChainId, @@ -57,12 +58,14 @@ class Hub implements EVM_Hub { chainId: ChainId, options?: HubOptions | undefined, ): Promise> { + const expectedChainId = options?.chainId ?? chainId + try { - const isEIP1559 = chainResolver.isSupport(chainId, 'EIP1559') - if (isEIP1559) return await MetaSwap.getGasOptions(chainId) - return await DeBank.getGasOptions(chainId) + const isEIP1559 = chainResolver.isSupport(expectedChainId, 'EIP1559') + if (isEIP1559) return await MetaSwap.getGasOptions(expectedChainId) + return await DeBank.getGasOptions(expectedChainId) } catch (error) { - return EthereumWeb3.getGasOptions(chainId) + return EthereumWeb3.getGasOptions(expectedChainId) } } getFungibleAsset( @@ -111,13 +114,15 @@ class Hub implements EVM_Hub { address: string, options?: HubOptions | undefined, ): Promise { - const { PLATFORM_ID = '', COIN_ID = '' } = getCoinGeckoConstants(chainId) + const expectedChainId = options?.chainId ?? chainId + const expectedCurrencyType = options?.currencyType ?? this.currencyType + const { PLATFORM_ID = '', COIN_ID = '' } = getCoinGeckoConstants(expectedChainId) if (isNativeTokenAddress(address)) { - return CoinGecko.getTokenPriceByCoinId(COIN_ID, options?.currencyType ?? this.currencyType) + return CoinGecko.getTokenPriceByCoinId(COIN_ID, expectedCurrencyType) } - return CoinGecko.getTokenPrice(PLATFORM_ID, address, options?.currencyType ?? this.currencyType) + return CoinGecko.getTokenPrice(PLATFORM_ID, address, expectedCurrencyType) } getNonFungibleTokenPrice( chainId: ChainId, @@ -132,7 +137,8 @@ class Hub implements EVM_Hub { address: string, options?: HubOptions | undefined, ): Promise { - const { TOKEN_ASSET_BASE_URI = [] } = getTokenAssetBaseURLConstants(chainId) + const expectedChainId = options?.chainId ?? chainId + const { TOKEN_ASSET_BASE_URI = [] } = getTokenAssetBaseURLConstants(expectedChainId) const checkSummedAddress = formatEthereumAddress(address) if (isSameAddress(getTokenConstants().NATIVE_TOKEN_ADDRESS, checkSummedAddress)) { @@ -158,7 +164,8 @@ class Hub implements EVM_Hub { account: string, options?: HubOptions | undefined, ): Promise>> { - return DeBank.getTransactions(account, { chainId }) + const expectedChainId = options?.chainId ?? chainId + return DeBank.getTransactions(account, { chainId: expectedChainId }) } async *getAllFungibleAssets(address: string): AsyncIterableIterator> { diff --git a/packages/plugins/Flow/src/state/Hub/hub.ts b/packages/plugins/Flow/src/state/Hub/hub.ts index c95fff787d63..5db1d78e5311 100644 --- a/packages/plugins/Flow/src/state/Hub/hub.ts +++ b/packages/plugins/Flow/src/state/Hub/hub.ts @@ -29,10 +29,11 @@ class Hub implements FlowHub { chainId: ChainId, options?: HubOptions | undefined, ): Promise>> { - const { FLOW_ADDRESS = '', FUSD_ADDRESS = '', TETHER_ADDRESS = '' } = getTokenConstants(chainId) + const expectedChainId = options?.chainId ?? chainId + const { FLOW_ADDRESS = '', FUSD_ADDRESS = '', TETHER_ADDRESS = '' } = getTokenConstants(expectedChainId) return [ createFungibleToken( - chainId, + expectedChainId, FLOW_ADDRESS, 'Flow', 'FLOW', @@ -40,7 +41,7 @@ class Hub implements FlowHub { new URL('../../assets/flow.png', import.meta.url).toString(), ), createFungibleToken( - chainId, + expectedChainId, FUSD_ADDRESS, 'Flow USD', 'FUSD', @@ -48,7 +49,7 @@ class Hub implements FlowHub { new URL('../../assets/FUSD.png', import.meta.url).toString(), ), createFungibleToken( - chainId, + expectedChainId, TETHER_ADDRESS, 'Tether USD', 'tUSD', @@ -79,7 +80,8 @@ class Hub implements FlowHub { account: string, options?: HubOptions | undefined, ): Promise>> { - return FlowRPC.getFungibleAssets(options?.chainId ?? this.chainId, account) + const expectedChainId = options?.chainId ?? this.chainId + return FlowRPC.getFungibleAssets(expectedChainId, account) } async getNonFungibleAsset( address: string, diff --git a/packages/plugins/Solana/src/state/Hub/hub.ts b/packages/plugins/Solana/src/state/Hub/hub.ts index 1278cc049c2b..f72de540ce01 100644 --- a/packages/plugins/Solana/src/state/Hub/hub.ts +++ b/packages/plugins/Solana/src/state/Hub/hub.ts @@ -85,14 +85,16 @@ class Hub implements SolanaHub { address: string, options?: HubOptions | undefined, ): Promise { - const { PLATFORM_ID = '', COIN_ID = '' } = getCoinGeckoConstants(chainId) - const { SOL_ADDRESS } = getTokenConstants(chainId) + const expectedChainId = options?.chainId ?? chainId + const expectedCurrencyType = options?.currencyType ?? this.currencyType + const { PLATFORM_ID = '', COIN_ID = '' } = getCoinGeckoConstants(expectedChainId) + const { SOL_ADDRESS } = getTokenConstants(expectedChainId) if (isSameAddress(address, SOL_ADDRESS)) { - return CoinGecko.getTokenPriceByCoinId(COIN_ID, options?.currencyType ?? this.currencyType) + return CoinGecko.getTokenPriceByCoinId(COIN_ID, expectedCurrencyType) } - return CoinGecko.getTokenPrice(PLATFORM_ID, address, options?.currencyType ?? this.currencyType) + return CoinGecko.getTokenPrice(PLATFORM_ID, address, expectedCurrencyType) } getNonFungibleTokenPrice( chainId: ChainId, From 563d64d5d4db35a7a70a6976e3111a12f8305169 Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 12:50:52 +0800 Subject: [PATCH 09/14] fix: token icon url --- .../components/FungibleTokenTable/index.tsx | 41 ++++++++++++++++--- .../src/web3/useFungibleAssets.ts | 18 ++++++++ .../src/UI/components/TokenIcon/index.tsx | 5 +-- .../evm/token-asset-base-url.json | 20 +++++++-- .../web3-shared/evm/constants/chains.json | 9 ++-- 5 files changed, 75 insertions(+), 18 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx index 8ba6fa217b7c..19b3c064a487 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx @@ -7,11 +7,18 @@ import { useDashboardI18N } from '../../../../locales' import { EmptyPlaceholder } from '../EmptyPlaceholder' import { LoadingPlaceholder } from '../../../../components/LoadingPlaceholder' import { FungibleTokenTableRow } from '../FungibleTokenTableRow' -import { CurrencyType, formatBalance, FungibleAsset, minus, NetworkPluginID, toZero } from '@masknet/web3-shared-base' import { DashboardRoutes, EMPTY_LIST } from '@masknet/shared-base' -import { useCurrentWeb3NetworkPluginID, useFungibleAssets, useWeb3State, Web3Helper } from '@masknet/plugin-infra/web3' -import { PluginMessages } from '../../../../API' import { useRemoteControlledDialog } from '@masknet/shared-base-ui' +import { CurrencyType, formatBalance, FungibleAsset, minus, NetworkPluginID, toZero } from '@masknet/web3-shared-base' +import { + useCurrentWeb3NetworkPluginID, + useFungibleAssets, + useNativeToken, + useWeb3State, + Web3Helper, +} from '@masknet/plugin-infra/web3' +import { PluginMessages } from '../../../../API' +import type { ChainId } from '@masknet/web3-shared-evm' const useStyles = makeStyles()((theme) => ({ container: { @@ -56,16 +63,21 @@ const useStyles = makeStyles()((theme) => ({ })) interface TokenTableProps { - selectedChainId: number | null + selectedChainId?: ChainId } export const FungibleTokenTable = memo(({ selectedChainId }) => { const navigate = useNavigate() + const { value: nativeToken } = useNativeToken(NetworkPluginID.PLUGIN_EVM, { + chainId: selectedChainId, + }) const { value: fungibleAssets = EMPTY_LIST, loading: fungibleAssetsLoading, error: fungibleAssetsError, - } = useFungibleAssets(NetworkPluginID.PLUGIN_EVM) + } = useFungibleAssets(NetworkPluginID.PLUGIN_EVM, undefined, { + chainId: selectedChainId, + }) const { setDialog: openSwapDialog } = useRemoteControlledDialog(PluginMessages.Swap.swapDialogUpdated) const onSwap = useCallback( @@ -115,8 +127,25 @@ export const FungibleTokenTable = memo(({ selectedChainId }) => return 0 }) + if (!results.length && nativeToken) { + return [ + { + ...nativeToken, + balance: '0', + }, + ] + } + return results - }, [fungibleAssets, selectedChainId]) + }, [nativeToken, fungibleAssets, selectedChainId]) + + console.log('DEBUG: dataSource') + console.log({ + selectedChainId, + fungibleAssets, + nativeToken, + dataSource, + }) return ( >>(async () => { if (!account || !hub) return EMPTY_LIST @@ -36,6 +50,10 @@ export function useFungibleAssets< const assets = await asyncIteratorToArray(hub?.getAllFungibleAssets?.(account)) const filteredAssets = assets.length && schemaType ? assets.filter((x) => x.schema === schemaType) : assets + console.log({ + assets, + }) + return filteredAssets .filter((x) => !isBlockedToken(x)) .sort((a, z) => { diff --git a/packages/shared/src/UI/components/TokenIcon/index.tsx b/packages/shared/src/UI/components/TokenIcon/index.tsx index 431fcaaff178..f04485b8ad90 100644 --- a/packages/shared/src/UI/components/TokenIcon/index.tsx +++ b/packages/shared/src/UI/components/TokenIcon/index.tsx @@ -8,6 +8,7 @@ import { useImageFailOver } from '../../../hooks' import { useAsyncRetry } from 'react-use' import { EMPTY_LIST } from '@masknet/shared-base' import { useImageBase64 } from '../../../hooks/useImageBase64' +import { first } from 'lodash-es' const useStyles = makeStyles()((theme) => ({ icon: { @@ -35,9 +36,7 @@ export function TokenIcon(props: TokenIconProps) { const logoURLs = await hub?.getFungibleTokenIconURLs?.(chainId, address) return [logoURL, ...(logoURLs ?? [])].filter(Boolean) as string[] }, [chainId, address, logoURL, hub]) - - const { value: trustedLogoURL } = useImageFailOver(urls, '') - const base64 = useImageBase64(`${address}_${chainId}`, trustedLogoURL) + const base64 = useImageBase64(`${address}_${chainId}`, first(urls)) return } diff --git a/packages/web3-constants/evm/token-asset-base-url.json b/packages/web3-constants/evm/token-asset-base-url.json index 2f84ef4263c0..27db391aef51 100644 --- a/packages/web3-constants/evm/token-asset-base-url.json +++ b/packages/web3-constants/evm/token-asset-base-url.json @@ -36,17 +36,29 @@ "https://raw.githubusercontent.com/dimensiondev/assets/master/blockchains/polygon", "https://rawcdn.githack.com/dimensiondev/assets/master/blockchains/polygon" ], - "Arbitrum": [], + "Arbitrum": [ + "https://raw.githubusercontent.com/dimensiondev/assets/master/blockchains/atbitrum", + "https://rawcdn.githack.com/dimensiondev/assets/master/blockchains/atbitrum" + ], "Arbitrum_Rinkeby": [], - "xDai": [], + "xDai": [ + "https://raw.githubusercontent.com/dimensiondev/assets/master/blockchains/xdai", + "https://rawcdn.githack.com/dimensiondev/assets/master/blockchains/xdai" + ], "Avalanche": [ "https://raw.githubusercontent.com/dimensiondev/assets/master/blockchains/avalanchec", "https://rawcdn.githack.com/dimensiondev/assets/master/blockchains/avalanchec" ], "Avalanche_Fuji": [], "Celo": [], - "Fantom": [], - "Aurora": [], + "Fantom": [ + "https://raw.githubusercontent.com/dimensiondev/assets/master/blockchains/fantom", + "https://rawcdn.githack.com/dimensiondev/assets/master/blockchains/fantom" + ], + "Aurora": [ + "https://raw.githubusercontent.com/dimensiondev/assets/master/blockchains/aurora", + "https://rawcdn.githack.com/dimensiondev/assets/master/blockchains/aurora" + ], "Aurora_Testnet": [], "Conflux": [], "Harmony": [ diff --git a/packages/web3-shared/evm/constants/chains.json b/packages/web3-shared/evm/constants/chains.json index 5f4caf87073f..f741a772f625 100644 --- a/packages/web3-shared/evm/constants/chains.json +++ b/packages/web3-shared/evm/constants/chains.json @@ -1296,15 +1296,15 @@ "chainId": 250, "name": "Fantom", "symbol": "FTM", - "decimals": 18 + "decimals": 18, + "logoURL": "https://static.debank.com/image/ftm_token/logo_url/ftm/33fdb9c5067e94f3a1b9e78f6fa86984.png" }, "infoURL": "https://fantom.foundation", "explorers": [ { "name": "ftmscan", "url": "https://ftmscan.com", - "standard": "EIP3091", - "logoURL": "https://static.debank.com/image/ftm_token/logo_url/ftm/33fdb9c5067e94f3a1b9e78f6fa86984.png" + "standard": "EIP3091" } ] }, @@ -2225,8 +2225,7 @@ { "name": "snowtrace", "url": "https://snowtrace.io/", - "standard": "EIP3091", - "logoURL": "https://snowtrace.io/images/svg/brands/main.svg?v=21.12.4.1" + "standard": "EIP3091" } ] }, From f05f7d7731b32e279ec332c6a6b0675d9a1b05df Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 13:08:54 +0800 Subject: [PATCH 10/14] fix: build error --- .../dashboard/src/pages/Wallets/components/Assets/index.tsx | 2 +- .../pages/Wallets/components/FungibleTokenTable/index.tsx | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/Assets/index.tsx b/packages/dashboard/src/pages/Wallets/components/Assets/index.tsx index 53927168aa98..ad3eb05a19e8 100644 --- a/packages/dashboard/src/pages/Wallets/components/Assets/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/Assets/index.tsx @@ -99,7 +99,7 @@ export const Assets = memo(({ network }) => { )} - + ({ })) interface TokenTableProps { - selectedChainId?: ChainId + selectedChainId?: Web3Helper.ChainIdAll } export const FungibleTokenTable = memo(({ selectedChainId }) => { const navigate = useNavigate() - const { value: nativeToken } = useNativeToken(NetworkPluginID.PLUGIN_EVM, { + const { value: nativeToken } = useNativeToken<'all'>(NetworkPluginID.PLUGIN_EVM, { chainId: selectedChainId, }) const { value: fungibleAssets = EMPTY_LIST, loading: fungibleAssetsLoading, error: fungibleAssetsError, - } = useFungibleAssets(NetworkPluginID.PLUGIN_EVM, undefined, { + } = useFungibleAssets<'all'>(NetworkPluginID.PLUGIN_EVM, undefined, { chainId: selectedChainId, }) const { setDialog: openSwapDialog } = useRemoteControlledDialog(PluginMessages.Swap.swapDialogUpdated) From d12bf9034450f731f078d60a178ff7ebf3c8eca2 Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 13:13:50 +0800 Subject: [PATCH 11/14] refactor: remove logs --- .../Wallets/components/FungibleTokenTable/index.tsx | 8 -------- packages/plugin-infra/src/web3/useFungibleAssets.ts | 11 ----------- 2 files changed, 19 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx index 5caace1de543..5b211f7f0bda 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx @@ -139,14 +139,6 @@ export const FungibleTokenTable = memo(({ selectedChainId }) => return results }, [nativeToken, fungibleAssets, selectedChainId]) - console.log('DEBUG: dataSource') - console.log({ - selectedChainId, - fungibleAssets, - nativeToken, - dataSource, - }) - return ( >>(async () => { if (!account || !hub) return EMPTY_LIST const isTrustedToken = currySameAddress(trustedTokens.map((x) => x.address)) @@ -50,10 +43,6 @@ export function useFungibleAssets< const assets = await asyncIteratorToArray(hub?.getAllFungibleAssets?.(account)) const filteredAssets = assets.length && schemaType ? assets.filter((x) => x.schema === schemaType) : assets - console.log({ - assets, - }) - return filteredAssets .filter((x) => !isBlockedToken(x)) .sort((a, z) => { From aa5c52815f21e9cd6b801a36b4c7e83d390b5ecd Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 13:22:06 +0800 Subject: [PATCH 12/14] refactor: add global resolver --- .../web3-shared/base/src/utils/resolver.ts | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/web3-shared/base/src/utils/resolver.ts b/packages/web3-shared/base/src/utils/resolver.ts index 3ed1c21bcb68..487a1483e5ac 100644 --- a/packages/web3-shared/base/src/utils/resolver.ts +++ b/packages/web3-shared/base/src/utils/resolver.ts @@ -1,5 +1,5 @@ import urlcat from 'urlcat' -import type { ChainDescriptor, NetworkDescriptor, ProviderDescriptor } from '../specs' +import { ChainDescriptor, CurrencyType, NetworkDescriptor, ProviderDescriptor, SourceType } from '../specs' export function createLookupTableResolver(map: Record, fallback: T | ((key: K) => T)) { function resolveFallback(key: K) { @@ -157,3 +157,29 @@ export type ReturnNetworkResolver = ReturnType< export type ReturnProviderResolver = ReturnType< Wrapper['createProviderResolver'] > + +export const resolveSourceName = createLookupTableResolver( + { + [SourceType.DeBank]: 'DeBank', + [SourceType.Zerion]: 'Zerion', + [SourceType.RSS3]: 'RSS3', + [SourceType.OpenSea]: 'OpenSea', + [SourceType.Rarible]: 'Rarible', + [SourceType.NFTScan]: 'NFTScan', + [SourceType.Zora]: 'Zora', + }, + (providerType) => { + throw new Error(`Unknown provider type: ${providerType}.`) + }, +) + +export const resolveCurrencyName = createLookupTableResolver( + { + [CurrencyType.BTC]: 'BTC', + [CurrencyType.NATIVE]: 'ETH', + [CurrencyType.USD]: 'USD', + }, + (CurrencyType) => { + throw new Error(`Unknown currency type: ${CurrencyType}.`) + }, +) From 1dead72cbec7d7673aa1eee532862c50966f3b98 Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 13:22:25 +0800 Subject: [PATCH 13/14] fix: lint errors --- .../src/pages/Wallets/components/FungibleTokenTable/index.tsx | 1 - packages/plugin-infra/src/web3/useGasOptions.ts | 2 +- packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts | 2 +- packages/shared/src/UI/components/TokenIcon/index.tsx | 3 +-- packages/web3-providers/src/zerion/index.ts | 2 +- 5 files changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx index 5b211f7f0bda..eb699e9b35fb 100644 --- a/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx +++ b/packages/dashboard/src/pages/Wallets/components/FungibleTokenTable/index.tsx @@ -18,7 +18,6 @@ import { Web3Helper, } from '@masknet/plugin-infra/web3' import { PluginMessages } from '../../../../API' -import type { ChainId } from '@masknet/web3-shared-evm' const useStyles = makeStyles()((theme) => ({ container: { diff --git a/packages/plugin-infra/src/web3/useGasOptions.ts b/packages/plugin-infra/src/web3/useGasOptions.ts index 1b2e620fbd41..eedbb569844e 100644 --- a/packages/plugin-infra/src/web3/useGasOptions.ts +++ b/packages/plugin-infra/src/web3/useGasOptions.ts @@ -1,5 +1,5 @@ import { useAsyncRetry } from 'react-use' -import type { GasOptionType, NetworkPluginID } from '@masknet/web3-shared-base' +import type { NetworkPluginID } from '@masknet/web3-shared-base' import type { Web3Helper } from '../web3-helpers' import { useChainId } from './useChainId' import { useWeb3Hub } from './useWeb3Hub' diff --git a/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts b/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts index 88f67afa59d5..f634df76773c 100644 --- a/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts +++ b/packages/plugin-infra/src/web3/useTrustedFungibleTokens.ts @@ -1,5 +1,5 @@ import { useMemo } from 'react' -import { Subscription, useSubscription } from 'use-subscription' +import { useSubscription } from 'use-subscription' import type { NetworkPluginID } from '@masknet/web3-shared-base' import { EMPTY_ARRAY } from '../utils/subscription' import type { Web3Helper } from '../web3-helpers' diff --git a/packages/shared/src/UI/components/TokenIcon/index.tsx b/packages/shared/src/UI/components/TokenIcon/index.tsx index f04485b8ad90..26dadc46be65 100644 --- a/packages/shared/src/UI/components/TokenIcon/index.tsx +++ b/packages/shared/src/UI/components/TokenIcon/index.tsx @@ -1,11 +1,10 @@ import { memo } from 'react' +import { useAsyncRetry } from 'react-use' import { Avatar, AvatarProps } from '@mui/material' import { makeStyles, useStylesExtends } from '@masknet/theme' import NO_IMAGE_COLOR from './constants' import { useChainId, useWeb3Hub, Web3Helper } from '@masknet/plugin-infra/web3' import type { NetworkPluginID } from '@masknet/web3-shared-base' -import { useImageFailOver } from '../../../hooks' -import { useAsyncRetry } from 'react-use' import { EMPTY_LIST } from '@masknet/shared-base' import { useImageBase64 } from '../../../hooks/useImageBase64' import { first } from 'lodash-es' diff --git a/packages/web3-providers/src/zerion/index.ts b/packages/web3-providers/src/zerion/index.ts index 5906b93f09f6..c90375e6523f 100644 --- a/packages/web3-providers/src/zerion/index.ts +++ b/packages/web3-providers/src/zerion/index.ts @@ -1,7 +1,7 @@ import io from 'socket.io-client' import { values } from 'lodash-unified' import { getEnumAsArray } from '@dimensiondev/kit' -import { FungibleAsset, Pageable, Transaction, HubOptions, createPageable } from '@masknet/web3-shared-base' +import { FungibleAsset, Transaction, HubOptions, createPageable } from '@masknet/web3-shared-base' import { ChainId, getZerionConstants, SchemaType } from '@masknet/web3-shared-evm' import type { SocketRequestBody, From 7dd9e7841a0cf2e4abd880c24952e85ada28e6ed Mon Sep 17 00:00:00 2001 From: guanbinrui Date: Fri, 10 Jun 2022 13:32:13 +0800 Subject: [PATCH 14/14] fix: lint errors --- packages/plugin-infra/src/web3/useFungibleToken.ts | 2 +- packages/shared/src/UI/components/TokenIcon/index.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plugin-infra/src/web3/useFungibleToken.ts b/packages/plugin-infra/src/web3/useFungibleToken.ts index 727eb8febb4e..c0392d916487 100644 --- a/packages/plugin-infra/src/web3/useFungibleToken.ts +++ b/packages/plugin-infra/src/web3/useFungibleToken.ts @@ -12,6 +12,6 @@ export function useFungibleToken | undefined>(async () => { if (!connection) return - return (connection?.getFungibleToken)(address ?? '', options) + return connection?.getFungibleToken?.(address ?? '', options) }, [address, connection]) } diff --git a/packages/shared/src/UI/components/TokenIcon/index.tsx b/packages/shared/src/UI/components/TokenIcon/index.tsx index 26dadc46be65..040fa4f66a53 100644 --- a/packages/shared/src/UI/components/TokenIcon/index.tsx +++ b/packages/shared/src/UI/components/TokenIcon/index.tsx @@ -1,5 +1,6 @@ import { memo } from 'react' import { useAsyncRetry } from 'react-use' +import { first } from 'lodash-unified' import { Avatar, AvatarProps } from '@mui/material' import { makeStyles, useStylesExtends } from '@masknet/theme' import NO_IMAGE_COLOR from './constants' @@ -7,7 +8,6 @@ import { useChainId, useWeb3Hub, Web3Helper } from '@masknet/plugin-infra/web3' import type { NetworkPluginID } from '@masknet/web3-shared-base' import { EMPTY_LIST } from '@masknet/shared-base' import { useImageBase64 } from '../../../hooks/useImageBase64' -import { first } from 'lodash-es' const useStyles = makeStyles()((theme) => ({ icon: {