From 32b5fb19ae8c692975fca8f3e792813c9657c368 Mon Sep 17 00:00:00 2001 From: Eric Le Ponner Date: Fri, 22 Dec 2023 14:42:51 +0100 Subject: [PATCH] WalletDriver_Metamask now keeps MetaMaskInpageProvider instance and uses it to register to "chainChanged" events. Signed-off-by: Eric Le Ponner --- src/utils/wallet/WalletDriver_Metamask.ts | 24 ++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/utils/wallet/WalletDriver_Metamask.ts b/src/utils/wallet/WalletDriver_Metamask.ts index 2951afd96..af457c359 100644 --- a/src/utils/wallet/WalletDriver_Metamask.ts +++ b/src/utils/wallet/WalletDriver_Metamask.ts @@ -38,6 +38,8 @@ import {MetaMaskInpageProvider} from "@metamask/providers"; export class WalletDriver_Metamask extends WalletDriver_Ethereum { + private metamaskProvider: MetaMaskInpageProvider|null = null + // // Public // @@ -79,9 +81,11 @@ export class WalletDriver_Metamask extends WalletDriver_Ethereum { // public async makeProvider(): Promise { - 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) } @@ -89,10 +93,24 @@ export class WalletDriver_Metamask extends WalletDriver_Ethereum { return WalletDriver_Metamask.fetchMetamaskErrorCode(reason) == 4001 } + public async connect(network: string): Promise { + const result = await super.connect(network) + this.metamaskProvider?.once('chainChanged', this.handleDisconnect) + return Promise.resolve(result) + } + + public async disconnect(): Promise { + 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) {