2018-10-11 02:02:47 -07:00
|
|
|
import Web3 from 'web3'
|
2019-10-28 23:43:19 -07:00
|
|
|
import helpers from './helpers'
|
2018-10-02 04:07:57 -07:00
|
|
|
import { constants } from './constants'
|
2017-12-19 07:17:49 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
const defaultNetId = helpers.netIdByBranch(constants.CORE)
|
2017-12-19 07:17:49 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
export default async function getWeb3(netId = defaultNetId, onAccountChange) {
|
|
|
|
let web3 = null
|
|
|
|
netId = Number(netId)
|
2018-10-11 01:17:07 -07:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
|
|
|
|
if (window.ethereum) {
|
|
|
|
web3 = new Web3(window.ethereum)
|
|
|
|
console.log('Injected web3 detected.')
|
|
|
|
try {
|
|
|
|
await window.ethereum.enable()
|
|
|
|
} catch (e) {
|
|
|
|
throw Error('You have denied access to your accounts')
|
|
|
|
}
|
|
|
|
window.ethereum.autoRefreshOnNetworkChange = true
|
|
|
|
} else if (window.web3) {
|
|
|
|
web3 = new Web3(window.web3.currentProvider)
|
|
|
|
console.log('Injected web3 detected.')
|
|
|
|
}
|
2018-11-21 07:46:51 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
const network = constants.NETWORKS[netId]
|
|
|
|
const injectedWeb3 = web3 !== null
|
|
|
|
let netIdName = network.NAME
|
|
|
|
let defaultAccount = null
|
|
|
|
let networkMatch = false
|
2018-11-21 07:46:51 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
if (web3) {
|
|
|
|
const accounts = await web3.eth.getAccounts()
|
|
|
|
defaultAccount = accounts[0] || null
|
2018-11-21 07:46:51 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
if (!defaultAccount) {
|
|
|
|
console.error('Unlock your wallet')
|
|
|
|
}
|
2018-11-21 07:46:51 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
let currentAccount = defaultAccount ? defaultAccount.toLowerCase() : ''
|
|
|
|
web3.currentProvider.publicConfigStore.on('update', function(obj) {
|
|
|
|
const account = obj.selectedAddress
|
|
|
|
if (account && account !== currentAccount) {
|
|
|
|
currentAccount = account
|
|
|
|
onAccountChange(account)
|
2018-10-11 02:02:47 -07:00
|
|
|
}
|
2019-10-28 23:43:19 -07:00
|
|
|
})
|
2018-10-11 01:17:07 -07:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
const web3NetId = await web3.eth.net.getId()
|
|
|
|
if (web3NetId === netId) {
|
|
|
|
networkMatch = true
|
|
|
|
} else {
|
|
|
|
web3 = null
|
|
|
|
}
|
|
|
|
}
|
2018-10-11 01:17:07 -07:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
if (!web3) {
|
|
|
|
web3 = new Web3(new Web3.providers.HttpProvider(network.RPC))
|
|
|
|
}
|
2018-10-11 01:17:07 -07:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
document.title = `${netIdName} - POA Governance DApp`
|
2017-12-19 07:17:49 -08:00
|
|
|
|
2019-10-28 23:43:19 -07:00
|
|
|
return {
|
|
|
|
web3Instance: web3,
|
|
|
|
netId,
|
|
|
|
netIdName,
|
|
|
|
injectedWeb3,
|
|
|
|
defaultAccount,
|
|
|
|
networkMatch
|
|
|
|
}
|
|
|
|
}
|