diff --git a/jest.config.js b/jest.config.js index 840decce..caa40f12 100644 --- a/jest.config.js +++ b/jest.config.js @@ -47,8 +47,8 @@ const baseConfig = { global: { branches: 70.68, functions: 72.32, - lines: 71.27, - statements: 71.39, + lines: 71.39, + statements: 71.51, }, }, diff --git a/src/initializeInpageProvider.test.ts b/src/initializeInpageProvider.test.ts index 8d4cd300..2de3642d 100644 --- a/src/initializeInpageProvider.test.ts +++ b/src/initializeInpageProvider.test.ts @@ -20,6 +20,27 @@ describe('setGlobalProvider', () => { new Event('ethereum#initialized'), ); }); + + it('should not throw an error if the global ethereum provider is already set', () => { + const errorSpy = jest.spyOn(console, 'error'); + + const mockProvider = {} as unknown as MetaMaskInpageProvider; + Object.defineProperty(window, 'ethereum', { + get() { + return {}; + }, + set() { + throw new Error('window.ethereum already set'); + }, + configurable: false, + }); + expect(() => setGlobalProvider(mockProvider)).not.toThrow(); + + expect(errorSpy).toHaveBeenCalledWith( + 'MetaMask encountered an error setting the global Ethereum provider - this is likely due to another Ethereum wallet extension also setting the global Ethereum provider:', + expect.any(Error), + ); + }); }); describe('announceCaip294WalletData', () => { diff --git a/src/initializeInpageProvider.ts b/src/initializeInpageProvider.ts index 420e77f5..b56d76d3 100644 --- a/src/initializeInpageProvider.ts +++ b/src/initializeInpageProvider.ts @@ -98,8 +98,15 @@ export function initializeProvider({ export function setGlobalProvider( providerInstance: MetaMaskInpageProvider, ): void { - (window as Record).ethereum = providerInstance; - window.dispatchEvent(new Event('ethereum#initialized')); + try { + (window as Record).ethereum = providerInstance; + window.dispatchEvent(new Event('ethereum#initialized')); + } catch (error) { + console.error( + 'MetaMask encountered an error setting the global Ethereum provider - this is likely due to another Ethereum wallet extension also setting the global Ethereum provider:', + error, + ); + } } /**