eslint + prettier configuration

This commit is contained in:
viktor 2018-07-11 18:50:14 +03:00
parent 98afd57a52
commit f730cd9967
35 changed files with 5924 additions and 4283 deletions

8
.babelrc Normal file
View File

@ -0,0 +1,8 @@
{
"presets": [
"es2015",
"stage-1",
"react"
],
"plugins": ["transform-decorators-legacy"]
}

16
.eslintrc Normal file
View File

@ -0,0 +1,16 @@
{
"extends": [
"react-app",
"plugin:prettier/recommended"
],
"plugins": [
"dependencies"
],
"rules": {
"no-control-regex": 0,
"dependencies/no-cycles": "error",
"dependencies/no-unresolved": ["error", {
"ignore": ["web3"]
}]
}
}

2
.nvmrc
View File

@ -1 +1 @@
v8.3.0
v8.11.3

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
assets
build_scripts
config
public
scripts
submodules
*.js

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"semi": false,
"singleQuote": true,
"printWidth": 120
}

144
build_scripts/build.js Normal file
View File

@ -0,0 +1,144 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
console.log((err.message || err) + '\n');
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

92
build_scripts/start.js Normal file
View File

@ -0,0 +1,92 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `detect()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

27
build_scripts/test.js Normal file
View File

@ -0,0 +1,27 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
}
jest.run(argv);

90
config/env.js Normal file
View File

@ -0,0 +1,90 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv').config({
path: dotenvFile,
});
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

55
config/paths.js Normal file
View File

@ -0,0 +1,55 @@
'use strict';
const path = require('path');
const fs = require('fs');
const url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appBuild: resolveApp('build'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveApp('src/index.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveApp('src/setupTests.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
};

18
config/polyfills.js Normal file
View File

@ -0,0 +1,18 @@
'use strict';
if (typeof Promise === 'undefined') {
// Rejection tracking prevents a common issue where React gets into an
// inconsistent state due to an error, but it gets swallowed by a Promise,
// and the user has no idea what causes React's erratic future behavior.
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js');
}
// fetch() polyfill for making API calls.
require('whatwg-fetch');
// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');
require('babel-polyfill')

View File

@ -0,0 +1,266 @@
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Errors should be considered fatal in development
require.resolve('react-error-overlay'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Next line is not used in dev but WebpackDevServer crashes without it:
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
// ** ADDING/UPDATING LOADERS **
// The "file" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list for "file" loader.
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "file" loader exclusion list.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};

View File

@ -0,0 +1,332 @@
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
throw new Error('Production builds must have NODE_ENV=production.');
}
// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';
// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
? // Making sure that the publicPath goes back to to build folder.
{ publicPath: Array(cssFilename.split('/').length).join('../') }
: {};
// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
// Don't attempt to continue if there are any errors.
bail: true,
// We generate sourcemaps in production. This is slow but gives good results.
// You can exclude the *.map files from the build during deployment.
devtool: 'source-map',
// In production, we only want to load the polyfills and the app code.
entry: [require.resolve('./polyfills'), paths.appIndexJs],
output: {
// The build folder.
path: paths.appBuild,
// Generated JS file names (with nested folders).
// There will be one main bundle, and one file per asynchronous chunk.
// We don't currently advertise code splitting but Webpack supports it.
filename: 'static/js/[name].[chunkhash:8].js',
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
// ** ADDING/UPDATING LOADERS **
// The "file" loader handles all assets unless explicitly excluded.
// The `exclude` list *must* be updated with every change to loader extensions.
// When adding a new loader, you must add its `test`
// as a new entry in the `exclude` list in the "file" loader.
// "file" loader makes sure those assets end up in the `build` folder.
// When you `import` an asset, you get its filename.
{
exclude: [
/\.html$/,
/\.(js|jsx)$/,
/\.css$/,
/\.json$/,
/\.bmp$/,
/\.gif$/,
/\.jpe?g$/,
/\.png$/,
],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// "url" loader works just like "file" loader but it also embeds
// assets smaller than specified size as data URLs to avoid requests.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
compact: true,
},
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: require.resolve('style-loader'),
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: true,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
extractTextPluginOptions
)
),
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
// ** STOP ** Are you adding a new loader?
// Remember to add the new extension(s) to the "file" loader exclusion list.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV was set to production here.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Minify the code.
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebookincubator/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
},
output: {
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebookincubator/create-react-app/issues/2488
ascii_only: true,
},
sourceMap: true,
}),
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
new ExtractTextPlugin({
filename: cssFilename,
}),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
new ManifestPlugin({
fileName: 'asset-manifest.json',
}),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
new SWPrecacheWebpackPlugin({
// By default, a cache-busting query parameter is appended to requests
// used to populate the caches, to ensure the responses are fresh.
// If a URL is already hashed by Webpack, then there is no concern
// about it being stale, and the cache-busting can be skipped.
dontCacheBustUrlsMatching: /\.\w{8}\./,
filename: 'service-worker.js',
logger(message) {
if (message.indexOf('Total precache size is') === 0) {
// This message occurs for every build and is a bit too noisy.
return;
}
if (message.indexOf('Skipping static resource') === 0) {
// This message obscures real errors so we ignore it.
// https://github.com/facebookincubator/create-react-app/issues/2612
return;
}
console.log(message);
},
minify: true,
// For unknown URLs, fallback to the index page
navigateFallback: publicUrl + '/index.html',
// Ignores URLs starting from /__ (useful for Firebase):
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
navigateFallbackWhitelist: [/^(?!\/__).*/],
// Don't precache sourcemaps (they're large) and build asset manifest:
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
},
};

View File

@ -0,0 +1,92 @@
'use strict';
const errorOverlayMiddleware = require('react-error-overlay/middleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const config = require('./webpack.config.dev');
const paths = require('./paths');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';
module.exports = function(proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebookincubator/create-react-app/issues/2271
// https://github.com/facebookincubator/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: config.output.publicPath,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.plugin` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebookincubator/create-react-app/issues/293
watchOptions: {
ignored: /node_modules/,
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === 'https',
host: host,
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
},
public: allowedHost,
proxy,
setup(app) {
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware());
},
};
};

7367
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -2,22 +2,42 @@
"name": "poa-dapps-validators",
"version": "0.2.0",
"private": true,
"homepage": "https://poanetwork.github.io/",
"homepage": "https://validators.poa.network",
"dependencies": {
"ajv": "^6.5.2",
"babel-core": "^6.26.3",
"babel-eslint": "^7.2.3",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react-app": "^3.0.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"babel-runtime": "6.23.0",
"eslint": "^4.1.1",
"eslint-config-prettier": "2.9.0",
"eslint-config-react-app": "^2.1.0",
"eslint-plugin-dependencies": "^2.4.0",
"eslint-plugin-flowtype": "^2.34.1",
"eslint-plugin-import": "^2.6.0",
"eslint-plugin-jsx-a11y": "^5.1.1",
"eslint-plugin-prettier": "2.6.0",
"eslint-plugin-react": "^7.1.0",
"gh-pages": "^1.2.0",
"moment": "^2.19.3",
"moment": "^2.22.2",
"node-sass-chokidar": "1.3.0",
"nodemon": "^1.17.5",
"npm-run-all": "^4.1.2",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"npm-run-all": "^4.1.3",
"prettier": "^1.13.7",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-error-overlay": "^1.0.9",
"react-places-autocomplete": "^5.4.3",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-scripts": "1.1.4",
"react-select": "^1.2.1",
"sweetalert": "^2.0.8",
"sweetalert": "^2.1.0",
"web3": "1.0.0-beta.34"
},
"scripts": {
@ -26,10 +46,32 @@
"build-css": "node-sass-chokidar src/stylesheets/application.scss -o src/stylesheets --output-style=compressed",
"watch-css": "nodemon -e scss -x \"npm run build-css\"",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"start": "node scripts/start.js",
"build-js": "react-scripts build",
"build": "npm-run-all build-css build-js",
"build": "node scripts/build.js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
"eject": "react-scripts eject",
"lint": "./node_modules/.bin/eslint src"
},
"eslintConfig": {
"extends": [
"react-app",
"plugin:prettier/recommended"
],
"plugins": [
"dependencies"
],
"rules": {
"no-control-regex": 0,
"dependencies/no-cycles": "error",
"dependencies/no-unresolved": [
"error",
{
"ignore": [
"web3"
]
}
]
}
}
}

144
scripts/build.js Normal file
View File

@ -0,0 +1,144 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
console.log((err.message || err) + '\n');
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

92
scripts/start.js Normal file
View File

@ -0,0 +1,92 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `detect()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

View File

@ -1,61 +1,67 @@
import React, {Component} from 'react';
import React, { Component } from 'react'
import Validator from './Validator'
import Loading from './Loading'
export default class AllValidators extends Component {
constructor(props){
super(props);
this.getMetadataContract = this.getMetadataContract.bind(this);
constructor(props) {
super(props)
this.getMetadataContract = this.getMetadataContract.bind(this)
this.state = {
validators: [],
loading: true,
loading: true
}
this.getValidatorsData.call(this);
this.getValidatorsData.call(this)
}
componentWillMount() {
const netId = this.props.web3Config.netId;
this.setState({loading: true, netId: netId})
const { props } = this
const { web3Config } = props
const { netId } = web3Config
this.setState({ loading: true, netId: netId })
}
async getValidatorsData() {
const netId = this.props.web3Config.netId;
this.getMetadataContract()[this.props.methodToCall](netId).then((data) => {
for (let i = 0; i < data.length; i++) {
data[i].index = i + 1;
}
this.setState({
validators: data,
loading: false,
reload: false,
netId
const netId = this.props.web3Config.netId
this.getMetadataContract()
[this.props.methodToCall](netId)
.then(data => {
for (let i = 0; i < data.length; i++) {
data[i].index = i + 1
}
this.setState({
validators: data,
loading: false,
reload: false,
netId
})
})
})
}
shouldComponentUpdate(nextProps, nextState){
if(nextProps.web3Config.netId !== this.state.netId){
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.web3Config.netId !== this.state.netId) {
this.getValidatorsData.call(this)
return false;
return false
}
return true;
return true
}
getMetadataContract(){
return this.props.web3Config.metadataContract;
getMetadataContract() {
return this.props.web3Config.metadataContract
}
render() {
const loading = this.state.loading ? <Loading netId={this.state.netId} /> : ''
const filtered = this.state.validators.filter((validator, index) => {
return Object.values(validator).some( val =>
String(val).toLowerCase().includes(this.props.searchTerm)
);
return Object.values(validator).some(val =>
String(val)
.toLowerCase()
.includes(this.props.searchTerm)
)
})
let validators = [];
for(let [index, validator] of filtered.entries()) {
let childrenWithProps = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, { miningkey: validator.address });
let validators = []
for (let [index, validator] of filtered.entries()) {
let childrenWithProps = React.Children.map(this.props.children, child => {
return React.cloneElement(child, { miningkey: validator.address })
})
validators.push(
<Validator
key={index}
address={validator.address}
address={validator.address}
firstName={validator.firstName}
lastName={validator.lastName}
fullAddress={validator.fullAddress}
@ -73,17 +79,21 @@ export default class AllValidators extends Component {
</Validator>
)
}
const isValidatorsPage = this.props.methodToCall === 'getAllValidatorsData';
const validatorsCountObj = <div className="validators-count">
<span className="validators-count-label">Total number of validators: </span>
<span className="validators-count-val">{this.state.validators.length}</span>
</div>;
const validatorsCount = isValidatorsPage ? validatorsCountObj : '';
return (<div className="container">
{loading}
{validatorsCount}
{validators}
</div>)
const isValidatorsPage = this.props.methodToCall === 'getAllValidatorsData'
const validatorsCountObj = (
<div className="validators-count">
<span className="validators-count-label">Total number of validators: </span>
<span className="validators-count-val">{this.state.validators.length}</span>
</div>
)
const validatorsCount = isValidatorsPage ? validatorsCountObj : ''
return (
<div className="container">
{loading}
{validatorsCount}
{validators}
</div>
)
}
}

View File

@ -1,26 +1,26 @@
import React, { Component } from 'react';
import './stylesheets/application.css';
import PlacesAutocomplete, { geocodeByAddress } from 'react-places-autocomplete';
import moment from 'moment';
import Loading from './Loading';
import { messages } from './messages';
import helpers from './helpers';
import { constants } from "./constants";
import React, { Component } from 'react'
import './stylesheets/application.css'
import PlacesAutocomplete, { geocodeByAddress } from 'react-places-autocomplete'
import moment from 'moment'
import Loading from './Loading'
import { messages } from './messages'
import helpers from './helpers'
import { constants } from './constants'
class App extends Component {
constructor(props){
super(props);
constructor(props) {
super(props)
this.checkValidation = this.checkValidation.bind(this)
this.onClick = this.onClick.bind(this);
this.onChangeFormField = this.onChangeFormField.bind(this);
this.getKeysManager = this.getKeysManager.bind(this);
this.getMetadataContract = this.getMetadataContract.bind(this);
this.getVotingKey = this.getVotingKey.bind(this);
this.onChangeAutoComplete = ((address) => {
const form = this.state.form;
form.fullAddress = address;
this.setState({form})
})
this.onClick = this.onClick.bind(this)
this.onChangeFormField = this.onChangeFormField.bind(this)
this.getKeysManager = this.getKeysManager.bind(this)
this.getMetadataContract = this.getMetadataContract.bind(this)
this.getVotingKey = this.getVotingKey.bind(this)
this.onChangeAutoComplete = address => {
const form = this.state.form
form.fullAddress = address
this.setState({ form })
}
this.onSelect = this.onSelectAutocomplete.bind(this)
this.state = {
web3Config: {},
@ -34,19 +34,21 @@ class App extends Component {
licenseId: ''
},
hasData: false
}
this.defaultValues = null;
this.setMetadata.call(this);
this.defaultValues = null
this.setMetadata.call(this)
}
async setMetadata(){
const currentData = await this.getMetadataContract().getValidatorData({votingKey: this.getVotingKey()});
async setMetadata() {
const currentData = await this.getMetadataContract().getValidatorData({
votingKey: this.getVotingKey()
})
const hasData = currentData.postal_code ? true : false
this.defaultValues = currentData;
const pendingChange = await this.getMetadataContract().getPendingChange({votingKey: this.getVotingKey()});
if(Number(pendingChange.minThreshold) > 0 ) {
this.defaultValues = currentData
const pendingChange = await this.getMetadataContract().getPendingChange({
votingKey: this.getVotingKey()
})
if (Number(pendingChange.minThreshold) > 0) {
var msg = `
First Name: <b>${pendingChange.firstName}</b> <br/>
Last Name: <b>${pendingChange.lastName}</b> <br/>
@ -55,8 +57,8 @@ class App extends Component {
License ID: <b>${pendingChange.licenseId}</b> <br/>
US state: <b>${pendingChange.us_state}</b> <br/>
Zip Code: <b>${pendingChange.postal_code}</b> <br/>
`;
helpers.generateAlert("warning", "You have pending changes!", msg);
`
helpers.generateAlert('warning', 'You have pending changes!', msg)
}
this.setState({
form: {
@ -66,133 +68,135 @@ class App extends Component {
us_state: currentData.us_state,
firstName: currentData.firstName,
lastName: currentData.lastName,
licenseId: currentData.licenseId,
licenseId: currentData.licenseId
},
hasData
});
})
}
getKeysManager(){
return this.props.web3Config.keysManager;
getKeysManager() {
return this.props.web3Config.keysManager
}
getMetadataContract(){
return this.props.web3Config.metadataContract;
getMetadataContract() {
return this.props.web3Config.metadataContract
}
getVotingKey(){
return this.props.web3Config.votingKey;
getVotingKey() {
return this.props.web3Config.votingKey
}
checkValidation() {
const isAfter = moment(this.state.form.expirationDate).isAfter(moment());
let keys = Object.keys(this.state.form);
keys.forEach((key) => {
if(!this.state.form[key]){
this.setState({loading: false})
helpers.generateAlert("warning", "Warning!", `${key} cannot be empty`);
return false;
const isAfter = moment(this.state.form.expirationDate).isAfter(moment())
let keys = Object.keys(this.state.form)
keys.forEach(key => {
if (!this.state.form[key]) {
this.setState({ loading: false })
helpers.generateAlert('warning', 'Warning!', `${key} cannot be empty`)
return false
}
})
if(isAfter){
if (isAfter) {
} else {
this.setState({loading: false})
helpers.generateAlert("warning", "Warning!", "Expiration date should be valid");
return false;
this.setState({ loading: false })
helpers.generateAlert('warning', 'Warning!', 'Expiration date should be valid')
return false
}
return true;
return true
}
async onSelectAutocomplete(data) {
let place = await geocodeByAddress(data)
let address_components = {};
let address_components = {}
for (var i = 0; i < place[0].address_components.length; i++) {
var addressType = place[0].address_components[i].types[0];
switch(addressType) {
case "postal_code":
address_components.postal_code = place[0].address_components[i].short_name;
break;
case "street_number":
address_components.street_number = place[0].address_components[i].short_name;
break;
case "route":
address_components.route = place[0].address_components[i].short_name;
break;
case "locality":
address_components.locality = place[0].address_components[i].short_name;
break;
case "administrative_area_level_1":
address_components.administrative_area_level_1 = place[0].address_components[i].short_name;
break;
var addressType = place[0].address_components[i].types[0]
switch (addressType) {
case 'postal_code':
address_components.postal_code = place[0].address_components[i].short_name
break
case 'street_number':
address_components.street_number = place[0].address_components[i].short_name
break
case 'route':
address_components.route = place[0].address_components[i].short_name
break
case 'locality':
address_components.locality = place[0].address_components[i].short_name
break
case 'administrative_area_level_1':
address_components.administrative_area_level_1 = place[0].address_components[i].short_name
break
default:
break;
break
}
let form = this.state.form;
form.fullAddress= `${address_components.street_number} ${address_components.route} ${address_components.locality}`;
form.us_state= address_components.administrative_area_level_1;
form.postal_code= address_components.postal_code;
let form = this.state.form
form.fullAddress = `${address_components.street_number} ${address_components.route} ${
address_components.locality
}`
form.us_state = address_components.administrative_area_level_1
form.postal_code = address_components.postal_code
this.setState({
form
});
})
}
}
async onClick() {
this.setState({loading:true});
const isFormValid = this.checkValidation();
if(isFormValid){
const votingKey = this.getVotingKey();
this.setState({ loading: true })
const isFormValid = this.checkValidation()
if (isFormValid) {
const votingKey = this.getVotingKey()
console.log('voting', votingKey)
const isValid = await this.getKeysManager().isVotingActive(votingKey);
console.log(isValid);
if(isValid){
// // add loading screen
const isValid = await this.getKeysManager().isVotingActive(votingKey)
console.log(isValid)
if (isValid) {
// // add loading screen
await this.sendTxToContract()
} else {
this.setState({loading:false});
helpers.generateAlert("warning", "Warning!", messages.invalidaVotingKey);
return;
this.setState({ loading: false })
helpers.generateAlert('warning', 'Warning!', messages.invalidaVotingKey)
return
}
}
}
async sendTxToContract(){
this.getMetadataContract().createMetadata({
firstName: this.state.form.firstName,
lastName: this.state.form.lastName,
licenseId: this.state.form.licenseId,
fullAddress: this.state.form.fullAddress,
state: this.state.form.us_state,
zipcode: this.state.form.postal_code,
expirationDate: moment(this.state.form.expirationDate).unix(),
votingKey: this.getVotingKey(),
hasData: this.state.hasData
}).then((receipt) => {
console.log(receipt);
this.setState({loading: false})
helpers.generateAlert("success", "Congratulations!", "Your metadata was sent!");
}).catch((error) => {
console.error(error.message);
let errDescription
if (error.message.includes(constants.userDeniedTransactionPattern))
errDescription = `Error: User ${constants.userDeniedTransactionPattern}`
else
errDescription = error.message
this.setState({loading: false})
var msg = `
async sendTxToContract() {
this.getMetadataContract()
.createMetadata({
firstName: this.state.form.firstName,
lastName: this.state.form.lastName,
licenseId: this.state.form.licenseId,
fullAddress: this.state.form.fullAddress,
state: this.state.form.us_state,
zipcode: this.state.form.postal_code,
expirationDate: moment(this.state.form.expirationDate).unix(),
votingKey: this.getVotingKey(),
hasData: this.state.hasData
})
.then(receipt => {
console.log(receipt)
this.setState({ loading: false })
helpers.generateAlert('success', 'Congratulations!', 'Your metadata was sent!')
})
.catch(error => {
console.error(error.message)
let errDescription
if (error.message.includes(constants.userDeniedTransactionPattern))
errDescription = `Error: User ${constants.userDeniedTransactionPattern}`
else errDescription = error.message
this.setState({ loading: false })
var msg = `
Something went wrong!<br/><br/>
${errDescription}
`;
helpers.generateAlert("error", "Error!", msg);
})
`
helpers.generateAlert('error', 'Error!', msg)
})
}
onChangeFormField(event) {
const field = event.target.id;
const value = event.target.value;
let form = this.state.form;
form[field] = value;
this.setState({form});
const field = event.target.id
const value = event.target.value
let form = this.state.form
form[field] = value
this.setState({ form })
}
render() {
const BtnAction = this.state.hasData ? "Update" : "Set";
const BtnAction = this.state.hasData ? 'Update' : 'Set'
const AutocompleteItem = ({ formattedSuggestion }) => (
<div className="custom-container">
<strong>{ formattedSuggestion.mainText }</strong>{' '}
<small>{ formattedSuggestion.secondaryText }</small>
<strong>{formattedSuggestion.mainText}</strong> <small>{formattedSuggestion.secondaryText}</small>
</div>
)
@ -201,39 +205,47 @@ class App extends Component {
onChange: this.onChangeAutoComplete,
id: 'address'
}
let loader = this.state.loading ? <Loading /> : '';
let loader = this.state.loading ? <Loading /> : ''
let createKeyBtn = (
<div className="create-keys">
<form className="create-keys-form">
<div className="create-keys-form-i">
<label htmlFor="first-name">First name</label>
<input type="text" id="firstName" value={this.state.form.firstName} onChange={this.onChangeFormField}/>
<input type="text" id="firstName" value={this.state.form.firstName} onChange={this.onChangeFormField} />
<label htmlFor="last-name">Last name</label>
<input type="text" id="lastName" value={this.state.form.lastName} onChange={this.onChangeFormField}/>
<input type="text" id="lastName" value={this.state.form.lastName} onChange={this.onChangeFormField} />
<label htmlFor="address">Address</label>
<PlacesAutocomplete onSelect={this.onSelect} inputProps={inputProps} autocompleteItem={AutocompleteItem} />
<label htmlFor="state">State</label>
<input type="text" id="us_state" value={this.state.form.us_state} onChange={this.onChangeFormField}/>
<input type="text" id="us_state" value={this.state.form.us_state} onChange={this.onChangeFormField} />
</div>
<div className="create-keys-form-i">
<label htmlFor="zip">Zip code</label>
<input type="text" id="postal_code" value={this.state.form.postal_code} onChange={this.onChangeFormField}/>
<input type="text" id="postal_code" value={this.state.form.postal_code} onChange={this.onChangeFormField} />
<label htmlFor="licenseId">License id</label>
<input type="text" id="licenseId" value={this.state.form.licenseId} onChange={this.onChangeFormField}/>
<input type="text" id="licenseId" value={this.state.form.licenseId} onChange={this.onChangeFormField} />
<label htmlFor="expirationDate">License expiration</label>
<input type="date" id="expirationDate" value={this.state.form.expirationDate} onChange={this.onChangeFormField}/>
<input
type="date"
id="expirationDate"
value={this.state.form.expirationDate}
onChange={this.onChangeFormField}
/>
</div>
</form>
<button onClick={this.onClick} className="create-keys-button">{BtnAction} Metadata</button>
</div>)
let content = createKeyBtn;
<button onClick={this.onClick} className="create-keys-button">
{BtnAction} Metadata
</button>
</div>
)
let content = createKeyBtn
return (
<div className="container">
{loader}
{content}
</div>
);
)
}
}
export default App;
export default App

View File

@ -1,8 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
const div = document.createElement('div')
ReactDOM.render(<App />, div)
})

View File

@ -1,21 +1,29 @@
import React from 'react';
import moment from 'moment';
const Footer = ({netId}) => {
const footerClassName = netId === '77' ? 'sokol' : '';
import React from 'react'
import moment from 'moment'
const Footer = ({ netId }) => {
const footerClassName = netId === '77' ? 'sokol' : ''
return (
<footer className={`footer ${footerClassName}`}>
<div className="container">
<p className="footer-rights">{moment().format('YYYY')} POA Network. All rights reserved.</p>
<a href="/poa-dapps-keys-generation" className="footer-logo"></a>
<div className="socials">
<a href="https://twitter.com/poanetwork" className="socials-i socials-i_twitter">Twitter</a>
<a href="https://poa.network" className="socials-i socials-i_oracles">POA Network</a>
<a href="https://t.me/oraclesnetwork" className="socials-i socials-i_telegram">Telegram</a>
<a href="https://github.com/poanetwork/" className="socials-i socials-i_github">GitHub</a>
<footer className={`footer ${footerClassName}`}>
<div className="container">
<p className="footer-rights">{moment().format('YYYY')} POA Network. All rights reserved.</p>
<a href="/poa-dapps-keys-generation" className="footer-logo" />
<div className="socials">
<a href="https://twitter.com/poanetwork" className="socials-i socials-i_twitter">
Twitter
</a>
<a href="https://poa.network" className="socials-i socials-i_oracles">
POA Network
</a>
<a href="https://t.me/oraclesnetwork" className="socials-i socials-i_telegram">
Telegram
</a>
<a href="https://github.com/poanetwork/" className="socials-i socials-i_github">
GitHub
</a>
</div>
</div>
</div>
</footer>
</footer>
)
}
export default Footer;
export default Footer

View File

@ -1,30 +1,30 @@
import React from 'react';
const styles = (netId) => {
import React from 'react'
const styles = netId => {
const core = {
backgroundColor: 'rgba(35, 29, 115, 0.8)'
};
}
const sokol = {
backgroundColor: 'rgba(47, 109, 99, 0.8)'
}
switch(netId) {
switch (netId) {
case '77':
return sokol;
return sokol
case '99':
return core;
return core
default:
return {};
return {}
}
}
const Loading = ({netId}) => (
const Loading = ({ netId }) => (
<div className="loading-container" style={styles(netId)}>
<div className="loading">
<div className="loading-i"></div>
<div className="loading-i"></div>
<div className="loading-i"></div>
<div className="loading-i"></div>
<div className="loading-i"></div>
<div className="loading-i"></div>
<div className="loading-i" />
<div className="loading-i" />
<div className="loading-i" />
<div className="loading-i" />
<div className="loading-i" />
<div className="loading-i" />
</div>
</div>
)
export default Loading;
export default Loading

View File

@ -1,13 +1,13 @@
import React, {Component} from 'react';
import React, { Component } from 'react'
class Validator extends Component {
constructor(props) {
super(props);
super(props)
this.state = {
confirmation: null
}
this.props.metadataContract.getConfirmations({miningKey: this.props.address}).then((confirmation) => {
this.setState({confirmation: confirmation[0]})
this.props.metadataContract.getConfirmations({ miningKey: this.props.address }).then(confirmation => {
this.setState({ confirmation: confirmation[0] })
})
}
@ -24,71 +24,81 @@ class Validator extends Component {
createdDate,
updatedDate,
index,
children,
} = this.props;
children
} = this.props
const showAllValidators = this.props.methodToCall === 'getAllValidatorsData';
const showAllValidators = this.props.methodToCall === 'getAllValidatorsData'
const confirmations = showAllValidators ? '' : <div className="confirmations">
<div>{this.state.confirmation} confirmations</div>
</div>;
const confirmations = showAllValidators ? (
''
) : (
<div className="confirmations">
<div>{this.state.confirmation} confirmations</div>
</div>
)
const indexAndAddress = showAllValidators ? `#${index}. ${address}` : address;
const pendingChangeDate = !updatedDate ? '' : <div className="validators-table-i">
<p>Pending Change Date</p>
<p>{updatedDate}</p>
</div>;
const indexAndAddress = showAllValidators ? `#${index}. ${address}` : address
const pendingChangeDate = !updatedDate ? (
''
) : (
<div className="validators-table-i">
<p>Pending Change Date</p>
<p>{updatedDate}</p>
</div>
)
return(
return (
<div className="validators-i">
<div className="validators-header">
<div className="validators-header--address">{indexAndAddress}</div>
<div>{confirmations}</div>
<div>{children}</div>
</div>
<div className="validators-body">
<div className="validators-notary left">
<p className="validators-title">Notary</p>
<div className="validators-table">
<div className="validators-table-i">
<p>Full Name</p>
<p>{firstName} {lastName}</p>
<div className="validators-header">
<div className="validators-header--address">{indexAndAddress}</div>
<div>{confirmations}</div>
<div>{children}</div>
</div>
<div className="validators-body">
<div className="validators-notary left">
<p className="validators-title">Notary</p>
<div className="validators-table">
<div className="validators-table-i">
<p>Full Name</p>
<p>
{firstName} {lastName}
</p>
</div>
<div className="validators-table-i">
<p>Address</p>
<p>{fullAddress}</p>
</div>
<div className="validators-table-i">
<p>State</p>
<p>{us_state}</p>
</div>
<div className="validators-table-i">
<p>Zip Code</p>
<p>{postal_code}</p>
</div>
</div>
<div className="validators-table-i">
<p>Address</p>
<p>{fullAddress}</p>
</div>
<div className="validators-table-i">
<p>State</p>
<p>{us_state}</p>
</div>
<div className="validators-table-i">
<p>Zip Code</p>
<p>{postal_code}</p>
</div>
<div className="validators-license right">
<p className="validators-title">Notary license</p>
<div className="validators-table">
<div className="validators-table-i">
<p>License ID</p>
<p>{licenseId}</p>
</div>
<div className="validators-table-i">
<p>License Expiration</p>
<p>{expirationDate}</p>
</div>
<div className="validators-table-i">
<p>Miner Creation Date</p>
<p>{createdDate}</p>
</div>
{pendingChangeDate}
</div>
</div>
</div>
<div className="validators-license right">
<p className="validators-title">Notary license</p>
<div className="validators-table">
<div className="validators-table-i">
<p>License ID</p>
<p>{licenseId}</p>
</div>
<div className="validators-table-i">
<p>License Expiration</p>
<p>{expirationDate}</p>
</div>
<div className="validators-table-i">
<p>Miner Creation Date</p>
<p>{createdDate}</p>
</div>
{pendingChangeDate}
</div>
</div>
</div>
</div>
)
}
}
export default Validator;
export default Validator

View File

@ -1,14 +1,14 @@
const constants = {};
constants.organization = 'poanetwork';
constants.repoName = 'poa-chain-spec';
constants.addressesSourceFile = 'contracts.json';
const constants = {}
constants.organization = 'poanetwork'
constants.repoName = 'poa-chain-spec'
constants.addressesSourceFile = 'contracts.json'
constants.ABIsSources = {
'KeysManager': 'KeysManager.abi.json',
'PoaNetworkConsensus': 'PoaNetworkConsensus.abi.json',
'ValidatorMetadata': 'ValidatorMetadata.abi.json'
};
constants.userDeniedTransactionPattern = 'User denied transaction';
KeysManager: 'KeysManager.abi.json',
PoaNetworkConsensus: 'PoaNetworkConsensus.abi.json',
ValidatorMetadata: 'ValidatorMetadata.abi.json'
}
constants.userDeniedTransactionPattern = 'User denied transaction'
module.exports = {
constants
};
}

View File

@ -1,18 +1,18 @@
import Web3 from 'web3';
import helpers from "./helpers";
import Web3 from 'web3'
import helpers from './helpers'
export default class KeysManager {
async init({web3, netId, addresses}){
let web3_10 = new Web3(web3.currentProvider);
const {KEYS_MANAGER_ADDRESS} = addresses;
console.log('Keys Manager address ', KEYS_MANAGER_ADDRESS);
const branch = helpers.getBranch(netId);
async init({ web3, netId, addresses }) {
let web3_10 = new Web3(web3.currentProvider)
const { KEYS_MANAGER_ADDRESS } = addresses
console.log('Keys Manager address ', KEYS_MANAGER_ADDRESS)
const branch = helpers.getBranch(netId)
let KeysManagerAbi = await helpers.getABI(branch, 'KeysManager')
this.keysInstance = new web3_10.eth.Contract(KeysManagerAbi, KEYS_MANAGER_ADDRESS);
this.keysInstance = new web3_10.eth.Contract(KeysManagerAbi, KEYS_MANAGER_ADDRESS)
}
async isVotingActive(votingKey) {
return await this.keysInstance.methods.isVotingActive(votingKey).call();
}
}
return await this.keysInstance.methods.isVotingActive(votingKey).call()
}
}

View File

@ -1,42 +1,42 @@
import PoaConsensus from './PoaConsensus.contract'
import Web3 from 'web3';
import moment from 'moment';
import helpers from "./helpers";
import helpersGlobal from "../helpers";
import { messages } from '../messages';
import Web3 from 'web3'
import moment from 'moment'
import helpers from './helpers'
import helpersGlobal from '../helpers'
import { messages } from '../messages'
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);
for (; i < l; i += 2) {
var code = parseInt(hex.substr(i, 2), 16)
if (code === 0) continue // this is added
str += String.fromCharCode(code)
}
return str;
};
return str
}
export default class Metadata {
async init({web3, netId, addresses}){
this.web3_10 = new Web3(web3.currentProvider);
const {METADATA_ADDRESS, MOC} = addresses;
async init({ web3, netId, addresses }) {
this.web3_10 = new Web3(web3.currentProvider)
const { METADATA_ADDRESS, MOC } = addresses
console.log('Metadata contract Address: ', METADATA_ADDRESS)
const branch = helpers.getBranch(netId);
const branch = helpers.getBranch(netId)
let MetadataAbi = await helpers.getABI(branch, 'ValidatorMetadata')
this.metadataInstance = new this.web3_10.eth.Contract(MetadataAbi, METADATA_ADDRESS);
this.MOC_ADDRESS = MOC;
this.addresses = addresses;
this.metadataInstance = new this.web3_10.eth.Contract(MetadataAbi, METADATA_ADDRESS)
this.MOC_ADDRESS = MOC
this.addresses = addresses
const poaInstance = new PoaConsensus();
await poaInstance.init({web3: this.web3_10, netId, addresses});
this.mocRemoved = await poaInstance.isMasterOfCeremonyRemoved();
this.miningKeys = await poaInstance.getValidators();
const poaInstance = new PoaConsensus()
await poaInstance.init({ web3: this.web3_10, netId, addresses })
this.mocRemoved = await poaInstance.isMasterOfCeremonyRemoved()
this.miningKeys = await poaInstance.getValidators()
}
async createMetadata({
firstName,
@ -59,7 +59,7 @@ export default class Metadata {
this.web3_10.utils.fromAscii(state),
this.web3_10.utils.fromAscii(zipcode),
expirationDate
).send({from: votingKey, gasPrice});
).send({ from: votingKey, gasPrice })
}
getMocData() {
@ -73,21 +73,22 @@ export default class Metadata {
expirationDate: '2021-07-23',
licenseId: '2206724',
us_state: 'CA',
postal_code: '94404',
postal_code: '94404'
}
}
async getValidatorData({votingKey, miningKey}){
miningKey = miningKey || await this.getMiningByVoting(votingKey);
async getValidatorData({ votingKey, miningKey }) {
miningKey = miningKey || (await this.getMiningByVoting(votingKey))
if (!miningKey) {
helpersGlobal.generateAlert("warning", "Warning!", messages.invalidaVotingKey);
return {};
helpersGlobal.generateAlert('warning', 'Warning!', messages.invalidaVotingKey)
return {}
}
let validatorData = await this.metadataInstance.methods.validators(miningKey).call();
let validatorData = await this.metadataInstance.methods.validators(miningKey).call()
let createdDate = validatorData.createdDate > 0 ? moment.unix(validatorData.createdDate).format('YYYY-MM-DD') : ''
let updatedDate = validatorData.updatedDate > 0 ? moment.unix(validatorData.updatedDate).format('YYYY-MM-DD') : ''
let expirationDate = validatorData.expirationDate > 0 ? moment.unix(validatorData.expirationDate).format('YYYY-MM-DD') : ''
let expirationDate =
validatorData.expirationDate > 0 ? moment.unix(validatorData.expirationDate).format('YYYY-MM-DD') : ''
return {
firstName: toAscii(validatorData.firstName),
lastName: toAscii(validatorData.lastName),
@ -97,53 +98,54 @@ export default class Metadata {
expirationDate,
licenseId: toAscii(validatorData.licenseId),
us_state: toAscii(validatorData.state),
postal_code: toAscii(validatorData.zipcode),
postal_code: toAscii(validatorData.zipcode)
}
}
async getMiningByVoting(votingKey){
async getMiningByVoting(votingKey) {
let miningKey
try {
miningKey = await this.metadataInstance.methods.getMiningByVotingKey(votingKey).call();
} catch(e) {
miningKey = await this.metadataInstance.methods.getMiningByVotingKey(votingKey).call()
} catch (e) {
console.log(e.message)
}
return miningKey;
return miningKey
}
async getAllValidatorsData(netId){
let all = [];
return new Promise(async(resolve, reject) => {
console.log(this.miningKeys);
const mocAddressLowercase = this.MOC_ADDRESS.toLowerCase();
async getAllValidatorsData(netId) {
let all = []
return new Promise(async (resolve, reject) => {
console.log(this.miningKeys)
const mocAddressLowercase = this.MOC_ADDRESS.toLowerCase()
for (let key of this.miningKeys) {
let data;
let data
if (key.toLowerCase() === mocAddressLowercase) {
if (this.mocRemoved) {
continue;
continue
}
data = this.getMocData();
data = this.getMocData()
} else {
data = await this.getValidatorData({miningKey: key});
data = await this.getValidatorData({ miningKey: key })
}
data.address = key;
all.push(data);
}
resolve(all);
data.address = key
all.push(data)
}
resolve(all)
})
}
async getPendingChange({votingKey, miningKey}){
miningKey = miningKey || await this.getMiningByVoting(votingKey);
async getPendingChange({ votingKey, miningKey }) {
miningKey = miningKey || (await this.getMiningByVoting(votingKey))
if (!miningKey) {
helpersGlobal.generateAlert("warning", "Warning!", messages.invalidaVotingKey);
return {};
helpersGlobal.generateAlert('warning', 'Warning!', messages.invalidaVotingKey)
return {}
}
let pendingChanges = await this.metadataInstance.methods.pendingChanges(miningKey).call();
let pendingChanges = await this.metadataInstance.methods.pendingChanges(miningKey).call()
let createdDate = pendingChanges.createdDate > 0 ? moment.unix(pendingChanges.createdDate).format('YYYY-MM-DD') : ''
let updatedDate = pendingChanges.updatedDate > 0 ? moment.unix(pendingChanges.updatedDate).format('YYYY-MM-DD') : ''
let expirationDate = pendingChanges.expirationDate > 0 ? moment.unix(pendingChanges.expirationDate).format('YYYY-MM-DD') : ''
let expirationDate =
pendingChanges.expirationDate > 0 ? moment.unix(pendingChanges.expirationDate).format('YYYY-MM-DD') : ''
return {
firstName: toAscii(pendingChanges.firstName),
lastName: toAscii(pendingChanges.lastName),
@ -161,8 +163,8 @@ export default class Metadata {
async getAllPendingChanges() {
let pendingChanges = []
for (let key of this.miningKeys) {
let pendingChange = await this.getPendingChange({miningKey: key})
pendingChange.address = key;
let pendingChange = await this.getPendingChange({ miningKey: key })
pendingChange.address = key
if (pendingChange.postal_code) {
pendingChanges.push(pendingChange)
}
@ -170,45 +172,52 @@ export default class Metadata {
return pendingChanges
}
async confirmPendingChange({miningKeyToConfirm, senderVotingKey}) {
let alreadyConfirmed = await this.metadataInstance.methods.isAddressAlreadyVoted(miningKeyToConfirm, senderVotingKey).call();
async confirmPendingChange({ miningKeyToConfirm, senderVotingKey }) {
let alreadyConfirmed = await this.metadataInstance.methods
.isAddressAlreadyVoted(miningKeyToConfirm, senderVotingKey)
.call()
console.log(alreadyConfirmed)
if(alreadyConfirmed){
throw(
{message:
`You already confirmed this change.`})
if (alreadyConfirmed) {
throw {
message: `You already confirmed this change.`
}
}
const miningKeySender = await this.getMiningByVoting(senderVotingKey);
if(miningKeySender === miningKeyToConfirm){
throw(
{message:
`You cannot confirm your own changes.\n
Please ask other validators to verify your new information.`})
const miningKeySender = await this.getMiningByVoting(senderVotingKey)
if (miningKeySender === miningKeyToConfirm) {
throw {
message: `You cannot confirm your own changes.\n
Please ask other validators to verify your new information.`
}
}
const gasPrice = this.web3_10.utils.toWei('2', 'gwei')
return await this.metadataInstance.methods.confirmPendingChange(miningKeyToConfirm).send({from: senderVotingKey, gasPrice});
return await this.metadataInstance.methods
.confirmPendingChange(miningKeyToConfirm)
.send({ from: senderVotingKey, gasPrice })
}
async getConfirmations({miningKey}) {
return await this.metadataInstance.methods.confirmations(miningKey).call();
async getConfirmations({ miningKey }) {
return await this.metadataInstance.methods.confirmations(miningKey).call()
}
async getMinThreshold({miningKey}) {
let validatorData = await this.metadataInstance.methods.validators(miningKey).call();
return validatorData.minThreshold;
async getMinThreshold({ miningKey }) {
let validatorData = await this.metadataInstance.methods.validators(miningKey).call()
return validatorData.minThreshold
}
async finalize({miningKeyToConfirm, senderVotingKey}) {
const confirmations = await this.getConfirmations({miningKey: miningKeyToConfirm});
const getMinThreshold = await this.getMinThreshold({miningKey: miningKeyToConfirm});
if(Number(confirmations[0]) < Number(getMinThreshold)){
throw(
{message:
`There is not enough confimations.\n
The minimum threshold to finalize is ${getMinThreshold}.`})
async finalize({ miningKeyToConfirm, senderVotingKey }) {
const confirmations = await this.getConfirmations({
miningKey: miningKeyToConfirm
})
const getMinThreshold = await this.getMinThreshold({
miningKey: miningKeyToConfirm
})
if (Number(confirmations[0]) < Number(getMinThreshold)) {
throw {
message: `There is not enough confimations.\n
The minimum threshold to finalize is ${getMinThreshold}.`
}
}
const gasPrice = this.web3_10.utils.toWei('2', 'gwei')
return await this.metadataInstance.methods.finalize(miningKeyToConfirm).send({from: senderVotingKey, gasPrice});
return await this.metadataInstance.methods.finalize(miningKeyToConfirm).send({ from: senderVotingKey, gasPrice })
}
}

View File

@ -1,26 +1,26 @@
import Web3 from 'web3';
import helpers from "./helpers";
import Web3 from 'web3'
import helpers from './helpers'
export default class POAConsensus {
async init({web3, netId, addresses}){
let web3_10 = new Web3(web3.currentProvider);
const {POA_ADDRESS} = addresses;
console.log('POA Address ' , POA_ADDRESS)
async init({ web3, netId, addresses }) {
let web3_10 = new Web3(web3.currentProvider)
const { POA_ADDRESS } = addresses
console.log('POA Address ', POA_ADDRESS)
const branch = helpers.getBranch(netId);
const branch = helpers.getBranch(netId)
let poaConsensusAbi = await helpers.getABI(branch, 'PoaNetworkConsensus')
this.poaInstance = new web3_10.eth.Contract(poaConsensusAbi, POA_ADDRESS);
this.poaInstance = new web3_10.eth.Contract(poaConsensusAbi, POA_ADDRESS)
}
async getValidators(){
async getValidators() {
console.log(this.poaInstance)
return await this.poaInstance.methods.getValidators().call();
return await this.poaInstance.methods.getValidators().call()
}
async isMasterOfCeremonyRemoved(){
async isMasterOfCeremonyRemoved() {
if (this.poaInstance.methods.isMasterOfCeremonyRemoved) {
return await this.poaInstance.methods.isMasterOfCeremonyRemoved().call();
return await this.poaInstance.methods.isMasterOfCeremonyRemoved().call()
}
return false;
return false
}
}
}

View File

@ -8,33 +8,35 @@ import messages from '../messages'
MOC: '0xCf260eA317555637C55F70e55dbA8D5ad8414Cb0'
}*/
export default (web3Config) => {
let branch;
switch (web3Config.netId) {
case '77':
branch = 'sokol'
break;
case '99':
branch = 'core'
break;
default:
branch = 'core'
break;
}
return new Promise((resolve, reject) => {
fetch(helpers.addressesURL(branch)).then((response) => {
response.json().then((json) => {
resolve({addresses: json, web3Config});
})
}).catch(function(err) {
let addr = helpers.addressesURL(branch);
let msg = `
export default web3Config => {
let branch
switch (web3Config.netId) {
case '77':
branch = 'sokol'
break
case '99':
branch = 'core'
break
default:
branch = 'core'
break
}
return new Promise((resolve, reject) => {
fetch(helpers.addressesURL(branch))
.then(response => {
response.json().then(json => {
resolve({ addresses: json, web3Config })
})
})
.catch(function(err) {
let addr = helpers.addressesURL(branch)
let msg = `
Something went wrong!<br/><br/>
${messages.wrongRepo(addr)}
`
helpersGlobal.generateAlert("error", "Error!", msg);
reject(err);
});
})
helpersGlobal.generateAlert('error', 'Error!', msg)
reject(err)
})
})
}

View File

@ -1,40 +1,44 @@
import { constants } from "../constants";
import { constants } from '../constants'
function addressesURL(branch) {
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/${constants.addressesSourceFile}`;
console.log(URL);
return URL;
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/${
constants.addressesSourceFile
}`
console.log(URL)
return URL
}
function ABIURL(branch, contract) {
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/abis/${constants.ABIsSources[contract]}`;
console.log(URL);
return URL;
const URL = `https://raw.githubusercontent.com/${constants.organization}/${constants.repoName}/${branch}/abis/${
constants.ABIsSources[contract]
}`
console.log(URL)
return URL
}
function getABI(branch, contract) {
let addr = helpers.ABIURL(branch, contract);
return fetch(addr).then(function(response) {
return response.json();
})
let addr = helpers.ABIURL(branch, contract)
return fetch(addr).then(function(response) {
return response.json()
})
}
function getBranch(netId) {
switch (netId) {
case '77':
return 'sokol'
case '99':
return 'core'
default:
return 'core'
}
switch (netId) {
case '77':
return 'sokol'
case '99':
return 'core'
default:
return 'core'
}
}
const helpers = {
addressesURL,
ABIURL,
getABI,
getBranch
addressesURL,
ABIURL,
getABI,
getBranch
}
export default helpers

View File

@ -1,30 +1,38 @@
import Web3 from 'web3'
const POA_CORE = { RPC_URL: 'https://core.poa.network', netIdName: 'CORE', netId: '99' }
const POA_SOKOL = { RPC_URL: 'https://sokol.poa.network', netIdName: 'SOKOL', netId: '77' }
const POA_CORE = {
RPC_URL: 'https://core.poa.network',
netIdName: 'CORE',
netId: '99'
}
const POA_SOKOL = {
RPC_URL: 'https://sokol.poa.network',
netIdName: 'SOKOL',
netId: '77'
}
let getWeb3 = () => {
return new Promise(function (resolve, reject) {
return new Promise(function(resolve, reject) {
// Wait for loading completion to avoid race conditions with web3 injection timing.
window.addEventListener('load', function () {
window.addEventListener('load', function() {
var results
var web3 = window.web3
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider.
var errorMsg = null;
var errorMsg = null
web3 = new window.Web3(web3.currentProvider)
web3.version.getNetwork((err, netId) => {
let netIdName;
console.log('netId', netId);
let netIdName
console.log('netId', netId)
switch (netId) {
case "99":
case '99':
netIdName = 'Core'
console.log('This is Core', netId)
break;
case "77":
break
case '77':
netIdName = 'Sokol'
console.log('This is Sokol', netId)
break;
break
default:
netIdName = 'ERROR'
errorMsg = `You aren't connected to POA Network.
@ -33,9 +41,9 @@ let getWeb3 = () => {
console.log('This is an unknown network.', netId)
}
document.title = `${netIdName} - POA validators dApp`
var defaultAccount = web3.eth.defaultAccount || null;
if(errorMsg !== null){
reject({message: errorMsg})
var defaultAccount = web3.eth.defaultAccount || null
if (errorMsg !== null) {
reject({ message: errorMsg })
}
results = {
web3Instance: web3,
@ -47,11 +55,10 @@ let getWeb3 = () => {
resolve(results)
})
console.log('Injected web3 detected.');
console.log('Injected web3 detected.')
} else {
// Fallback to localhost if no web3 injection.
const network = window.location.host.indexOf('sokol') !== -1 ? POA_SOKOL : POA_CORE
document.title = `${network.netIdName} - POA validators dApp`
@ -66,25 +73,25 @@ let getWeb3 = () => {
defaultAccount: null
}
resolve(results)
console.log('No web3 instance injected, using Local web3.');
console.error('Metamask not found');
console.log('No web3 instance injected, using Local web3.')
console.error('Metamask not found')
}
})
})
}
const setWeb3 = (netId) => {
let network;
switch(netId){
const setWeb3 = netId => {
let network
switch (netId) {
case '77':
network = POA_SOKOL;
break;
network = POA_SOKOL
break
case '99':
network = POA_CORE;
break;
network = POA_CORE
break
default:
network = POA_CORE
break;
break
}
const provider = new Web3.providers.HttpProvider(network.RPC_URL)
return new Web3(provider)
@ -92,5 +99,4 @@ const setWeb3 = (netId) => {
export default getWeb3
export {setWeb3};
export { setWeb3 }

View File

@ -1,17 +1,17 @@
import swal from 'sweetalert';
import swal from 'sweetalert'
function generateAlert(icon, title, msg) {
var content = document.createElement("div");
content.innerHTML = `<div style="line-height: 1.6;">${msg}</div>`
swal({
icon: icon,
title: title,
content: content
});
var content = document.createElement('div')
content.innerHTML = `<div style="line-height: 1.6;">${msg}</div>`
swal({
icon: icon,
title: title,
content: content
})
}
let helpers = {
generateAlert
generateAlert
}
export default helpers
export default helpers

View File

@ -1,71 +1,68 @@
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import KeysManager from './contracts/KeysManager.contract'
import Metadata from './contracts/Metadata.contract'
import getWeb3, {setWeb3} from './getWeb3'
import getWeb3, { setWeb3 } from './getWeb3'
import helpers from './helpers'
import {
Router,
Route,
NavLink
} from 'react-router-dom'
import { Router, Route, NavLink } from 'react-router-dom'
import createBrowserHistory from 'history/createBrowserHistory'
import Loading from './Loading'
import Footer from './Footer';
import Footer from './Footer'
import AllValidators from './AllValidators'
import Select from 'react-select'
import "react-select/dist/react-select.css";
import networkAddresses from './contracts/addresses';
import 'react-select/dist/react-select.css'
import networkAddresses from './contracts/addresses'
let errorMsgNoMetamaskAccount = `Your MetaMask is locked.
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.`;
Check POA Network <a href='https://github.com/poanetwork/wiki' target='blank'>wiki</a> for more info.`
const history = createBrowserHistory()
let Header = ({netId, onChange, injectedWeb3}) => {
let select;
let headerClassName = netId === '77' ? 'sokol' : '';
const logoClassName = netId === '77' ? 'header-logo-sokol' : 'header-logo';
if(!injectedWeb3) {
select = <Select id="netId"
let Header = ({ netId, onChange, injectedWeb3 }) => {
let select
let headerClassName = netId === '77' ? 'sokol' : ''
const logoClassName = netId === '77' ? 'header-logo-sokol' : 'header-logo'
if (!injectedWeb3) {
select = (
<Select
id="netId"
value={netId}
onChange={onChange}
style={{
width: '150px',
width: '150px'
}}
wrapperStyle={{
width: '150px',
width: '150px'
}}
clearable={false}
options={[
{ value: '77', label: 'Network: Sokol' },
{ value: '99', label: 'Network: Core' },
]} />
options={[{ value: '77', label: 'Network: Sokol' }, { value: '99', label: 'Network: Core' }]}
/>
)
}
return (
<header id="header" className={`header ${headerClassName}`}>
<div className="container">
<a href="/poa-dapps-validators" className={logoClassName}></a>
{select}
<a href="/poa-dapps-validators" className={logoClassName} />
{select}
</div>
</header>
)
}
class AppMainRouter extends Component {
constructor(props){
super(props);
constructor(props) {
super(props)
this.rootPath = '/poa-dapps-validators'
history.listen(this.onRouteChange.bind(this));
this.onSetRender = this.onSetRender.bind(this);
this.onPendingChangesRender = this.onPendingChangesRender.bind(this);
history.listen(this.onRouteChange.bind(this))
this.onSetRender = this.onSetRender.bind(this)
this.onPendingChangesRender = this.onPendingChangesRender.bind(this)
this.onAllValidatorsRender = this.onAllValidatorsRender.bind(this)
this.onConfirmPendingChange = this.onConfirmPendingChange.bind(this);
this.onFinalize = this.onFinalize.bind(this);
this.onSearch = this.onSearch.bind(this);
this.onNetworkChange = this.onNetworkChange.bind(this);
this.onConfirmPendingChange = this.onConfirmPendingChange.bind(this)
this.onFinalize = this.onFinalize.bind(this)
this.onSearch = this.onSearch.bind(this)
this.onNetworkChange = this.onNetworkChange.bind(this)
this.state = {
showSearch: true,
keysManager: null,
@ -78,80 +75,83 @@ class AppMainRouter extends Component {
netId: '',
error: false
}
getWeb3().then(async (web3Config) => {
return networkAddresses(web3Config)
}).then(async (config) => {
const {web3Config, addresses} = config;
const keysManager = new KeysManager()
await keysManager.init({
web3: web3Config.web3Instance,
netId: web3Config.netId,
addresses,
getWeb3()
.then(async web3Config => {
return networkAddresses(web3Config)
})
const metadataContract = new Metadata()
await metadataContract.init({
web3: web3Config.web3Instance,
netId: web3Config.netId,
addresses,
.then(async config => {
const { web3Config, addresses } = config
const keysManager = new KeysManager()
await keysManager.init({
web3: web3Config.web3Instance,
netId: web3Config.netId,
addresses
})
const metadataContract = new Metadata()
await metadataContract.init({
web3: web3Config.web3Instance,
netId: web3Config.netId,
addresses
})
this.setState({
votingKey: web3Config.defaultAccount,
keysManager,
metadataContract,
loading: false,
injectedWeb3: web3Config.injectedWeb3,
netId: web3Config.netId
})
})
this.setState({
votingKey: web3Config.defaultAccount,
keysManager,
metadataContract,
loading: false,
injectedWeb3: web3Config.injectedWeb3,
netId: web3Config.netId,
.catch(error => {
console.error(error.message)
this.setState({ loading: false, error: true })
helpers.generateAlert('error', 'Error!', error.message)
})
}).catch((error) => {
console.error(error.message);
this.setState({loading: false, error: true});
helpers.generateAlert("error", "Error!", error.message);
})
}
onRouteChange(){
const setMetadata = this.rootPath + "/set";
if(history.location.pathname === setMetadata){
this.setState({showSearch: false})
if(this.state.injectedWeb3 === false){
helpers.generateAlert("warning", "Warning!", 'Metamask was not found');
onRouteChange() {
const setMetadata = this.rootPath + '/set'
if (history.location.pathname === setMetadata) {
this.setState({ showSearch: false })
if (this.state.injectedWeb3 === false) {
helpers.generateAlert('warning', 'Warning!', 'Metamask was not found')
}
} else {
this.setState({showSearch: true})
this.setState({ showSearch: true })
}
}
checkForVotingKey(cb){
if(this.state.votingKey && !this.state.loading){
return cb();
checkForVotingKey(cb) {
if (this.state.votingKey && !this.state.loading) {
return cb()
} else {
helpers.generateAlert("warning", "Warning!", errorMsgNoMetamaskAccount);
helpers.generateAlert('warning', 'Warning!', errorMsgNoMetamaskAccount)
return ''
}
}
onSetRender() {
if (!this.state.netId) {
return '';
return ''
}
return this.checkForVotingKey(() => {
return <App web3Config={this.state}/>
});
return <App web3Config={this.state} />
})
}
async _onBtnClick({event, methodToCall, successMsg}){
event.preventDefault();
async _onBtnClick({ event, methodToCall, successMsg }) {
event.preventDefault()
this.checkForVotingKey(async () => {
this.setState({loading: true})
const miningKey = event.currentTarget.getAttribute('miningkey');
try{
this.setState({ loading: true })
const miningKey = event.currentTarget.getAttribute('miningkey')
try {
let result = await this.state.metadataContract[methodToCall]({
miningKeyToConfirm: miningKey,
senderVotingKey: this.state.votingKey
});
console.log(result);
this.setState({loading: false})
helpers.generateAlert("success", "Congratulations!", successMsg);
} catch(error) {
this.setState({loading: false})
console.error(error.message);
helpers.generateAlert("error", "Error!", error.message);
})
console.log(result)
this.setState({ loading: false })
helpers.generateAlert('success', 'Congratulations!', successMsg)
} catch (error) {
this.setState({ loading: false })
console.error(error.message)
helpers.generateAlert('error', 'Error!', error.message)
}
})
}
@ -160,84 +160,103 @@ class AppMainRouter extends Component {
event,
methodToCall: 'confirmPendingChange',
successMsg: 'You have successfully confirmed the change!'
});
})
}
async onFinalize(event){
async onFinalize(event) {
await this._onBtnClick({
event,
methodToCall: 'finalize',
successMsg: 'You have successfully finalized the change!'
});
})
}
onPendingChangesRender() {
return this.state.loading || this.state.error? '' : <AllValidators
ref="AllValidatorsRef"
methodToCall="getAllPendingChanges"
searchTerm={this.state.searchTerm}
web3Config={this.state}>
<button onClick={this.onFinalize} className="create-keys-button finalize">Finalize</button>
<button onClick={this.onConfirmPendingChange} className="create-keys-button">Confirm</button>
</AllValidators>;
return this.state.loading || this.state.error ? (
''
) : (
<AllValidators
ref="AllValidatorsRef"
methodToCall="getAllPendingChanges"
searchTerm={this.state.searchTerm}
web3Config={this.state}
>
<button onClick={this.onFinalize} className="create-keys-button finalize">
Finalize
</button>
<button onClick={this.onConfirmPendingChange} className="create-keys-button">
Confirm
</button>
</AllValidators>
)
}
onAllValidatorsRender() {
return this.state.loading || this.state.error ? '' : <AllValidators
searchTerm={this.state.searchTerm}
methodToCall="getAllValidatorsData"
web3Config={this.state}
/>
return this.state.loading || this.state.error ? (
''
) : (
<AllValidators searchTerm={this.state.searchTerm} methodToCall="getAllValidatorsData" web3Config={this.state} />
)
}
onSearch(term){
this.setState({searchTerm: term.target.value.toLowerCase()})
onSearch(term) {
this.setState({ searchTerm: term.target.value.toLowerCase() })
}
async onNetworkChange(e){
const netId = e.value;
const web3 = setWeb3(netId);
networkAddresses({netId}).then(async (config) => {
const {addresses} = config;
const keysManager = new KeysManager();
async onNetworkChange(e) {
const netId = e.value
const web3 = setWeb3(netId)
networkAddresses({ netId }).then(async config => {
const { addresses } = config
const keysManager = new KeysManager()
await keysManager.init({
web3,
netId,
addresses
});
})
const metadataContract = new Metadata()
await metadataContract.init({
web3,
netId,
addresses
});
this.setState({netId: e.value, keysManager, metadataContract})
})
this.setState({ netId: e.value, keysManager, metadataContract })
})
}
render(){
render() {
console.log('v2.09')
const search = this.state.showSearch ? <input type="search" className="search-input" onChange={this.onSearch}/> : ''
const search = this.state.showSearch ? (
<input type="search" className="search-input" onChange={this.onSearch} />
) : (
''
)
const loading = this.state.loading ? <Loading netId={this.state.netId} /> : ''
return (
<Router history={history}>
<section className="content">
<Header netId={this.state.netId} onChange={this.onNetworkChange} injectedWeb3={this.state.injectedWeb3} />
{loading}
<div className="nav-container">
<div className="container">
<div className="nav">
<NavLink className="nav-i" exact activeClassName="nav-i_active" to={`${this.rootPath}/`}>All</NavLink>
<NavLink className="nav-i" activeClassName="nav-i_active" to={`${this.rootPath}/set`}>Set metadata</NavLink>
<NavLink className="nav-i" activeClassName="nav-i_active" to={`${this.rootPath}/pending-changes`}>Pending changes</NavLink>
{loading}
<div className="nav-container">
<div className="container">
<div className="nav">
<NavLink className="nav-i" exact activeClassName="nav-i_active" to={`${this.rootPath}/`}>
All
</NavLink>
<NavLink className="nav-i" activeClassName="nav-i_active" to={`${this.rootPath}/set`}>
Set metadata
</NavLink>
<NavLink className="nav-i" activeClassName="nav-i_active" to={`${this.rootPath}/pending-changes`}>
Pending changes
</NavLink>
</div>
{search}
</div>
{search}
</div>
</div>
<Route exact path={`${this.rootPath}/`} render={this.onAllValidatorsRender} web3Config={this.state}/>
<Route exact path="/" render={this.onAllValidatorsRender} web3Config={this.state}/>
<Route path={`${this.rootPath}/set`} render={this.onSetRender} />
<Route path={`${this.rootPath}/pending-changes`} render={this.onPendingChangesRender} />
<Footer netId={this.state.netId} />
<Route exact path={`${this.rootPath}/`} render={this.onAllValidatorsRender} web3Config={this.state} />
<Route exact path="/" render={this.onAllValidatorsRender} web3Config={this.state} />
<Route path={`${this.rootPath}/set`} render={this.onSetRender} />
<Route path={`${this.rootPath}/pending-changes`} render={this.onPendingChangesRender} />
<Footer netId={this.state.netId} />
</section>
</Router>
)
}
}
ReactDOM.render(<AppMainRouter />, document.getElementById('root'));
registerServiceWorker();
ReactDOM.render(<AppMainRouter />, document.getElementById('root'))
registerServiceWorker()

View File

@ -1,9 +1,10 @@
let messages = {};
let messages = {}
messages.wrongRepo = function(repo) {
return `There is no such file in configured repo ${repo}`;
};
messages.invalidaVotingKey = "The key is not valid voting Key or you are connected to the wrong chain! Please make sure you have loaded correct voting key in Metamask"
return `There is no such file in configured repo ${repo}`
}
messages.invalidaVotingKey =
'The key is not valid voting Key or you are connected to the wrong chain! Please make sure you have loaded correct voting key in Metamask'
module.exports = {
messages
};
}

View File

@ -13,33 +13,31 @@ const isLocalhost = Boolean(
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
)
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
const publicUrl = new URL(process.env.PUBLIC_URL, window.location)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
checkValidServiceWorker(swUrl)
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
registerValidSW(swUrl)
}
});
})
}
}
@ -48,7 +46,7 @@ function registerValidSW(swUrl) {
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
const installingWorker = registration.installing
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
@ -56,20 +54,20 @@ function registerValidSW(swUrl) {
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
console.log('New content is available; please refresh.')
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
console.log('Content is cached for offline use.')
}
}
};
};
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker(swUrl) {
@ -77,32 +75,27 @@ function checkValidServiceWorker(swUrl) {
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
if (response.status === 404 || response.headers.get('content-type').indexOf('javascript') === -1) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
registerValidSW(swUrl)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
console.log('No internet connection found. App is running in offline mode.')
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
registration.unregister()
})
}
}