(Refactor) Store networks' information in constant object

This commit is contained in:
Vadim Arasev 2018-10-11 19:02:59 +03:00
parent 5225243055
commit 130397ab40
9 changed files with 137 additions and 152 deletions

View File

@ -42,7 +42,7 @@ class App extends Component {
await this.keysManager.init({
web3: web3Config.web3Instance,
netId: web3Config.netId,
addresses,
addresses
});
this.setState({
isDisabledBtn: false,
@ -99,7 +99,7 @@ class App extends Component {
}
async onClick() {
this.setState({loading:true});
const initialKey = window.web3.eth.defaultAccount;
const initialKey = this.state.web3Config.defaultAccount;
let isValid
try {
isValid = await this.keysManager.isInitialKeyValid(initialKey);

View File

@ -1,9 +1,10 @@
import React from "react";
import moment from "moment";
import helpers from "./helpers";
import { constants } from "./constants";
const Footer = ({netId}) => {
const footerClassName = helpers.isTestnet(netId) ? "sokol" : "";
const footerClassName = netId in constants.NETWORKS && constants.NETWORKS[netId].TESTNET ? "sokol" : "";
return (
<footer className={`footer ${footerClassName}`}>
<div className="container">

View File

@ -1,8 +1,8 @@
import React from 'react';
import helpers from "./helpers";
import { constants } from "./constants";
let Header = ({netId}) => {
const thisIsTestnet = helpers.isTestnet(netId);
const thisIsTestnet = netId in constants.NETWORKS && constants.NETWORKS[netId].TESTNET;
const headerClassName = thisIsTestnet ? "sokol" : "";
const logoClassName = thisIsTestnet ? "header-logo-sokol" : "header-logo";
return (

View File

@ -8,16 +8,12 @@ const styles = (netId) => {
const sokol = {
backgroundColor: 'rgba(47, 109, 99, 0.8)'
}
switch(netId) {
case constants.NETID_SOKOL:
case constants.NETID_DAI_TEST:
return sokol;
case constants.NETID_CORE:
case constants.NETID_DAI:
return core;
default:
return {};
if (netId in constants.NETWORKS) {
return constants.NETWORKS[netId].TESTNET ? sokol : core
}
return core
}
const Loading = ({netId}) => (
<div className="loading-container" style={styles(netId)}>

View File

@ -5,23 +5,7 @@ import helpers from "./helpers";
//}
export default (web3Config) => {
let branch;
switch (web3Config.netId) {
case constants.NETID_DAI_TEST:
branch = "dai-test";
break;
case constants.NETID_SOKOL:
branch = "sokol";
break;
case constants.NETID_DAI:
branch = "dai";
break;
case constants.NETID_CORE:
default:
branch = "core";
break;
}
const branch = constants.NETWORKS[web3Config.netId].BRANCH;
return new Promise((resolve, reject) => {
fetch(helpers.addressesURL(branch)).then((response) => {
response.json().then((json) => {

View File

@ -7,10 +7,32 @@ constants.ABIsSources = {
};
constants.userDeniedTransactionPattern = 'User denied transaction';
constants.NETID_SOKOL = "77";
constants.NETID_CORE = "99";
constants.NETID_DAI_TEST = "79";
constants.NETID_DAI = "100";
constants.NETWORKS = {
'77': {
NAME: 'Sokol',
RPC: 'https://sokol.poa.network',
BRANCH: 'sokol',
TESTNET: true
},
'99': {
NAME: 'Core',
RPC: 'https://core.poa.network',
BRANCH: 'core',
TESTNET: false
},
'79': {
NAME: 'Dai-Test',
RPC: 'http://40.112.48.125',
BRANCH: 'dai-test',
TESTNET: true
},
'100': {
NAME: 'Dai',
RPC: 'https://dai.poa.network',
BRANCH: 'dai',
TESTNET: false
}
};
module.exports = {
constants

View File

@ -1,9 +1,12 @@
import Web3 from "web3";
import { constants } from "./constants";
let errorMsgNoMetamaskAccount = `You haven't chosen any account in MetaMask.
const errorMsgNoMetamaskAccount = `You haven't chosen any account in MetaMask.
Please choose your initial key in MetaMask and reload the page.
Check POA Network <a href='https://github.com/poanetwork/wiki' target='blank'>wiki</a> for more info.`;
const errorMsgDeniedAccess = "You have denied access to your accounts";
function generateElement(msg){
let errorNode = document.createElement("div");
errorNode.innerHTML = `<div style="line-height: 1.6;">
@ -14,66 +17,66 @@ function generateElement(msg){
let getWeb3 = () => {
return new Promise(function (resolve, reject) {
// Wait for loading completion to avoid race conditions with web3 injection timing.
window.addEventListener('load', function () {
var results
var web3 = window.web3
window.addEventListener("load", async function () {
let web3;
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider.
var errorMsg = null;
web3 = new window.Web3(web3.currentProvider)
web3.version.getNetwork((err, netId) => {
let netIdName;
switch (netId) {
case constants.NETID_SOKOL:
netIdName = "Sokol";
console.log("This is sokol");
break
case constants.NETID_DAI_TEST:
netIdName = "Dai-Test";
console.log("This is Dai-Test");
break
case constants.NETID_CORE:
netIdName = "Core";
console.log("This is Core");
break
case constants.NETID_DAI:
netIdName = "Dai";
console.log("This is Dai");
break
default:
netIdName = "Unknown";
errorMsg = `You aren't connected to POA Network.
Please switch on Metamask and refresh the page.
Check POA Network <a href='https://github.com/poanetwork/wiki' target='blank'>wiki</a> for more info.
<b>Current Network ID</b> is <i>${netId}</i>`;
console.log("This is an unknown network.", netId);
}
results = {
web3Instance: web3,
netIdName,
netId,
injectedWeb3: true
}
document.title = `${netIdName} - Dapp Keys Generation`
var defaultAccount = web3.eth.defaultAccount || null;
if(defaultAccount === null){
reject({msg: errorMsgNoMetamaskAccount, node: generateElement(errorMsgNoMetamaskAccount)})
}
if(errorMsg !== null){
reject({msg: errorMsg, node: generateElement(errorMsg)})
}
resolve(results)
})
console.log('Injected web3 detected.');
if (window.ethereum) {
web3 = new Web3(window.ethereum);
console.log("Injected web3 detected.");
try {
await window.ethereum.enable();
} catch (e) {
reject({msg: errorMsgDeniedAccess, node: generateElement(errorMsgDeniedAccess)});
return;
}
} else if (window.web3) {
web3 = new Web3(window.web3.currentProvider);
console.log("Injected web3 detected.");
} else {
reject({msg: errorMsgNoMetamaskAccount, node: generateElement(errorMsgNoMetamaskAccount)})
console.error('Metamask not found');
console.error("Metamask not found");
reject({msg: errorMsgNoMetamaskAccount, node: generateElement(errorMsgNoMetamaskAccount)});
return;
}
const netId = await web3.eth.net.getId();
console.log("netId", netId);
let netIdName;
let errorMsg = null;
if (netId in constants.NETWORKS) {
netIdName = constants.NETWORKS[netId].NAME;
console.log(`This is ${netIdName}`);
} else {
netIdName = "ERROR";
errorMsg = `You aren't connected to POA Network.
Please switch on Metamask and refresh the page.
Check POA Network <a href='https://github.com/poanetwork/wiki' target='blank'>wiki</a> for more info.
<b>Current Network ID</b> is <i>${netId}</i>`;
console.log("This is an unknown network.");
}
document.title = `${netIdName} - DApp Keys Generation`;
if (errorMsg !== null) {
reject({msg: errorMsg, node: generateElement(errorMsg)});
return;
}
const accounts = await web3.eth.getAccounts();
const defaultAccount = accounts[0] || null;
if (defaultAccount === null) {
reject({msg: errorMsgNoMetamaskAccount, node: generateElement(errorMsgNoMetamaskAccount)});
return;
}
resolve({
web3Instance: web3,
netIdName,
netId,
defaultAccount
});
})
})
}

View File

@ -4,65 +4,47 @@ import swal from 'sweetalert';
var toAscii = function(hex) {
var str = '',
i = 0,
l = hex.length;
i = 0,
l = hex.length;
if (hex.substring(0, 2) === '0x') {
i = 2;
i = 2;
}
for (; i < l; i+=2) {
var code = parseInt(hex.substr(i, 2), 16);
if (code === 0) continue; // this is added
str += String.fromCharCode(code);
var code = parseInt(hex.substr(i, 2), 16);
if (code === 0) continue; // this is added
str += String.fromCharCode(code);
}
return str;
};
function addressesURL(branch) {
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/${constants.addressesSourceFile}`;
return URL;
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/${constants.addressesSourceFile}`;
return URL;
}
function ABIURL(branch, contract) {
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/abis/${constants.ABIsSources[contract]}`;
return URL;
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/abis/${constants.ABIsSources[contract]}`;
return URL;
}
function getABI(branch, contract) {
let addr = ABIURL(branch, contract);
return fetch(addr).then(function(response) {
return response.json();
})
let addr = ABIURL(branch, contract);
return fetch(addr).then(function(response) {
return response.json();
})
}
function wrongRepoAlert(addr) {
var content = document.createElement("div");
content.innerHTML = `<div>
Something went wrong!<br/><br/>
${messages.wrongRepo(addr)}
</div>`;
swal({
icon: 'error',
title: 'Error',
content: content
});
}
function getBranch(netId) {
switch (netId) {
case constants.NETID_DAI_TEST:
return "dai-test";
case constants.NETID_SOKOL:
return "sokol";
case constants.NETID_DAI:
return "dai";
case constants.NETID_CORE:
default:
return "core";
}
}
function isTestnet(netId) {
return netId === constants.NETID_SOKOL || netId === constants.NETID_DAI_TEST;
var content = document.createElement("div");
content.innerHTML = `<div>
Something went wrong!<br/><br/>
${messages.wrongRepo(addr)}
</div>`;
swal({
icon: 'error',
title: 'Error',
content: content
});
}
let helpers = {
@ -70,9 +52,7 @@ let helpers = {
addressesURL,
ABIURL,
getABI,
wrongRepoAlert,
getBranch,
isTestnet
wrongRepoAlert
}
export default helpers

View File

@ -1,24 +1,27 @@
import Web3 from 'web3';
import addressGenerator from './addressGenerator';
import helpers from "./helpers";
import { constants } from "./constants";
export default class KeysManager {
async init({web3, netId, addresses}){
this.web3_10 = new Web3(web3.currentProvider);
const {KEYS_MANAGER_ADDRESS} = addresses;
console.log('Keys Manager ', KEYS_MANAGER_ADDRESS);
const branch = helpers.getBranch(netId);
const KeysManagerAbi = await helpers.getABI(branch, 'KeysManager')
const KeysManagerAbi = await helpers.getABI(constants.NETWORKS[netId].BRANCH, 'KeysManager')
this.keysInstance = new this.web3_10.eth.Contract(KeysManagerAbi, KEYS_MANAGER_ADDRESS);
this.netId = netId;
this.instance = new web3.eth.Contract(KeysManagerAbi, KEYS_MANAGER_ADDRESS);
const networkName = constants.NETWORKS[netId].NAME.toLowerCase();
if (networkName === 'dai-test' || networkName === 'dai') {
this.gasPrice = web3.utils.toWei('0', 'gwei');
} else {
this.gasPrice = web3.utils.toWei('2', 'gwei');
}
}
async isInitialKeyValid(initialKey) {
return new Promise((resolve, reject) => {
const methods = this.keysInstance.methods
const methods = this.instance.methods
let getInitialKeyStatus
if (methods.getInitialKeyStatus) {
getInitialKeyStatus = methods.getInitialKeyStatus
@ -37,14 +40,10 @@ export default class KeysManager {
return await addressGenerator();
}
createKeys({mining, voting, payout, sender}){
let gasPrice = '2';
if (this.netId === constants.NETID_DAI_TEST || this.netId === constants.NETID_DAI) {
gasPrice = '0';
}
return this.keysInstance.methods.createKeys(mining, voting, payout).send({
createKeys({mining, voting, payout, sender}) {
return this.instance.methods.createKeys(mining, voting, payout).send({
from: sender,
gasPrice: this.web3_10.utils.toWei(gasPrice, 'gwei')
gasPrice: this.gasPrice
});
}
}