Skip to content

Commit

Permalink
refactor: improve code (#6377)
Browse files Browse the repository at this point in the history
* refactort: kv storage

* refactor: simple provider state

* refactor: update comments

* fix: USD formatter

* fix: format currency

* fix: comments

* refactor: reduce code

* refactor: disable pt

Co-authored-by: unclebill <[email protected]>
  • Loading branch information
guanbinrui and UncleBill authored May 30, 2022
1 parent dbace05 commit 70da94b
Show file tree
Hide file tree
Showing 29 changed files with 133 additions and 173 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ const ContractInteraction = memo(() => {
</Typography>
<Typography>
{!isGreaterThan(tokenValueUSD, pow10(9)) ? (
<FormattedCurrency value={tokenValueUSD} sign="$" formatter={formatCurrency} />
<FormattedCurrency value={tokenValueUSD} formatter={formatCurrency} />
) : null}
</Typography>
</>
Expand Down Expand Up @@ -412,7 +412,7 @@ const ContractInteraction = memo(() => {
</Typography>

<Typography className={classes.gasPrice}>
<FormattedCurrency value={totalUSD} sign="$" formatter={formatCurrency} />
<FormattedCurrency value={totalUSD} formatter={formatCurrency} />
</Typography>
</div>
) : null}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ const TokenDetail = memo(() => {
/>
</Typography>
<Typography className={classes.text}>
<FormattedCurrency value={getTokenUSDValue(currentToken)} sign="$" formatter={formatCurrency} />
<FormattedCurrency value={getTokenUSDValue(currentToken)} formatter={formatCurrency} />
</Typography>
<div className={classes.controller}>
<div onClick={openBuyDialog}>
Expand Down
7 changes: 3 additions & 4 deletions packages/mask/src/plugin-infra/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ import { WalletMessages, WalletRPC } from '../plugins/Wallet/messages'

export function createSharedContext(pluginID: string, signal: AbortSignal): Plugin.Shared.SharedContext {
return {
createKVStorage<T extends object>(type: 'memory' | 'persistent', name: string, defaultValues: T) {
if (type === 'memory')
return InMemoryStorages.Plugin.createSubScope(`${pluginID}_${name}`, defaultValues, signal)
else return PersistentStorages.Plugin.createSubScope(`${pluginID}_${name}`, defaultValues, signal)
createKVStorage<T extends object>(type: 'memory' | 'persistent', defaultValues: T) {
if (type === 'memory') return InMemoryStorages.Plugin.createSubScope(pluginID, defaultValues, signal)
else return PersistentStorages.Plugin.createSubScope(pluginID, defaultValues, signal)
},

nativeType: nativeAPI?.type,
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/plugins/PoolTogether/base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const base: Plugin.Shared.Definition = {
enableRequirement: {
architecture: { app: true, web: true },
networks: { type: 'opt-out', networks: {} },
target: 'stable',
target: 'insider',
},
contribution: { postContent: new Set([URL_PATTERN]) },
}
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ export function SavingsForm({ chainId, protocol, tab, onClose }: SavingsFormProp
</Typography>
) : (
<Typography variant="body2" textAlign="right" className={classes.tokenValueUSD}>
&asymp; <FormattedCurrency value={tokenValueUSD} sign="$" formatter={formatCurrency} />
&asymp; <FormattedCurrency value={tokenValueUSD} formatter={formatCurrency} />
{estimatedGas > 0 ? (
<span className={classes.gasFee}>+ {formatBalance(estimatedGas, 18)} ETH</span>
) : (
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/plugins/Tips/SNSAdaptor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { TipsEntranceDialog } from './TipsEntranceDialog'
const sns: Plugin.SNSAdaptor.Definition = {
...base,
init(_, context) {
setupStorage(context.createKVStorage('memory', '', storageDefaultValue))
setupStorage(context.createKVStorage('memory', storageDefaultValue))
},
ApplicationEntries: [
(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/plugins/Trader/SNSAdaptor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const sns: Plugin.SNSAdaptor.Definition<
> = {
...base,
init(signal, context) {
setupStorage(context.createKVStorage('persistent', '', storageDefaultValue))
setupStorage(context.createKVStorage('persistent', storageDefaultValue))
},
SearchResultBox: SearchResultInspector,
GlobalInjection: function Component() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export const InputTokenPanel = memo<InputTokenPanelProps>(
),
endAdornment: (
<Typography className={classes.price}>
&asymp; <FormattedCurrency value={tokenValueUSD} sign="$" formatter={formatCurrency} />
&asymp; <FormattedCurrency value={tokenValueUSD} formatter={formatCurrency} />
</Typography>
),
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ export function TickersTable(props: TickersTableProps) {
</TableCell>
{ticker.price ? (
<TableCell className={classes.cell}>
<FormattedCurrency value={ticker.price} sign="$" formatter={formatCurrency} />
<FormattedCurrency value={ticker.price} formatter={formatCurrency} />
</TableCell>
) : null}
<TableCell className={classes.cell}>
<FormattedCurrency value={ticker.volume} sign="$" formatter={formatCurrency} />
<FormattedCurrency value={ticker.volume} formatter={formatCurrency} />
</TableCell>
<TableCell className={classes.cell}>{formatElapsed(ticker.updated.getTime())}</TableCell>
</TableRow>
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/plugins/hooks/usePriceLineChart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function usePriceLineChart(
id: string,
opts: { color?: string; sign?: string },
) {
const { color = 'steelblue', sign = '$' } = opts
const { color = 'steelblue', sign = 'USD' } = opts

useLineChart(svgRef, data, dimension, id, {
color,
Expand Down
6 changes: 1 addition & 5 deletions packages/plugin-infra/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,7 @@ export namespace Plugin.Shared {
/**
* A lightweight K/V storage used to store some simple data.
*/
createKVStorage<T extends object>(
type: 'memory' | 'persistent',
name: string,
defaultValues: T,
): ScopedStorage<T>
createKVStorage<T extends object>(type: 'memory' | 'persistent', defaultValues: T): ScopedStorage<T>
/** The selected account of Mask Wallet */
account: Subscription<string>
/** The selected chainId of Mask Wallet */
Expand Down
11 changes: 5 additions & 6 deletions packages/plugin-infra/src/web3-state/AddressBook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class AddressBookState<

constructor(
protected context: Plugin.Shared.SharedContext,
protected defaultValue: AddressBook,
protected chainIds: ChainId[],
protected subscriptions: {
chainId?: Subscription<ChainId>
},
Expand All @@ -24,11 +24,10 @@ export class AddressBookState<
formatAddress(a: string): string
},
) {
const { storage } = this.context
.createKVStorage('persistent', 'AddressBook', {})
.createSubScope('AddressBook', {
value: defaultValue,
})
const defaultValue = Object.fromEntries(chainIds.map((x) => [x, []] as [ChainId, string[]])) as AddressBook
const { storage } = this.context.createKVStorage('persistent', {}).createSubScope('AddressBook', {
value: defaultValue,
})
this.storage = storage.value

if (this.subscriptions.chainId) {
Expand Down
5 changes: 3 additions & 2 deletions packages/plugin-infra/src/web3-state/NameService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class NameServiceState<

constructor(
protected context: Plugin.Shared.SharedContext,
protected defaultValue: DomainBooks,
protected chainIds: ChainId[],
protected subscriptions: {
chainId?: Subscription<ChainId>
},
Expand All @@ -24,7 +24,8 @@ export class NameServiceState<
formatAddress(a: string): string
},
) {
const { storage } = context.createKVStorage('memory', 'NameService', {}).createSubScope('NameService', {
const defaultValue = Object.fromEntries(chainIds.map((x) => [x, {}])) as DomainBooks
const { storage } = context.createKVStorage('memory', {}).createSubScope('NameService', {
value: defaultValue,
})
this.storage = storage.value
Expand Down
25 changes: 20 additions & 5 deletions packages/plugin-infra/src/web3-state/Provider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { clone, first } from 'lodash-unified'
import type { Subscription } from 'use-subscription'
import { delay } from '@dimensiondev/kit'
import { delay, getEnumAsArray } from '@dimensiondev/kit'
import {
EnhanceableSite,
ExtensionSite,
Expand Down Expand Up @@ -38,19 +38,34 @@ export class ProviderState<
constructor(
protected context: Plugin.Shared.SharedContext,
protected providers: Record<ProviderType, WalletProvider<ChainId, ProviderType, Web3Provider, Web3>>,
protected defaultValue: ProviderStorage<Account<ChainId>, ProviderType>,
protected options: {
isValidAddress(a?: string): boolean
isValidChainId(a?: number): boolean
isSameAddress(a?: string, b?: string): boolean
getDefaultChainId(): ChainId
getDefaultNetworkType(): NetworkType
getDefaultProviderType(): ProviderType
getNetworkTypeFromChainId(chainId: ChainId): NetworkType
},
) {
const { storage } = this.context
.createKVStorage('memory', 'Provider', {})
.createSubScope('Provider', defaultValue)
const defaultValue: ProviderStorage<Account<ChainId>, ProviderType> = {
accounts: Object.fromEntries(
Object.keys(providers).map((x) => [
x,
{
account: '',
chainId: options.getDefaultChainId(),
},
]),
) as Record<ProviderType, Account<ChainId>>,
providers: Object.fromEntries(
[...getEnumAsArray(EnhanceableSite), ...getEnumAsArray(ExtensionSite)].map((x) => [
x.value,
options.getDefaultProviderType(),
]),
) as Record<EnhanceableSite | ExtensionSite, ProviderType>,
}
const { storage } = this.context.createKVStorage('memory', {}).createSubScope('Provider', defaultValue)
this.storage = storage

this.setupSubscriptions()
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-infra/src/web3-state/RiskWarning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class RiskWarningState implements Web3RiskWarningState {
formatAddress(a: string): string
},
) {
const { storage } = this.context.createKVStorage('memory', 'RiskWarning', {}).createSubScope('RiskWarning', {
const { storage } = this.context.createKVStorage('memory', {}).createSubScope('RiskWarning', {
value: {},
})

Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-infra/src/web3-state/Settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class SettingsState implements Web3SettingsState {
public nonFungibleAssetSourceType?: Subscription<SourceType>

constructor(context: Plugin.Shared.SharedContext) {
const { storage } = context.createKVStorage('memory', 'Settings', {}).createSubScope('Settings', {
const { storage } = context.createKVStorage('memory', {}).createSubScope('Settings', {
currencyType: CurrencyType.USD,
gasOptionType: GasOptionType.NORMAL,
fungibleAssetSourceType: SourceType.DeBank,
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-infra/src/web3-state/Token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class TokenState<ChainId, SchemaType> implements Web3TokenState<ChainId,
formatAddress(a: string): string
},
) {
const { storage } = context.createKVStorage('persistent', 'Token', {}).createSubScope('Token', defaultValue)
const { storage } = context.createKVStorage('persistent', {}).createSubScope('Token', defaultValue)
this.storage = storage

if (this.subscriptions.account) {
Expand Down
14 changes: 8 additions & 6 deletions packages/plugin-infra/src/web3-state/Transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class TransactionState<ChainId, Transaction> implements Web3TransactionSt

constructor(
protected context: Plugin.Shared.SharedContext,
protected defaultValue: TransactionStorage<ChainId, Transaction>,
protected chainIds: ChainId[],
protected subscriptions: {
account?: Subscription<string>
chainId?: Subscription<ChainId>
Expand All @@ -36,11 +36,13 @@ export class TransactionState<ChainId, Transaction> implements Web3TransactionSt
formatAddress(a: string): string
},
) {
const { storage } = this.context
.createKVStorage('persistent', 'Transaction', {})
.createSubScope('Transaction', {
value: defaultValue,
})
const defaultValue = Object.fromEntries(chainIds.map((x) => [x, {}])) as TransactionStorage<
ChainId,
Transaction
>
const { storage } = this.context.createKVStorage('persistent', {}).createSubScope('Transaction', {
value: defaultValue,
})
this.storage = storage.value

if (this.subscriptions.chainId && this.subscriptions.account) {
Expand Down
19 changes: 10 additions & 9 deletions packages/plugins/EVM/src/state/AddressBook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ export class AddressBook extends AddressBookState<ChainId> {
chainId?: Subscription<ChainId>
},
) {
const defaultValue = Object.fromEntries(
getEnumAsArray(ChainId).map((x) => [x.value, []] as [ChainId, string[]]),
) as Record<ChainId, string[]>

super(context, defaultValue, subscriptions, {
isValidAddress,
isSameAddress,
formatAddress: formatEthereumAddress,
})
super(
context,
getEnumAsArray(ChainId).map((x) => x.value),
subscriptions,
{
isValidAddress,
isSameAddress,
formatAddress: formatEthereumAddress,
},
)
}
}
20 changes: 10 additions & 10 deletions packages/plugins/EVM/src/state/NameService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@ export class NameService extends NameServiceState<ChainId> {
chainId?: Subscription<ChainId>
},
) {
const defaultValue = Object.fromEntries(getEnumAsArray(ChainId).map((x) => [x.value, {}])) as Record<
ChainId,
Record<string, string>
>

super(context, defaultValue, subscriptions, {
isValidName: (x) => x !== '0x',
isValidAddress: (x) => isValidAddress(x) && !isZeroAddress(x),
formatAddress: formatEthereumAddress,
})
super(
context,
getEnumAsArray(ChainId).map((x) => x.value),
subscriptions,
{
isValidName: (x) => x !== '0x',
isValidAddress: (x) => isValidAddress(x) && !isZeroAddress(x),
formatAddress: formatEthereumAddress,
},
)
}

private async createENS() {
Expand Down
25 changes: 3 additions & 22 deletions packages/plugins/EVM/src/state/Provider.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { getEnumAsArray } from '@dimensiondev/kit'
import type { Plugin } from '@masknet/plugin-infra'
import { ProviderState, ProviderStorage } from '@masknet/plugin-infra/web3'
import { EnhanceableSite, ExtensionSite } from '@masknet/shared-base'
import { ProviderState } from '@masknet/plugin-infra/web3'
import { Account, isSameAddress } from '@masknet/web3-shared-base'
import {
ChainId,
Expand All @@ -19,30 +17,13 @@ import { Providers } from './Connection/provider'

export class Provider extends ProviderState<ChainId, ProviderType, NetworkType, Web3Provider, Web3> {
constructor(context: Plugin.Shared.SharedContext) {
const defaultValue: ProviderStorage<Account<ChainId>, ProviderType> = {
accounts: Object.fromEntries(
getEnumAsArray(ProviderType).map((x) => [
x.value,
{
account: '',
chainId: ChainId.Mainnet,
},
]),
) as Record<ProviderType, Account<ChainId>>,
providers: Object.fromEntries(
[...getEnumAsArray(EnhanceableSite), ...getEnumAsArray(ExtensionSite)].map((x) => [
x.value,
ProviderType.MaskWallet,
]),
) as Record<EnhanceableSite | ExtensionSite, ProviderType>,
}

super(context, Providers, defaultValue, {
super(context, Providers, {
isSameAddress,
isValidAddress,
isValidChainId,
getDefaultChainId: () => ChainId.Mainnet,
getDefaultNetworkType: () => NetworkType.Ethereum,
getDefaultProviderType: () => ProviderType.MaskWallet,
getNetworkTypeFromChainId: (chainId: ChainId) =>
chainResolver.chainNetworkType(chainId) ?? NetworkType.Ethereum,
})
Expand Down
16 changes: 8 additions & 8 deletions packages/plugins/EVM/src/state/Transaction.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { Subscription } from 'use-subscription'
import { getEnumAsArray } from '@dimensiondev/kit'
import type { Plugin } from '@masknet/plugin-infra'
import type { TransactionStorage } from '@masknet/plugin-infra/web3'
import { TransactionState } from '@masknet/plugin-infra/web3'
import { ChainId, Transaction as EVM_Transaction, formatEthereumAddress } from '@masknet/web3-shared-evm'

Expand All @@ -13,12 +12,13 @@ export class Transaction extends TransactionState<ChainId, EVM_Transaction> {
chainId?: Subscription<ChainId>
},
) {
const defaultValue = Object.fromEntries(
getEnumAsArray(ChainId).map((x) => [x.value, {}]),
) as TransactionStorage<ChainId, EVM_Transaction>

super(context, defaultValue, subscriptions, {
formatAddress: formatEthereumAddress,
})
super(
context,
getEnumAsArray(ChainId).map((x) => x.value),
subscriptions,
{
formatAddress: formatEthereumAddress,
},
)
}
}
Loading

0 comments on commit 70da94b

Please sign in to comment.