Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: chain detailed #3679

Merged
merged 7 commits into from
Jul 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion packages/maskbook/src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,6 @@
"plugin_wallet_switch_network": "Swtich to {{network}}",
"plugin_wallet_switch_network_under_going": "Switching to {{network}}…",
"plugin_wallet_not_availabe_on": "Not available on {{network}}.",
"plugin_wallet_swtich_to": "Please switch to {{network}} on {{provider}}.",
"plugin_wallet_settings_portfolio_data_source_primary": "Portfolio Data Source",
"plugin_wallet_settings_portfolio_data_source_secondary": "Select the source of portfolio data.",
"plugin_wallet_settings_collectible_data_source_primary": "Collectible Data Source",
Expand Down
1 change: 0 additions & 1 deletion packages/maskbook/src/_locales/ja/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,6 @@
"plugin_wallet_switch_network": "",
"plugin_wallet_switch_network_under_going": "",
"plugin_wallet_not_availabe_on": "",
"plugin_wallet_swtich_to": "",
"plugin_wallet_settings_portfolio_data_source_primary": "ポートフォリオデータのソーズ",
"plugin_wallet_settings_portfolio_data_source_secondary": "ポートフォリオデータのソースを選択",
"plugin_wallet_settings_collectible_data_source_primary": "コレクションデータのソース",
Expand Down
1 change: 0 additions & 1 deletion packages/maskbook/src/_locales/ko/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,6 @@
"plugin_wallet_switch_network": "",
"plugin_wallet_switch_network_under_going": "",
"plugin_wallet_not_availabe_on": "",
"plugin_wallet_swtich_to": "",
"plugin_wallet_settings_portfolio_data_source_primary": "포트폴리오 데이터 소스",
"plugin_wallet_settings_portfolio_data_source_secondary": "포트폴리오 데이터 소스 선택",
"plugin_wallet_settings_collectible_data_source_primary": "수집품 데이터 소스",
Expand Down
1 change: 0 additions & 1 deletion packages/maskbook/src/_locales/zh/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,6 @@
"plugin_wallet_switch_network": "",
"plugin_wallet_switch_network_under_going": "",
"plugin_wallet_not_availabe_on": "",
"plugin_wallet_swtich_to": "",
"plugin_wallet_settings_portfolio_data_source_primary": "投資組合資料來源",
"plugin_wallet_settings_portfolio_data_source_secondary": "選擇投資組合資料來源。",
"plugin_wallet_settings_collectible_data_source_primary": "收藏品資料來源",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import {
ERC20TokenDetailed,
EthereumTokenType,
formatEthereumAddress,
getChainDetailed,
isChainIdValid,
} from '@masknet/web3-shared'
import { Flags } from '../../../utils'

interface TokenList {
keywords: string[]
Expand Down Expand Up @@ -45,13 +46,7 @@ export async function fetchERC20TokensFromTokenList(
chainId = ChainId.Mainnet,
): Promise<ERC20TokenDetailed[]> {
return (await fetchTokenList(url)).tokens
.filter(
(x) =>
x.chainId === chainId &&
(process.env.NODE_ENV === 'production' && process.env.build === 'stable'
? getChainDetailed(chainId)?.network === 'mainnet'
: true),
)
.filter((x) => x.chainId === chainId && isChainIdValid(chainId, Flags.wallet_allow_testnet))
.map((x) => ({
type: EthereumTokenType.ERC20,
...x,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function PostInspector(props: PostInspectorProps) {
(t) =>
({
address: t.address,
type: isSameAddress(t.address, NATIVE_TOKEN_ADDRESS)
type: isSameAddress(t.address, NATIVE_TOKEN_ADDRESS ?? '')
Copy link
Member Author

@guanbinrui guanbinrui Jul 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why will NATIVE_TOKEN_ADDRESS be yield to undefined? If it could beundefined, then the typing is wrong.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use isNative

export const isNative = currySameAddress(getTokenConstants().NATIVE_TOKEN_ADDRESS)

? EthereumTokenType.Native
: EthereumTokenType.ERC20,
} as Pick<FungibleToken, 'address' | 'type'>),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,7 @@ export function RedPacket(props: RedPacketProps) {
// the red packet can fetch without account
if (!availability || !token)
return (
<EthereumChainBoundary
chainId={payload.network ? getChainIdFromName(payload.network) ?? ChainId.Mainnet : ChainId.Mainnet}>
<EthereumChainBoundary chainId={getChainIdFromName(payload.network ?? '') ?? ChainId.Mainnet}>
<Card className={classes.root} component="article" elevation={0}>
<Skeleton
animation="wave"
Expand Down Expand Up @@ -258,8 +257,7 @@ export function RedPacket(props: RedPacketProps) {
)

return (
<EthereumChainBoundary
chainId={payload.network ? getChainIdFromName(payload.network) ?? ChainId.Mainnet : ChainId.Mainnet}>
<EthereumChainBoundary chainId={getChainIdFromName(payload.network ?? '') ?? ChainId.Mainnet}>
<Card className={classNames(classes.root)} component="article" elevation={0}>
<div className={classes.header}>
<Typography className={classes.from} variant="body1" color="inherit">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function useAvailabilityComputed(account: string, payload: RedPacketJSONP
const isClaimed = availability.claimed_amount ? availability.claimed_amount !== '0' : availability.ifclaimed
const isRefunded = isEmpty && Number.parseInt(availability.claimed, 10) < Number.parseInt(availability.total, 10)
const isCreator = isSameAddress(payload?.sender.address ?? '', account)
const parsedChainId = payload.network ? getChainIdFromName(payload.network) : ChainId.Mainnet
const parsedChainId = getChainIdFromName(payload.network ?? '') ?? ChainId.Mainnet
Copy link
Member Author

@guanbinrui guanbinrui Jul 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cc @zhouhanseng The parsedChainid will not be undefined.

return {
...asyncResult,
computed: {
Expand Down
4 changes: 2 additions & 2 deletions packages/maskbook/src/plugins/RedPacket/SNSAdaptor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Plugin } from '@masknet/plugin-infra'
import { EthereumTokenType, formatBalance, getChainDetailed, getChainIdFromName } from '@masknet/web3-shared'
import { ChainId, EthereumTokenType, formatBalance, getChainDetailed, getChainIdFromName } from '@masknet/web3-shared'
import MaskbookPluginWrapper from '../../MaskbookPluginWrapper'
import { base } from '../base'
import { RedPacketMetaKey } from '../constants'
Expand All @@ -25,7 +25,7 @@ const sns: Plugin.SNSAdaptor.Definition = {
[
RedPacketMetaKey,
(payload: RedPacketJSONPayload) => {
const chainId = getChainIdFromName(payload.network ?? 'ETH')
const chainId = getChainIdFromName(payload.network ?? '') ?? ChainId.Mainnet
const chainDetailed = getChainDetailed(chainId)
const tokenDetailed =
payload.token_type === EthereumTokenType.Native ? chainDetailed?.nativeCurrency : payload.token
Expand Down
52 changes: 25 additions & 27 deletions packages/maskbook/src/plugins/Wallet/services/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
CurrencyType,
EthereumTokenType,
formatEthereumAddress,
getChainDetailed,
getChainIdFromName,
getTokenConstants,
isChainIdMainnet,
NetworkType,
pow10,
} from '@masknet/web3-shared'
Expand Down Expand Up @@ -101,32 +101,30 @@ export async function getAssetsList(
}

function formatAssetsFromDebank(data: BalanceRecord[]) {
return data.map((x): Asset => {
const chainId = getChainIdFromName(x.id)
return {
chain: x.chain,
token:
chainId && getChainDetailed(chainId)?.network === 'mainnet'
? createNativeToken(getChainIdFromName(x.id) ?? ChainId.Mainnet)
: createERC20Token(
getChainIdFromName(x.chain) ?? ChainId.Mainnet,
formatEthereumAddress(x.id),
x.decimals,
x.name,
x.symbol,
),
balance: new BigNumber(x.balance).toFixed(),
price: {
[CurrencyType.USD]: new BigNumber(x.price).toFixed(),
},
value: {
[CurrencyType.USD]: new BigNumber(x.price)
.multipliedBy(new BigNumber(x.balance).dividedBy(pow10(x.decimals)))
.toFixed(),
},
logoURL: x.logo_url,
}
})
return data
.filter((x) => getChainIdFromName(x.chain))
.map((y): Asset => {
const chainId = getChainIdFromName(y.chain) ?? ChainId.Mainnet
// the asset id is the token address or the name of the chain
const chainIdFormId = getChainIdFromName(y.id)
return {
chain: y.chain,
token:
chainIdFormId && isChainIdMainnet(chainIdFormId)
? createNativeToken(chainId)
: createERC20Token(chainId, formatEthereumAddress(y.id), y.decimals, y.name, y.symbol),
balance: new BigNumber(y.balance).toFixed(),
price: {
[CurrencyType.USD]: new BigNumber(y.price).toFixed(),
},
value: {
[CurrencyType.USD]: new BigNumber(y.price)
.multipliedBy(new BigNumber(y.balance).dividedBy(pow10(y.decimals)))
.toFixed(),
},
logoURL: y.logo_url,
}
})
}

const filterAssetType = ['compound', 'trash', 'uniswap', 'uniswap-v2', 'nft']
Expand Down
27 changes: 7 additions & 20 deletions packages/maskbook/src/web3/UI/EthereumChainBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ import {
getNetworkTypeFromChainId,
NetworkType,
ProviderType,
resolveProviderName,
useAccount,
useAllowTestnet,
useChainDetailed,
useChainId,
useChainIdValid,
} from '@masknet/web3-shared'
import { useValueRef, delay } from '@masknet/shared'
import { ActionButtonPromise } from '../../extension/options-page/DashboardComponents/ActionButton'
Expand All @@ -29,20 +27,16 @@ export function EthereumChainBoundary(props: EthereumChainBoundaryProps) {
const { t } = useI18N()
const account = useAccount()
const chainId = useChainId()
const chainDetailed = useChainDetailed()
const allowTestnet = useAllowTestnet()
const chainIdValid = useChainIdValid()
const providerType = useValueRef(currentProviderSettings)

const expectedChainId = props.chainId
const expectedNetwork = getChainName(expectedChainId)
const acutalChainId = chainId
const actualNetwork = getChainName(acutalChainId)

// if false then the user should switch network manually
const isSwitchable = true

// if testnets were not allowed it will not guide the user to switch the network
const isAllowed = allowTestnet || chainDetailed?.network === 'mainnet'
// if false then it will not guide the user to switch the network
const isAllowed = chainIdValid && !!account

const onSwitch = useCallback(async () => {
// a short time loading makes the user fells better
Expand All @@ -67,8 +61,9 @@ export function EthereumChainBoundary(props: EthereumChainBoundaryProps) {
if (!networkType) return
if (networkType === NetworkType.Ethereum) await Services.Ethereum.switchEthereumChain(expectedChainId)
else await Services.Ethereum.addEthereumChain(chainDetailedCAIP, account)
}, [account, isAllowed, isSwitchable, providerType, expectedChainId])
}, [account, isAllowed, providerType, expectedChainId])

// matched
if (acutalChainId === expectedChainId) return <>{props.children}</>

if (!isAllowed)
Expand All @@ -92,16 +87,8 @@ export function EthereumChainBoundary(props: EthereumChainBoundaryProps) {
network: actualNetwork,
})}
</span>
{isSwitchable ? null : (
<span>
{t('plugin_wallet_swtich_to', {
network: expectedNetwork,
provider: resolveProviderName(providerType),
})}
</span>
)}
</Typography>
{isSwitchable ? (
{isAllowed ? (
<ActionButtonPromise
variant="contained"
size="small"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export function EthereumWalletConnectedBoundary(props: EthereumWalletConnectedBo
</Grid>
)

if (!chainIdValid)
if (!chainIdValid && !offChain)
return (
<Grid container>
<ActionButton className={classes.button} disabled fullWidth variant="contained" size="large">
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/src/UI/components/TokenIcon/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { useStylesExtends } from '../../UIHelper/custom-ui-helper'
function resolveTokenIconURLs(address: string, baseURIs: string[], chainId: ChainId, logoURI?: string) {
const checkSummedAddress = formatEthereumAddress(address)

if (isSameAddress(getTokenConstants().NATIVE_TOKEN_ADDRESS, checkSummedAddress)) {
if (isSameAddress(getTokenConstants().NATIVE_TOKEN_ADDRESS ?? '', checkSummedAddress)) {
return baseURIs.map((x) => `${x}/info/logo.png`)
}

Expand Down Expand Up @@ -57,7 +57,7 @@ export function TokenIcon(props: TokenIconProps) {
const chainDetailed = useChainDetailed()
const tokenBlockie = useBlockie(address)
const { TOKEN_ASSET_BASE_URI } = useTokenAssetBaseURLConstants(chainId)
const tokenURIs = resolveTokenIconURLs(address, TOKEN_ASSET_BASE_URI, chainId ?? chainId_, logoURI)
const tokenURIs = resolveTokenIconURLs(address, TOKEN_ASSET_BASE_URI ?? [], chainId ?? chainId_, logoURI)
const { value: logoURL, loading } = useImageFailOver(chainDetailed ? tokenURIs : [], '')

return (
Expand Down
18 changes: 9 additions & 9 deletions packages/web3-shared/src/assets/chains.json
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@
},
{
"name": "Optimistic Ethereum",
"chain": "ETH",
"chain": "OPT",
"network": "mainnet",
"rpc": ["https://mainnet.optimism.io/"],
"faucets": [],
Expand Down Expand Up @@ -367,7 +367,7 @@
},
{
"name": "ELA-ETH-Sidechain Mainnet",
"chain": "ETH",
"chain": "ELA-ETH",
"network": "mainnet",
"rpc": ["https://mainrpc.elaeth.io"],
"faucets": [],
Expand All @@ -379,7 +379,7 @@
},
{
"name": "ELA-ETH-Sidechain Testnet",
"chain": "ETH",
"chain": "ELA-ETH",
"network": "testnet",
"rpc": ["https://rpc.elaeth.io"],
"faucets": ["https://faucet.elaeth.io/"],
Expand All @@ -391,7 +391,7 @@
},
{
"name": "ELA-DID-Sidechain Mainnet",
"chain": "ETH",
"chain": "ELA-ETH",
"network": "mainnet",
"rpc": [],
"faucets": [],
Expand All @@ -403,7 +403,7 @@
},
{
"name": "ELA-DID-Sidechain Testnet",
"chain": "ETH",
"chain": "ELA-ETH",
"network": "testnet",
"rpc": [],
"faucets": [],
Expand Down Expand Up @@ -729,7 +729,7 @@
},
{
"name": "Optimistic Ethereum Testnet Kovan",
"chain": "ETH",
"chain": "OPT",
"network": "kovan",
"rpc": ["https://kovan.optimism.io/"],
"faucets": [],
Expand Down Expand Up @@ -1028,7 +1028,7 @@
},
{
"name": "HOO Smart Chain Testnet",
"chain": "ETH",
"chain": "HOO",
"network": "testnet",
"rpc": ["https://http-testnet.hoosmartchain.com"],
"faucets": ["https://faucet-testnet.hscscan.com/"],
Expand Down Expand Up @@ -1142,7 +1142,7 @@
},
{
"name": "Optimistic Ethereum Testnet Goerli",
"chain": "ETH",
"chain": "OPT",
"network": "goerli",
"rpc": ["https://goerli.optimism.io/"],
"faucets": [],
Expand Down Expand Up @@ -1936,7 +1936,7 @@
},
{
"name": "Firenze test network",
"chain": "ETH",
"chain": "FIR",
"network": "testnet",
"rpc": ["https://ethnode.primusmoney.com/firenze"],
"faucets": [],
Expand Down
4 changes: 2 additions & 2 deletions packages/web3-shared/src/context/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useContext, createContext } from 'react'
import { createContainer } from 'unstated-next'
import { useSubscription } from 'use-subscription'
import type { Web3ProviderType } from './type'
import { getChainDetailed } from '../utils'
import { getChainDetailed, isChainIdValid } from '../utils'

export type { Web3ProviderType } from './type'

Expand Down Expand Up @@ -46,7 +46,7 @@ export function useWeb3State() {
erc20Tokens,
erc20TokensCount,
portfolioProvider,
chainIdValid: !account || !!(allowTestnet && chainDetailed) || chainDetailed?.network === 'mainnet',
chainIdValid: !account || isChainIdValid(chainId, allowTestnet),
}
}

Expand Down
5 changes: 5 additions & 0 deletions packages/web3-shared/src/hooks/useChainIdValid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { useWeb3StateContext } from '../context'

export function useChainIdValid() {
return useWeb3StateContext().chainIdValid
}
Loading