improve network switch

This commit is contained in:
Max Alekseenko 2019-09-12 22:12:32 +03:00
parent 863b1d21f2
commit a412ab9114
6 changed files with 100 additions and 109 deletions

View File

@ -374,6 +374,9 @@ export class BallotCard extends React.Component {
if (!contractsStore.votingKey) {
swal('Warning!', messages.NO_METAMASK_MSG, 'warning')
return
} else if (!contractsStore.networkMatch) {
swal('Warning!', messages.NETWORK_MATCH_ERROR, 'warning')
return
} else if (!contractsStore.isValidVotingKey) {
swal('Warning!', messages.invalidVotingKeyMsg(contractsStore.votingKey), 'warning')
return
@ -511,6 +514,9 @@ export class BallotCard extends React.Component {
if (!contractsStore.votingKey) {
swal('Warning!', messages.NO_METAMASK_MSG, 'warning')
return
} else if (!contractsStore.networkMatch) {
swal('Warning!', messages.NETWORK_MATCH_ERROR, 'warning')
return
} else if (!contractsStore.isValidVotingKey) {
swal('Warning!', messages.invalidVotingKeyMsg(contractsStore.votingKey), 'warning')
return

View File

@ -255,6 +255,9 @@ export class NewBallot extends React.Component {
if (!contractsStore.votingKey) {
swal('Warning!', messages.NO_METAMASK_MSG, 'warning')
return
} else if (!contractsStore.networkMatch) {
swal('Warning!', messages.NETWORK_MATCH_ERROR, 'warning')
return
} else if (!contractsStore.isValidVotingKey) {
swal('Warning!', messages.invalidVotingKeyMsg(contractsStore.votingKey), 'warning')
return

View File

@ -7,7 +7,7 @@ import ballotsStore from './stores/BallotsStore'
import commonStore from './stores/CommonStore'
import contractsStore from './stores/ContractsStore'
import createBrowserHistory from 'history/createBrowserHistory'
import getWeb3, { changeNetwork } from './utils/getWeb3'
import getWeb3 from './utils/getWeb3'
import registerServiceWorker from './utils/registerServiceWorker'
import swal from 'sweetalert2'
import validatorStore from './stores/ValidatorStore'
@ -32,7 +32,12 @@ class AppMainRouter extends Component {
super(props)
commonStore.showLoading()
getWeb3()
window.addEventListener('load', () => this.initChain())
}
initChain = () => {
const netId = window.localStorage.netId
getWeb3(netId, this.onAccountChange)
.then(async web3Config => {
await this.initialize(web3Config)
commonStore.hideLoading()
@ -83,8 +88,7 @@ class AppMainRouter extends Component {
await Promise.all(promises)
await contractsStore.setMiningKey(web3Config)
await contractsStore.setVotingKey(web3Config)
await this.setKeys(web3Config.defaultAccount)
contractsStore.getKeysBallotThreshold()
contractsStore.getProxyBallotThreshold()
@ -94,25 +98,28 @@ class AppMainRouter extends Component {
await contractsStore.getAllValidatorMetadata()
await contractsStore.getAllBallots()
}
onNetworkChange = e => {
commonStore.showLoading()
window.localStorage.netId = e.value
contractsStore.resetContracts()
ballotsStore.reset()
this.initChain()
}
onAccountChange = account => {
this.setKeys(account)
}
setKeys = async account => {
await contractsStore.setMiningKey(account)
await contractsStore.setVotingKey(account)
console.log('votingKey', contractsStore.votingKey)
console.log('miningKey', contractsStore.miningKey)
}
onNetworkChange = async e => {
commonStore.showLoading()
const netId = e.value
const web3Config = changeNetwork(netId)
contractsStore.resetContracts()
ballotsStore.reset()
await this.initialize(web3Config)
commonStore.hideLoading()
}
render() {
return (
<Provider {...stores}>

View File

@ -87,6 +87,7 @@ class ContractsStore {
this.web3Instance = web3Config.web3Instance
this.netId = web3Config.netId
this.injectedWeb3 = web3Config.injectedWeb3
this.networkMatch = web3Config.networkMatch
}
@action('Reset contracts')
@ -199,14 +200,14 @@ class ContractsStore {
}
@action('Set voting key')
setVotingKey = web3Config => {
this.votingKey = web3Config.defaultAccount
setVotingKey = account => {
this.votingKey = account
}
@action('Set mining key')
setMiningKey = async web3Config => {
setMiningKey = async account => {
try {
this.miningKey = await this.keysManager.instance.methods.miningKeyByVoting(web3Config.defaultAccount).call()
this.miningKey = await this.keysManager.instance.methods.miningKeyByVoting(account).call()
} catch (e) {
console.log(e)
this.miningKey = '0x0000000000000000000000000000000000000000'

View File

@ -1,95 +1,70 @@
import Web3 from 'web3'
import { messages } from './messages'
import helpers from './helpers'
import { constants } from './constants'
import { netIdByName } from './helpers'
let getWeb3 = () => {
return new Promise((resolve, reject) => {
// Wait for loading completion to avoid race conditions with web3 injection timing.
window.addEventListener('load', async () => {
let web3 = null
const defaultNetId = helpers.netIdByName(constants.CORE)
// 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) {
console.error('User denied account access')
reject({ message: messages.USER_DENIED_ACCOUNT_ACCESS })
return
}
} else if (typeof window.web3 !== 'undefined') {
web3 = new Web3(window.web3.currentProvider)
console.log('Injected web3 detected.')
}
export default async function getWeb3(netId = defaultNetId, onAccountChange) {
let web3 = null
netId = Number(netId)
let errorMsg = null
let netIdName
let netId
let defaultAccount = null
let injectedWeb3 = web3 !== null
// 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')
}
} else if (window.web3) {
web3 = new Web3(window.web3.currentProvider)
console.log('Injected web3 detected.')
}
if (web3) {
netId = await web3.eth.net.getId()
console.log('netId', netId)
if (!(netId in constants.NETWORKS)) {
netIdName = 'ERROR'
errorMsg = messages.WRONG_NETWORK_MSG
console.log('This is an unknown network.')
} else {
netIdName = constants.NETWORKS[netId].NAME
console.log(`This is ${netIdName}`)
}
const accounts = await web3.eth.getAccounts()
defaultAccount = accounts[0] || null
} else {
// Fallback to local if no web3 injection.
console.log('No web3 instance injected, using Local web3.')
console.error('Metamask not found')
netId = netIdByName(constants.CORE)
const network = constants.NETWORKS[netId]
web3 = new Web3(new Web3.providers.HttpProvider(network.RPC))
netIdName = network.NAME
}
document.title = `${netIdName} - POA Network Governance DApp`
if (errorMsg !== null) {
reject({ message: errorMsg })
return
}
resolve({
web3Instance: web3,
netIdName,
netId,
defaultAccount,
injectedWeb3
})
})
})
}
export const changeNetwork = netId => {
const network = constants.NETWORKS[netId]
const provider = new Web3.providers.HttpProvider(network.RPC)
const web3Instance = new Web3(provider)
let netIdName = network.NAME
let injectedWeb3 = web3 !== null
let defaultAccount = null
let networkMatch = false
if (web3) {
const accounts = await web3.eth.getAccounts()
defaultAccount = accounts[0] || null
if (!defaultAccount) {
console.error('Unlock your wallet')
}
let currentAccount = defaultAccount ? defaultAccount.toLowerCase() : ''
web3.currentProvider.publicConfigStore.on('update', function(obj) {
const account = obj.selectedAddress
if (account && account !== currentAccount) {
currentAccount = account
onAccountChange(account)
}
})
const web3NetId = await web3.eth.net.getId()
if (web3NetId === netId) {
networkMatch = true
} else {
web3 = null
}
}
if (!web3) {
web3 = new Web3(new Web3.providers.HttpProvider(network.RPC))
}
document.title = `${netIdName} - POA Validators DApp`
return {
web3Instance,
netIdName: network.NAME,
web3Instance: web3,
netId,
defaultAccount: null,
injectedWeb3: false
netIdName,
injectedWeb3,
defaultAccount,
networkMatch
}
}
export default getWeb3

View File

@ -16,9 +16,7 @@ messages.PROPOSED_ADDRESS_IS_NOT_ADDRESS_MSG = "Proposed address isn't address"
messages.END_TIME_SHOULD_BE_GREATER_THAN_NOW_MSG = 'Ballot end time should be greater than now'
messages.BALLOT_TYPE_IS_EMPTY_MSG = 'Ballot type is empty'
messages.USER_DENIED_ACCOUNT_ACCESS = 'You have denied access to your accounts'
messages.NO_METAMASK_MSG = `You haven't chosen any account in MetaMask.
Please, choose your voting key in MetaMask and reload the page.
Check POA Network <a href='https://github.com/poanetwork/wiki' target='blank'>wiki</a> for more info.`
messages.NO_METAMASK_MSG = 'Your MetaMask is locked.'
messages.WRONG_NETWORK_MSG = `You aren't connected to POA Network.
Please, switch on POA plugin and refresh the page.
Check POA Network <a href='https://github.com/poanetwork/wiki' target='blank'>wiki</a> for more info.`
@ -49,6 +47,7 @@ messages.DESCRIPTION_IS_EMPTY = 'Description cannot be empty'
messages.wrongRepo = repo => {
return `There is no contracts.json in configured repo ${repo}`
}
messages.NETWORK_MATCH_ERROR = 'Networks do not match. Change the network in Metamask.'
module.exports = {
messages
}