Skip to content

Commit

Permalink
refactor: cleanup setup method in providers; split IOContext
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack-Works committed Jan 5, 2024
1 parent c91497a commit 678aeae
Show file tree
Hide file tree
Showing 37 changed files with 167 additions and 161 deletions.
36 changes: 22 additions & 14 deletions packages/app/src/initialization/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,31 @@ async function reject(): Promise<never> {
}

const WalletIO: WalletAPI.IOContext = {
wallets: EMPTY_ARRAY,
hasPaymentPassword: reject,
openPopupWindow: reject,
openWalletConnectDialog: async (uri: string) => {
await WalletConnectQRCodeModal.openAndWaitForClose({
uri,
})
MaskWalletContext: {
wallets: EMPTY_ARRAY,
addWallet: reject,
allPersonas: EMPTY_ARRAY,
disconnectAllWalletsFromOrigin: reject,
removeWallet: reject,
renameWallet: reject,
resetAllWallets: reject,
sdk_grantEIP2255Permission: reject,
selectMaskWalletAccount: reject,
},
closeWalletConnectDialog: () => {
WalletConnectQRCodeModal.close()
MessageContext: {
hasPaymentPassword: reject,
openPopupWindow: reject,
send: reject,
},
WalletConnectContext: {
openWalletConnectDialog: async (uri: string) => {
await WalletConnectQRCodeModal.openAndWaitForClose({ uri })
},
closeWalletConnectDialog: () => {
WalletConnectQRCodeModal.close()
},
},
sdk_grantEIP2255Permission: reject,
disconnectAllWalletsFromOrigin: reject,
selectMaskWalletAccount: reject,
addWallet: reject,
signWithPersona: reject,
send: reject,
}
export function initWallet() {
return setup(WalletIO)
Expand Down
70 changes: 36 additions & 34 deletions packages/mask/shared-ui/initialization/walletSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,50 @@ import * as shared from /* webpackDefer: true */ '@masknet/shared'
import { defer, delay } from '@masknet/kit'

await initWallet({
addWallet: Services.Wallet.addWallet,
signWithPersona: (a, b, c, d) => Services.Identity.signWithPersona(a, b, c, location.origin, d),
closeWalletConnectDialog: () => {
if (Sniffings.is_popup_page) {
CrossIsolationMessages.events.popupWalletConnectEvent.sendToAll({ open: false })
return
}
shared.WalletConnectQRCodeModal.close()
},
openPopupWindow: Services.Helper.openPopupWindow,
openWalletConnectDialog: async (uri: string) => {
if (Sniffings.is_popup_page) {
const [promise, resolve, reject] = defer<boolean>()
const callback = ({ open }: { open: boolean }) => (!open ? resolve(true) : undefined)
WalletConnectContext: {
openWalletConnectDialog: async (uri: string) => {
if (Sniffings.is_popup_page) {
const [promise, resolve, reject] = defer<boolean>()
const callback = ({ open }: { open: boolean }) => (!open ? resolve(true) : undefined)

delay(5000).then(() => reject(new Error('timeout')))
CrossIsolationMessages.events.popupWalletConnectEvent.on(callback)
CrossIsolationMessages.events.popupWalletConnectEvent.sendToAll({ uri, open: true })
delay(5000).then(() => reject(new Error('timeout')))
CrossIsolationMessages.events.popupWalletConnectEvent.on(callback)
CrossIsolationMessages.events.popupWalletConnectEvent.sendToAll({ uri, open: true })

await promise.finally(() => CrossIsolationMessages.events.popupWalletConnectEvent.off(callback))
} else {
await shared.WalletConnectQRCodeModal.openAndWaitForClose({
uri,
})
}
await promise.finally(() => CrossIsolationMessages.events.popupWalletConnectEvent.off(callback))
} else {
await shared.WalletConnectQRCodeModal.openAndWaitForClose({
uri,
})
}
},
closeWalletConnectDialog: () => {
if (Sniffings.is_popup_page) {
CrossIsolationMessages.events.popupWalletConnectEvent.sendToAll({ open: false })
return
}
shared.WalletConnectQRCodeModal.close()
},
},
MessageContext: {
openPopupWindow: Services.Helper.openPopupWindow,
send: Services.Wallet.send,
hasPaymentPassword: Services.Wallet.hasPassword,
},

send: Services.Wallet.send,
selectMaskWalletAccount: Services.Wallet.selectMaskAccount,

sdk_grantEIP2255Permission: Services.Wallet.sdk_grantEIP2255Permission,
disconnectAllWalletsFromOrigin: Services.Wallet.disconnectAllWalletsFromOrigin,
wallets: createSubscriptionFromAsync(
() => Services.Wallet.getWallets(),
EMPTY_LIST,
CrossIsolationMessages.events.walletsUpdated.on,
),
hasPaymentPassword: Services.Wallet.hasPassword,
MaskWalletContext: {
wallets: createSubscriptionFromAsync(
() => Services.Wallet.getWallets(),
EMPTY_LIST,
CrossIsolationMessages.events.walletsUpdated.on,
),
allPersonas,
resetAllWallets: Services.Wallet.resetAllWallets,
removeWallet: Services.Wallet.removeWallet,
renameWallet: Services.Wallet.renameWallet,
addWallet: Services.Wallet.addWallet,
sdk_grantEIP2255Permission: Services.Wallet.sdk_grantEIP2255Permission,
selectMaskWalletAccount: Services.Wallet.selectMaskAccount,
disconnectAllWalletsFromOrigin: Services.Wallet.disconnectAllWalletsFromOrigin,
},
})
2 changes: 1 addition & 1 deletion packages/shared/src/hooks/useSocialAccountsBySettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function useSocialAccountsBySettings(
identity: SocialIdentity | null | undefined,
typeWhitelist: SocialAddressType[] | undefined,
sorter: ((a: SocialAccount<Web3Helper.ChainIdAll>, z: SocialAccount<Web3Helper.ChainIdAll>) => number) | undefined,
signWithPersona: WalletAPI.IOContext['signWithPersona'],
signWithPersona: WalletAPI.SignWithPersona,
) {
const [
socialAccounts,
Expand Down
6 changes: 3 additions & 3 deletions packages/web3-hooks/base/src/useHiddenAddressConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type StorageValue = StorageValueV1 | StorageValueV2 | StorageValueV3
export function useHiddenAddressConfig(
personaPubkey: string | undefined,
pluginID: PluginID | undefined,
signWithPersona: WalletAPI.IOContext['signWithPersona'],
signWithPersona: WalletAPI.SignWithPersona,
) {
return useQuery({
queryKey: ['next-id', 'hidden-address', pluginID, personaPubkey],
Expand Down Expand Up @@ -54,7 +54,7 @@ export function useHiddenAddressConfigOf(
personaPubkey: string | undefined,
pluginID: PluginID | undefined,
socialId: string | undefined,
signWithPersona: WalletAPI.IOContext['signWithPersona'],
signWithPersona: WalletAPI.SignWithPersona,
): [string[] | undefined, ReturnType<typeof useHiddenAddressConfig>] {
const result = useHiddenAddressConfig(personaPubkey, pluginID, signWithPersona)
return [result.data ? getHiddenAddressesOf(result.data, socialId?.toLowerCase()) : undefined, result]
Expand All @@ -74,7 +74,7 @@ type ConfigResult = [UseQueryResult<Record<string, string[]>>, (config: Record<s
*/
export function useUnlistedAddressConfig(
{ identifier, pluginID, socialIds }: Options,
signWithPersona: WalletAPI.IOContext['signWithPersona'],
signWithPersona: WalletAPI.SignWithPersona,
): ConfigResult {
const query = useHiddenAddressConfig(identifier?.publicKeyAsHex, pluginID, signWithPersona)
const { data: unlistedAddressConfig } = query
Expand Down
2 changes: 1 addition & 1 deletion packages/web3-providers/src/Storage/apis/Storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export class Web3Storage {
proofIdentity: string,
platform: NextIDPlatform,
signerOrPublicKey: string | ECKeyIdentifier,
signWithPersona: WalletAPI.IOContext['signWithPersona'],
signWithPersona: WalletAPI.SignWithPersona,
) {
if (!platform || !signerOrPublicKey) throw new Error('Instantiation parameter error.')
return new NextIDStorage(proofIdentity, platform, signerOrPublicKey, signWithPersona)
Expand Down
2 changes: 1 addition & 1 deletion packages/web3-providers/src/Storage/storages/NextID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class NextIDStorage implements StorageAPI.Storage {
private proofIdentity: string, // proof identity as key
private platform: NextIDPlatform, // proof platform
private signerOrPublicKey: string | ECKeyIdentifier, // publicKey, like SocialIdentity publicKey or PersonaIdentifier publicKeyAsHex
private signWithPersona?: WalletAPI.IOContext['signWithPersona'],
private signWithPersona?: WalletAPI.SignWithPersona,
) {
if (typeof this.signerOrPublicKey === 'string') {
this.publicKeyAsHex = this.signerOrPublicKey
Expand Down
9 changes: 3 additions & 6 deletions packages/web3-providers/src/Web3/Base/state/Provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,13 @@ export abstract class ProviderState<ChainId extends number, ProviderType extends
protected abstract getDefaultProviderType(): ProviderType
protected abstract getNetworkTypeFromChainId(chainId: ChainId): NetworkType
constructor(
protected context: WalletAPI.IOContext,
public signWithPersona: WalletAPI.SignWithPersona,
protected storage: StorageObject<ProviderStorage<Account<ChainId>, ProviderType>>,
) {
this.signWithPersona = context.signWithPersona
}
) {}
protected init() {
this.setupSubscriptions()
this.setupProviders()
}
public signWithPersona

protected setupSubscriptions() {
if (!this.site) return
Expand Down Expand Up @@ -110,7 +107,7 @@ export abstract class ProviderState<ChainId extends number, ProviderType extends
})

try {
await provider.setup(this.context)
await Promise.resolve(provider.setup?.())
} catch {
// ignore setup errors
}
Expand Down
2 changes: 0 additions & 2 deletions packages/web3-providers/src/Web3/Base/state/Token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
type NonFungibleTokenContract,
isSameAddress,
} from '@masknet/web3-shared-base'
import type { WalletAPI } from '../../../entry-types.js'

export interface TokenStorage<ChainId extends number, SchemaType> {
fungibleTokenList: Record<string, Array<FungibleToken<ChainId, SchemaType>>>
Expand Down Expand Up @@ -55,7 +54,6 @@ export abstract class TokenState<ChainId extends number, SchemaType> implements
>

constructor(
protected context: WalletAPI.IOContext,
protected storage: StorageObject<TokenStorage<ChainId, SchemaType>>,
protected subscriptions: {
account?: Subscription<string>
Expand Down
2 changes: 1 addition & 1 deletion packages/web3-providers/src/Web3/EVM/apis/ComposerAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { WalletAPI } from '../../../entry-types.js'

let instance: EVMComposer<ConnectionContext> | undefined
export class Composer {
static compose(signWithPersona: WalletAPI.IOContext['signWithPersona']) {
static compose(signWithPersona: WalletAPI.SignWithPersona) {
if (instance) return instance

instance = EVMComposer.from<ConnectionContext>(
Expand Down
2 changes: 1 addition & 1 deletion packages/web3-providers/src/Web3/EVM/apis/RequestAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class EVMRequestAPI extends EVMRequestReadonlyAPI {

try {
await Composer.compose(this.Provider.signWithPersona).dispatch(context, async () => {
if (!context.writeable) return
if (!context.writable) return
try {
switch (context.method) {
case EthereumMethodType.MASK_LOGIN:
Expand Down
5 changes: 2 additions & 3 deletions packages/web3-providers/src/Web3/EVM/apis/Web3StateAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,8 @@ export async function createEVMState(context: WalletAPI.IOContext): Promise<Web3
IdentityService: () => new IdentityService.EVMIdentityService(),
NameService: () => new NameService.EVMNameService(nameService),
RiskWarning: () => new RiskWarning.EVMRiskWarning(state.Provider?.account, riskWarning),
Message: () => new Message.EVMMessage(context, messages),
Token: () =>
new Token.EVMToken(context, { account: state.Provider?.account, chainId: state.Provider?.chainId }, token),
Message: () => new Message.EVMMessage(context.MessageContext, messages),
Token: () => new Token.EVMToken({ account: state.Provider?.account, chainId: state.Provider?.chainId }, token),
Transaction: () =>
new Transaction.EVMTransaction(
{ chainId: state.Provider?.chainId, account: state.Provider?.account },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class ContractWallet implements Middleware<ConnectionContext> {
protected account: AbstractAccountAPI.Provider<ChainId, UserOperation, Transaction>,
protected bundler: BundlerAPI.Provider,
protected funder: FunderAPI.Provider<ChainId>,
private signWithPersona: WalletAPI.IOContext['signWithPersona'],
private signWithPersona: WalletAPI.SignWithPersona,
) {}

private async getNonce(context: ConnectionContext) {
Expand Down Expand Up @@ -114,7 +114,7 @@ export class ContractWallet implements Middleware<ConnectionContext> {
}

async fn(context: ConnectionContext, next: () => Promise<void>) {
if (!context.writeable) {
if (!context.writable) {
await next()
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class CustomNetworkAPI implements Middleware<ConnectionContext> {

async fn(context: ConnectionContext, next: () => Promise<void>) {
const customNetwork = this.networks?.find((x) => x.isCustomized && isSameURL(x.rpcUrl, context.providerURL))
if (!customNetwork || context.risky || !context.writeable || isMaskOnlyMethodType(context.method)) {
if (!customNetwork || context.risky || !context.writable || isMaskOnlyMethodType(context.method)) {
await next()
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class MaskWallet implements Middleware<ConnectionContext> {
}

async fn(context: ConnectionContext, next: () => Promise<void>) {
if (!context.writeable) {
if (!context.writable) {
await next()
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export class Popups implements Middleware<ConnectionContext> {
}

async fn(context: ConnectionContext, next: () => Promise<void>) {
if (!context.risky || !context.writeable) {
if (!context.risky || !context.writable) {
await next()
return
}
Expand Down
14 changes: 7 additions & 7 deletions packages/web3-providers/src/Web3/EVM/libs/ConnectionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ let pid = 0

export class ConnectionContext {
private id = 0
private _writeable = true
private _writable = true
private _error: Error | null = null
private _result: unknown
private _account = ''
Expand Down Expand Up @@ -53,8 +53,8 @@ export class ConnectionContext {
return PayloadEditor.fromPayload(this.request, this._options)
}

get writeable() {
return this._writeable
get writable() {
return this._writable
}

get account() {
Expand Down Expand Up @@ -197,12 +197,12 @@ export class ConnectionContext {
* JSON RPC response object
*/
get response() {
if (this._writeable) return
if (this._writable) return
return createJsonRpcResponse(this.id, this._result)
}

get error() {
if (this._writeable) return null
if (this._writable) return null
if (this.errorEditor.presence) return this.errorEditor.error
return null
}
Expand Down Expand Up @@ -237,8 +237,8 @@ export class ConnectionContext {
* Seal a request by resolving or rejecting it.
*/
end(error: Error | null = null, result?: unknown) {
if (!this._writeable) return
this._writeable = false
if (!this._writable) return
this._writable = false
this.error = error
this.result = result
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import * as SmartPay from /* webpackDefer: true */ '../../../SmartPay/index.js'
import type { WalletAPI } from '../../../entry-types.js'

export class Interceptor implements Middleware<ConnectionContext> {
constructor(private signWithPersona: WalletAPI.IOContext['signWithPersona']) {
constructor(private signWithPersona: WalletAPI.SignWithPersona) {
this.composers = {
[ProviderType.None]: Composer.from(new NoneWallet()),
[ProviderType.MaskWallet]: Composer.from(
Expand Down Expand Up @@ -40,7 +40,7 @@ export class Interceptor implements Middleware<ConnectionContext> {

async fn(context: ConnectionContext, next: () => Promise<void>) {
const composer = this.composers[context.providerType]
if (!composer || !context.writeable) {
if (!composer || !context.writable) {
await next()
return
}
Expand Down
6 changes: 0 additions & 6 deletions packages/web3-providers/src/Web3/EVM/providers/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import type { WalletAPI } from '../../../entry-types.js'
import type { EVMWalletProvider } from './index.js'

export abstract class BaseEVMWalletProvider implements EVMWalletProvider {
protected context: WalletAPI.IOContext | undefined

constructor(protected providerType: ProviderType) {}

public emitter = new Emitter<WalletAPI.ProviderEvents<ChainId, ProviderType>>()
Expand All @@ -44,10 +42,6 @@ export abstract class BaseEVMWalletProvider implements EVMWalletProvider {
return true
}

async setup(context: WalletAPI.IOContext): Promise<void> {
this.context = context
}

// Switch chain with RPC calls by default
async switchChain(chainId: ChainId): Promise<void> {
if (!isValidChainId(chainId)) throw new Error('Invalid chain id.')
Expand Down

0 comments on commit 678aeae

Please sign in to comment.