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 d503c2f
Show file tree
Hide file tree
Showing 21 changed files with 140 additions and 68 deletions.
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
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
21 changes: 14 additions & 7 deletions packages/plugins/EVM/src/state/Connection/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,20 @@ class Connection implements EVM_Connection {
}
}

getWeb3(options?: EVM_Web3ConnectionOptions) {
const web3 = new Web3(
createWeb3Provider((requestArguments: RequestArguments) => this.hijackedRequest(requestArguments, options)),
)
return Promise.resolve(web3)
}

getWeb3Provider(options?: EVM_Web3ConnectionOptions) {
const web3Provider = createWeb3Provider((requestArguments: RequestArguments) =>
this.hijackedRequest(requestArguments, options),
)
return Promise.resolve(web3Provider)
}

async connect(options?: EVM_Web3ConnectionOptions): Promise<Account<ChainId>> {
return this.hijackedRequest<Account<ChainId>>(
{
Expand Down Expand Up @@ -392,13 +406,6 @@ class Connection implements EVM_Connection {
)
}

getWeb3(options?: EVM_Web3ConnectionOptions) {
const web3 = new Web3(
createWeb3Provider((requestArguments: RequestArguments) => this.hijackedRequest(requestArguments, options)),
)
return Promise.resolve(web3)
}

async getWeb3Contract<T extends BaseContract>(
address: string,
ABI: AbiItem[],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { SharedContextSettings, Web3StateSettings } from '../../../settings'

export class MaskWallet implements Middleware<Context> {
async fn(context: Context, next: () => Promise<void>) {
const { Connection: Protocol } = Web3StateSettings.value
const { Connection } = Web3StateSettings.value
const { hasNativeAPI, send, account, chainId, signTransaction, signPersonalMessage, signTypedData } =
SharedContextSettings.value

Expand Down Expand Up @@ -44,7 +44,7 @@ export class MaskWallet implements Middleware<Context> {
break
}

const connection = await Protocol?.getConnection?.({
const connection = await Connection?.getConnection?.({
chainId: context.chainId,
})
const tx = await connection?.sendSignedTransaction?.(rawTransaction, {
Expand Down
4 changes: 2 additions & 2 deletions packages/plugins/EVM/src/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { RiskWarning } from './RiskWarning'
import { Token } from './Token'
import { Transaction } from './Transaction'
import { NameService } from './NameService'
import { Protocol } from './Connection'
import { Connection } from './Connection'
import { Provider } from './Provider'
import { Wallet } from './Wallet'
import { Others } from './Others'
Expand Down Expand Up @@ -47,7 +47,7 @@ export function createWeb3State(context: Plugin.Shared.SharedContext): EVM_Web3S
}),
TransactionFormatter: new TransactionFormatter(context),
TransactionWatcher: new TransactionWatcher(context),
Connection: new Protocol(context, {
Connection: new Connection(context, {
chainId: Provider_.chainId,
account: Provider_.account,
providerType: Provider_.providerType,
Expand Down
4 changes: 3 additions & 1 deletion packages/plugins/Flow/src/state/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
Block,
Transaction,
TransactionDetailed,
Web3Provider,
} from '@masknet/web3-shared-flow'
import { createConnection } from './Connection/connection'

Expand All @@ -28,7 +29,8 @@ export class Connection extends ConnectionState<
Transaction,
TransactionDetailed,
never,
Web3
Web3,
Web3Provider
> {
constructor(
private context: Plugin.Shared.SharedContext,
Expand Down
Loading

0 comments on commit d503c2f

Please sign in to comment.