diff --git a/src/index.js b/src/index.js index abc3853..4025217 100644 --- a/src/index.js +++ b/src/index.js @@ -37,7 +37,7 @@ class AppMainRouter extends Component { } initChain = () => { - const netId = window.localStorage.netId + const netId = window.sessionStorage.netId getWeb3(netId, this.onAccountChange) .then(async web3Config => { await this.initialize(web3Config) @@ -103,6 +103,7 @@ class AppMainRouter extends Component { onNetworkChange = e => { commonStore.showLoading(getNetworkBranch(e.value)) window.localStorage.netId = e.value + window.sessionStorage.netId = e.value contractsStore.resetContracts() ballotsStore.reset() this.initChain() diff --git a/src/utils/getWeb3.js b/src/utils/getWeb3.js index a7d2294..9553b48 100644 --- a/src/utils/getWeb3.js +++ b/src/utils/getWeb3.js @@ -4,9 +4,8 @@ import { constants } from './constants' const defaultNetId = helpers.netIdByBranch(constants.CORE) -export default async function getWeb3(netId = defaultNetId, onAccountChange) { +export default async function getWeb3(netId, onAccountChange) { let web3 = null - netId = Number(netId) // Checking if Web3 has been injected by the browser (Mist/MetaMask) if (window.ethereum) { @@ -23,6 +22,32 @@ export default async function getWeb3(netId = defaultNetId, onAccountChange) { console.log('Injected web3 detected.') } + if (!netId) { + // Load for the first time in the current browser's session + if (web3) { + // MetaMask (or another plugin) is injected + netId = await web3.eth.net.getId() + if (!(netId in constants.NETWORKS)) { + // If plugin's netId is unsupported, try to use + // the previously chosen netId + netId = window.localStorage.netId + } + } else { + // MetaMask (or another plugin) is not injected, + // so try to use the previously chosen netId + netId = window.localStorage.netId + } + if (!(netId in constants.NETWORKS)) { + // If plugin's netId and/or previously chosen netId are not supported, + // fallback to default netId + netId = defaultNetId + } + window.localStorage.netId = netId + window.sessionStorage.netId = netId + } + + netId = Number(netId) + const network = constants.NETWORKS[netId] const injectedWeb3 = web3 !== null let netIdName = network.NAME