Skip to content

Commit

Permalink
chore: add useWeb3Provider
Browse files Browse the repository at this point in the history
  • Loading branch information
guanbinrui committed May 25, 2022
1 parent 0df8aa3 commit 6d23332
Show file tree
Hide file tree
Showing 24 changed files with 161 additions and 90 deletions.
1 change: 1 addition & 0 deletions packages/mask/shared-ui/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,7 @@
"plugin_collectible_invalid_reserve_price": "Invalid reserve price",
"plugin_collectible_place_a_bid": "Place a Bid",
"plugin_collectible_make_an_offer": "Make an Offer",
"plugin_collectible_legal_text": "By checking this box, I agree to OpenSea's <terms>Terms of Service</terms>.",
"plugin_collectibles_name": "Collectibles",
"plugin_collectibles_description": "Display specific information of collectibles in OpenSea and Rarible, make an offer directly on social media.",
"plugin_cryptoartai_description_title": "Description",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const ConnectWalletPage = memo(() => {
) as Web3Helper.Web3ProviderDescriptor<NetworkPluginID.PLUGIN_EVM>[]

const { ProviderIconClickBait } = useWeb3UI(NetworkPluginID.PLUGIN_EVM).SelectProviderDialog ?? {}
const { Connection: Protocol } = useWeb3State(NetworkPluginID.PLUGIN_EVM)
const { Connection } = useWeb3State(NetworkPluginID.PLUGIN_EVM)

const onClick = useCallback(
async (
Expand All @@ -89,7 +89,7 @@ const ConnectWalletPage = memo(() => {
return
}

const connection = await Protocol?.getConnection?.({
const connection = await Connection?.getConnection?.({
chainId: network.chainId,
providerType: provider.type,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,6 @@ import Check from '@mui/icons-material/Check'
import type { ChainId, SchemaType } from '@masknet/web3-shared-evm'
import { FungibleToken, isSameAddress, formatBalance } from '@masknet/web3-shared-base'

export interface SelectTokenPanelProps {
amount: string
balance: string
token?: FungibleToken<ChainId, SchemaType>
onAmountChange: (amount: string) => void
onTokenChange: (token: FungibleToken<ChainId, SchemaType>) => void
tokens?: FungibleToken<ChainId, SchemaType>[]
}

const MIN_AMOUNT_LENGTH = 1
const MAX_AMOUNT_LENGTH = 79

Expand All @@ -34,27 +25,34 @@ const useStyles = makeStyles()((theme) => ({
height: 24,
},
input: {},

check: {
flex: 1,
display: 'flex',
justifyContent: 'end',
color: theme.palette.text.primary,
},
}))

export interface SelectTokenPanelProps {
amount: string
balance: string
token?: FungibleToken<ChainId, SchemaType>
onAmountChange: (amount: string) => void
onTokenChange: (token: FungibleToken<ChainId, SchemaType>) => void
tokens?: FungibleToken<ChainId, SchemaType>[]
}

export function SelectTokenListPanel(props: SelectTokenPanelProps) {
const { t } = useI18N()
const { amount, balance, token, onAmountChange, onTokenChange, tokens = [] } = props
const ref = useRef<HTMLElement>(null)

const { t } = useI18N()
const ref = useRef<HTMLElement>(null)
const { classes } = useStyles()

const [haveMenu, setHaveMenu] = useState(true)

const width = useMemo(() => {
if (!ref.current) return
const style = window.getComputedStyle(ref.current)
return style.width
return window.getComputedStyle(ref.current).width
}, [ref.current])

useEffect(() => {
Expand Down Expand Up @@ -130,14 +128,14 @@ export function SelectTokenListPanel(props: SelectTokenPanelProps) {
{t('plugin_collectible_price')}
</Typography>
<Typography variant="body1" color="colorPrimary">
{t('wallet_balance')}:
<span style={{ marginRight: 4 }}>{t('wallet_balance')}:</span>
<FormattedBalance
value={balance}
decimals={token?.decimals}
significant={6}
formatter={formatBalance}
/>
{token?.symbol}
<span style={{ marginLeft: 4 }}>{token?.symbol}</span>
</Typography>
</div>
<FormControl className={classes.input} variant="outlined" fullWidth>
Expand Down
4 changes: 2 additions & 2 deletions packages/mask/src/plugins/Collectible/hooks/useAssetOrder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { getOrderUnitPrice } from '@masknet/web3-providers'
import { NetworkPluginID, ZERO } from '@masknet/web3-shared-base'
import type { AssetOrder } from '../../../../../web3-providers/src/opensea/types'
import { isOpenSeaSupportedChainId } from '../pipes'
import { useOpenSeaSDK } from './useOpenSeaSDK'
import { useOpenSea } from './useOpenSea'

export function useAssetOrder(address?: string, tokenId?: string) {
const chainId = useChainId(NetworkPluginID.PLUGIN_EVM)
const SDK = useOpenSeaSDK(isOpenSeaSupportedChainId(chainId) ? chainId : undefined)
const SDK = useOpenSea(isOpenSeaSupportedChainId(chainId) ? chainId : undefined)
return useAsyncRetry(async () => {
if (!address || !tokenId) return
const asset = await SDK?.api.getAsset({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { useMemo } from 'react'
import { OpenSeaPort } from 'opensea-js'
import { useWeb3 } from '@masknet/plugin-infra/web3'
import { useWeb3Provider } from '@masknet/plugin-infra/web3'
import type { ChainId } from '@masknet/web3-shared-evm'
import { NetworkPluginID } from '@masknet/web3-shared-base'
import { OpenSeaAPI_Key } from '../constants'
import { resolveOpenSeaNetwork } from '../pipes'

export function useOpenSeaSDK(chainId?: ChainId.Mainnet | ChainId.Rinkeby) {
const web3 = useWeb3(NetworkPluginID.PLUGIN_EVM)
export function useOpenSea(chainId?: ChainId.Mainnet | ChainId.Rinkeby) {
const web3Provider = useWeb3Provider(NetworkPluginID.PLUGIN_EVM)

return useMemo(() => {
if (!chainId || !web3) return
if (!chainId || !web3Provider) return
return new OpenSeaPort(
web3,
web3Provider,
{
apiKey: OpenSeaAPI_Key,
networkName: resolveOpenSeaNetwork(chainId),
},
console.log,
)
}, [web3])
}, [web3Provider])
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,17 @@ export function ConnectWalletDialog(props: ConnectWalletDialogProps) {
)
// #endregion

const { Connection: Protocol, Others } = useWeb3State(pluginID) as Web3Helper.Web3StateAll
const { Connection, Others } = useWeb3State(pluginID) as Web3Helper.Web3StateAll

const connection = useAsyncRetry<true>(async () => {
if (!open) return true

if (!networkType || !providerType || !Others || !Protocol) throw new Error('Failed to connect to provider.')
if (!networkType || !providerType || !Others || !Connection) throw new Error('Failed to connect to provider.')

const chainId = Others?.networkResolver.networkChainId(networkType)
if (!chainId) throw new Error('Failed to connect to provider.')

const connection = await Protocol.getConnection?.({
const connection = await Connection.getConnection?.({
chainId,
providerType,
})
Expand Down
13 changes: 10 additions & 3 deletions packages/plugin-infra/src/web3-helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ export declare namespace Web3Helper {

export type Web3<T extends NetworkPluginID = never> = T extends never ? never : Definition[T]['Web3']

export type Web3Provider<T extends NetworkPluginID = never> = T extends never
? never
: Definition[T]['Web3Provider']

export type Web3ProviderState<T extends NetworkPluginID = never> = T extends never
? never
: ProviderState<Definition[T]['ChainId'], Definition[T]['ProviderType'], Definition[T]['NetworkType']>
Expand All @@ -88,7 +92,8 @@ export declare namespace Web3Helper {
Definition[T]['Transaction'],
Definition[T]['TransactionDetailed'],
Definition[T]['TransactionSignature'],
Definition[T]['Web3']
Definition[T]['Web3'],
Definition[T]['Web3Provider']
>

export type Web3ConnectionOptions<T extends NetworkPluginID = never> = T extends never
Expand All @@ -106,7 +111,8 @@ export declare namespace Web3Helper {
Definition[T]['Transaction'],
Definition[T]['TransactionDetailed'],
Definition[T]['TransactionSignature'],
Definition[T]['Web3']
Definition[T]['Web3'],
Definition[T]['Web3Provider']
>
export type Web3HubOptions<T extends NetworkPluginID = never> = T extends never
? never
Expand Down Expand Up @@ -167,7 +173,8 @@ export declare namespace Web3Helper {
Definition[NetworkPluginID]['Transaction'],
Definition[NetworkPluginID]['TransactionDetailed'],
Definition[NetworkPluginID]['TransactionSignature'],
Definition[NetworkPluginID]['Web3']
Definition[NetworkPluginID]['Web3'],
Definition[NetworkPluginID]['Web3Provider']
>
export type Web3HubAll = Hub<
Definition[NetworkPluginID]['ChainId'],
Expand Down
18 changes: 13 additions & 5 deletions packages/plugin-infra/src/web3-state/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class ConnectionState<
TransactionDetailed,
TransactionSignature,
Web3,
Web3Provider,
Web3ConnectionOptions extends ConnectionOptions<ChainId, ProviderType, Transaction> = ConnectionOptions<
ChainId,
ProviderType,
Expand All @@ -27,6 +28,7 @@ export class ConnectionState<
TransactionDetailed,
TransactionSignature,
Web3,
Web3Provider,
Web3ConnectionOptions
>
{
Expand All @@ -45,6 +47,7 @@ export class ConnectionState<
TransactionDetailed,
TransactionSignature,
Web3,
Web3Provider,
Web3ConnectionOptions
>,
protected subscription: {
Expand All @@ -54,16 +57,21 @@ export class ConnectionState<
},
) {}

async getWeb3(options?: Web3ConnectionOptions) {
const connection = await this.getConnection(options)
return connection.getWeb3(options)
}

async getWeb3Provider(options?: Web3ConnectionOptions) {
const connection = await this.getConnection(options)
return connection.getWeb3Provider(options)
}

async getConnection(options?: Web3ConnectionOptions) {
return this.createConnection(
options?.chainId ?? this.subscription.chainId?.getCurrentValue(),
options?.account ?? this.subscription.account?.getCurrentValue(),
options?.providerType ?? this.subscription.providerType?.getCurrentValue(),
)
}

async getWeb3(options?: Web3ConnectionOptions) {
const connection = await this.getConnection(options)
return connection.getWeb3(options)
}
}
2 changes: 1 addition & 1 deletion packages/plugin-infra/src/web3-state/Provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class ProviderState<
NetworkType extends string,
Web3Provider,
Web3,
> implements Web3ProviderState<ChainId, ProviderType, NetworkType>
> implements Web3ProviderState<ChainId, ProviderType, NetworkType, Web3Provider, Web3>
{
protected site = getSiteType()
protected storage: StorageObject<ProviderStorage<Account<ChainId>, ProviderType>> = null!
Expand Down
Empty file.
1 change: 1 addition & 0 deletions packages/plugin-infra/src/web3/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export * from './useWallet'
export * from './useWalletPrimary'
export * from './useWallets'
export * from './useWeb3'
export * from './useWeb3Provider'
export * from './useWeb3Connection'
export * from './useWeb3Hub'
export * from './useWeb3State'
Expand Down
8 changes: 4 additions & 4 deletions packages/plugin-infra/src/web3/useWeb3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ import { useWeb3State } from './useWeb3State'
export function useWeb3<T extends NetworkPluginID>(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions<T>) {
type GetWeb3 = (options?: Web3Helper.Web3ConnectionOptions<T>) => Promise<Web3Helper.Web3<T>>

const { Connection: Protocol } = useWeb3State(pluginID)
const { Connection } = useWeb3State(pluginID)
const chainId = useChainId(pluginID)
const account = useAccount(pluginID)
const providerType = useProviderType(pluginID)

const { value: web3 = null } = useAsyncRetry(async () => {
if (!Protocol?.getWeb3) return null
return (Protocol.getWeb3 as GetWeb3)({
if (!Connection?.getWeb3) return null
return (Connection.getWeb3 as GetWeb3)({
account,
chainId,
providerType,
...options,
} as Web3Helper.Web3ConnectionOptions<T>)
}, [account, chainId, providerType, Protocol, JSON.stringify(options)])
}, [account, chainId, providerType, Connection, JSON.stringify(options)])

return web3
}
8 changes: 4 additions & 4 deletions packages/plugin-infra/src/web3/useWeb3Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ export function useWeb3Connection<T extends NetworkPluginID>(
) {
type GetConnection = (options?: Web3Helper.Web3ConnectionOptions<T>) => Promise<Web3Helper.Web3Connection<T>>

const { Connection: Protocol } = useWeb3State(pluginID)
const { Connection } = useWeb3State(pluginID)
const chainId = useChainId(pluginID)
const account = useAccount(pluginID)
const providerType = useProviderType(pluginID)

const { value: connection = null } = useAsyncRetry(async () => {
if (!Protocol?.getConnection) return
return (Protocol.getConnection as GetConnection)?.({
if (!Connection?.getConnection) return
return (Connection.getConnection as GetConnection)?.({
account,
chainId,
providerType,
...options,
} as Web3Helper.Web3ConnectionOptions<T>)
}, [account, chainId, providerType, Protocol, JSON.stringify(options)])
}, [account, chainId, providerType, Connection, JSON.stringify(options)])

return connection
}
28 changes: 28 additions & 0 deletions packages/plugin-infra/src/web3/useWeb3Provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useAsyncRetry } from 'react-use'
import type { NetworkPluginID } from '@masknet/web3-shared-base'
import type { Web3Helper } from '../web3-helpers'
import { useAccount } from './useAccount'
import { useChainId } from './useChainId'
import { useProviderType } from './useProviderType'
import { useWeb3State } from './useWeb3State'

export function useWeb3Provider<T extends NetworkPluginID>(pluginID?: T, options?: Web3Helper.Web3ConnectionOptions<T>) {
type GetWeb3Provider = (options?: Web3Helper.Web3ConnectionOptions<T>) => Promise<Web3Helper.Web3Provider<T>>

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)({
account,
chainId,
providerType,
...options,
} as Web3Helper.Web3ConnectionOptions<T>)
}, [account, chainId, providerType, Connection, JSON.stringify(options)])

return web3Provider
}
6 changes: 4 additions & 2 deletions packages/plugins/EVM/src/state/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import type {
TransactionDetailed,
TransactionSignature,
Web3,
Web3Provider,
} from '@masknet/web3-shared-evm'
import { createConnection } from './Connection/connection'

export class Protocol extends ConnectionState<
export class Connection extends ConnectionState<
ChainId,
SchemaType,
ProviderType,
Expand All @@ -23,7 +24,8 @@ export class Protocol extends ConnectionState<
Transaction,
TransactionDetailed,
TransactionSignature,
Web3
Web3,
Web3Provider
> {
constructor(
private context: Plugin.Shared.SharedContext,
Expand Down
Loading

0 comments on commit 6d23332

Please sign in to comment.