Skip to content

Commit 098e396

Browse files
authored
fix: catch error when ethereum provider is set before our attempt to set (#416)
* catch error when ethereum provider is set before our attempt to set * update jest.config
1 parent f0ca94b commit 098e396

3 files changed

Lines changed: 32 additions & 4 deletions

File tree

jest.config.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ const baseConfig = {
4747
global: {
4848
branches: 70.68,
4949
functions: 72.32,
50-
lines: 71.27,
51-
statements: 71.39,
50+
lines: 71.39,
51+
statements: 71.51,
5252
},
5353
},
5454

src/initializeInpageProvider.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@ describe('setGlobalProvider', () => {
2020
new Event('ethereum#initialized'),
2121
);
2222
});
23+
24+
it('should not throw an error if the global ethereum provider is already set', () => {
25+
const errorSpy = jest.spyOn(console, 'error');
26+
27+
const mockProvider = {} as unknown as MetaMaskInpageProvider;
28+
Object.defineProperty(window, 'ethereum', {
29+
get() {
30+
return {};
31+
},
32+
set() {
33+
throw new Error('window.ethereum already set');
34+
},
35+
configurable: false,
36+
});
37+
expect(() => setGlobalProvider(mockProvider)).not.toThrow();
38+
39+
expect(errorSpy).toHaveBeenCalledWith(
40+
'MetaMask encountered an error setting the global Ethereum provider - this is likely due to another Ethereum wallet extension also setting the global Ethereum provider:',
41+
expect.any(Error),
42+
);
43+
});
2344
});
2445

2546
describe('announceCaip294WalletData', () => {

src/initializeInpageProvider.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,15 @@ export function initializeProvider({
9898
export function setGlobalProvider(
9999
providerInstance: MetaMaskInpageProvider,
100100
): void {
101-
(window as Record<string, any>).ethereum = providerInstance;
102-
window.dispatchEvent(new Event('ethereum#initialized'));
101+
try {
102+
(window as Record<string, any>).ethereum = providerInstance;
103+
window.dispatchEvent(new Event('ethereum#initialized'));
104+
} catch (error) {
105+
console.error(
106+
'MetaMask encountered an error setting the global Ethereum provider - this is likely due to another Ethereum wallet extension also setting the global Ethereum provider:',
107+
error,
108+
);
109+
}
103110
}
104111

105112
/**

0 commit comments

Comments
 (0)