aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/provider_factory.ts
blob: d7740752172050eb04016acedd83066c0b797576 (plain) (blame)
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
import { EmptyWalletSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders';
import { Provider } from 'ethereum-types';
import * as _ from 'lodash';

import { BLOCK_POLLING_INTERVAL_MS, ETHEREUM_NODE_URL_BY_NETWORK } from '../constants';
import { Maybe, Network } from '../types';

export const providerFactory = {
    getInjectedProviderIfExists: (): Maybe<Provider> => {
        const injectedProviderIfExists = (window as any).ethereum;
        if (!_.isUndefined(injectedProviderIfExists)) {
            return injectedProviderIfExists;
        }
        const injectedWeb3IfExists = (window as any).web3;
        if (!_.isUndefined(injectedWeb3IfExists) && !_.isUndefined(injectedWeb3IfExists.currentProvider)) {
            return injectedWeb3IfExists.currentProvider;
        }
        return undefined;
    },
    getFallbackNoSigningProvider: (network: Network): Provider => {
        const providerEngine = new Web3ProviderEngine({
            pollingInterval: BLOCK_POLLING_INTERVAL_MS,
        });
        // Intercept calls to `eth_accounts` and always return empty
        providerEngine.addProvider(new EmptyWalletSubprovider());
        // Construct an RPC subprovider, all data based requests will be sent via the RPCSubprovider
        // TODO(bmillman): make this more resilient to infura failures
        const rpcUrl = ETHEREUM_NODE_URL_BY_NETWORK[network];
        providerEngine.addProvider(new RPCSubprovider(rpcUrl));
        // // Start the Provider Engine
        providerEngine.start();
        // This feels a bit dirty, but was the only way I could think of
        // checking to see if this engine is our fallback engine, and not
        // another Web3Provider engine provided by some dapp browser
        (providerEngine as any).zeroExInstantFallbackEngine = true;
        return providerEngine;
    },
};