-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
get-browser-extension.ts
52 lines (44 loc) · 1.61 KB
/
get-browser-extension.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { MetaMaskInpageProvider } from '@metamask/providers';
import { wrapExtensionProvider } from '../provider/wrapExtensionProvider';
import { eip6963RequestProvider } from './eip6963RequestProvider';
export async function getBrowserExtension({
mustBeMetaMask,
debug,
}: {
mustBeMetaMask: boolean;
debug?: boolean;
}): Promise<MetaMaskInpageProvider> {
if (typeof window === 'undefined') {
throw new Error(`window not available`);
}
let extensionProvider: MetaMaskInpageProvider;
try {
extensionProvider = await eip6963RequestProvider();
return wrapExtensionProvider({ provider: extensionProvider, debug });
} catch (e) {
const { ethereum } = window;
if (!ethereum) {
throw new Error('Ethereum not found in window object');
}
// The `providers` field is populated when CoinBase Wallet extension is also installed
// The expected object is an array of providers, the MetaMask provider is inside
// See https://docs.cloud.coinbase.com/wallet-sdk/docs/injected-provider-guidance for
if ('providers' in ethereum) {
if (Array.isArray(ethereum.providers)) {
const provider = mustBeMetaMask
? ethereum.providers.find((p: any) => p.isMetaMask)
: ethereum.providers[0];
if (!provider) {
throw new Error('No suitable provider found');
}
return wrapExtensionProvider({ provider, debug });
}
} else if (mustBeMetaMask && !ethereum.isMetaMask) {
throw new Error('MetaMask provider not found in Ethereum');
}
return wrapExtensionProvider({
provider: ethereum,
debug,
});
}
}