Skip to content

Commit

Permalink
WalletDriver_Metamask now keeps MetaMaskInpageProvider instance and u…
Browse files Browse the repository at this point in the history
…ses it to register to "chainChanged" events.

Signed-off-by: Eric Le Ponner <[email protected]>
  • Loading branch information
ericleponner committed Dec 22, 2023
1 parent 78b3114 commit 32b5fb1
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/utils/wallet/WalletDriver_Metamask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import {MetaMaskInpageProvider} from "@metamask/providers";

export class WalletDriver_Metamask extends WalletDriver_Ethereum {

private metamaskProvider: MetaMaskInpageProvider|null = null

//
// Public
//
Expand Down Expand Up @@ -79,20 +81,36 @@ export class WalletDriver_Metamask extends WalletDriver_Ethereum {
//

public async makeProvider(): Promise<BrowserProvider|null> {
const options = { mustBeMetaMask: true }
const p = (await detectEthereumProvider(options) ?? null)
const result = p !== null ? new ethers.BrowserProvider(p as MetaMaskInpageProvider) : null
if (this.metamaskProvider === null) {
const options = { mustBeMetaMask: true }
this.metamaskProvider = (await detectEthereumProvider(options) ?? null)
}
const result = this.metamaskProvider !== null ? new ethers.BrowserProvider(this.metamaskProvider) : null
return Promise.resolve(result)
}

public isCancelError(reason: unknown): boolean {
return WalletDriver_Metamask.fetchMetamaskErrorCode(reason) == 4001
}

public async connect(network: string): Promise<string[]> {
const result = await super.connect(network)
this.metamaskProvider?.once('chainChanged', this.handleDisconnect)
return Promise.resolve(result)
}

public async disconnect(): Promise<void> {
this.metamaskProvider?.off("chainChanged", this.handleDisconnect)
this.metamaskProvider = null
return super.disconnect()
}

//
// Private
//

private readonly handleDisconnect = () => this.disconnect()

private static fetchMetamaskErrorCode(reason: unknown): number|null {
let result: number|null
if (typeof reason == "object" && reason != null) {
Expand Down

0 comments on commit 32b5fb1

Please sign in to comment.