@@ -4,6 +4,7 @@ import React, {
44 useContext,
55 useMemo,
66 useState,
7+ useEffect,
78} from 'react';
89import { Just, Nothing } from 'folktale/maybe';
910import * as azimuth from 'azimuth-js';
@@ -11,25 +12,36 @@ import Web3 from 'web3';
1112import { includes } from 'lodash';
1213
1314import { CONTRACT_ADDRESSES } from '../lib/contracts';
14−import { NETWORK_TYPES } from '../lib/network';
15+import { NETWORK_TYPES, chainIdToNetworkType } from '../lib/network';
1516import { isDevelopment } from '../lib/flags';
1617import { BRIDGE_ERROR } from '../lib/error';
1718
1819function _useNetwork(initialNetworkType = null) {
19− const [networkType, _setNetworkType] = useState(initialNetworkType);
20+ const [networkType, setNetworkType] = useState(initialNetworkType);
2021
21− const setNetworkType = networkType => {
22− if (!includes(NETWORK_TYPES, networkType)) {
23− throw new Error(BRIDGE_ERROR.INVALID_NETWORK_TYPE);
24− }
25− _setNetworkType(networkType);
26− };
22+ const [metamask, setMetamask] = useState(false);
23+
24+ useEffect(() => {
25+ (async () => {
26+ if (window.ethereum) {
27+ try {
28+ await window.ethereum.enable();
29+ setMetamask(true);
30+ setNetworkType(chainIdToNetworkType(window.ethereum.chainId));
31+ } catch (e) {
32+ console.log('Metamask denied');
33+ }
34+ }
35+ })();
36+ }, []);
2737
2838 const { web3, contracts } = useMemo(() => {
2939 // given a web3 provider and contract addresses,
3040 // build the web3 and contracts objects
3141 const initWeb3 = (provider, contractAddresses) => {
32− const web3 = new Web3(provider);
42+ // use an in-window eth provider if possible
43+ const _provider = metamask ? window.ethereum : provider;
44+ const web3 = new Web3(_provider);
3345 const contracts = azimuth.initContracts(web3, contractAddresses);
3446
3547 return {
@@ -88,7 +100,7 @@ function _useNetwork(initialNetworkType = null) {
88100 };
89101 }
90102 }
91− }, [networkType]);
103+ }, [networkType, metamask]);
92104
93105 return { networkType, setNetworkType, web3, contracts };
94106}