diff --git a/.eslintrc.js b/.eslintrc.js index cfb2e3088..0b69e664e 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -41,36 +41,9 @@ module.exports = { }, rules: { - /* TODO: Remove these when upgrading to `@metamask/eslint-config@2` */ - 'array-callback-return': 'error', - 'callback-return': 'error', - 'consistent-return': 'error', - 'global-require': 'error', - 'guard-for-in': 'error', - 'implicit-arrow-linebreak': 'error', - 'import/extensions': ['error', 'never', { 'json': 'always' }], - 'import/no-extraneous-dependencies': 'error', - 'import/order': 'error', - 'import/unambiguous': 'error', - 'max-statements-per-line': ['error', { 'max': 1 }], - 'no-case-declarations': 'error', - 'no-constant-condition': 'error', - 'no-dupe-else-if': 'error', - 'no-empty': 'error', - 'no-empty-function': 'error', - 'no-eq-null': 'error', - 'no-global-assign': 'error', - 'no-loop-func': 'error', - 'no-negated-condition': 'error', - 'no-nested-ternary': 'error', - 'no-param-reassign': 'error', - 'no-plusplus': ['error', { 'allowForLoopAfterthoughts': true }], - 'no-process-exit': 'error', - 'no-prototype-builtins': 'error', - 'no-shadow': 'error', - 'no-template-curly-in-string': 'error', - 'no-useless-catch': 'error', - 'no-useless-concat': 'error', + 'default-param-last': 'off', + 'require-atomic-updates': 'off', + 'import/no-unassigned-import': 'off', 'prefer-destructuring': ['error', { 'VariableDeclarator': { 'array': false, @@ -83,33 +56,6 @@ module.exports = { }, { 'enforceForRenamedProperties': false, }], - 'prefer-rest-params': 'error', - 'prefer-spread': 'error', - 'radix': 'error', - 'require-unicode-regexp': 'error', - /* End v2 rules */ - 'arrow-parens': 'error', - 'no-tabs': 'error', - 'no-mixed-operators': 'error', - 'import/default': 'error', - 'import/export': 'error', - 'import/named': 'error', - 'import/namespace': 'error', - 'import/newline-after-import': 'error', - 'import/no-absolute-path': 'error', - 'import/no-amd': 'error', - 'import/no-anonymous-default-export': 'error', - 'import/no-duplicates': 'error', - 'import/no-dynamic-require': 'error', - 'import/no-mutable-exports': 'error', - 'import/no-named-as-default': 'error', - 'import/no-named-as-default-member': 'error', - 'import/no-named-default': 'error', - 'import/no-self-import': 'error', - 'import/no-unresolved': ['error', { 'commonjs': true }], - 'import/no-unused-modules': 'error', - 'import/no-useless-path-segments': ['error', { 'commonjs': true }], - 'import/no-webpack-loader-syntax': 'error', 'react/no-unused-prop-types': 'error', 'react/no-unused-state': 'error', 'react/jsx-boolean-value': 'error', @@ -121,7 +67,7 @@ module.exports = { 'react/jsx-no-duplicate-props': 'error', 'react/jsx-closing-bracket-location': 'error', 'react/jsx-first-prop-new-line': ['error', 'multiline'], - 'react/jsx-max-props-per-line': ['error', { 'maximum': 1, 'when': 'multiline' } ], + 'react/jsx-max-props-per-line': ['error', { 'maximum': 1, 'when': 'multiline' }], 'react/jsx-tag-spacing': ['error', { 'closingSlash': 'never', 'beforeSelfClosing': 'always', diff --git a/app/scripts/background.js b/app/scripts/background.js index b88d3b83f..3df32dfeb 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -2,7 +2,7 @@ * @file The entry point for the web extension singleton process. */ // these need to run before anything else -/* eslint-disable import/order */ +/* eslint-disable import/first,import/order */ import './lib/freezeGlobals' import setupFetchDebugging from './lib/setupFetchDebugging' /* eslint-enable import/order */ @@ -39,9 +39,10 @@ import { ENVIRONMENT_TYPE_NOTIFICATION, ENVIRONMENT_TYPE_FULLSCREEN, } from './lib/enums' +/* eslint-enable import/first */ // METAMASK_TEST_CONFIG is used in e2e tests to set the default network to localhost -const firstTimeState = Object.assign({}, rawFirstTimeState, global.METAMASK_TEST_CONFIG) +const firstTimeState = { ...rawFirstTimeState, ...global.METAMASK_TEST_CONFIG } log.setDefaultLevel(process.env.METAMASK_DEBUG ? 'debug' : 'warn') diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index 4c5bcecc2..d85aca3f2 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -10,7 +10,7 @@ const fs = require('fs') const path = require('path') const inpageContent = fs.readFileSync(path.join(__dirname, '..', '..', 'dist', 'chrome', 'inpage.js'), 'utf8') -const inpageSuffix = '//# sourceURL=' + extension.runtime.getURL('inpage.js') + '\n' +const inpageSuffix = `//# sourceURL=${extension.runtime.getURL('inpage.js')}\n` const inpageBundle = inpageContent + inpageSuffix // Eventually this streaming injection could be replaced with: @@ -115,7 +115,7 @@ function forwardTrafficBetweenMuxers (channelName, muxA, muxB) { function logStreamDisconnectWarning (remoteLabel, err) { let warningMsg = `MetamaskContentscript - lost connection to ${remoteLabel}` if (err) { - warningMsg += '\n' + err.stack + warningMsg += `\n${err.stack}` } console.warn(warningMsg) } @@ -139,9 +139,8 @@ function doctypeCheck () { const { doctype } = window.document if (doctype) { return doctype.name === 'html' - } else { - return true } + return true } /** diff --git a/app/scripts/controllers/alert.js b/app/scripts/controllers/alert.js index af49b9df6..820e1a80b 100644 --- a/app/scripts/controllers/alert.js +++ b/app/scripts/controllers/alert.js @@ -32,20 +32,18 @@ const defaultState = { * alert related state */ export default class AlertController { + /** * @constructor * @param {AlertControllerOptions} [opts] - Controller configuration parameters */ constructor (opts = {}) { const { initState, preferencesStore } = opts - const state = Object.assign( - {}, - defaultState, - initState, - { - unconnectedAccountAlertShownOrigins: {}, - }, - ) + const state = { + ...defaultState, + ...initState, + unconnectedAccountAlertShownOrigins: {}, + } this.store = new ObservableStore(state) this.selectedAddress = preferencesStore.getState().selectedAddress diff --git a/app/scripts/controllers/app-state.js b/app/scripts/controllers/app-state.js index e967b462b..c29b76a40 100644 --- a/app/scripts/controllers/app-state.js +++ b/app/scripts/controllers/app-state.js @@ -2,6 +2,7 @@ import EventEmitter from 'events' import ObservableStore from 'obs-store' export default class AppStateController extends EventEmitter { + /** * @constructor * @param opts @@ -18,11 +19,11 @@ export default class AppStateController extends EventEmitter { super() this.onInactiveTimeout = onInactiveTimeout || (() => undefined) - this.store = new ObservableStore(Object.assign({ + this.store = new ObservableStore({ timeoutMinutes: 0, connectedStatusPopoverHasBeenShown: true, - defaultHomeActiveTabName: null, - }, initState)) + defaultHomeActiveTabName: null, ...initState, + }) this.timer = null this.isUnlocked = isUnlocked diff --git a/app/scripts/controllers/cached-balances.js b/app/scripts/controllers/cached-balances.js index 3cee10df0..87ca28662 100644 --- a/app/scripts/controllers/cached-balances.js +++ b/app/scripts/controllers/cached-balances.js @@ -12,6 +12,7 @@ import ObservableStore from 'obs-store' * a cache of account balances in local storage */ export default class CachedBalancesController { + /** * Creates a new controller instance * @@ -23,9 +24,7 @@ export default class CachedBalancesController { this.accountTracker = accountTracker this.getNetwork = getNetwork - const initState = Object.assign({ - cachedBalances: {}, - }, opts.initState) + const initState = { cachedBalances: {}, ...opts.initState } this.store = new ObservableStore(initState) this._registerUpdates() diff --git a/app/scripts/controllers/detect-tokens.js b/app/scripts/controllers/detect-tokens.js index 93b7af2a6..40980990c 100644 --- a/app/scripts/controllers/detect-tokens.js +++ b/app/scripts/controllers/detect-tokens.js @@ -7,11 +7,13 @@ import { MAINNET } from './network/enums' // By default, poll every 3 minutes const DEFAULT_INTERVAL = 180 * 1000 const SINGLE_CALL_BALANCES_ADDRESS = '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39' + /** * A controller that polls for token exchange * rates based on a user's current token list */ export default class DetectTokensController { + /** * Creates a DetectTokensController * diff --git a/app/scripts/controllers/incoming-transactions.js b/app/scripts/controllers/incoming-transactions.js index 7e8aa87d0..de588f38b 100644 --- a/app/scripts/controllers/incoming-transactions.js +++ b/app/scripts/controllers/incoming-transactions.js @@ -40,7 +40,7 @@ export default class IncomingTransactionsController { }) } - const initState = Object.assign({ + const initState = { incomingTransactions: {}, incomingTxLastFetchedBlocksByNetwork: { [ROPSTEN]: null, @@ -48,8 +48,8 @@ export default class IncomingTransactionsController { [KOVAN]: null, [GOERLI]: null, [MAINNET]: null, - }, - }, opts.initState) + }, ...opts.initState, + } this.store = new ObservableStore(initState) this.preferencesController.store.subscribe(pairwise((prevState, currState) => { @@ -265,9 +265,8 @@ function pairwise (fn) { if (first) { first = false return fn(value, value) - } else { - return fn(cache, value) } + return fn(cache, value) } finally { cache = value } diff --git a/app/scripts/controllers/network/createLocalhostClient.js b/app/scripts/controllers/network/createLocalhostClient.js index 447892016..efd19801c 100644 --- a/app/scripts/controllers/network/createLocalhostClient.js +++ b/app/scripts/controllers/network/createLocalhostClient.js @@ -26,7 +26,6 @@ function delay (time) { return new Promise((resolve) => setTimeout(resolve, time)) } - function createEstimateGasMiddleware () { return createAsyncMiddleware(async (req, _, next) => { if (req.method === 'eth_estimateGas' && inTest) { diff --git a/app/scripts/controllers/network/network.js b/app/scripts/controllers/network/network.js index 27d7093d1..29e878cc8 100644 --- a/app/scripts/controllers/network/network.js +++ b/app/scripts/controllers/network/network.js @@ -12,8 +12,6 @@ import createInfuraClient from './createInfuraClient' import createJsonRpcClient from './createJsonRpcClient' import createLocalhostClient from './createLocalhostClient' -const networks = { networkList: {} } - import { RINKEBY, MAINNET, @@ -21,6 +19,8 @@ import { INFURA_PROVIDER_TYPES, } from './enums' +const networks = { networkList: {} } + const env = process.env.METAMASK_ENV const { METAMASK_DEBUG } = process.env @@ -124,7 +124,7 @@ export default class NetworkController extends EventEmitter { this.setNetworkState('loading') return } - log.info('web3.getNetwork returned ' + network) + log.info(`web3.getNetwork returned ${network}`) this.setNetworkState(network, type) } }) @@ -212,7 +212,7 @@ export default class NetworkController extends EventEmitter { log.info('NetworkController - configureStandardProvider', rpcUrl) const networkClient = createJsonRpcClient({ rpcUrl }) // hack to add a 'rpc' network with chainId - networks.networkList['rpc'] = { + networks.networkList.rpc = { chainId, rpcUrl, ticker: ticker || 'ETH', @@ -222,7 +222,7 @@ export default class NetworkController extends EventEmitter { let settings = { network: chainId, } - settings = Object.assign(settings, networks.networkList['rpc']) + settings = Object.assign(settings, networks.networkList.rpc) this.networkConfig.putState(settings) this._setNetworkClient(networkClient) } diff --git a/app/scripts/controllers/onboarding.js b/app/scripts/controllers/onboarding.js index 7efb4523c..0ff92f5b1 100644 --- a/app/scripts/controllers/onboarding.js +++ b/app/scripts/controllers/onboarding.js @@ -17,6 +17,7 @@ import log from 'loglevel' * state related to onboarding */ export default class OnboardingController { + /** * Creates a new controller instance * @@ -26,13 +27,11 @@ export default class OnboardingController { const initialTransientState = { onboardingTabs: {}, } - const initState = Object.assign( - { - seedPhraseBackedUp: true, - }, - opts.initState, - initialTransientState, - ) + const initState = { + seedPhraseBackedUp: true, + ...opts.initState, + ...initialTransientState, + } this.store = new ObservableStore(initState) this.preferencesController = opts.preferencesController this.completedOnboarding = this.preferencesController.store.getState().completedOnboarding @@ -64,7 +63,7 @@ export default class OnboardingController { log.debug('Ignoring registerOnboarding; user already onboarded') return } - const onboardingTabs = Object.assign({}, this.store.getState().onboardingTabs) + const onboardingTabs = { ...this.store.getState().onboardingTabs } if (!onboardingTabs[location] || onboardingTabs[location] !== tabId) { log.debug(`Registering onboarding tab at location '${location}' with tabId '${tabId}'`) onboardingTabs[location] = tabId diff --git a/app/scripts/controllers/permissions/index.js b/app/scripts/controllers/permissions/index.js index f82cb1c75..093983343 100644 --- a/app/scripts/controllers/permissions/index.js +++ b/app/scripts/controllers/permissions/index.js @@ -36,7 +36,8 @@ export class PermissionsController { showPermissionRequest, } = {}, restoredPermissions = {}, - restoredState = {}) { + restoredState = {}, + ) { // additional top-level store key set in _initializeMetadataStore this.store = new ObservableStore({ @@ -334,7 +335,7 @@ export class PermissionsController { .filter((acc) => acc !== account) if (newPermittedAccounts.length === 0) { - this.removePermissionsFor({ [origin]: [ 'eth_accounts' ] }) + this.removePermissionsFor({ [origin]: ['eth_accounts'] }) } else { this.permissions.updateCaveatFor( diff --git a/app/scripts/controllers/permissions/permissionsLog.js b/app/scripts/controllers/permissions/permissionsLog.js index 3a6f02537..eda7c394a 100644 --- a/app/scripts/controllers/permissions/permissionsLog.js +++ b/app/scripts/controllers/permissions/permissionsLog.js @@ -113,7 +113,7 @@ export default class PermissionsLogController { // eth_requestAccounts is a special case; we need to extract the accounts // from it activityEntry = this.logRequest(req, isInternal) - requestedMethods = [ 'eth_accounts' ] + requestedMethods = ['eth_accounts'] } else { // no-op next() @@ -292,9 +292,9 @@ export default class PermissionsLogController { // eth_accounts requires special handling, because of information // we store about the accounts const existingEthAccountsEntry = ( - history[origin] && history[origin]['eth_accounts'] + history[origin] && history[origin].eth_accounts ) - const newEthAccountsEntry = newEntries['eth_accounts'] + const newEthAccountsEntry = newEntries.eth_accounts if (existingEthAccountsEntry && newEthAccountsEntry) { @@ -306,7 +306,7 @@ export default class PermissionsLogController { ) // merge old and new eth_accounts history entries - newOriginHistory['eth_accounts'] = { + newOriginHistory.eth_accounts = { lastApproved, accounts: { ...existingEthAccountsEntry.accounts, @@ -364,7 +364,7 @@ export default class PermissionsLogController { } } } - return [ ...accounts ] + return [...accounts] } } diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 739004d93..c82a1adbc 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -26,7 +26,7 @@ export default class PreferencesController { * */ constructor (opts = {}) { - const initState = Object.assign({ + const initState = { frequentRpcListDetail: [], accountTokens: {}, assetImages: {}, @@ -61,8 +61,8 @@ export default class PreferencesController { metaMetricsSendCount: 0, // ENS decentralized website resolution - ipfsGateway: 'dweb.link', - }, opts.initState) + ipfsGateway: 'dweb.link', ...opts.initState, + } this.diagnostics = opts.diagnostics this.network = opts.network @@ -152,7 +152,6 @@ export default class PreferencesController { this.store.updateState({ firstTimeFlowType: type }) } - getSuggestedTokens () { return this.store.getState().suggestedTokens } @@ -215,7 +214,6 @@ export default class PreferencesController { } next() - return } /** @@ -228,7 +226,7 @@ export default class PreferencesController { const textDirection = (['ar', 'dv', 'fa', 'he', 'ku'].includes(key)) ? 'rtl' : 'auto' this.store.updateState({ currentLocale: key, - textDirection: textDirection, + textDirection, }) return textDirection } @@ -282,7 +280,6 @@ export default class PreferencesController { return address } - /** * Adds addresses to the identities object without removing identities * @@ -470,7 +467,7 @@ export default class PreferencesController { */ setAccountLabel (account, label) { if (!account) { - throw new Error('setAccountLabel requires a valid address, got ' + String(account)) + throw new Error(`setAccountLabel requires a valid address, got ${String(account)}`) } const address = normalizeAddress(account) const { identities } = this.store.getState() @@ -491,7 +488,6 @@ export default class PreferencesController { * */ - updateRpc (newRpcDetails) { const rpcList = this.getFrequentRpcListDetail() const index = rpcList.findIndex((element) => { @@ -508,6 +504,7 @@ export default class PreferencesController { } return Promise.resolve(rpcList) } + /** * Adds custom RPC url to state. * @@ -529,7 +526,7 @@ export default class PreferencesController { if (url !== 'http://localhost:8545') { let checkedChainId // eslint-disable-next-line radix - if (!!chainId && !Number.isNaN(parseInt(chainId))) { + if (Boolean(chainId) && !Number.isNaN(parseInt(chainId))) { checkedChainId = chainId } rpcList.push({ rpcUrl: url, chainId: checkedChainId, ticker, nickname, rpcPrefs }) diff --git a/app/scripts/controllers/threebox.js b/app/scripts/controllers/threebox.js index dc83f3673..080fac6cc 100644 --- a/app/scripts/controllers/threebox.js +++ b/app/scripts/controllers/threebox.js @@ -1,6 +1,6 @@ import ObservableStore from 'obs-store' -/* eslint-disable import/order */ +/* eslint-disable import/first,import/order */ const Box = process.env.IN_TEST ? require('../../../development/mock-3box') : require('3box') @@ -13,6 +13,7 @@ import Migrator from '../lib/migrator' import migrations from '../migrations' import createOriginMiddleware from '../lib/createOriginMiddleware' import createMetamaskMiddleware from './network/createMetamaskMiddleware' +/* eslint-enable import/first */ const SYNC_TIMEOUT = 60 * 1000 // one minute @@ -42,9 +43,8 @@ export default class ThreeBoxController { if (isUnlocked && accounts[0]) { const appKeyAddress = await this.keyringController.getAppKeyAddress(accounts[0], 'wallet://3box.metamask.io') return [appKeyAddress] - } else { - return [] } + return [] }, processPersonalMessage: async (msgParams) => { const accounts = await this.keyringController.getAccounts() diff --git a/app/scripts/controllers/token-rates.js b/app/scripts/controllers/token-rates.js index 4ef8b8ff8..bbc4ad778 100644 --- a/app/scripts/controllers/token-rates.js +++ b/app/scripts/controllers/token-rates.js @@ -3,7 +3,6 @@ import log from 'loglevel' import { normalize as normalizeAddress } from 'eth-sig-util' import ethUtil from 'ethereumjs-util' - // By default, poll every 3 minutes const DEFAULT_INTERVAL = 180 * 1000 @@ -12,6 +11,7 @@ const DEFAULT_INTERVAL = 180 * 1000 * rates based on a user's current token list */ export default class TokenRatesController { + /** * Creates a TokenRatesController * diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index ffc8246db..96ac1c5fd 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -6,9 +6,6 @@ import EthQuery from 'ethjs-query' import { ethErrors } from 'eth-json-rpc-errors' import abi from 'human-standard-token-abi' import abiDecoder from 'abi-decoder' - -abiDecoder.addABI(abi) - import NonceTracker from 'nonce-tracker' import log from 'loglevel' import { @@ -19,7 +16,6 @@ import { DEPLOY_CONTRACT_ACTION_KEY, CONTRACT_INTERACTION_KEY, } from '../../../../ui/app/helpers/constants/transactions' - import cleanErrorStack from '../../lib/cleanErrorStack' import { hexToBn, bnToHex, BnMultiplyByFraction } from '../../lib/util' import { TRANSACTION_NO_CONTRACT_ERROR_KEY } from '../../../../ui/app/helpers/constants/error-keys' @@ -27,7 +23,6 @@ import TransactionStateManager from './tx-state-manager' import TxGasUtil from './tx-gas-utils' import PendingTransactionTracker from './pending-tx-tracker' import * as txUtils from './lib/util' - import { TRANSACTION_TYPE_CANCEL, TRANSACTION_TYPE_RETRY, @@ -35,6 +30,7 @@ import { TRANSACTION_STATUS_APPROVED, } from './enums' +abiDecoder.addABI(abi) const SIMPLE_GAS_COST = '0x5208' // Hex for 21000, cost of a simple send. const MAX_MEMSTORE_TX_LIST_SIZE = 100 // Number of transactions (by unique nonces) to keep in memory @@ -53,7 +49,6 @@ const MAX_MEMSTORE_TX_LIST_SIZE = 100 // Number of transactions (by unique nonce
- nonceTracker calculating nonces - @class @param {Object} - opts @param {Object} opts.initState - initial transaction list default is an empty array @@ -137,9 +132,8 @@ export default class TransactionController extends EventEmitter { const integerChainId = parseInt(networkState) if (Number.isNaN(integerChainId)) { return 0 - } else { - return integerChainId } + return integerChainId } /** @@ -201,6 +195,7 @@ export default class TransactionController extends EventEmitter { const normalizedTxParams = txUtils.normalizeTxParams(txParams) txUtils.validateTxParams(normalizedTxParams) + /** `generateTxMeta` adds the default txMeta properties to the passed object. These include the tx's `id`. As we use the id for determining order of @@ -233,7 +228,7 @@ export default class TransactionController extends EventEmitter { } } - txMeta['origin'] = origin + txMeta.origin = origin const { transactionCategory, getCodeResponse } = await this._determineTransactionCategory(txParams) txMeta.transactionCategory = transactionCategory @@ -497,7 +492,7 @@ export default class TransactionController extends EventEmitter { const txMeta = this.txStateManager.getTx(txId) // add network/chain id const chainId = this.getChainId() - const txParams = Object.assign({}, txMeta.txParams, { chainId }) + const txParams = { ...txMeta.txParams, chainId } // sign tx const fromAddress = txParams.from const ethTx = new Transaction(txParams) @@ -606,19 +601,25 @@ export default class TransactionController extends EventEmitter { // /** maps methods for convenience*/ _mapMethods () { + /** @returns {Object} - the state in transaction controller */ this.getState = () => this.memStore.getState() + /** @returns {string|number} - the network number stored in networkStore */ this.getNetwork = () => this.networkStore.getState() + /** @returns {string} - the user selected address */ this.getSelectedAddress = () => this.preferencesStore.getState().selectedAddress + /** @returns {array} - transactions whos status is unapproved */ this.getUnapprovedTxCount = () => Object.keys(this.txStateManager.getUnapprovedTxList()).length + /** @returns {number} - number of transactions that have the status submitted @param {string} account - hex prefixed account */ this.getPendingTxCount = (account) => this.txStateManager.getPendingTransactions(account).length + /** see txStateManager */ this.getFilteredTxList = (opts) => this.txStateManager.getFilteredTxList(opts) } diff --git a/app/scripts/controllers/transactions/pending-tx-tracker.js b/app/scripts/controllers/transactions/pending-tx-tracker.js index 3ae85e4fa..e1b33cb2f 100644 --- a/app/scripts/controllers/transactions/pending-tx-tracker.js +++ b/app/scripts/controllers/transactions/pending-tx-tracker.js @@ -15,11 +15,11 @@ import EthQuery from 'ethjs-query' @param {function} config.getPendingTransactions a function for getting an array of transactions, @param {function} config.publishTransaction a async function for publishing raw transactions, - @class */ export default class PendingTransactionTracker extends EventEmitter { + /** * We wait this many blocks before emitting a 'tx:dropped' event * @@ -196,7 +196,6 @@ export default class PendingTransactionTracker extends EventEmitter { if (await this._checkIfTxWasDropped(txMeta)) { this.emit('tx:dropped', txId) - return } } diff --git a/app/scripts/controllers/transactions/tx-state-manager.js b/app/scripts/controllers/transactions/tx-state-manager.js index bbdd51872..b5c7e3353 100644 --- a/app/scripts/controllers/transactions/tx-state-manager.js +++ b/app/scripts/controllers/transactions/tx-state-manager.js @@ -4,6 +4,7 @@ import log from 'loglevel' import createId from '../../lib/random-id' import { generateHistoryEntry, replayHistory, snapshotFromTxMeta } from './lib/tx-state-history-helpers' import { getFinalStates, normalizeTxParams } from './lib/util' + /** TransactionStateManager is responsible for the state of a transaction and storing the transaction @@ -31,9 +32,8 @@ export default class TransactionStateManager extends EventEmitter { super() this.store = new ObservableStore( - Object.assign({ - transactions: [], - }, initState)) + { transactions: [], ...initState }, + ) this.txHistoryLimit = txHistoryLimit this.getNetwork = getNetwork } @@ -47,13 +47,13 @@ export default class TransactionStateManager extends EventEmitter { if (netId === 'loading') { throw new Error('MetaMask is having trouble connecting to the network') } - return Object.assign({ + return { id: createId(), time: (new Date()).getTime(), status: 'unapproved', metamaskNetworkId: netId, - loadingDefaults: true, - }, opts) + loadingDefaults: true, ...opts, + } } /** @@ -202,6 +202,7 @@ export default class TransactionStateManager extends EventEmitter { this._saveTxList(transactions) return txMeta } + /** @param {number} txId @returns {Object} - the txMeta who matches the given id if none found @@ -241,7 +242,6 @@ export default class TransactionStateManager extends EventEmitter { this._saveTxList(txList) } - /** merges txParams obj onto txMeta.txParams use extend to ensure that all fields are filled @@ -326,6 +326,7 @@ export default class TransactionStateManager extends EventEmitter { }) return filteredTxList } + /** @param {string} key - the key to check @@ -340,9 +341,8 @@ export default class TransactionStateManager extends EventEmitter { return txList.filter((txMeta) => { if (key in txMeta.txParams) { return filter(txMeta.txParams[key]) - } else { - return filter(txMeta[key]) } + return filter(txMeta[key]) }) } @@ -373,6 +373,7 @@ export default class TransactionStateManager extends EventEmitter { setTxStatusUnapproved (txId) { this._setTxStatus(txId, 'unapproved') } + /** should update the status of the tx to 'approved'. @param {number} txId - the txMeta Id @@ -417,7 +418,6 @@ export default class TransactionStateManager extends EventEmitter { this._setTxStatus(txId, 'dropped') } - /** should update the status of the tx to 'failed'. and put the error on the txMeta diff --git a/app/scripts/inpage.js b/app/scripts/inpage.js index 3cb837373..546f0a362 100644 --- a/app/scripts/inpage.js +++ b/app/scripts/inpage.js @@ -30,12 +30,14 @@ const restoreContextAfterImports = () => { cleanContextForImports() +/* eslint-disable import/first */ import log from 'loglevel' import LocalMessageDuplexStream from 'post-message-stream' import { initProvider } from '@metamask/inpage-provider' // TODO:deprecate:2020 import setupWeb3 from './lib/setupWeb3' +/* eslint-enable import/first */ restoreContextAfterImports() @@ -58,7 +60,6 @@ initProvider({ // TODO:deprecate:2020 // Setup web3 - if (typeof window.web3 !== 'undefined') { throw new Error(`MetaMask detected another web3. MetaMask will not work reliably with another web3 extension. diff --git a/app/scripts/lib/ComposableObservableStore.js b/app/scripts/lib/ComposableObservableStore.js index 3fb90b4b6..ef8e91f22 100644 --- a/app/scripts/lib/ComposableObservableStore.js +++ b/app/scripts/lib/ComposableObservableStore.js @@ -5,6 +5,7 @@ import ObservableStore from 'obs-store' * structure of child stores based on configuration */ export default class ComposableObservableStore extends ObservableStore { + /** * Create a new store * diff --git a/app/scripts/lib/cleanErrorStack.js b/app/scripts/lib/cleanErrorStack.js index 46e069e8e..c68c29b9e 100644 --- a/app/scripts/lib/cleanErrorStack.js +++ b/app/scripts/lib/cleanErrorStack.js @@ -15,7 +15,7 @@ export default function cleanErrorStack (err) { } else if (msg === '') { err.stack = err.name } else { - err.stack = err.name + ': ' + err.message + err.stack = `${err.name}: ${err.message}` } return err diff --git a/app/scripts/lib/createStreamSink.js b/app/scripts/lib/createStreamSink.js index 5a9d0808e..ad0a67959 100644 --- a/app/scripts/lib/createStreamSink.js +++ b/app/scripts/lib/createStreamSink.js @@ -4,7 +4,7 @@ import promiseToCallback from 'promise-to-callback' class AsyncWritableStream extends WritableStream { constructor (asyncWriteFn, _opts) { - const opts = Object.assign({ objectMode: true }, _opts) + const opts = { objectMode: true, ..._opts } super(opts) this._asyncWriteFn = asyncWriteFn } diff --git a/app/scripts/lib/decrypt-message-manager.js b/app/scripts/lib/decrypt-message-manager.js index 060a11d9b..a31074f12 100644 --- a/app/scripts/lib/decrypt-message-manager.js +++ b/app/scripts/lib/decrypt-message-manager.js @@ -26,6 +26,7 @@ const hexRe = /^[0-9A-Fa-f]+$/ug */ export default class DecryptMessageManager extends EventEmitter { + /** * Controller in charge of managing - storing, adding, removing, updating - DecryptMessage. * @@ -100,7 +101,6 @@ export default class DecryptMessageManager extends EventEmitter { return default: reject(new Error(`MetaMask Decryption: Unknown problem: ${JSON.stringify(msgParams)}`)) - return } }) }) @@ -128,8 +128,8 @@ export default class DecryptMessageManager extends EventEmitter { const msgId = createId() const msgData = { id: msgId, - msgParams: msgParams, - time: time, + msgParams, + time, status: 'unapproved', type: MESSAGE_TYPE.ETH_DECRYPT, } diff --git a/app/scripts/lib/encryption-public-key-manager.js b/app/scripts/lib/encryption-public-key-manager.js index 8d78bf8bd..2631dc7d3 100644 --- a/app/scripts/lib/encryption-public-key-manager.js +++ b/app/scripts/lib/encryption-public-key-manager.js @@ -23,6 +23,7 @@ import { MESSAGE_TYPE } from './enums' */ export default class EncryptionPublicKeyManager extends EventEmitter { + /** * Controller in charge of managing - storing, adding, removing, updating - EncryptionPublicKey. * @@ -94,7 +95,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter { return default: reject(new Error(`MetaMask EncryptionPublicKey: Unknown problem: ${JSON.stringify(address)}`)) - return } }) }) @@ -118,7 +118,7 @@ export default class EncryptionPublicKeyManager extends EventEmitter { const msgData = { id: msgId, msgParams: address, - time: time, + time, status: 'unapproved', type: MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY, } diff --git a/app/scripts/lib/ens-ipfs/resolver.js b/app/scripts/lib/ens-ipfs/resolver.js index 67acba8c7..cc307e617 100644 --- a/app/scripts/lib/ens-ipfs/resolver.js +++ b/app/scripts/lib/ens-ipfs/resolver.js @@ -36,7 +36,7 @@ export default async function resolveEnsToIpfsContentId ({ provider, name }) { decodedContentHash = contentHash.helpers.cidV0ToV1Base32(decodedContentHash) } - return { type: type, hash: decodedContentHash } + return { type, hash: decodedContentHash } } if (isLegacyResolver[0]) { // lookup content id diff --git a/app/scripts/lib/extractEthjsErrorMessage.js b/app/scripts/lib/extractEthjsErrorMessage.js index 6d9d0bf2d..0dde04f06 100644 --- a/app/scripts/lib/extractEthjsErrorMessage.js +++ b/app/scripts/lib/extractEthjsErrorMessage.js @@ -19,7 +19,6 @@ export default function extractEthjsErrorMessage (errorMessage) { const payloadAndError = errorMessage.slice(ethJsRpcSlug.length) const originalError = payloadAndError.slice(payloadAndError.indexOf(errorLabelPrefix) + errorLabelPrefix.length) return originalError - } else { - return errorMessage } + return errorMessage } diff --git a/app/scripts/lib/local-store.js b/app/scripts/lib/local-store.js index 5d51b5f72..e7f05781c 100644 --- a/app/scripts/lib/local-store.js +++ b/app/scripts/lib/local-store.js @@ -6,11 +6,12 @@ import { checkForError } from './util' * A wrapper around the extension's storage local API */ export default class ExtensionStore { + /** * @constructor */ constructor () { - this.isSupported = !!(extension.storage.local) + this.isSupported = Boolean(extension.storage.local) if (!this.isSupported) { log.error('Storage local API not available.') } @@ -29,9 +30,8 @@ export default class ExtensionStore { // if the object is empty, treat it as undefined if (isEmpty(result)) { return undefined - } else { - return result } + return result } /** diff --git a/app/scripts/lib/message-manager.js b/app/scripts/lib/message-manager.js index 6c74b017a..280003c40 100644 --- a/app/scripts/lib/message-manager.js +++ b/app/scripts/lib/message-manager.js @@ -115,8 +115,8 @@ export default class MessageManager extends EventEmitter { const msgId = createId() const msgData = { id: msgId, - msgParams: msgParams, - time: time, + msgParams, + time, status: 'unapproved', type: MESSAGE_TYPE.ETH_SIGN, } @@ -279,8 +279,7 @@ function normalizeMsgData (data) { if (data.slice(0, 2) === '0x') { // data is already hex return data - } else { - // data is unicode, convert to hex - return ethUtil.bufferToHex(Buffer.from(data, 'utf8')) } + // data is unicode, convert to hex + return ethUtil.bufferToHex(Buffer.from(data, 'utf8')) } diff --git a/app/scripts/lib/personal-message-manager.js b/app/scripts/lib/personal-message-manager.js index 7e6ac3c4e..52c0f9bad 100644 --- a/app/scripts/lib/personal-message-manager.js +++ b/app/scripts/lib/personal-message-manager.js @@ -28,6 +28,7 @@ const hexRe = /^[0-9A-Fa-f]+$/ug */ export default class PersonalMessageManager extends EventEmitter { + /** * Controller in charge of managing - storing, adding, removing, updating - PersonalMessage. * @@ -100,7 +101,6 @@ export default class PersonalMessageManager extends EventEmitter { return default: reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) - return } }) }) @@ -128,8 +128,8 @@ export default class PersonalMessageManager extends EventEmitter { const msgId = createId() const msgData = { id: msgId, - msgParams: msgParams, - time: time, + msgParams, + time, status: 'unapproved', type: MESSAGE_TYPE.PERSONAL_SIGN, } diff --git a/app/scripts/lib/random-id.js b/app/scripts/lib/random-id.js index eebba0619..9345fcaad 100644 --- a/app/scripts/lib/random-id.js +++ b/app/scripts/lib/random-id.js @@ -2,7 +2,7 @@ const MAX = Number.MAX_SAFE_INTEGER let idCounter = Math.round(Math.random() * MAX) export default function createRandomId () { - idCounter = idCounter % MAX + idCounter %= MAX // eslint-disable-next-line no-plusplus return idCounter++ } diff --git a/app/scripts/lib/seed-phrase-verifier.js b/app/scripts/lib/seed-phrase-verifier.js index f07e63a2c..71b9e2819 100644 --- a/app/scripts/lib/seed-phrase-verifier.js +++ b/app/scripts/lib/seed-phrase-verifier.js @@ -30,8 +30,8 @@ const seedPhraseVerifier = { const keyring = new Keyring(opts) const restoredAccounts = await keyring.getAccounts() - log.debug('Created accounts: ' + JSON.stringify(createdAccounts)) - log.debug('Restored accounts: ' + JSON.stringify(restoredAccounts)) + log.debug(`Created accounts: ${JSON.stringify(createdAccounts)}`) + log.debug(`Restored accounts: ${JSON.stringify(restoredAccounts)}`) if (restoredAccounts.length !== createdAccounts.length) { // this should not happen... @@ -40,7 +40,7 @@ const seedPhraseVerifier = { for (let i = 0; i < restoredAccounts.length; i++) { if (restoredAccounts[i].toLowerCase() !== createdAccounts[i].toLowerCase()) { - throw new Error('Not identical accounts! Original: ' + createdAccounts[i] + ', Restored: ' + restoredAccounts[i]) + throw new Error(`Not identical accounts! Original: ${createdAccounts[i]}, Restored: ${restoredAccounts[i]}`) } } }, diff --git a/app/scripts/lib/typed-message-manager.js b/app/scripts/lib/typed-message-manager.js index 8c3caca2e..64ce6427c 100644 --- a/app/scripts/lib/typed-message-manager.js +++ b/app/scripts/lib/typed-message-manager.js @@ -28,6 +28,7 @@ import { MESSAGE_TYPE } from './enums' */ export default class TypedMessageManager extends EventEmitter { + /** * Controller in charge of managing - storing, adding, removing, updating - TypedMessage. */ @@ -119,8 +120,8 @@ export default class TypedMessageManager extends EventEmitter { const msgId = createId() const msgData = { id: msgId, - msgParams: msgParams, - time: time, + msgParams, + time, status: 'unapproved', type: MESSAGE_TYPE.ETH_SIGN_TYPED_DATA, } diff --git a/app/scripts/lib/util.js b/app/scripts/lib/util.js index 6d06758b3..08998d6cc 100644 --- a/app/scripts/lib/util.js +++ b/app/scripts/lib/util.js @@ -27,9 +27,8 @@ const getEnvironmentTypeMemo = memoize((url) => { return ENVIRONMENT_TYPE_FULLSCREEN } else if (parsedUrl.pathname === '/notification.html') { return ENVIRONMENT_TYPE_NOTIFICATION - } else { - return ENVIRONMENT_TYPE_BACKGROUND } + return ENVIRONMENT_TYPE_BACKGROUND }) /** diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index e7d1de51d..1c99424bc 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -63,7 +63,6 @@ import accountImporter from './account-import-strategies' import selectChainId from './lib/select-chain-id' import seedPhraseVerifier from './lib/seed-phrase-verifier' - import backgroundMetaMetricsEvent from './lib/background-metametrics' export default class MetamaskController extends EventEmitter { @@ -274,7 +273,6 @@ export default class MetamaskController extends EventEmitter { this.encryptionPublicKeyManager = new EncryptionPublicKeyManager() this.typedMessageManager = new TypedMessageManager({ networkController: this.networkController }) - this.store.updateStructure({ AppStateController: this.appStateController.store, TransactionController: this.txController.store, @@ -407,7 +405,7 @@ export default class MetamaskController extends EventEmitter { */ getState () { const { vault } = this.keyringController.store.getState() - const isInitialized = !!vault + const isInitialized = Boolean(vault) return { ...{ isInitialized }, @@ -929,7 +927,6 @@ export default class MetamaskController extends EventEmitter { return { ...keyState, identities } } - // // Account Management // @@ -1029,7 +1026,6 @@ export default class MetamaskController extends EventEmitter { return address } - /** * Imports an account with the specified import strategy. * These are defined in app/scripts/account-import-strategies @@ -1041,7 +1037,7 @@ export default class MetamaskController extends EventEmitter { */ async importAccountWithStrategy (strategy, args) { const privateKey = await accountImporter.importAccount(strategy, args) - const keyring = await this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ]) + const keyring = await this.keyringController.addNewKeyring('Simple Key Pair', [privateKey]) const accounts = await keyring.getAccounts() // update accounts in preferences controller const allAccounts = await this.keyringController.getAccounts() @@ -1116,10 +1112,10 @@ export default class MetamaskController extends EventEmitter { cancelMessage (msgId, cb) { const { messageManager } = this messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) + if (!cb || typeof cb !== 'function') { return } + cb(null, this.getState()) } // personal_sign methods: @@ -1175,10 +1171,10 @@ export default class MetamaskController extends EventEmitter { cancelPersonalMessage (msgId, cb) { const messageManager = this.personalMessageManager messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) + if (!cb || typeof cb !== 'function') { return } + cb(null, this.getState()) } // eth_decrypt methods @@ -1260,10 +1256,10 @@ export default class MetamaskController extends EventEmitter { cancelDecryptMessage (msgId, cb) { const messageManager = this.decryptMessageManager messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) + if (!cb || typeof cb !== 'function') { return } + cb(null, this.getState()) } // eth_getEncryptionPublicKey methods @@ -1318,10 +1314,10 @@ export default class MetamaskController extends EventEmitter { cancelEncryptionPublicKey (msgId, cb) { const messageManager = this.encryptionPublicKeyManager messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) + if (!cb || typeof cb !== 'function') { return } + cb(null, this.getState()) } // eth_signTypedData methods @@ -1379,10 +1375,10 @@ export default class MetamaskController extends EventEmitter { cancelTypedMessage (msgId, cb) { const messageManager = this.typedMessageManager messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) + if (!cb || typeof cb !== 'function') { return } + cb(null, this.getState()) } //============================================================================= @@ -1872,6 +1868,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -1892,7 +1889,6 @@ export default class MetamaskController extends EventEmitter { return rpcUrl } - /** * A method for selecting a custom URL for an ethereum RPC provider. * @param {string} rpcTarget - A URL for a valid Ethereum RPC API. @@ -1938,6 +1934,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -1954,6 +1951,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -1970,6 +1968,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -1986,6 +1985,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -2002,6 +2002,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -2013,6 +2014,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } @@ -2029,11 +2031,11 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } - /** * A method for setting a user's current locale, affecting the language rendered. * @param {string} key - Locale identifier. @@ -2046,6 +2048,7 @@ export default class MetamaskController extends EventEmitter { return } catch (err) { cb(err) + // eslint-disable-next-line no-useless-return return } } diff --git a/app/scripts/migrations/002.js b/app/scripts/migrations/002.js index a726d01e3..24df7f4de 100644 --- a/app/scripts/migrations/002.js +++ b/app/scripts/migrations/002.js @@ -1,12 +1,11 @@ -const version = 2 - import { cloneDeep } from 'lodash' +const version = 2 export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { diff --git a/app/scripts/migrations/003.js b/app/scripts/migrations/003.js index 9584fb889..08e4be468 100644 --- a/app/scripts/migrations/003.js +++ b/app/scripts/migrations/003.js @@ -1,13 +1,13 @@ +import { cloneDeep } from 'lodash' + const version = 3 const oldTestRpc = 'https://rawtestrpc.metamask.io/' const newTestRpc = 'https://testrpc.metamask.io/' -import { cloneDeep } from 'lodash' - export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { diff --git a/app/scripts/migrations/004.js b/app/scripts/migrations/004.js index d2d3136f3..48741a267 100644 --- a/app/scripts/migrations/004.js +++ b/app/scripts/migrations/004.js @@ -1,11 +1,11 @@ -const version = 4 - import { cloneDeep } from 'lodash' +const version = 4 + export default { version, - migrate: function (versionedData) { + migrate (versionedData) { const safeVersionedData = cloneDeep(versionedData) safeVersionedData.meta.version = version try { diff --git a/app/scripts/migrations/005.js b/app/scripts/migrations/005.js index 00f3ca552..baead6890 100644 --- a/app/scripts/migrations/005.js +++ b/app/scripts/migrations/005.js @@ -1,5 +1,3 @@ -const version = 5 - /* This migration moves state from the flat state trie into KeyringController substate @@ -8,11 +6,12 @@ This migration moves state from the flat state trie into KeyringController subst import { cloneDeep } from 'lodash' +const version = 5 export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -20,7 +19,7 @@ export default { const newState = selectSubstateForKeyringController(state) versionedData.data = newState } catch (err) { - console.warn('MetaMask Migration #5' + err.stack) + console.warn(`MetaMask Migration #5${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/006.js b/app/scripts/migrations/006.js index b53015315..8d1e72935 100644 --- a/app/scripts/migrations/006.js +++ b/app/scripts/migrations/006.js @@ -1,5 +1,3 @@ -const version = 6 - /* This migration moves KeyringController.selectedAddress to PreferencesController.selectedAddress @@ -8,10 +6,12 @@ This migration moves KeyringController.selectedAddress to PreferencesController. import { cloneDeep } from 'lodash' +const version = 6 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = migrateState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/007.js b/app/scripts/migrations/007.js index bacf005fa..41272ee3b 100644 --- a/app/scripts/migrations/007.js +++ b/app/scripts/migrations/007.js @@ -1,5 +1,3 @@ -const version = 7 - /* This migration breaks out the TransactionManager substate @@ -8,10 +6,12 @@ This migration breaks out the TransactionManager substate import { cloneDeep } from 'lodash' +const version = 7 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/008.js b/app/scripts/migrations/008.js index a4537ae9b..6f25bbcd5 100644 --- a/app/scripts/migrations/008.js +++ b/app/scripts/migrations/008.js @@ -1,5 +1,3 @@ -const version = 8 - /* This migration breaks out the NoticeController substate @@ -8,10 +6,12 @@ This migration breaks out the NoticeController substate import { cloneDeep } from 'lodash' +const version = 8 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/009.js b/app/scripts/migrations/009.js index 3fddf7aa9..f63297836 100644 --- a/app/scripts/migrations/009.js +++ b/app/scripts/migrations/009.js @@ -1,5 +1,3 @@ -const version = 9 - /* This migration breaks out the CurrencyController substate @@ -8,10 +6,12 @@ This migration breaks out the CurrencyController substate import { cloneDeep, merge } from 'lodash' +const version = 9 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/010.js b/app/scripts/migrations/010.js index c8dd42aaf..354b19871 100644 --- a/app/scripts/migrations/010.js +++ b/app/scripts/migrations/010.js @@ -1,5 +1,3 @@ -const version = 10 - /* This migration breaks out the ShapeShiftController substate @@ -8,10 +6,12 @@ This migration breaks out the ShapeShiftController substate import { cloneDeep, merge } from 'lodash' +const version = 10 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/011.js b/app/scripts/migrations/011.js index d465bf5a6..d8f852f9f 100644 --- a/app/scripts/migrations/011.js +++ b/app/scripts/migrations/011.js @@ -1,5 +1,3 @@ -const version = 11 - /* This migration removes the discaimer state from our app, which was integrated into our notices. @@ -8,10 +6,12 @@ This migration removes the discaimer state from our app, which was integrated in import { cloneDeep } from 'lodash' +const version = 11 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/012.js b/app/scripts/migrations/012.js index fc3ddc59c..d01edbc41 100644 --- a/app/scripts/migrations/012.js +++ b/app/scripts/migrations/012.js @@ -1,5 +1,3 @@ -const version = 12 - /* This migration modifies our notices to delete their body after being read. @@ -8,10 +6,12 @@ This migration modifies our notices to delete their body after being read. import { cloneDeep } from 'lodash' +const version = 12 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/013.js b/app/scripts/migrations/013.js index 433face72..530fc687c 100644 --- a/app/scripts/migrations/013.js +++ b/app/scripts/migrations/013.js @@ -1,5 +1,3 @@ -const version = 13 - /* This migration modifies the network config from ambiguous 'testnet' to explicit 'ropsten' @@ -8,10 +6,12 @@ This migration modifies the network config from ambiguous 'testnet' to explicit import { cloneDeep } from 'lodash' +const version = 13 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/014.js b/app/scripts/migrations/014.js index e7a7b8c99..630aa2051 100644 --- a/app/scripts/migrations/014.js +++ b/app/scripts/migrations/014.js @@ -1,5 +1,3 @@ -const version = 14 - /* This migration removes provider from config and moves it too NetworkController. @@ -8,10 +6,12 @@ This migration removes provider from config and moves it too NetworkController. import { cloneDeep } from 'lodash' +const version = 14 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/015.js b/app/scripts/migrations/015.js index de6ce94bc..682eb8db7 100644 --- a/app/scripts/migrations/015.js +++ b/app/scripts/migrations/015.js @@ -1,5 +1,3 @@ -const version = 15 - /* This migration sets transactions with the 'Gave up submitting tx.' err message @@ -9,10 +7,12 @@ to a 'failed' stated import { cloneDeep } from 'lodash' +const version = 15 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -20,7 +20,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/016.js b/app/scripts/migrations/016.js index dcef6f313..974a1125d 100644 --- a/app/scripts/migrations/016.js +++ b/app/scripts/migrations/016.js @@ -1,5 +1,3 @@ -const version = 16 - /* This migration sets transactions with the 'Gave up submitting tx.' err message @@ -9,10 +7,12 @@ to a 'failed' stated import { cloneDeep } from 'lodash' +const version = 16 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -20,7 +20,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/017.js b/app/scripts/migrations/017.js index 8e43863ad..497cbe33e 100644 --- a/app/scripts/migrations/017.js +++ b/app/scripts/migrations/017.js @@ -1,5 +1,3 @@ -const version = 17 - /* This migration sets transactions who were retried and marked as failed to submitted @@ -8,10 +6,12 @@ This migration sets transactions who were retried and marked as failed to submit import { cloneDeep } from 'lodash' +const version = 17 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/018.js b/app/scripts/migrations/018.js index c2dc39b26..bb57ddf0c 100644 --- a/app/scripts/migrations/018.js +++ b/app/scripts/migrations/018.js @@ -1,5 +1,3 @@ -const version = 18 - /* This migration updates "transaction state history" to diffs style @@ -12,11 +10,12 @@ import { migrateFromSnapshotsToDiffs, } from '../controllers/transactions/lib/tx-state-history-helpers' +const version = 18 export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -24,7 +23,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/019.js b/app/scripts/migrations/019.js index d99fa6aa8..4c786b7c9 100644 --- a/app/scripts/migrations/019.js +++ b/app/scripts/migrations/019.js @@ -1,6 +1,4 @@ -const version = 19 - /* This migration sets transactions as failed @@ -10,10 +8,12 @@ whos nonce is too high import { cloneDeep } from 'lodash' +const version = 19 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -21,7 +21,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/020.js b/app/scripts/migrations/020.js index eaf6dcbc0..eb8080124 100644 --- a/app/scripts/migrations/020.js +++ b/app/scripts/migrations/020.js @@ -1,5 +1,3 @@ -const version = 20 - /* This migration ensures previous installations @@ -10,10 +8,12 @@ so that we can version notices in the future. import { cloneDeep } from 'lodash' +const version = 20 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -21,7 +21,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/021.js b/app/scripts/migrations/021.js index c57266f08..ac3170131 100644 --- a/app/scripts/migrations/021.js +++ b/app/scripts/migrations/021.js @@ -1,5 +1,3 @@ -const version = 21 - /* This migration removes the BlackListController from disk state @@ -8,10 +6,12 @@ This migration removes the BlackListController from disk state import { cloneDeep } from 'lodash' +const version = 21 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -19,7 +19,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/022.js b/app/scripts/migrations/022.js index 630bc2022..76f96a0ae 100644 --- a/app/scripts/migrations/022.js +++ b/app/scripts/migrations/022.js @@ -1,6 +1,4 @@ -const version = 22 - /* This migration adds submittedTime to the txMeta if it is not their @@ -9,10 +7,12 @@ This migration adds submittedTime to the txMeta if it is not their import { cloneDeep } from 'lodash' +const version = 22 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -20,7 +20,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/023.js b/app/scripts/migrations/023.js index b6f9a1038..5f0363d53 100644 --- a/app/scripts/migrations/023.js +++ b/app/scripts/migrations/023.js @@ -1,6 +1,4 @@ -const version = 23 - /* This migration removes transactions that are no longer usefull down to 40 total @@ -9,10 +7,12 @@ This migration removes transactions that are no longer usefull down to 40 total import { cloneDeep } from 'lodash' +const version = 23 + export default { version, - migrate: function (originalVersionedData) { + migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version try { @@ -20,7 +20,7 @@ export default { const newState = transformState(state) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) }, diff --git a/app/scripts/migrations/024.js b/app/scripts/migrations/024.js index 07257d428..84a998d12 100644 --- a/app/scripts/migrations/024.js +++ b/app/scripts/migrations/024.js @@ -1,6 +1,4 @@ -const version = 24 - /* This migration ensures that the from address in txParams is to lower case for @@ -10,10 +8,12 @@ all unapproved transactions import { cloneDeep } from 'lodash' +const version = 24 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/025.js b/app/scripts/migrations/025.js index 0f5f568ab..72bcdbf01 100644 --- a/app/scripts/migrations/025.js +++ b/app/scripts/migrations/025.js @@ -1,6 +1,4 @@ // next version number -const version = 25 - /* normalizes txParams on unconfirmed txs @@ -10,10 +8,12 @@ import ethUtil from 'ethereumjs-util' import { cloneDeep } from 'lodash' +const version = 25 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/026.js b/app/scripts/migrations/026.js index 2282455ef..e6cb9db85 100644 --- a/app/scripts/migrations/026.js +++ b/app/scripts/migrations/026.js @@ -1,5 +1,3 @@ -const version = 26 - /* This migration moves the identities stored in the KeyringController @@ -9,6 +7,8 @@ This migration moves the identities stored in the KeyringController import { cloneDeep } from 'lodash' +const version = 26 + export default { version, migrate (originalVersionedData) { @@ -18,7 +18,7 @@ export default { const state = versionedData.data versionedData.data = transformState(state) } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) return Promise.reject(err) } return Promise.resolve(versionedData) diff --git a/app/scripts/migrations/027.js b/app/scripts/migrations/027.js index 2607f03da..42e024f56 100644 --- a/app/scripts/migrations/027.js +++ b/app/scripts/migrations/027.js @@ -1,6 +1,4 @@ // next version number -const version = 27 - /* normalizes txParams on unconfirmed txs @@ -8,10 +6,12 @@ normalizes txParams on unconfirmed txs */ import { cloneDeep } from 'lodash' +const version = 27 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/028.js b/app/scripts/migrations/028.js index 522067f8b..fa816ca53 100644 --- a/app/scripts/migrations/028.js +++ b/app/scripts/migrations/028.js @@ -1,6 +1,4 @@ // next version number -const version = 28 - /* normalizes txParams on unconfirmed txs @@ -8,10 +6,12 @@ normalizes txParams on unconfirmed txs */ import { cloneDeep } from 'lodash' +const version = 28 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/029.js b/app/scripts/migrations/029.js index 345d1ad92..4773eb466 100644 --- a/app/scripts/migrations/029.js +++ b/app/scripts/migrations/029.js @@ -1,7 +1,8 @@ // next version number -const version = 29 import failTxsThat from './fail-tx' +const version = 29 + // time const seconds = 1000 const minutes = 60 * seconds diff --git a/app/scripts/migrations/030.js b/app/scripts/migrations/030.js index 351fbb269..6f11e27a5 100644 --- a/app/scripts/migrations/030.js +++ b/app/scripts/migrations/030.js @@ -1,6 +1,4 @@ // next version number -const version = 30 - /* removes invalid chaids from preferences and networkController for custom rpcs @@ -9,10 +7,12 @@ removes invalid chaids from preferences and networkController for custom rpcs import { cloneDeep } from 'lodash' +const version = 30 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data @@ -29,7 +29,7 @@ function transformState (state) { if (frequentRpcListDetail) { frequentRpcListDetail.forEach((rpc, index) => { // eslint-disable-next-line radix - if (!!rpc.chainId && Number.isNaN(parseInt(rpc.chainId))) { + if (Boolean(rpc.chainId) && Number.isNaN(parseInt(rpc.chainId))) { delete frequentRpcListDetail[index].chainId } }) diff --git a/app/scripts/migrations/031.js b/app/scripts/migrations/031.js index 14d4a7ef8..59a8dcf15 100644 --- a/app/scripts/migrations/031.js +++ b/app/scripts/migrations/031.js @@ -1,7 +1,8 @@ // next version number -const version = 31 import { cloneDeep } from 'lodash' +const version = 31 + /* * The purpose of this migration is to properly set the completedOnboarding flag based on the state * of the KeyringController. @@ -9,7 +10,7 @@ import { cloneDeep } from 'lodash' export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/032.js b/app/scripts/migrations/032.js index 4f807617d..fce4d65a6 100644 --- a/app/scripts/migrations/032.js +++ b/app/scripts/migrations/032.js @@ -1,12 +1,13 @@ -const version = 32 import { cloneDeep } from 'lodash' +const version = 32 + /** * The purpose of this migration is to set the {@code completedUiMigration} flag based on the user's UI preferences */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/033.js b/app/scripts/migrations/033.js index 70710e793..e1e0ea3b4 100644 --- a/app/scripts/migrations/033.js +++ b/app/scripts/migrations/033.js @@ -1,6 +1,4 @@ // next version number -const version = 33 - /* Cleans up notices and assocated notice controller code @@ -9,10 +7,12 @@ Cleans up notices and assocated notice controller code import { cloneDeep } from 'lodash' +const version = 33 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/034.js b/app/scripts/migrations/034.js index 92a8d909f..ba61131e4 100644 --- a/app/scripts/migrations/034.js +++ b/app/scripts/migrations/034.js @@ -1,13 +1,14 @@ -const version = 34 import { cloneDeep } from 'lodash' +const version = 34 + /** * The purpose of this migration is to enable the {@code privacyMode} feature flag and set the user as being migrated * if it was {@code false}. */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/035.js b/app/scripts/migrations/035.js index b483c35de..6ea634730 100644 --- a/app/scripts/migrations/035.js +++ b/app/scripts/migrations/035.js @@ -1,6 +1,4 @@ // next version number -const version = 35 - /* Removes the deprecated 'seedWords' state @@ -9,10 +7,12 @@ Removes the deprecated 'seedWords' state import { cloneDeep } from 'lodash' +const version = 35 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version versionedData.data = transformState(versionedData.data) diff --git a/app/scripts/migrations/036.js b/app/scripts/migrations/036.js index 0ba0bc035..2b64fc6ea 100644 --- a/app/scripts/migrations/036.js +++ b/app/scripts/migrations/036.js @@ -1,12 +1,13 @@ -const version = 36 import { cloneDeep } from 'lodash' +const version = 36 + /** * The purpose of this migration is to remove the {@code privacyMode} feature flag. */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/037.js b/app/scripts/migrations/037.js index 1d7f13810..e650337d4 100644 --- a/app/scripts/migrations/037.js +++ b/app/scripts/migrations/037.js @@ -1,7 +1,8 @@ -const version = 37 import { cloneDeep } from 'lodash' import { util } from '@metamask/controllers' +const version = 37 + /** * The purpose of this migration is to update the address book state * to the new schema with chainId as a key. @@ -9,7 +10,7 @@ import { util } from '@metamask/controllers' */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/038.js b/app/scripts/migrations/038.js index e5386f7a9..b104fe49f 100644 --- a/app/scripts/migrations/038.js +++ b/app/scripts/migrations/038.js @@ -1,12 +1,13 @@ -const version = 38 import { cloneDeep } from 'lodash' +const version = 38 + /** * The purpose of this migration is to assign all users to a test group for the fullScreenVsPopup a/b test */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/039.js b/app/scripts/migrations/039.js index f1f38c0a5..d190b4f9b 100644 --- a/app/scripts/migrations/039.js +++ b/app/scripts/migrations/039.js @@ -1,7 +1,8 @@ -const version = 39 import { cloneDeep } from 'lodash' import ethUtil from 'ethereumjs-util' +const version = 39 + const DAI_V1_CONTRACT_ADDRESS = '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359' const DAI_V1_TOKEN_SYMBOL = 'DAI' const SAI_TOKEN_SYMBOL = 'SAI' @@ -21,7 +22,7 @@ function isOldDai (token = {}) { */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/040.js b/app/scripts/migrations/040.js index ca243e4aa..93b0e72be 100644 --- a/app/scripts/migrations/040.js +++ b/app/scripts/migrations/040.js @@ -1,6 +1,7 @@ -const version = 40 import { cloneDeep } from 'lodash' +const version = 40 + /** * Site connections are now managed by the PermissionsController, and the * ProviderApprovalController is removed. This migration deletes all @@ -8,7 +9,7 @@ import { cloneDeep } from 'lodash' */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/041.js b/app/scripts/migrations/041.js index 83028ed1b..9e81312c3 100644 --- a/app/scripts/migrations/041.js +++ b/app/scripts/migrations/041.js @@ -1,12 +1,13 @@ -const version = 41 import { cloneDeep } from 'lodash' +const version = 41 + /** * PreferencesController.autoLogoutTimeLimit -> autoLockTimeLimit */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/042.js b/app/scripts/migrations/042.js index 4c1fb510a..ed8b9f7cc 100644 --- a/app/scripts/migrations/042.js +++ b/app/scripts/migrations/042.js @@ -1,13 +1,14 @@ -const version = 42 import { cloneDeep } from 'lodash' +const version = 42 + /** * Initialize `connectedStatusPopoverHasBeenShown` to `false` if it hasn't yet been set, * so that existing users are introduced to the new connected status indicator */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/043.js b/app/scripts/migrations/043.js index c024b7949..ad2dddde5 100644 --- a/app/scripts/migrations/043.js +++ b/app/scripts/migrations/043.js @@ -1,12 +1,13 @@ -const version = 43 import { cloneDeep } from 'lodash' +const version = 43 + /** * Remove unused 'currentAccountTab' state */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/044.js b/app/scripts/migrations/044.js index 39c9b546f..00a23c012 100644 --- a/app/scripts/migrations/044.js +++ b/app/scripts/migrations/044.js @@ -1,12 +1,13 @@ -const version = 44 import { cloneDeep } from 'lodash' +const version = 44 + /** * Remove unused 'mkrMigrationReminderTimestamp' state from the `AppStateController` */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/045.js b/app/scripts/migrations/045.js index 9ff7ded55..d8024a0f9 100644 --- a/app/scripts/migrations/045.js +++ b/app/scripts/migrations/045.js @@ -1,12 +1,13 @@ -const version = 45 import { cloneDeep } from 'lodash' +const version = 45 + /** * Replaces {@code PreferencesController.ipfsGateway} with 'dweb.link' if set */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/046.js b/app/scripts/migrations/046.js index 4f7d36db1..6b1ebdae0 100644 --- a/app/scripts/migrations/046.js +++ b/app/scripts/migrations/046.js @@ -1,12 +1,13 @@ -const version = 46 import { cloneDeep } from 'lodash' +const version = 46 + /** * Delete {@code ABTestController} state */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/047.js b/app/scripts/migrations/047.js index 255971ec3..371bf2135 100644 --- a/app/scripts/migrations/047.js +++ b/app/scripts/migrations/047.js @@ -1,12 +1,13 @@ -const version = 47 import { cloneDeep } from 'lodash' +const version = 47 + /** * Stringify the `metamaskNetworkId` property of all transactions */ export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/migrations/fail-tx.js b/app/scripts/migrations/fail-tx.js index c8b5f7c36..e6236ec4e 100644 --- a/app/scripts/migrations/fail-tx.js +++ b/app/scripts/migrations/fail-tx.js @@ -9,7 +9,7 @@ export default function failTxsThat (version, reason, condition) { const newState = transformState(state, condition, reason) versionedData.data = newState } catch (err) { - console.warn(`MetaMask Migration #${version}` + err.stack) + console.warn(`MetaMask Migration #${version}${err.stack}`) } return Promise.resolve(versionedData) diff --git a/app/scripts/migrations/template.js b/app/scripts/migrations/template.js index c9e3b795b..6427d49f4 100644 --- a/app/scripts/migrations/template.js +++ b/app/scripts/migrations/template.js @@ -1,6 +1,4 @@ // next version number -const version = 0 - /* description of migration and what it does @@ -9,10 +7,12 @@ description of migration and what it does import { cloneDeep } from 'lodash' +const version = 0 + export default { version, - migrate: async function (originalVersionedData) { + async migrate (originalVersionedData) { const versionedData = cloneDeep(originalVersionedData) versionedData.meta.version = version const state = versionedData.data diff --git a/app/scripts/platforms/extension.js b/app/scripts/platforms/extension.js index d5b025c02..c891ae97c 100644 --- a/app/scripts/platforms/extension.js +++ b/app/scripts/platforms/extension.js @@ -105,6 +105,7 @@ export default class ExtensionPlatform { }) } catch (e) { cb(e) + // eslint-disable-next-line no-useless-return return } } @@ -210,10 +211,11 @@ export default class ExtensionPlatform { url, { 'type': 'basic', - 'title': title, + title, 'iconUrl': extension.extension.getURL('../../images/icon-64.png'), - 'message': message, - }) + message, + }, + ) } _subscribeToNotificationClicked () { diff --git a/app/scripts/ui.js b/app/scripts/ui.js index 7a76b8778..a77c0d6a3 100644 --- a/app/scripts/ui.js +++ b/app/scripts/ui.js @@ -9,7 +9,6 @@ import '@formatjs/intl-relativetimeformat/polyfill' import { EventEmitter } from 'events' import PortStream from 'extension-port-stream' - import extension from 'extensionizer' import Dnode from 'dnode' @@ -151,7 +150,7 @@ function setupWeb3Connection (connectionStream) { function setupControllerConnection (connectionStream, cb) { const eventEmitter = new EventEmitter() const backgroundDnode = Dnode({ - sendUpdate: function (state) { + sendUpdate (state) { eventEmitter.emit('update', state) }, }) diff --git a/development/build/display.js b/development/build/display.js index 90ca4e7ba..e5556dd09 100644 --- a/development/build/display.js +++ b/development/build/display.js @@ -123,9 +123,8 @@ function getSymbolNormal (value) { return SYMBOLS.ThreeQuarters } else if (rounded === 7 / 8) { return SYMBOLS.SevenEighths - } else { - return SYMBOLS.Full } + return SYMBOLS.Full } // get partial block char for value (right-adjusted) @@ -144,7 +143,6 @@ function getSymbolNormalRight (value) { return SYMBOLS.RightEighth } else if (rounded === 1) { return SYMBOLS.Space - } else { - throw new Error('getSymbolNormalRight got unexpected result') } + throw new Error('getSymbolNormalRight got unexpected result') } diff --git a/development/build/etc.js b/development/build/etc.js index 81b9a17b7..92af2e338 100644 --- a/development/build/etc.js +++ b/development/build/etc.js @@ -9,7 +9,6 @@ const { createTask, composeParallel } = require('./task') module.exports = createEtcTasks - function createEtcTasks ({ browserPlatforms, livereload }) { const clean = createTask('clean', async function clean () { diff --git a/development/build/index.js b/development/build/index.js index a665410b2..0a9f519f8 100755 --- a/development/build/index.js +++ b/development/build/index.js @@ -31,7 +31,8 @@ function defineAllTasks () { const { clean, reload, zip } = createEtcTasks({ livereload, browserPlatforms }) // build for development (livereload) - createTask('dev', + createTask( + 'dev', composeSeries( clean, styleTasks.dev, @@ -45,7 +46,8 @@ function defineAllTasks () { ) // build for test development (livereload) - createTask('testDev', + createTask( + 'testDev', composeSeries( clean, styleTasks.dev, @@ -59,7 +61,8 @@ function defineAllTasks () { ) // build for prod release - createTask('prod', + createTask( + 'prod', composeSeries( clean, styleTasks.prod, @@ -73,7 +76,8 @@ function defineAllTasks () { ) // build for CI testing - createTask('test', + createTask( + 'test', composeSeries( clean, styleTasks.prod, diff --git a/development/build/manifest.js b/development/build/manifest.js index 71d335be0..1ea9e5ad5 100644 --- a/development/build/manifest.js +++ b/development/build/manifest.js @@ -7,7 +7,6 @@ const { createTask, composeSeries } = require('./task') module.exports = createManifestTasks - const scriptsToExcludeFromBackgroundDevBuild = { 'bg-libs.js': true, } diff --git a/development/build/scripts.js b/development/build/scripts.js index 4b06af86e..c6e3e4173 100644 --- a/development/build/scripts.js +++ b/development/build/scripts.js @@ -22,7 +22,6 @@ const { createTask, composeParallel, composeSeries, runInChildProcess } = requir module.exports = createScriptTasks - const dependencies = Object.keys((packageJSON && packageJSON.dependencies) || {}) const materialUIDependencies = ['@material-ui/core'] const reactDepenendencies = dependencies.filter((dep) => dep.match(/react/u)) @@ -72,7 +71,6 @@ function createScriptTasks ({ browserPlatforms, livereload }) { return { prod, dev, testDev, test } - function createTasksForBuildJsDeps ({ key, filename }) { return createTask(`scripts:deps:${key}`, bundleTask({ label: filename, @@ -83,7 +81,6 @@ function createScriptTasks ({ browserPlatforms, livereload }) { })) } - function createTasksForBuildJsExtension ({ taskPrefix, devMode, testing }) { const standardBundles = [ 'background', @@ -93,14 +90,12 @@ function createScriptTasks ({ browserPlatforms, livereload }) { const standardSubtasks = standardBundles.map((filename) => { return createTask(`${taskPrefix}:${filename}`, - createBundleTaskForBuildJsExtensionNormal({ filename, devMode, testing }), - ) + createBundleTaskForBuildJsExtensionNormal({ filename, devMode, testing })) }) // inpage must be built before contentscript // because inpage bundle result is included inside contentscript const contentscriptSubtask = createTask(`${taskPrefix}:contentscript`, - createTaskForBuildJsExtensionContentscript({ devMode, testing }), - ) + createTaskForBuildJsExtensionContentscript({ devMode, testing })) // task for initiating livereload const initiateLiveReload = async () => { @@ -159,7 +154,6 @@ function createScriptTasks ({ browserPlatforms, livereload }) { ) } - function bundleTask (opts) { let bundler @@ -203,7 +197,7 @@ function createScriptTasks ({ browserPlatforms, livereload }) { buildStream = buildStream .pipe(terser({ mangle: { - reserved: [ 'MetamaskInpageProvider' ], + reserved: ['MetamaskInpageProvider'], }, sourceMap: { content: true, @@ -287,9 +281,9 @@ function createScriptTasks ({ browserPlatforms, livereload }) { if (!opts.buildLib) { if (opts.devMode && opts.filename === 'ui.js') { - browserifyOpts['entries'] = ['./development/require-react-devtools.js', opts.filepath] + browserifyOpts.entries = ['./development/require-react-devtools.js', opts.filepath] } else { - browserifyOpts['entries'] = [opts.filepath] + browserifyOpts.entries = [opts.filepath] } } @@ -348,10 +342,8 @@ function createScriptTasks ({ browserPlatforms, livereload }) { return bundler } - } - function beep () { process.stdout.write('\x07') } @@ -364,13 +356,12 @@ function getEnvironment ({ devMode, test }) { return 'testing' } else if (process.env.CIRCLE_BRANCH === 'master') { return 'production' - } else if (/^Version-v(\d+)[.](\d+)[.](\d+)/u.test(process.env.CIRCLE_BRANCH)) { + } else if ((/^Version-v(\d+)[.](\d+)[.](\d+)/u).test(process.env.CIRCLE_BRANCH)) { return 'release-candidate' } else if (process.env.CIRCLE_BRANCH === 'develop') { return 'staging' } else if (process.env.CIRCLE_PULL_REQUEST) { return 'pull-request' - } else { - return 'other' } + return 'other' } diff --git a/development/build/static.js b/development/build/static.js index f32cd5c39..3d4c74394 100644 --- a/development/build/static.js +++ b/development/build/static.js @@ -9,7 +9,6 @@ const { createTask, composeSeries } = require('./task') module.exports = createStaticAssetTasks - const copyTargets = [ { src: `./app/_locales/`, diff --git a/development/build/styles.js b/development/build/styles.js index f57954c94..d6f3a7855 100644 --- a/development/build/styles.js +++ b/development/build/styles.js @@ -11,11 +11,9 @@ const rename = require('gulp-rename') const pump = pify(require('pump')) const { createTask } = require('./task') - // scss compilation and autoprefixing tasks module.exports = createStyleTasks - function createStyleTasks ({ livereload }) { const prod = createTask('styles:prod', createScssBuildTask({ @@ -44,7 +42,6 @@ function createStyleTasks ({ livereload }) { return { prod, dev, lint } - function createScssBuildTask ({ src, dest, devMode, pattern }) { return async function () { if (devMode) { @@ -75,5 +72,4 @@ function createStyleTasks ({ livereload }) { } } - } diff --git a/development/build/task.js b/development/build/task.js index 4a0a9d437..879ab1c97 100644 --- a/development/build/task.js +++ b/development/build/task.js @@ -8,7 +8,6 @@ module.exports = { detectAndRunEntryTask, tasks, taskEvents, createTask, runTask const { setupTaskDisplay } = require('./display') - function detectAndRunEntryTask () { // get requested task name and execute const taskName = process.argv[2] diff --git a/development/metamaskbot-build-announce.js b/development/metamaskbot-build-announce.js index a19acecc6..51d9617a2 100755 --- a/development/metamaskbot-build-announce.js +++ b/development/metamaskbot-build-announce.js @@ -57,7 +57,7 @@ async function start () { `dep viz: ${depVizLink}`, `all artifacts`, ] - const hiddenContent = `` + const hiddenContent = `` const exposedContent = `Builds ready [${SHORT_SHA1}]` const artifactsBody = `
${exposedContent}${hiddenContent}
` diff --git a/development/mock-3box.js b/development/mock-3box.js index 37ff02c7b..e4260c610 100644 --- a/development/mock-3box.js +++ b/development/mock-3box.js @@ -3,7 +3,7 @@ function delay (time) { } async function loadFromMock3Box (key) { - const res = await window.fetch('http://localhost:8889?key=' + key) + const res = await window.fetch(`http://localhost:8889?key=${key}`) const text = await res.text() return text.length ? JSON.parse(text) : null } diff --git a/development/sourcemap-validator.js b/development/sourcemap-validator.js index 0babb1d56..cb5f6f6c8 100644 --- a/development/sourcemap-validator.js +++ b/development/sourcemap-validator.js @@ -18,7 +18,6 @@ start().catch((error) => { process.exit(1) }) - async function start () { const targetFiles = [ `background.js`, diff --git a/development/static-server.js b/development/static-server.js index 368c186e9..a20908878 100644 --- a/development/static-server.js +++ b/development/static-server.js @@ -61,7 +61,7 @@ const main = async () => { } while (args.length) { - if (/^(--port|-p)$/u.test(args[0])) { + if ((/^(--port|-p)$/u).test(args[0])) { if (args[1] === undefined) { throw new Error('Missing port argument') } diff --git a/development/verify-locale-strings.js b/development/verify-locale-strings.js index f15344d4d..1d4c6e3a7 100644 --- a/development/verify-locale-strings.js +++ b/development/verify-locale-strings.js @@ -104,7 +104,7 @@ async function getLocale (code) { async function writeLocale (code, locale) { try { const localeFilePath = getLocalePath(code) - return writeFile(localeFilePath, JSON.stringify(locale, null, 2) + '\n', 'utf8') + return writeFile(localeFilePath, `${JSON.stringify(locale, null, 2)}\n`, 'utf8') } catch (e) { if (e.code === 'ENOENT') { log.error('Locale file not found') @@ -150,7 +150,7 @@ async function verifyLocale (code) { if (extraItems.length > 0) { if (fix) { - const newLocale = Object.assign({}, targetLocale) + const newLocale = { ...targetLocale } for (const item of extraItems) { delete newLocale[item] } @@ -215,7 +215,7 @@ async function verifyEnglishLocale () { } if (unusedMessages.length > 0 && fix) { - const newLocale = Object.assign({}, englishLocale) + const newLocale = { ...englishLocale } for (const key of unusedMessages) { delete newLocale[key] } @@ -244,7 +244,6 @@ async function * getFileContents (filenames) { } } - function compareLocalesForMissingItems ({ base, subject }) { return Object.keys(base).filter((key) => !subject[key]) } diff --git a/package.json b/package.json index 35e2eb4f7..f13bf1902 100644 --- a/package.json +++ b/package.json @@ -179,7 +179,7 @@ "@babel/preset-env": "^7.5.5", "@babel/preset-react": "^7.0.0", "@babel/register": "^7.5.5", - "@metamask/eslint-config": "^1.1.0", + "@metamask/eslint-config": "^3.0.0", "@metamask/forwarder": "^1.1.0", "@metamask/test-dapp": "^3.1.0", "@sentry/cli": "^1.49.0", diff --git a/test/e2e/benchmark.js b/test/e2e/benchmark.js index d418f38b7..d8b79a9eb 100644 --- a/test/e2e/benchmark.js +++ b/test/e2e/benchmark.js @@ -118,7 +118,7 @@ async function main () { let existingParentDirectory while (args.length) { - if (/^(--pages|-p)$/u.test(args[0])) { + if ((/^(--pages|-p)$/u).test(args[0])) { if (args[1] === undefined) { throw new Error('Missing pages argument') } @@ -129,7 +129,7 @@ async function main () { } } args.splice(0, 2) - } else if (/^(--samples|-s)$/u.test(args[0])) { + } else if ((/^(--samples|-s)$/u).test(args[0])) { if (args[1] === undefined) { throw new Error('Missing number of samples') } @@ -138,7 +138,7 @@ async function main () { throw new Error(`Invalid 'samples' argument given: '${args[1]}'`) } args.splice(0, 2) - } else if (/^(--out|-o)$/u.test(args[0])) { + } else if ((/^(--out|-o)$/u).test(args[0])) { if (args[1] === undefined) { throw new Error('Missing output filename') } diff --git a/test/e2e/from-import-ui.spec.js b/test/e2e/from-import-ui.spec.js index d471f41f3..d9b93bcad 100644 --- a/test/e2e/from-import-ui.spec.js +++ b/test/e2e/from-import-ui.spec.js @@ -223,7 +223,7 @@ describe('Using MetaMask with an existing account', function () { const txValues = await driver.findElements(By.css('.transaction-list-item__primary-currency')) assert.equal(txValues.length, 1) - assert.ok(/-1\s*ETH/u.test(await txValues[0].getText())) + assert.ok((/-1\s*ETH/u).test(await txValues[0].getText())) }) }) diff --git a/test/e2e/metamask-ui.spec.js b/test/e2e/metamask-ui.spec.js index c1c7a953d..f8c21d131 100644 --- a/test/e2e/metamask-ui.spec.js +++ b/test/e2e/metamask-ui.spec.js @@ -754,7 +754,7 @@ describe('MetaMask', function () { await driver.delay(regularDelayMs) await driver.wait(until.elementTextMatches(balance, /^87.*\s*ETH.*$/u), 10000) const tokenAmount = await balance.getText() - assert.ok(/^87.*\s*ETH.*$/u.test(tokenAmount)) + assert.ok((/^87.*\s*ETH.*$/u).test(tokenAmount)) await driver.delay(regularDelayMs) }) }) @@ -832,7 +832,7 @@ describe('MetaMask', function () { const balance = await driver.findElement(By.css('.wallet-overview .token-overview__primary-balance')) await driver.wait(until.elementTextMatches(balance, /^10\s*TST\s*$/u)) const tokenAmount = await balance.getText() - assert.ok(/^10\s*TST\s*$/u.test(tokenAmount)) + assert.ok((/^10\s*TST\s*$/u).test(tokenAmount)) await driver.delay(regularDelayMs) }) }) diff --git a/test/e2e/mock-3box/server.js b/test/e2e/mock-3box/server.js index c4fe9d9c7..1ac8a758c 100644 --- a/test/e2e/mock-3box/server.js +++ b/test/e2e/mock-3box/server.js @@ -33,6 +33,6 @@ const server = http.createServer(requestHandler) server.listen(port, (err) => { if (err) { console.log('mock 3box server error: ', err) - return + } }) diff --git a/test/e2e/send-edit.spec.js b/test/e2e/send-edit.spec.js index 4f7e0ae54..aa0fc6645 100644 --- a/test/e2e/send-edit.spec.js +++ b/test/e2e/send-edit.spec.js @@ -205,7 +205,7 @@ describe('Using MetaMask with an existing account', function () { const txValues = await driver.findElements(By.css('.transaction-list-item__primary-currency')) assert.equal(txValues.length, 1) - assert.ok(/-2.2\s*ETH/u.test(await txValues[0].getText())) + assert.ok((/-2.2\s*ETH/u).test(await txValues[0].getText())) }) }) }) diff --git a/test/e2e/signature-request.spec.js b/test/e2e/signature-request.spec.js index 03d7fcfe6..9e83cc25e 100644 --- a/test/e2e/signature-request.spec.js +++ b/test/e2e/signature-request.spec.js @@ -108,7 +108,7 @@ describe('MetaMask', function () { assert.equal(await title.getText(), 'Signature Request') assert.equal(await name.getText(), 'Ether Mail') assert.equal(await origin.getText(), 'http://127.0.0.1:8080') - assert.equal(await address.getText(), publicAddress.slice(0, 8) + '...' + publicAddress.slice(publicAddress.length - 8)) + assert.equal(await address.getText(), `${publicAddress.slice(0, 8)}...${publicAddress.slice(publicAddress.length - 8)}`) }) it('signs the transaction', async function () { diff --git a/test/e2e/webdriver/driver.js b/test/e2e/webdriver/driver.js index 2d8556850..dcd516e41 100644 --- a/test/e2e/webdriver/driver.js +++ b/test/e2e/webdriver/driver.js @@ -3,6 +3,7 @@ const { strict: assert } = require('assert') const { until, error: webdriverError } = require('selenium-webdriver') class Driver { + /** * @param {!ThenableWebDriver} driver - A {@code WebDriver} instance * @param {string} browser - The type of browser this driver is controlling @@ -61,8 +62,7 @@ class Driver { this.driver.wait(until.elementIsEnabled(element), this.timeout), ) return acc - }, []), - ) + }, [])) return elements } @@ -147,7 +147,7 @@ class Driver { } } - throw new Error('No window with title: ' + title) + throw new Error(`No window with title: ${title}`) } /** diff --git a/test/e2e/webdriver/firefox.js b/test/e2e/webdriver/firefox.js index aff7227a4..f5c8426ae 100644 --- a/test/e2e/webdriver/firefox.js +++ b/test/e2e/webdriver/firefox.js @@ -20,6 +20,7 @@ const GeckoDriverCommand = { * A wrapper around a {@code WebDriver} instance exposing Firefox-specific functionality */ class FirefoxDriver { + /** * Builds a {@link FirefoxDriver} instance * @param {{extensionPath: string}} options - the options for the build diff --git a/test/helper.js b/test/helper.js index 50ec1f2d8..d1b79335b 100644 --- a/test/helper.js +++ b/test/helper.js @@ -5,7 +5,6 @@ import Adapter from 'enzyme-adapter-react-16' import log from 'loglevel' import { JSDOM } from 'jsdom' - nock.disableNetConnect() nock.enableNetConnect('localhost') diff --git a/test/lib/createTxMeta.js b/test/lib/createTxMeta.js index 78f38bade..4dde18f62 100644 --- a/test/lib/createTxMeta.js +++ b/test/lib/createTxMeta.js @@ -1,10 +1,11 @@ import { snapshotFromTxMeta } from '../../app/scripts/controllers/transactions/lib/tx-state-history-helpers' export default function createTxMeta (partialMeta) { - const txMeta = Object.assign({ + const txMeta = { status: 'unapproved', txParams: {}, - }, partialMeta) + ...partialMeta, + } // initialize history txMeta.history = [] // capture initial snapshot of txMeta for history diff --git a/test/lib/render-helpers.js b/test/lib/render-helpers.js index 2224c2165..c0ac849ea 100644 --- a/test/lib/render-helpers.js +++ b/test/lib/render-helpers.js @@ -17,7 +17,7 @@ export function mountWithRouter (component, store = {}, pathname = '/') { history: new MemoryRouter().history, route: { location: { - pathname: pathname, + pathname, }, match: {}, }, diff --git a/test/unit/app/account-import-strategies.spec.js b/test/unit/app/account-import-strategies.spec.js index fa43826d6..3c6b6fbef 100644 --- a/test/unit/app/account-import-strategies.spec.js +++ b/test/unit/app/account-import-strategies.spec.js @@ -1,6 +1,6 @@ import assert from 'assert' import ethUtil from 'ethereumjs-util' -import accountImporter from '../../../app/scripts/account-import-strategies/index' +import accountImporter from '../../../app/scripts/account-import-strategies' describe('Account Import Strategies', function () { const privkey = '0x4cfd3e90fc78b0f86bf7524722150bb8da9c60cd532564d7ff43f5716514f553' @@ -8,19 +8,19 @@ describe('Account Import Strategies', function () { describe('private key import', function () { it('imports a private key and strips 0x prefix', async function () { - const importPrivKey = await accountImporter.importAccount('Private Key', [ privkey ]) + const importPrivKey = await accountImporter.importAccount('Private Key', [privkey]) assert.equal(importPrivKey, ethUtil.stripHexPrefix(privkey)) }) it('throws an error for empty string private key', async function () { await assert.rejects(async () => { - await accountImporter.importAccount('Private Key', [ '' ]) + await accountImporter.importAccount('Private Key', ['']) }, Error, 'no empty strings') }) it('throws an error for undefined string private key', async function () { await assert.rejects(async () => { - await accountImporter.importAccount('Private Key', [ undefined ]) + await accountImporter.importAccount('Private Key', [undefined]) }) await assert.rejects(async () => { @@ -30,7 +30,7 @@ describe('Account Import Strategies', function () { it('throws an error for invalid private key', async function () { await assert.rejects(async () => { - await accountImporter.importAccount('Private Key', [ 'popcorn' ]) + await accountImporter.importAccount('Private Key', ['popcorn']) }) }) }) @@ -40,7 +40,7 @@ describe('Account Import Strategies', function () { const wrongPassword = 'password2' try { - await accountImporter.importAccount('JSON File', [ json, wrongPassword]) + await accountImporter.importAccount('JSON File', [json, wrongPassword]) } catch (error) { assert.equal(error.message, 'Key derivation failed - possibly wrong passphrase') } @@ -48,7 +48,7 @@ describe('Account Import Strategies', function () { it('imports json string and password to return a private key', async function () { const fileContentsPassword = 'password1' - const importJson = await accountImporter.importAccount('JSON File', [ json, fileContentsPassword]) + const importJson = await accountImporter.importAccount('JSON File', [json, fileContentsPassword]) assert.equal(importJson, '0x5733876abe94146069ce8bcbabbde2677f2e35fa33e875e92041ed2ac87e5bc7') }) }) diff --git a/test/unit/app/controllers/detect-tokens-test.js b/test/unit/app/controllers/detect-tokens-test.js index 83ca9eb01..0b65e9258 100644 --- a/test/unit/app/controllers/detect-tokens-test.js +++ b/test/unit/app/controllers/detect-tokens-test.js @@ -22,7 +22,6 @@ describe('DetectTokensController', function () { beforeEach(async function () { - nock('https://api.infura.io') .get(/.*/u) .reply(200) diff --git a/test/unit/app/controllers/incoming-transactions-test.js b/test/unit/app/controllers/incoming-transactions-test.js index 7947a7102..727c394fa 100644 --- a/test/unit/app/controllers/incoming-transactions-test.js +++ b/test/unit/app/controllers/incoming-transactions-test.js @@ -2,12 +2,12 @@ import assert from 'assert' import sinon from 'sinon' import proxyquire from 'proxyquire' +import { ROPSTEN, RINKEBY, KOVAN, GOERLI, MAINNET } from '../../../../app/scripts/controllers/network/enums' + const IncomingTransactionsController = proxyquire('../../../../app/scripts/controllers/incoming-transactions', { '../lib/random-id': { default: () => 54321 }, }).default -import { ROPSTEN, RINKEBY, KOVAN, GOERLI, MAINNET } from '../../../../app/scripts/controllers/network/enums' - describe('IncomingTransactionsController', function () { const EMPTY_INIT_STATE = { incomingTransactions: {}, diff --git a/test/unit/app/controllers/metamask-controller-test.js b/test/unit/app/controllers/metamask-controller-test.js index 09000890f..3bd1b3689 100644 --- a/test/unit/app/controllers/metamask-controller-test.js +++ b/test/unit/app/controllers/metamask-controller-test.js @@ -104,11 +104,11 @@ describe('MetaMaskController', function () { showUnapprovedTx: noop, showUnconfirmedMessage: noop, encryptor: { - encrypt: function (_, object) { + encrypt (_, object) { this.object = object return Promise.resolve('mock-encrypted') }, - decrypt: function () { + decrypt () { return Promise.resolve(this.object) }, }, @@ -146,7 +146,7 @@ describe('MetaMaskController', function () { beforeEach(async function () { const password = 'a-fake-password' await metamaskController.createNewVaultAndRestore(password, TEST_SEED) - await metamaskController.importAccountWithStrategy('Private Key', [ importPrivkey ]) + await metamaskController.importAccountWithStrategy('Private Key', [importPrivkey]) }) it('adds private key to keyrings in KeyringController', async function () { @@ -306,9 +306,9 @@ describe('MetaMaskController', function () { it('should return the balance known by accountTracker', async function () { const accounts = {} const balance = '0x14ced5122ce0a000' - accounts[TEST_ADDRESS] = { balance: balance } + accounts[TEST_ADDRESS] = { balance } - metamaskController.accountTracker.store.putState({ accounts: accounts }) + metamaskController.accountTracker.store.putState({ accounts }) const gotten = await metamaskController.getBalance(TEST_ADDRESS) @@ -323,7 +323,7 @@ describe('MetaMaskController', function () { callback(undefined, balance) }) - metamaskController.accountTracker.store.putState({ accounts: accounts }) + metamaskController.accountTracker.store.putState({ accounts }) const gotten = await metamaskController.getBalance(TEST_ADDRESS, ethQuery) @@ -367,7 +367,7 @@ describe('MetaMaskController', function () { address = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' identities = { '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc': { - 'address': address, + address, 'name': 'Account 1', }, '0xc42edfcc21ed14dda456aa0756c153f7985d8813': { @@ -503,7 +503,6 @@ describe('MetaMaskController', function () { assert.equal(keyrings[0].unlockedAccount, accountToUnlock) }) - it('should call keyringController.addNewAccount', async function () { assert(metamaskController.keyringController.addNewAccount.calledOnce) }) @@ -524,7 +523,6 @@ describe('MetaMaskController', function () { assert(metamaskController.preferencesController.setAccountLabel.calledOnce) }) - }) describe('#setCustomRpc', function () { @@ -684,7 +682,7 @@ describe('MetaMaskController', function () { msgParams = { 'from': address, - 'data': data, + data, } const promise = metamaskController.newUnsignedMessage(msgParams) @@ -744,7 +742,7 @@ describe('MetaMaskController', function () { msgParams = { 'from': address, - 'data': data, + data, } const promise = metamaskController.newUnsignedPersonalMessage(msgParams) @@ -760,7 +758,7 @@ describe('MetaMaskController', function () { it('errors with no from in msgParams', async function () { try { await metamaskController.newUnsignedPersonalMessage({ - 'data': data, + data, }) assert.fail('should have thrown') } catch (error) { diff --git a/test/unit/app/controllers/permissions/helpers.js b/test/unit/app/controllers/permissions/helpers.js index 0378dc089..e920b851d 100644 --- a/test/unit/app/controllers/permissions/helpers.js +++ b/test/unit/app/controllers/permissions/helpers.js @@ -26,6 +26,7 @@ export function grantPermissions (permController, origin, permissions) { * @return {Function} A convenient wrapper for the requestUserApproval function. */ export function getRequestUserApprovalHelper (permController) { + /** * Returns a request object that can be passed to requestUserApproval. * diff --git a/test/unit/app/controllers/permissions/mocks.js b/test/unit/app/controllers/permissions/mocks.js index 54f47e5d8..578b39911 100644 --- a/test/unit/app/controllers/permissions/mocks.js +++ b/test/unit/app/controllers/permissions/mocks.js @@ -33,7 +33,7 @@ const keyringAccounts = deepFreeze([ '0xcc74c7a59194e5d9268476955650d1e285be703c', ]) -const getKeyringAccounts = async () => [ ...keyringAccounts ] +const getKeyringAccounts = async () => [...keyringAccounts] const getIdentities = () => { return keyringAccounts.reduce( @@ -261,7 +261,8 @@ const PERMS = { return { eth_accounts: { caveats: CAVEATS.eth_accounts(accounts), - } } + }, + } }, /** @@ -574,7 +575,7 @@ export const getters = deepFreeze({ return { origin, method: 'wallet_requestPermissions', - params: [ PERMS.requests[permissionName]() ], + params: [PERMS.requests[permissionName]()], } }, @@ -590,7 +591,7 @@ export const getters = deepFreeze({ return { origin, method: 'wallet_requestPermissions', - params: [ permissions ], + params: [permissions], } }, diff --git a/test/unit/app/controllers/permissions/permissions-controller-test.js b/test/unit/app/controllers/permissions/permissions-controller-test.js index f8aa6feaa..f51ed0800 100644 --- a/test/unit/app/controllers/permissions/permissions-controller-test.js +++ b/test/unit/app/controllers/permissions/permissions-controller-test.js @@ -170,7 +170,6 @@ describe('permissions controller', function () { let bAccounts = await permController.getAccounts(DOMAINS.b.origin) let cAccounts = await permController.getAccounts(DOMAINS.c.origin) - assert.deepEqual( aAccounts, [ACCOUNTS.a.primary], 'first origin should have correct accounts', @@ -189,7 +188,7 @@ describe('permissions controller', function () { Object.keys(notifications).forEach((origin) => { assert.deepEqual( notifications[origin], - [ NOTIFICATIONS.removedAccounts() ], + [NOTIFICATIONS.removedAccounts()], 'origin should have single wallet_accountsChanged:[] notification', ) }) @@ -447,12 +446,12 @@ describe('permissions controller', function () { ) await assert.doesNotThrow( - () => permController.validatePermittedAccounts([ keyringAccounts[0] ]), + () => permController.validatePermittedAccounts([keyringAccounts[0]]), 'should not throw on single keyring account', ) await assert.doesNotThrow( - () => permController.validatePermittedAccounts([ keyringAccounts[1] ]), + () => permController.validatePermittedAccounts([keyringAccounts[1]]), 'should not throw on single keyring account', ) }) @@ -655,7 +654,6 @@ describe('permissions controller', function () { }) }) - describe('removeAllAccountPermissions', function () { let permController, notifications @@ -1284,7 +1282,7 @@ describe('permissions controller', function () { assert.deepEqual( notifications[DOMAINS.a.origin], - [ NOTIFICATIONS.newAccounts(ACCOUNTS.a.permitted) ], + [NOTIFICATIONS.newAccounts(ACCOUNTS.a.permitted)], 'origin should have correct notification', ) }) diff --git a/test/unit/app/controllers/permissions/permissions-log-controller-test.js b/test/unit/app/controllers/permissions/permissions-log-controller-test.js index d6e3482c6..6f9fc104b 100644 --- a/test/unit/app/controllers/permissions/permissions-log-controller-test.js +++ b/test/unit/app/controllers/permissions/permissions-log-controller-test.js @@ -310,7 +310,7 @@ describe('permissions log', function () { ) // store the id of the current second entry - const nextFirstId = log[1]['id'] + const nextFirstId = log[1].id // add one more entry to log, putting it over the limit lastId = nanoid() @@ -356,7 +356,7 @@ describe('permissions log', function () { const req = RPC_REQUESTS.requestPermission( DOMAINS.a.origin, PERM_NAMES.test_method, ) - const res = { result: [ PERMS.granted.test_method() ] } + const res = { result: [PERMS.granted.test_method()] } // noop => no response logMiddleware({ ...req }, { ...res }, noop) @@ -384,7 +384,7 @@ describe('permissions log', function () { DOMAINS.a.origin, PERM_NAMES.test_method, ) delete req.params - const res = { result: [ PERMS.granted.test_method() ] } + const res = { result: [PERMS.granted.test_method()] } // no params => no response logMiddleware({ ...req }, { ...res }) @@ -400,7 +400,7 @@ describe('permissions log', function () { DOMAINS.a.origin, PERM_NAMES.eth_accounts, ) const res = { - result: [ PERMS.granted.eth_accounts(ACCOUNTS.a.permitted) ], + result: [PERMS.granted.eth_accounts(ACCOUNTS.a.permitted)], } logMiddleware({ ...req }, { ...res }) @@ -419,7 +419,7 @@ describe('permissions log', function () { clock.tick(1) - res.result = [ PERMS.granted.eth_accounts([ ACCOUNTS.a.permitted[0] ]) ] + res.result = [PERMS.granted.eth_accounts([ACCOUNTS.a.permitted[0]])] logMiddleware({ ...req }, { ...res }) @@ -438,7 +438,7 @@ describe('permissions log', function () { DOMAINS.a.origin, PERM_NAMES.eth_accounts, ) const res = { - result: [ PERMS.granted.eth_accounts(ACCOUNTS.a.permitted) ], + result: [PERMS.granted.eth_accounts(ACCOUNTS.a.permitted)], } delete res.result[0].caveats @@ -458,7 +458,7 @@ describe('permissions log', function () { DOMAINS.a.origin, PERM_NAMES.eth_accounts, ) const res = { - result: [ PERMS.granted.eth_accounts(ACCOUNTS.a.permitted) ], + result: [PERMS.granted.eth_accounts(ACCOUNTS.a.permitted)], } res.result[0].caveats.push({ foo: 'bar' }) @@ -558,7 +558,7 @@ describe('permissions log', function () { DOMAINS.a.origin, PERM_NAMES.test_method, ), res: { - result: [ PERMS.granted.test_method() ], + result: [PERMS.granted.test_method()], }, }) @@ -568,7 +568,7 @@ describe('permissions log', function () { DOMAINS.b.origin, PERM_NAMES.eth_accounts, ), res: { - result: [ PERMS.granted.eth_accounts(ACCOUNTS.b.permitted) ], + result: [PERMS.granted.eth_accounts(ACCOUNTS.b.permitted)], }, }) @@ -616,7 +616,7 @@ describe('permissions log', function () { DOMAINS.a.origin, PERM_NAMES.test_method, ), res: { - result: [ PERMS.granted.test_method() ], + result: [PERMS.granted.test_method()], }, }) diff --git a/test/unit/app/controllers/preferences-controller-test.js b/test/unit/app/controllers/preferences-controller-test.js index ca5001e36..3484dd210 100644 --- a/test/unit/app/controllers/preferences-controller-test.js +++ b/test/unit/app/controllers/preferences-controller-test.js @@ -119,7 +119,6 @@ describe('preferences controller', function () { address: '0xda22le', }) - preferencesController.setAccountLabel('0xda22le', 'Dazzle') assert.deepEqual(preferencesController.store.getState().identities['0xda22le'], { name: 'Dazzle', @@ -130,7 +129,7 @@ describe('preferences controller', function () { describe('getTokens', function () { it('should return an empty list initially', async function () { - preferencesController.setAddresses([ '0x7e57e2' ]) + preferencesController.setAddresses(['0x7e57e2']) await preferencesController.setSelectedAddress('0x7e57e2') const tokens = preferencesController.getTokens() @@ -144,7 +143,7 @@ describe('preferences controller', function () { const symbol = 'ABBR' const decimals = 5 - preferencesController.setAddresses([ '0x7e57e2' ]) + preferencesController.setAddresses(['0x7e57e2']) await preferencesController.setSelectedAddress('0x7e57e2') await preferencesController.addToken(address, symbol, decimals) @@ -162,7 +161,7 @@ describe('preferences controller', function () { const symbol = 'ABBR' const decimals = 5 - preferencesController.setAddresses([ '0x7e57e2' ]) + preferencesController.setAddresses(['0x7e57e2']) await preferencesController.setSelectedAddress('0x7e57e2') await preferencesController.addToken(address, symbol, decimals) @@ -241,7 +240,7 @@ describe('preferences controller', function () { describe('removeToken', function () { it('should remove the only token from its state', async function () { - preferencesController.setAddresses([ '0x7e57e2' ]) + preferencesController.setAddresses(['0x7e57e2']) await preferencesController.setSelectedAddress('0x7e57e2') await preferencesController.addToken('0xa', 'A', 5) await preferencesController.removeToken('0xa') @@ -251,7 +250,7 @@ describe('preferences controller', function () { }) it('should remove a token from its state', async function () { - preferencesController.setAddresses([ '0x7e57e2' ]) + preferencesController.setAddresses(['0x7e57e2']) await preferencesController.setSelectedAddress('0x7e57e2') await preferencesController.addToken('0xa', 'A', 4) await preferencesController.addToken('0xb', 'B', 5) diff --git a/test/unit/app/controllers/transactions/tx-controller-test.js b/test/unit/app/controllers/transactions/tx-controller-test.js index 01e874ff1..c9b5364c7 100644 --- a/test/unit/app/controllers/transactions/tx-controller-test.js +++ b/test/unit/app/controllers/transactions/tx-controller-test.js @@ -37,7 +37,7 @@ describe('Transaction Controller', function () { blockTrackerStub.getLatestBlock = noop txController = new TransactionController({ provider, - getGasPrice: function () { + getGasPrice () { return '0xee6b2800' }, networkStore: new ObservableStore(currentNetworkId), @@ -108,7 +108,6 @@ describe('Transaction Controller', function () { }) }) - describe('#newUnapprovedTransaction', function () { let stub, txMeta, txParams beforeEach(function () { @@ -387,7 +386,7 @@ describe('Transaction Controller', function () { { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams, history: [{}] }, ]) - expectedTxParams = Object.assign({}, txParams, { gasPrice: '0xb' }) + expectedTxParams = { ...txParams, gasPrice: '0xb' } }) afterEach(function () { @@ -453,7 +452,7 @@ describe('Transaction Controller', function () { }) it('should ignore the error "Transaction Failed: known transaction" and be as usual', async function () { - providerResultStub['eth_sendRawTransaction'] = async (_, __, ___, end) => { + providerResultStub.eth_sendRawTransaction = async (_, __, ___, end) => { end('Transaction Failed: known transaction') } const rawTx = '0xf86204831e848082520894f231d46dd78806e1dd93442cf33c7671f853874880802ca05f973e540f2d3c2f06d3725a626b75247593cb36477187ae07ecfe0a4db3cf57a00259b52ee8c58baaa385fb05c3f96116e58de89bcc165cb3bfdfc708672fed8a' @@ -547,7 +546,7 @@ describe('Transaction Controller', function () { _blockTrackerStub.getLatestBlock = noop const _txController = new TransactionController({ provider: _provider, - getGasPrice: function () { + getGasPrice () { return '0xee6b2800' }, networkStore: new ObservableStore(currentNetworkId), @@ -579,7 +578,7 @@ describe('Transaction Controller', function () { _blockTrackerStub.getLatestBlock = noop const _txController = new TransactionController({ provider: _provider, - getGasPrice: function () { + getGasPrice () { return '0xee6b2800' }, networkStore: new ObservableStore(currentNetworkId), diff --git a/test/unit/app/controllers/transactions/tx-state-manager-test.js b/test/unit/app/controllers/transactions/tx-state-manager-test.js index 3e1819c41..915e36362 100644 --- a/test/unit/app/controllers/transactions/tx-state-manager-test.js +++ b/test/unit/app/controllers/transactions/tx-state-manager-test.js @@ -587,13 +587,13 @@ describe('TransactionStateManager', function () { describe('#_removeTx', function () { it('should remove the transaction from the storage', function () { - txStateManager._saveTxList([ { id: 1 } ]) + txStateManager._saveTxList([{ id: 1 }]) txStateManager._removeTx(1) assert.ok(!txStateManager.getFullTxList().length, 'txList should be empty') }) it('should only remove the transaction with ID 1 from the storage', function () { - txStateManager._saveTxList([ { id: 1 }, { id: 2 } ]) + txStateManager._saveTxList([{ id: 1 }, { id: 2 }]) txStateManager._removeTx(1) assert.equal(txStateManager.getFullTxList()[0].id, 2, 'txList should have a id of 2') }) diff --git a/test/unit/app/controllers/transactions/tx-utils-test.js b/test/unit/app/controllers/transactions/tx-utils-test.js index 461a49d51..6923d53d5 100644 --- a/test/unit/app/controllers/transactions/tx-utils-test.js +++ b/test/unit/app/controllers/transactions/tx-utils-test.js @@ -70,7 +70,6 @@ describe('txUtils', function () { }) }) - describe('#validateFrom', function () { it('should error when from is not a hex string', function () { diff --git a/test/unit/app/nodeify-test.js b/test/unit/app/nodeify-test.js index c8d1c46d9..f6e9a3207 100644 --- a/test/unit/app/nodeify-test.js +++ b/test/unit/app/nodeify-test.js @@ -4,7 +4,7 @@ import nodeify from '../../../app/scripts/lib/nodeify' describe('nodeify', function () { const obj = { foo: 'bar', - promiseFunc: function (a) { + promiseFunc (a) { const solution = this.foo + a return Promise.resolve(solution) }, diff --git a/test/unit/app/typed-message-manager.spec.js b/test/unit/app/typed-message-manager.spec.js index 65ba33fbd..5ab7258ad 100644 --- a/test/unit/app/typed-message-manager.spec.js +++ b/test/unit/app/typed-message-manager.spec.js @@ -1,6 +1,6 @@ import assert from 'assert' import sinon from 'sinon' -import NetworkController from '../../../app/scripts/controllers/network/index' +import NetworkController from '../../../app/scripts/controllers/network' import TypedMessageManager from '../../../app/scripts/lib/typed-message-manager' describe('Typed Message Manager', function () { diff --git a/test/unit/migrations/023-test.js b/test/unit/migrations/023-test.js index 362b4dbe2..49f40b033 100644 --- a/test/unit/migrations/023-test.js +++ b/test/unit/migrations/023-test.js @@ -56,7 +56,6 @@ while (transactions20.length < 20) { transactions20.push({ status }) } - storage.data.TransactionController.transactions = transactions describe('storage is migrated successfully and the proper transactions are remove from state', function () { diff --git a/test/unit/migrations/024-test.js b/test/unit/migrations/024-test.js index 1aa050b73..446f85f07 100644 --- a/test/unit/migrations/024-test.js +++ b/test/unit/migrations/024-test.js @@ -18,13 +18,11 @@ const storage = { const transactions = [] - while (transactions.length <= 10) { transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675' }, status: 'unapproved' }) transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675' }, status: 'confirmed' }) } - storage.data.TransactionController.transactions = transactions describe('storage is migrated successfully and the txParams.from are lowercase', function () { diff --git a/test/unit/migrations/025-test.js b/test/unit/migrations/025-test.js index 6224eef5a..2cd3381ca 100644 --- a/test/unit/migrations/025-test.js +++ b/test/unit/migrations/025-test.js @@ -19,13 +19,11 @@ const storage = { const transactions = [] - while (transactions.length <= 10) { transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675', random: 'stuff', chainId: 2 }, status: 'unapproved' }) transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675' }, status: 'confirmed' }) } - storage.data.TransactionController.transactions = transactions describe('storage is migrated successfully and the txParams.from are lowercase', function () { diff --git a/test/unit/migrations/027-test.js b/test/unit/migrations/027-test.js index 126a3b620..959f30374 100644 --- a/test/unit/migrations/027-test.js +++ b/test/unit/migrations/027-test.js @@ -14,14 +14,12 @@ const oldStorage = { const transactions = [] - while (transactions.length < 9) { transactions.push({ status: 'rejected' }) transactions.push({ status: 'unapproved' }) transactions.push({ status: 'approved' }) } - oldStorage.data.TransactionController.transactions = transactions describe('migration #27', function () { diff --git a/test/unit/migrations/028-test.js b/test/unit/migrations/028-test.js index dd58b8a42..b352f0a29 100644 --- a/test/unit/migrations/028-test.js +++ b/test/unit/migrations/028-test.js @@ -24,11 +24,11 @@ describe('migration #28', function () { const testTokens = [{ address: '0xa', symbol: 'A', decimals: 4 }, { address: '0xb', symbol: 'B', decimals: 4 }] assert.equal(newTokens.length, 0, 'tokens is expected to have the length of 0') - assert.equal(newAccountTokens['0x6d14']['mainnet'].length, 2, 'tokens for address is expected to have the length of 2') - assert.equal(newAccountTokens['0x3695']['mainnet'].length, 2, 'tokens for address is expected to have the length of 2') + assert.equal(newAccountTokens['0x6d14'].mainnet.length, 2, 'tokens for address is expected to have the length of 2') + assert.equal(newAccountTokens['0x3695'].mainnet.length, 2, 'tokens for address is expected to have the length of 2') assert.equal(Object.keys(newAccountTokens).length, 2, 'account tokens should be created for all identities') - assert.deepEqual(newAccountTokens['0x6d14']['mainnet'], testTokens, 'tokens for address should be the same than before') - assert.deepEqual(newAccountTokens['0x3695']['mainnet'], testTokens, 'tokens for address should be the same than before') + assert.deepEqual(newAccountTokens['0x6d14'].mainnet, testTokens, 'tokens for address should be the same than before') + assert.deepEqual(newAccountTokens['0x3695'].mainnet, testTokens, 'tokens for address should be the same than before') done() }) .catch(done) diff --git a/test/unit/migrations/029-test.js b/test/unit/migrations/029-test.js index b47bd1b6c..ccde6b4cb 100644 --- a/test/unit/migrations/029-test.js +++ b/test/unit/migrations/029-test.js @@ -22,7 +22,7 @@ describe('storage is migrated successfully where transactions that are submitted migration29.migrate(storage) .then((migratedData) => { const txs = migratedData.data.TransactionController.transactions - const [ txMeta1 ] = txs + const [txMeta1] = txs assert.equal(migratedData.meta.version, 29) assert.equal(txMeta1.status, 'failed', 'old tx is auto failed') diff --git a/test/unit/migrations/migrator-test.js b/test/unit/migrations/migrator-test.js index de4d16c45..87468d917 100644 --- a/test/unit/migrations/migrator-test.js +++ b/test/unit/migrations/migrator-test.js @@ -49,7 +49,7 @@ describe('migrations', function () { migrationNumbers = fileNames .reduce((acc, filename) => { const name = filename.split('.')[0] - if (/^\d+$/u.test(name)) { + if ((/^\d+$/u).test(name)) { acc.push(name) } return acc @@ -69,7 +69,7 @@ describe('migrations', function () { const testNumbers = fileNames .reduce((acc, filename) => { const name = filename.split('-test.')[0] - if (/^\d+$/u.test(name)) { + if ((/^\d+$/u).test(name)) { acc.push(name) } return acc diff --git a/test/unit/ui/app/actions.spec.js b/test/unit/ui/app/actions.spec.js index accca3136..8f2dc0bbf 100644 --- a/test/unit/ui/app/actions.spec.js +++ b/test/unit/ui/app/actions.spec.js @@ -38,11 +38,11 @@ describe('Actions', function () { showUnapprovedTx: noop, showUnconfirmedMessage: noop, encryptor: { - encrypt: function (_, object) { + encrypt (_, object) { this.object = object return Promise.resolve('mock-encrypted') }, - decrypt: function () { + decrypt () { return Promise.resolve(this.object) }, }, @@ -56,7 +56,7 @@ describe('Actions', function () { await metamaskController.createNewVaultAndRestore(password, TEST_SEED) - await metamaskController.importAccountWithStrategy('Private Key', [ importPrivkey ]) + await metamaskController.importAccountWithStrategy('Private Key', [importPrivkey]) background = metamaskController.getApi() @@ -97,7 +97,6 @@ describe('Actions', function () { { type: 'HIDE_LOADING_INDICATION' }, ] - submitPasswordSpy = sinon.stub(background, 'submitPassword') submitPasswordSpy.callsFake((_, callback) => { @@ -114,8 +113,8 @@ describe('Actions', function () { it('displays warning error and unlock failed when verifySeed fails', async function () { const store = mockStore() - const displayWarningError = [ { type: 'DISPLAY_WARNING', value: 'error' } ] - const unlockFailedError = [ { type: 'UNLOCK_FAILED', value: 'error' } ] + const displayWarningError = [{ type: 'DISPLAY_WARNING', value: 'error' }] + const unlockFailedError = [{ type: 'UNLOCK_FAILED', value: 'error' }] verifySeedPhraseSpy = sinon.stub(background, 'verifySeedPhrase') verifySeedPhraseSpy.callsFake((callback) => { @@ -861,7 +860,7 @@ describe('Actions', function () { 'value': '0x0', } - const txData = { id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: txParams } + const txData = { id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams } beforeEach(async function () { await metamaskController.txController.txStateManager.addTx(txData) diff --git a/test/unit/ui/app/reducers/app.spec.js b/test/unit/ui/app/reducers/app.spec.js index 027f574f2..7ba811cc3 100644 --- a/test/unit/ui/app/reducers/app.spec.js +++ b/test/unit/ui/app/reducers/app.spec.js @@ -122,7 +122,6 @@ describe('App State', function () { type: actions.MODAL_CLOSE, }) - assert.equal(newState.modal.open, false) assert.equal(newState.modal.modalState.name, null) }) diff --git a/test/unit/ui/app/reducers/metamask.spec.js b/test/unit/ui/app/reducers/metamask.spec.js index 3b232c0f6..1a872b14e 100644 --- a/test/unit/ui/app/reducers/metamask.spec.js +++ b/test/unit/ui/app/reducers/metamask.spec.js @@ -209,7 +209,8 @@ describe('MetaMask Reducers', function () { it('clears send', function () { const initStateSend = { send: - { gasLimit: null, + { + gasLimit: null, gasPrice: null, gasTotal: null, tokenBalance: null, @@ -220,7 +221,8 @@ describe('MetaMask Reducers', function () { errors: {}, maxModeOn: false, editingTransactionId: null, - toNickname: '' }, + toNickname: '', + }, } const sendState = { @@ -240,7 +242,6 @@ describe('MetaMask Reducers', function () { }, } - const state = reduceMetamask(sendState, { type: actionConstants.CLEAR_SEND, }) diff --git a/ui/app/components/app/account-list-item/tests/account-list-item-component.test.js b/ui/app/components/app/account-list-item/tests/account-list-item-component.test.js index 46630bfcc..d42bd7bc9 100644 --- a/ui/app/components/app/account-list-item/tests/account-list-item-component.test.js +++ b/ui/app/components/app/account-list-item/tests/account-list-item-component.test.js @@ -25,7 +25,7 @@ describe('AccountListItem Component', function () { handleClick={propsMethodSpies.handleClick} icon={} /> - ), { context: { t: (str) => str + '_t' } }) + ), { context: { t: (str) => `${str}_t` } }) }) afterEach(function () { diff --git a/ui/app/components/app/account-menu/account-menu.container.js b/ui/app/components/app/account-menu/account-menu.container.js index a9739dccc..c08537264 100644 --- a/ui/app/components/app/account-menu/account-menu.container.js +++ b/ui/app/components/app/account-menu/account-menu.container.js @@ -32,7 +32,7 @@ function mapStateToProps (state) { isAccountMenuOpen, addressConnectedDomainMap: getAddressConnectedDomainMap(state), originOfCurrentTab: origin, - selectedAddress: selectedAddress, + selectedAddress, keyrings: getMetaMaskKeyrings(state), accounts, shouldShowAccountsSearch: accounts.length >= SHOW_SEARCH_ACCOUNTS_MIN_COUNT, diff --git a/ui/app/components/app/account-menu/tests/account-menu.test.js b/ui/app/components/app/account-menu/tests/account-menu.test.js index 5dfbd4f1d..e0166dd08 100644 --- a/ui/app/components/app/account-menu/tests/account-menu.test.js +++ b/ui/app/components/app/account-menu/tests/account-menu.test.js @@ -4,7 +4,7 @@ import sinon from 'sinon' import configureMockStore from 'redux-mock-store' import { Provider } from 'react-redux' import { mountWithRouter } from '../../../../../../test/lib/render-helpers' -import AccountMenu from '../index' +import AccountMenu from '..' describe('Account Menu', function () { diff --git a/ui/app/components/app/add-token-button/add-token-button.component.js b/ui/app/components/app/add-token-button/add-token-button.component.js index b1d327a21..1ddf2b1ff 100644 --- a/ui/app/components/app/add-token-button/add-token-button.component.js +++ b/ui/app/components/app/add-token-button/add-token-button.component.js @@ -5,7 +5,6 @@ import { useI18nContext } from '../../../hooks/useI18nContext' import { ADD_TOKEN_ROUTE } from '../../../helpers/constants/routes' import Button from '../../ui/button' - export default function AddTokenButton () { const addTokenEvent = useMetricEvent({ eventOpts: { diff --git a/ui/app/components/app/app-header/tests/app-header.test.js b/ui/app/components/app/app-header/tests/app-header.test.js index e70684a09..76ece07a7 100644 --- a/ui/app/components/app/app-header/tests/app-header.test.js +++ b/ui/app/components/app/app-header/tests/app-header.test.js @@ -3,7 +3,7 @@ import React from 'react' import sinon from 'sinon' import { shallow } from 'enzyme' import MetaFoxLogo from '../../../ui/metafox-logo' -import AppHeader from '../index' +import AppHeader from '..' describe('App Header', function () { let wrapper diff --git a/ui/app/components/app/asset-list-item/asset-list-item.js b/ui/app/components/app/asset-list-item/asset-list-item.js index ad644f400..e5ff8212f 100644 --- a/ui/app/components/app/asset-list-item/asset-list-item.js +++ b/ui/app/components/app/asset-list-item/asset-list-item.js @@ -13,7 +13,6 @@ import { useMetricEvent } from '../../../hooks/useMetricEvent' import { updateSendToken } from '../../../store/actions' import { SEND_ROUTE } from '../../../helpers/constants/routes' - const AssetListItem = ({ className, 'data-testid': dataTestId, diff --git a/ui/app/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js b/ui/app/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js index 7b88c14d6..bf226df7e 100644 --- a/ui/app/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js +++ b/ui/app/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.js @@ -6,7 +6,6 @@ import ErrorMessage from '../../../ui/error-message' import { PageContainerFooter } from '../../../ui/page-container' import { ConfirmPageContainerSummary, ConfirmPageContainerWarning } from '.' - export default class ConfirmPageContainerContent extends Component { static propTypes = { action: PropTypes.string, @@ -40,9 +39,9 @@ export default class ConfirmPageContainerContent extends Component { if (detailsComponent && dataComponent) { return this.renderTabs() - } else { - return detailsComponent || dataComponent } + return detailsComponent || dataComponent + } renderTabs () { diff --git a/ui/app/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js b/ui/app/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js index c72600274..f2e2c0f2b 100644 --- a/ui/app/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js +++ b/ui/app/components/app/confirm-page-container/confirm-page-container-header/confirm-page-container-header.component.js @@ -11,7 +11,6 @@ import { shortenAddress } from '../../../../helpers/utils/util' import AccountMismatchWarning from '../../../ui/account-mismatch-warning/account-mismatch-warning.component' import { useI18nContext } from '../../../../hooks/useI18nContext' - export default function ConfirmPageContainerHeader ({ onEdit, showEdit, diff --git a/ui/app/components/app/connected-accounts-list/connected-accounts-list.component.js b/ui/app/components/app/connected-accounts-list/connected-accounts-list.component.js index 854539477..1208b1f12 100644 --- a/ui/app/components/app/connected-accounts-list/connected-accounts-list.component.js +++ b/ui/app/components/app/connected-accounts-list/connected-accounts-list.component.js @@ -32,7 +32,7 @@ export default class ConnectedAccountsList extends PureComponent { return new Error( `Warning: Failed prop type: '${propName}' of component '${componentName}' must be a boolean. Received: ${typeof props[propName]}`, ) - } else if (props[propName] && !props['removePermittedAccount']) { + } else if (props[propName] && !props.removePermittedAccount) { return new Error( `Warning: Failed prop type: '${propName}' of component '${componentName}' requires prop 'removePermittedAccount'.`, ) diff --git a/ui/app/components/app/connected-status-indicator/connected-status-indicator.component.js b/ui/app/components/app/connected-status-indicator/connected-status-indicator.component.js index 5954565b5..d000aaf7a 100644 --- a/ui/app/components/app/connected-status-indicator/connected-status-indicator.component.js +++ b/ui/app/components/app/connected-status-indicator/connected-status-indicator.component.js @@ -13,7 +13,7 @@ export default class ConnectedStatusIndicator extends Component { } static propTypes = { - status: PropTypes.oneOf([ STATUS_CONNECTED, STATUS_CONNECTED_TO_ANOTHER_ACCOUNT, STATUS_NOT_CONNECTED ]), + status: PropTypes.oneOf([STATUS_CONNECTED, STATUS_CONNECTED_TO_ANOTHER_ACCOUNT, STATUS_NOT_CONNECTED]), onClick: PropTypes.func, } diff --git a/ui/app/components/app/connected-status-indicator/connected-status-indicator.container.js b/ui/app/components/app/connected-status-indicator/connected-status-indicator.container.js index 678e5175e..17034f32d 100644 --- a/ui/app/components/app/connected-status-indicator/connected-status-indicator.container.js +++ b/ui/app/components/app/connected-status-indicator/connected-status-indicator.container.js @@ -12,7 +12,6 @@ import { } from '../../../selectors' import ConnectedStatusIndicator from './connected-status-indicator.component' - const mapStateToProps = (state) => { const selectedAddress = getSelectedAddress(state) const addressConnectedDomainMap = getAddressConnectedDomainMap(state) diff --git a/ui/app/components/app/contact-list/contact-list.component.js b/ui/app/components/app/contact-list/contact-list.component.js index b41bfe1c1..b959fb9c0 100644 --- a/ui/app/components/app/contact-list/contact-list.component.js +++ b/ui/app/components/app/contact-list/contact-list.component.js @@ -67,9 +67,8 @@ export default class ContactList extends PureComponent { return 1 } else if (letter1 === letter2) { return 0 - } else { - return -1 } + return -1 }) .map(([letter, groupItems]) => ( {children} diff --git a/ui/app/components/app/dropdowns/network-dropdown.js b/ui/app/components/app/dropdowns/network-dropdown.js index 3a95e348a..16b645858 100644 --- a/ui/app/components/app/dropdowns/network-dropdown.js +++ b/ui/app/components/app/dropdowns/network-dropdown.js @@ -135,45 +135,44 @@ class NetworkDropdown extends Component { if ((rpc === 'http://localhost:8545') || currentRpcTarget) { return null - } else { - const { chainId } = entry - return ( - this.props.hideNetworkDropdown()} - onClick={() => this.props.setRpcTarget(rpc, chainId, ticker, nickname)} + } + const { chainId } = entry + return ( + this.props.hideNetworkDropdown()} + onClick={() => this.props.setRpcTarget(rpc, chainId, ticker, nickname)} + style={{ + fontSize: '16px', + lineHeight: '20px', + padding: '12px 0', + }} + > + { + currentRpcTarget + ? + :
+ } + + - { - currentRpcTarget - ? - :
- } - - - {nickname || rpc} - - { - e.stopPropagation() - this.props.delRpcTarget(rpc) - }} - /> -
- ) - } + {nickname || rpc} + + { + e.stopPropagation() + this.props.delRpcTarget(rpc) + }} + /> +
+ ) }) } diff --git a/ui/app/components/app/gas-customization/advanced-gas-inputs/tests/advanced-gas-input-component.test.js b/ui/app/components/app/gas-customization/advanced-gas-inputs/tests/advanced-gas-input-component.test.js index 8130a5179..a18e0e114 100644 --- a/ui/app/components/app/gas-customization/advanced-gas-inputs/tests/advanced-gas-input-component.test.js +++ b/ui/app/components/app/gas-customization/advanced-gas-inputs/tests/advanced-gas-input-component.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import AdvancedTabContent from '../index' +import AdvancedTabContent from '..' describe('Advanced Gas Inputs', function () { let wrapper, clock @@ -29,7 +29,8 @@ describe('Advanced Gas Inputs', function () { context: { t: (str) => str, }, - }) + }, + ) }) afterEach(function () { diff --git a/ui/app/components/app/gas-customization/gas-modal-page-container/tests/gas-modal-page-container-container.test.js b/ui/app/components/app/gas-customization/gas-modal-page-container/tests/gas-modal-page-container-container.test.js index bc2e45ba7..f27d0de52 100644 --- a/ui/app/components/app/gas-customization/gas-modal-page-container/tests/gas-modal-page-container-container.test.js +++ b/ui/app/components/app/gas-customization/gas-modal-page-container/tests/gas-modal-page-container-container.test.js @@ -168,21 +168,18 @@ describe('gas-modal-page-container container', function () { const tests = [ { mockState: baseMockState, expectedResult: baseExpectedResult, mockOwnProps: baseMockOwnProps }, { - mockState: Object.assign({}, baseMockState, { - metamask: { ...baseMockState.metamask, balance: '0xfffffffffffffffffffff' }, - }), - expectedResult: Object.assign({}, baseExpectedResult, { balance: '0xfffffffffffffffffffff', insufficientBalance: false }), + mockState: { ...baseMockState, metamask: { ...baseMockState.metamask, balance: '0xfffffffffffffffffffff' } }, + expectedResult: { ...baseExpectedResult, balance: '0xfffffffffffffffffffff', insufficientBalance: false }, mockOwnProps: baseMockOwnProps, }, { mockState: baseMockState, - mockOwnProps: Object.assign({}, baseMockOwnProps, { - transaction: { id: 34, status: 'submitted' }, - }), - expectedResult: Object.assign({}, baseExpectedResult, { isSpeedUp: true, transaction: { id: 34 } }), + mockOwnProps: { ...baseMockOwnProps, transaction: { id: 34, status: 'submitted' } }, + expectedResult: { ...baseExpectedResult, isSpeedUp: true, transaction: { id: 34 } }, }, { - mockState: Object.assign({}, baseMockState, { + mockState: { + ...baseMockState, metamask: { ...baseMockState.metamask, preferences: { @@ -194,7 +191,7 @@ describe('gas-modal-page-container container', function () { type: 'rinkeby', }, }, - }), + }, mockOwnProps: baseMockOwnProps, expectedResult: { ...baseExpectedResult, @@ -206,7 +203,8 @@ describe('gas-modal-page-container container', function () { }, }, { - mockState: Object.assign({}, baseMockState, { + mockState: { + ...baseMockState, metamask: { ...baseMockState.metamask, preferences: { @@ -218,7 +216,7 @@ describe('gas-modal-page-container container', function () { type: 'rinkeby', }, }, - }), + }, mockOwnProps: baseMockOwnProps, expectedResult: { ...baseExpectedResult, @@ -226,7 +224,8 @@ describe('gas-modal-page-container container', function () { }, }, { - mockState: Object.assign({}, baseMockState, { + mockState: { + ...baseMockState, metamask: { ...baseMockState.metamask, preferences: { @@ -238,7 +237,7 @@ describe('gas-modal-page-container container', function () { type: 'mainnet', }, }, - }), + }, mockOwnProps: baseMockOwnProps, expectedResult: baseExpectedResult, }, @@ -404,7 +403,7 @@ describe('gas-modal-page-container container', function () { }) it('should return the expected props when isConfirm is false', function () { - const result = mergeProps(Object.assign({}, stateProps, { isConfirm: false }), dispatchProps, ownProps) + const result = mergeProps({ ...stateProps, isConfirm: false }, dispatchProps, ownProps) assert.equal(result.isConfirm, false) assert.equal(result.someOtherStateProp, 'baz') @@ -435,7 +434,7 @@ describe('gas-modal-page-container container', function () { }) it('should dispatch the expected actions from obSubmit when isConfirm is false and isSpeedUp is true', function () { - const result = mergeProps(Object.assign({}, stateProps, { isSpeedUp: true, isConfirm: false }), dispatchProps, ownProps) + const result = mergeProps({ ...stateProps, isSpeedUp: true, isConfirm: false }, dispatchProps, ownProps) result.onSubmit() diff --git a/ui/app/components/app/gas-customization/gas-price-button-group/gas-price-button-group.component.js b/ui/app/components/app/gas-customization/gas-price-button-group/gas-price-button-group.component.js index 8916c7e8e..77c098983 100644 --- a/ui/app/components/app/gas-customization/gas-price-button-group/gas-price-button-group.component.js +++ b/ui/app/components/app/gas-customization/gas-price-button-group/gas-price-button-group.component.js @@ -4,7 +4,6 @@ import ButtonGroup from '../../../ui/button-group' import Button from '../../../ui/button' import { GAS_ESTIMATE_TYPES } from '../../../../helpers/constants/common' - const GAS_OBJECT_PROPTYPES_SHAPE = { gasEstimateType: PropTypes.oneOf(Object.values(GAS_ESTIMATE_TYPES)).isRequired, feeInPrimaryCurrency: PropTypes.string, diff --git a/ui/app/components/app/gas-customization/gas-price-button-group/tests/gas-price-button-group-component.test.js b/ui/app/components/app/gas-customization/gas-price-button-group/tests/gas-price-button-group-component.test.js index 24a89e165..4cd44066c 100644 --- a/ui/app/components/app/gas-customization/gas-price-button-group/tests/gas-price-button-group-component.test.js +++ b/ui/app/components/app/gas-customization/gas-price-button-group/tests/gas-price-button-group-component.test.js @@ -41,11 +41,11 @@ describe('GasPriceButtonGroup Component', function () { showCheck: true, } - mockButtonPropsAndFlags = Object.assign({}, { + mockButtonPropsAndFlags = { className: mockGasPriceButtonGroupProps.className, handleGasPriceSelection: mockGasPriceButtonGroupProps.handleGasPriceSelection, showCheck: mockGasPriceButtonGroupProps.showCheck, - }) + } sinon.spy(GasPriceButtonGroup.prototype, 'renderButton') sinon.spy(GasPriceButtonGroup.prototype, 'renderButtonContent') @@ -81,7 +81,7 @@ describe('GasPriceButtonGroup Component', function () { assert.deepEqual( GasPriceButtonGroup.prototype.renderButton.getCall(i).args, [ - Object.assign({}, mockGasPriceButtonGroupProps.gasButtonInfo[i]), + { ...mockGasPriceButtonGroupProps.gasButtonInfo[i] }, mockPropsAndFlags, i, ], @@ -109,7 +109,7 @@ describe('GasPriceButtonGroup Component', function () { beforeEach(function () { GasPriceButtonGroup.prototype.renderButtonContent.resetHistory() const renderButtonResult = GasPriceButtonGroup.prototype.renderButton( - Object.assign({}, mockGasPriceButtonGroupProps.gasButtonInfo[0]), + { ...mockGasPriceButtonGroupProps.gasButtonInfo[0] }, mockButtonPropsAndFlags, ) wrappedRenderButtonResult = shallow(renderButtonResult) @@ -225,7 +225,6 @@ describe('GasPriceButtonGroup Component', function () { assert.equal(wrappedRenderButtonContentResult.children().length, 5) }) - it('should render no elements if all args passed', function () { const renderButtonContentResult = GasPriceButtonGroup.prototype.renderButtonContent({}, {}) const wrappedRenderButtonContentResult = shallow(renderButtonContentResult) diff --git a/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js b/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js index f60e36be1..ff6dd9390 100644 --- a/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js +++ b/ui/app/components/app/gas-customization/gas-price-chart/gas-price-chart.utils.js @@ -127,7 +127,7 @@ export function setTickPosition (axis, n, newPosition, secondNewPosition) { /* eslint-disable babel/no-invalid-this */ export function appendOrUpdateCircle ({ data, itemIndex, cx, cy, cssId, appendOnly }) { const circle = this.main - .select('.c3-selected-circles' + this.getTargetSelectorSuffix(data.id)) + .select(`.c3-selected-circles${this.getTargetSelectorSuffix(data.id)}`) .selectAll(`.c3-selected-circle-${itemIndex}`) if (appendOnly || circle.empty()) { @@ -182,7 +182,6 @@ export function setSelectedCircle ({ ) } - export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimatedTimesMax) { const gasPricesMaxPadded = gasPricesMax + 1 const chart = c3.generate({ @@ -216,8 +215,8 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate tick: { values: [Math.floor(gasPrices[0]), Math.ceil(gasPricesMax)], outer: false, - format: function (val) { - return val + ' GWEI' + format (val) { + return `${val} GWEI` }, }, padding: { left: gasPricesMax / 50, right: gasPricesMax / 50 }, @@ -260,7 +259,7 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate format: { title: (v) => v.toPrecision(4), }, - contents: function (d) { + contents (d) { const titleFormat = this.config.tooltip_format_title let text d.forEach((el) => { @@ -270,7 +269,7 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate }) return `${text}
` }, - position: function () { + position () { if (d3.select('#overlayed-circle').empty()) { return { top: -100, left: -100 } } @@ -332,7 +331,7 @@ export function generateChart (gasPrices, estimatedTimes, gasPricesMax, estimate const tHeight = this.tooltip.property('offsetHeight') const position = this.config.tooltip_position.call(this, dataToShow, tWidth, tHeight, element) // Set tooltip - this.tooltip.style('top', position.top + 'px').style('left', position.left + 'px') + this.tooltip.style('top', `${position.top}px`).style('left', `${position.left}px`) } } diff --git a/ui/app/components/app/gas-customization/gas-price-chart/tests/gas-price-chart.component.test.js b/ui/app/components/app/gas-customization/gas-price-chart/tests/gas-price-chart.component.test.js index df8a58b55..d95fa63a1 100644 --- a/ui/app/components/app/gas-customization/gas-price-chart/tests/gas-price-chart.component.test.js +++ b/ui/app/components/app/gas-customization/gas-price-chart/tests/gas-price-chart.component.test.js @@ -69,7 +69,7 @@ describe('GasPriceChart Component', function () { './gas-price-chart.utils.js': gasPriceChartUtilsSpies, 'd3': { ...d3, - select: function (...args) { + select (...args) { const result = d3.select(...args) return result.empty() ? mockSelectReturn diff --git a/ui/app/components/app/info-box/tests/info-box.test.js b/ui/app/components/app/info-box/tests/info-box.test.js index 6112a25ad..5ad89b4fd 100644 --- a/ui/app/components/app/info-box/tests/info-box.test.js +++ b/ui/app/components/app/info-box/tests/info-box.test.js @@ -3,7 +3,7 @@ import React from 'react' import sinon from 'sinon' import { shallow } from 'enzyme' -import InfoBox from '../index' +import InfoBox from '..' describe('InfoBox', function () { diff --git a/ui/app/components/app/menu-bar/tests/menu-bar.test.js b/ui/app/components/app/menu-bar/tests/menu-bar.test.js index 416179d17..1212977be 100644 --- a/ui/app/components/app/menu-bar/tests/menu-bar.test.js +++ b/ui/app/components/app/menu-bar/tests/menu-bar.test.js @@ -3,7 +3,7 @@ import React from 'react' import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' import { mountWithRouter } from '../../../../../../test/lib/render-helpers' -import MenuBar from '../index' +import MenuBar from '..' const initState = { activeTab: {}, diff --git a/ui/app/components/app/menu-droppo.js b/ui/app/components/app/menu-droppo.js index e460fe118..35d7b458e 100644 --- a/ui/app/components/app/menu-droppo.js +++ b/ui/app/components/app/menu-droppo.js @@ -74,11 +74,11 @@ export default class MenuDroppoComponent extends Component { this.manageListeners() - const baseStyle = Object.assign( - { position: 'fixed' }, - style, - { zIndex }, - ) + const baseStyle = { + position: 'fixed', + ...style, + zIndex, + } return (
diff --git a/ui/app/components/app/modals/account-details-modal/account-details-modal.component.js b/ui/app/components/app/modals/account-details-modal/account-details-modal.component.js index 858ae8296..faa910c43 100644 --- a/ui/app/components/app/modals/account-details-modal/account-details-modal.component.js +++ b/ui/app/components/app/modals/account-details-modal/account-details-modal.component.js @@ -52,7 +52,7 @@ export default class AccountDetailsModal extends Component { diff --git a/ui/app/components/app/modals/cancel-transaction/cancel-transaction.component.js b/ui/app/components/app/modals/cancel-transaction/cancel-transaction.component.js index 2d01711ff..f13cca550 100644 --- a/ui/app/components/app/modals/cancel-transaction/cancel-transaction.component.js +++ b/ui/app/components/app/modals/cancel-transaction/cancel-transaction.component.js @@ -26,7 +26,6 @@ export default class CancelTransaction extends PureComponent { if (transactionStatus !== SUBMITTED_STATUS) { showTransactionConfirmedModal() - return } } diff --git a/ui/app/components/app/modals/confirm-delete-network/tests/confirm-delete-network.test.js b/ui/app/components/app/modals/confirm-delete-network/tests/confirm-delete-network.test.js index e5c2ceeb5..adf8de80a 100644 --- a/ui/app/components/app/modals/confirm-delete-network/tests/confirm-delete-network.test.js +++ b/ui/app/components/app/modals/confirm-delete-network/tests/confirm-delete-network.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import ConfirmDeleteNetwork from '../index' +import ConfirmDeleteNetwork from '..' describe('Confirm Delete Network', function () { let wrapper diff --git a/ui/app/components/app/modals/confirm-remove-account/tests/confirm-remove-account.test.js b/ui/app/components/app/modals/confirm-remove-account/tests/confirm-remove-account.test.js index 6aa26ba70..12f6d3655 100644 --- a/ui/app/components/app/modals/confirm-remove-account/tests/confirm-remove-account.test.js +++ b/ui/app/components/app/modals/confirm-remove-account/tests/confirm-remove-account.test.js @@ -5,7 +5,7 @@ import { Provider } from 'react-redux' import sinon from 'sinon' import configureStore from 'redux-mock-store' import { mount } from 'enzyme' -import ConfirmRemoveAccount from '../index' +import ConfirmRemoveAccount from '..' describe('Confirm Remove Account', function () { let wrapper @@ -26,7 +26,6 @@ describe('Confirm Remove Account', function () { }, } - const mockStore = configureStore() const store = mockStore(state) diff --git a/ui/app/components/app/modals/confirm-reset-account/tests/confirm-reset-account.test.js b/ui/app/components/app/modals/confirm-reset-account/tests/confirm-reset-account.test.js index d9e05c6a7..005993059 100644 --- a/ui/app/components/app/modals/confirm-reset-account/tests/confirm-reset-account.test.js +++ b/ui/app/components/app/modals/confirm-reset-account/tests/confirm-reset-account.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import ConfirmResetAccount from '../index' +import ConfirmResetAccount from '..' describe('Confirm Reset Account', function () { let wrapper diff --git a/ui/app/components/app/modals/deposit-ether-modal/deposit-ether-modal.container.js b/ui/app/components/app/modals/deposit-ether-modal/deposit-ether-modal.container.js index 5c7c8caec..7217ac21e 100644 --- a/ui/app/components/app/modals/deposit-ether-modal/deposit-ether-modal.container.js +++ b/ui/app/components/app/modals/deposit-ether-modal/deposit-ether-modal.container.js @@ -30,5 +30,4 @@ function mapDispatchToProps (dispatch) { } } - export default connect(mapStateToProps, mapDispatchToProps)(DepositEtherModal) diff --git a/ui/app/components/app/modals/fade-modal.js b/ui/app/components/app/modals/fade-modal.js index 89cace146..72d1c7288 100644 --- a/ui/app/components/app/modals/fade-modal.js +++ b/ui/app/components/app/modals/fade-modal.js @@ -22,14 +22,14 @@ const insertRule = (css) => { const insertKeyframesRule = (keyframes) => { // random name // eslint-disable-next-line no-plusplus - const name = 'anim_' + (++index) + (+new Date()) + const name = `anim_${++index}${Number(new Date())}` let css = `@keyframes ${name} {` Object.keys(keyframes).forEach((key) => { - css += key + ' {' + css += `${key} {` Object.keys(keyframes[key]).forEach((property) => { - const part = ':' + keyframes[key][property] + ';' + const part = `:${keyframes[key][property]};` css += property + part }) @@ -179,15 +179,15 @@ class FadeModal extends Component { const { willHide } = this.state const { modalStyle } = this.props - const backdropStyle = Object.assign({}, { + const backdropStyle = { animationName: willHide ? animation.hideBackdropAnimation : animation.showBackdropAnimation, - animationTimingFunction: (willHide ? animation.hide : animation.show).animationTimingFunction, - }, this.props.backdropStyle) - const contentStyle = Object.assign({}, { + animationTimingFunction: (willHide ? animation.hide : animation.show).animationTimingFunction, ...this.props.backdropStyle, + } + const contentStyle = { animationDuration: (willHide ? animation.hide : animation.show).animationDuration, animationName: willHide ? animation.hideContentAnimation : animation.showContentAnimation, - animationTimingFunction: (willHide ? animation.hide : animation.show).animationTimingFunction, - }, this.props.contentStyle) + animationTimingFunction: (willHide ? animation.hide : animation.show).animationTimingFunction, ...this.props.contentStyle, + } const backdrop = this.props.backdrop ? ( diff --git a/ui/app/components/app/modals/metametrics-opt-in-modal/tests/metametrics-opt-in-modal.test.js b/ui/app/components/app/modals/metametrics-opt-in-modal/tests/metametrics-opt-in-modal.test.js index e35549cbe..bd39976b3 100644 --- a/ui/app/components/app/modals/metametrics-opt-in-modal/tests/metametrics-opt-in-modal.test.js +++ b/ui/app/components/app/modals/metametrics-opt-in-modal/tests/metametrics-opt-in-modal.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import MetaMetricsOptIn from '../index' +import MetaMetricsOptIn from '..' describe('MetaMetrics Opt In', function () { let wrapper diff --git a/ui/app/components/app/modals/qr-scanner/qr-scanner.component.js b/ui/app/components/app/modals/qr-scanner/qr-scanner.component.js index fd79c9e41..d78db3d14 100644 --- a/ui/app/components/app/modals/qr-scanner/qr-scanner.component.js +++ b/ui/app/components/app/modals/qr-scanner/qr-scanner.component.js @@ -144,7 +144,6 @@ export default class QrScanner extends Component { // To parse other type of links // For ex. EIP-681 (https://eips.ethereum.org/EIPS/eip-681) - // Ethereum address links - fox ex. ethereum:0x.....1111 if (content.split('ethereum:').length > 1) { @@ -161,7 +160,6 @@ export default class QrScanner extends Component { return { type, values } } - stopAndClose = () => { if (this.codeReader) { this.codeReader.reset() diff --git a/ui/app/components/app/modals/qr-scanner/qr-scanner.container.js b/ui/app/components/app/modals/qr-scanner/qr-scanner.container.js index fca9d61ad..98472c6ea 100644 --- a/ui/app/components/app/modals/qr-scanner/qr-scanner.container.js +++ b/ui/app/components/app/modals/qr-scanner/qr-scanner.container.js @@ -2,7 +2,6 @@ import { connect } from 'react-redux' import { hideModal, qrCodeDetected } from '../../../../store/actions' import QrScanner from './qr-scanner.component' - const mapDispatchToProps = (dispatch) => { return { hideModal: () => dispatch(hideModal()), diff --git a/ui/app/components/app/modals/reject-transactions/tests/reject-transactions.test.js b/ui/app/components/app/modals/reject-transactions/tests/reject-transactions.test.js index 93f4495da..1d8a1df68 100644 --- a/ui/app/components/app/modals/reject-transactions/tests/reject-transactions.test.js +++ b/ui/app/components/app/modals/reject-transactions/tests/reject-transactions.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import RejectTransactionsModal from '../index' +import RejectTransactionsModal from '..' describe('Reject Transactions Model', function () { let wrapper diff --git a/ui/app/components/app/modals/transaction-confirmed/tests/transaction-confirmed.test.js b/ui/app/components/app/modals/transaction-confirmed/tests/transaction-confirmed.test.js index ad8ba565d..971ed324c 100644 --- a/ui/app/components/app/modals/transaction-confirmed/tests/transaction-confirmed.test.js +++ b/ui/app/components/app/modals/transaction-confirmed/tests/transaction-confirmed.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import TransactionConfirmed from '../index' +import TransactionConfirmed from '..' describe('Transaction Confirmed', function () { it('clicks ok to submit and hide modal', function () { diff --git a/ui/app/components/app/network-display/network-display.component.js b/ui/app/components/app/network-display/network-display.component.js index 2dbe96adf..eb89755c3 100644 --- a/ui/app/components/app/network-display/network-display.component.js +++ b/ui/app/components/app/network-display/network-display.component.js @@ -57,7 +57,7 @@ export default class NetworkDisplay extends Component {
{ diff --git a/ui/app/components/app/permission-page-container/permission-page-container-content/permission-page-container-content.component.js b/ui/app/components/app/permission-page-container/permission-page-container-content/permission-page-container-content.component.js index a10f89b9a..94895e92d 100644 --- a/ui/app/components/app/permission-page-container/permission-page-container-content/permission-page-container-content.component.js +++ b/ui/app/components/app/permission-page-container/permission-page-container-content/permission-page-container-content.component.js @@ -95,7 +95,7 @@ export default class PermissionPageContainerContent extends PureComponent { ) }) } { selectedIdentities.length > 6 - ? t('plusXMore', [ selectedIdentities.length - 6 ]) + ? t('plusXMore', [selectedIdentities.length - 6]) : null }
@@ -115,23 +115,19 @@ export default class PermissionPageContainerContent extends PureComponent { } else if (allIdentitiesSelected) { return t( 'connectToAll', - [ this.renderAccountTooltip(t('connectToAllAccounts')) ], + [this.renderAccountTooltip(t('connectToAllAccounts'))], ) } else if (selectedIdentities.length > 1) { return t( 'connectToMultiple', [ - this.renderAccountTooltip(t('connectToMultipleNumberOfAccounts', [ selectedIdentities.length ])), - ], - ) - } else { - return t( - 'connectTo', - [ - this.getAccountDescriptor(selectedIdentities[0]), + this.renderAccountTooltip(t('connectToMultipleNumberOfAccounts', [selectedIdentities.length])), ], ) } + return t('connectTo', [ + this.getAccountDescriptor(selectedIdentities[0]), + ]) } render () { diff --git a/ui/app/components/app/selected-account/selected-account.container.js b/ui/app/components/app/selected-account/selected-account.container.js index 22e6cc5ef..154bf4311 100644 --- a/ui/app/components/app/selected-account/selected-account.container.js +++ b/ui/app/components/app/selected-account/selected-account.container.js @@ -2,7 +2,6 @@ import { connect } from 'react-redux' import { getSelectedIdentity } from '../../../selectors' import SelectedAccount from './selected-account.component' - const mapStateToProps = (state) => { return { selectedIdentity: getSelectedIdentity(state), diff --git a/ui/app/components/app/signature-request/signature-request-message/signature-request-message.component.js b/ui/app/components/app/signature-request/signature-request-message/signature-request-message.component.js index 16b6c3bea..5c4b455d3 100644 --- a/ui/app/components/app/signature-request/signature-request-message/signature-request-message.component.js +++ b/ui/app/components/app/signature-request/signature-request-message/signature-request-message.component.js @@ -14,7 +14,7 @@ export default class SignatureRequestMessage extends PureComponent { renderNode (data) { return (
- {Object.entries(data).map(([ label, value ], i) => ( + {Object.entries(data).map(([label, value], i) => (
key - describe('Outgoing transaction', function () { beforeEach(function () { global.eth = { diff --git a/ui/app/components/app/transaction-activity-log/transaction-activity-log.util.js b/ui/app/components/app/transaction-activity-log/transaction-activity-log.util.js index ba45b9be0..ed07e1ee4 100644 --- a/ui/app/components/app/transaction-activity-log/transaction-activity-log.util.js +++ b/ui/app/components/app/transaction-activity-log/transaction-activity-log.util.js @@ -1,13 +1,5 @@ import { getHexGasTotal } from '../../../helpers/utils/confirm-tx.util' -// path constants -const STATUS_PATH = '/status' -const GAS_PRICE_PATH = '/txParams/gasPrice' -const GAS_LIMIT_PATH = '/txParams/gas' - -// op constants -const REPLACE_OP = 'replace' - import { TRANSACTION_TYPE_CANCEL, TRANSACTION_TYPE_RETRY, @@ -29,6 +21,13 @@ import { DROPPED_STATUS, } from './transaction-activity-log.constants' +// path constants +const STATUS_PATH = '/status' +const GAS_PRICE_PATH = '/txParams/gasPrice' +const GAS_LIMIT_PATH = '/txParams/gas' + +// op constants +const REPLACE_OP = 'replace' const eventPathsHash = { [STATUS_PATH]: true, diff --git a/ui/app/components/app/transaction-breakdown/transaction-breakdown.container.js b/ui/app/components/app/transaction-breakdown/transaction-breakdown.container.js index e52b0bce0..6aee276a7 100644 --- a/ui/app/components/app/transaction-breakdown/transaction-breakdown.container.js +++ b/ui/app/components/app/transaction-breakdown/transaction-breakdown.container.js @@ -17,7 +17,7 @@ const mapStateToProps = (state, ownProps) => { return { nativeCurrency: getNativeCurrency(state), - showFiat: (isMainnet || !!showFiatInTestnets), + showFiat: (isMainnet || Boolean(showFiatInTestnets)), totalInHex, gas, gasPrice, diff --git a/ui/app/components/app/transaction-icon/transaction-icon.js b/ui/app/components/app/transaction-icon/transaction-icon.js index 24f4f4715..d0c7ef455 100644 --- a/ui/app/components/app/transaction-icon/transaction-icon.js +++ b/ui/app/components/app/transaction-icon/transaction-icon.js @@ -20,7 +20,6 @@ import { APPROVED_STATUS, } from '../../../helpers/constants/transactions' - const ICON_MAP = { [TRANSACTION_CATEGORY_APPROVAL]: Approve, [TRANSACTION_CATEGORY_INTERACTION]: Interaction, diff --git a/ui/app/components/app/transaction-list-item/transaction-list-item.component.js b/ui/app/components/app/transaction-list-item/transaction-list-item.component.js index eb03d3003..0b64678ff 100644 --- a/ui/app/components/app/transaction-list-item/transaction-list-item.component.js +++ b/ui/app/components/app/transaction-list-item/transaction-list-item.component.js @@ -26,7 +26,6 @@ import TransactionIcon from '../transaction-icon' import { useTransactionTimeRemaining } from '../../../hooks/useTransactionTimeRemaining' import IconWithLabel from '../../ui/icon-with-label' - export default function TransactionListItem ({ transactionGroup, isEarliestNonce = false }) { const t = useI18nContext() const history = useHistory() @@ -54,7 +53,6 @@ export default function TransactionListItem ({ transactionGroup, isEarliestNonce const timeRemaining = useTransactionTimeRemaining(isPending, isEarliestNonce, submittedTime, gasPrice) - const isSignatureReq = category === TRANSACTION_CATEGORY_SIGNATURE_REQUEST const isApproval = category === TRANSACTION_CATEGORY_APPROVAL const isUnapproved = status === UNAPPROVED_STATUS diff --git a/ui/app/components/app/transaction-list/transaction-list.component.js b/ui/app/components/app/transaction-list/transaction-list.component.js index a293b8aa1..a05cf06f9 100644 --- a/ui/app/components/app/transaction-list/transaction-list.component.js +++ b/ui/app/components/app/transaction-list/transaction-list.component.js @@ -26,7 +26,6 @@ const tokenTransactionFilter = ({ }, }) => !TOKEN_CATEGORY_HASH[transactionCategory] - const getFilteredTransactionGroups = (transactionGroups, hideTokenTransactions, tokenAddress) => { if (hideTokenTransactions) { return transactionGroups.filter(tokenTransactionFilter) @@ -72,11 +71,10 @@ export default function TransactionList ({ hideTokenTransactions, tokenAddress } .then(({ blockTime }) => fetchGasEstimates(blockTime)) } prevState.current = { loaded: true, pendingTransactions, transactionTimeFeatureActive } - }, [fetchGasEstimates, fetchBasicGasAndTimeEstimates, transactionTimeFeatureActive, pendingTransactions ]) + }, [fetchGasEstimates, fetchBasicGasAndTimeEstimates, transactionTimeFeatureActive, pendingTransactions]) const viewMore = useCallback(() => setLimit((prev) => prev + PAGE_INCREMENT), []) - const pendingLength = pendingTransactions.length return ( diff --git a/ui/app/components/app/user-preferenced-currency-display/tests/user-preferenced-currency-display.component.test.js b/ui/app/components/app/user-preferenced-currency-display/tests/user-preferenced-currency-display.component.test.js index c5c903fd9..d9f271e10 100644 --- a/ui/app/components/app/user-preferenced-currency-display/tests/user-preferenced-currency-display.component.test.js +++ b/ui/app/components/app/user-preferenced-currency-display/tests/user-preferenced-currency-display.component.test.js @@ -7,7 +7,6 @@ import CurrencyDisplay from '../../../ui/currency-display' import * as currencyHook from '../../../../hooks/useCurrencyDisplay' import * as currencyPrefHook from '../../../../hooks/useUserPreferencedCurrency' - describe('UserPreferencedCurrencyDisplay Component', function () { describe('rendering', function () { beforeEach(function () { diff --git a/ui/app/components/ui/alert/index.js b/ui/app/components/ui/alert/index.js index 3bc1b4581..437bf492b 100644 --- a/ui/app/components/ui/alert/index.js +++ b/ui/app/components/ui/alert/index.js @@ -19,7 +19,7 @@ class Alert extends Component { animateIn (msg) { this.setState({ - msg: msg, + msg, visible: true, className: 'visible', }) diff --git a/ui/app/components/ui/alert/tests/alert.test.js b/ui/app/components/ui/alert/tests/alert.test.js index ec32d6633..70aaa5e16 100644 --- a/ui/app/components/ui/alert/tests/alert.test.js +++ b/ui/app/components/ui/alert/tests/alert.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { shallow } from 'enzyme' -import Alert from '../index' +import Alert from '..' describe('Alert', function () { let wrapper diff --git a/ui/app/components/ui/breadcrumbs/tests/breadcrumbs.component.test.js b/ui/app/components/ui/breadcrumbs/tests/breadcrumbs.component.test.js index 1fcf2aaea..63b9a3f51 100644 --- a/ui/app/components/ui/breadcrumbs/tests/breadcrumbs.component.test.js +++ b/ui/app/components/ui/breadcrumbs/tests/breadcrumbs.component.test.js @@ -15,8 +15,8 @@ describe('Breadcrumbs Component', function () { assert.ok(wrapper) assert.equal(wrapper.find('.breadcrumbs').length, 1) assert.equal(wrapper.find('.breadcrumb').length, 3) - assert.equal(wrapper.find('.breadcrumb').at(0).props().style['backgroundColor'], '#FFFFFF') - assert.equal(wrapper.find('.breadcrumb').at(1).props().style['backgroundColor'], '#D8D8D8') - assert.equal(wrapper.find('.breadcrumb').at(2).props().style['backgroundColor'], '#FFFFFF') + assert.equal(wrapper.find('.breadcrumb').at(0).props().style.backgroundColor, '#FFFFFF') + assert.equal(wrapper.find('.breadcrumb').at(1).props().style.backgroundColor, '#D8D8D8') + assert.equal(wrapper.find('.breadcrumb').at(2).props().style.backgroundColor, '#FFFFFF') }) }) diff --git a/ui/app/components/ui/currency-input/tests/currency-input.component.test.js b/ui/app/components/ui/currency-input/tests/currency-input.component.test.js index 24c819e56..1e7936978 100644 --- a/ui/app/components/ui/currency-input/tests/currency-input.component.test.js +++ b/ui/app/components/ui/currency-input/tests/currency-input.component.test.js @@ -137,7 +137,7 @@ describe('CurrencyInput Component', function () { /> , { - context: { t: (str) => str + '_t' }, + context: { t: (str) => `${str}_t` }, childContextTypes: { t: PropTypes.func }, }, ) diff --git a/ui/app/components/ui/dropdown/dropdown.stories.js b/ui/app/components/ui/dropdown/dropdown.stories.js index 82dd1ca4d..1ecb31bc9 100644 --- a/ui/app/components/ui/dropdown/dropdown.stories.js +++ b/ui/app/components/ui/dropdown/dropdown.stories.js @@ -12,14 +12,13 @@ const unnamedOptions = [...Array(10).keys()].map((index) => { }) const namedOptions = unnamedOptions.map((option, index) => { - return Object.assign({}, option, { name: `Option ${index}` }) + return { ...option, name: `Option ${index}` } }) const namedOptionsWithVeryLongNames = unnamedOptions.map((option, index) => { - return Object.assign({}, option, { name: `Option ${index} with a very${', very'.repeat(index)} long name` }) + return { ...option, name: `Option ${index} with a very${', very'.repeat(index)} long name` } }) - export const simple = () => ( ( /> ) - export const approve = () => ( } diff --git a/ui/app/components/ui/page-container/page-container.component.js b/ui/app/components/ui/page-container/page-container.component.js index b4af4e719..fd3b2eede 100644 --- a/ui/app/components/ui/page-container/page-container.component.js +++ b/ui/app/components/ui/page-container/page-container.component.js @@ -75,9 +75,8 @@ export default class PageContainer extends PureComponent { return contentComponent } else if (tabsComponent) { return this.renderActiveTabContent() - } else { - return null } + return null } render () { diff --git a/ui/app/components/ui/sender-to-recipient/sender-to-recipient.component.js b/ui/app/components/ui/sender-to-recipient/sender-to-recipient.component.js index 7af7b2af7..de7e54745 100644 --- a/ui/app/components/ui/sender-to-recipient/sender-to-recipient.component.js +++ b/ui/app/components/ui/sender-to-recipient/sender-to-recipient.component.js @@ -9,7 +9,6 @@ import AccountMismatchWarning from '../account-mismatch-warning/account-mismatch import { useI18nContext } from '../../../hooks/useI18nContext' import { DEFAULT_VARIANT, CARDS_VARIANT, FLAT_VARIANT } from './sender-to-recipient.constants' - const variantHash = { [DEFAULT_VARIANT]: 'sender-to-recipient--default', [CARDS_VARIANT]: 'sender-to-recipient--cards', @@ -161,7 +160,6 @@ RecipientWithAddress.propTypes = { onRecipientClick: PropTypes.func, } - function Arrow ({ variant }) { return variant === DEFAULT_VARIANT ? ( diff --git a/ui/app/components/ui/text-field/text-field.component.js b/ui/app/components/ui/text-field/text-field.component.js index 008e621d4..9e80e3bc8 100644 --- a/ui/app/components/ui/text-field/text-field.component.js +++ b/ui/app/components/ui/text-field/text-field.component.js @@ -146,7 +146,7 @@ const getBorderedThemeInputProps = ({ disableUnderline: true, classes: { root: inputRoot, - input: input, + input, focused: inputFocused, }, inputProps: { diff --git a/ui/app/components/ui/token-input/tests/token-input.component.test.js b/ui/app/components/ui/token-input/tests/token-input.component.test.js index 3ff94d879..a7cda504f 100644 --- a/ui/app/components/ui/token-input/tests/token-input.component.test.js +++ b/ui/app/components/ui/token-input/tests/token-input.component.test.js @@ -32,7 +32,8 @@ describe('TokenInput Component', function () { }} /> , - { context: { t }, + { + context: { t }, childContextTypes: { t: PropTypes.func, }, @@ -66,7 +67,8 @@ describe('TokenInput Component', function () { tokenExchangeRates={{ '0x1': 2 }} /> , - { context: { t }, + { + context: { t }, childContextTypes: { t: PropTypes.func, }, diff --git a/ui/app/components/ui/unit-input/unit-input.component.js b/ui/app/components/ui/unit-input/unit-input.component.js index 6c43aaf26..6a9b76e7c 100644 --- a/ui/app/components/ui/unit-input/unit-input.component.js +++ b/ui/app/components/ui/unit-input/unit-input.component.js @@ -59,7 +59,7 @@ export default class UnitInput extends PureComponent { const valueString = String(value) const valueLength = valueString.length || 1 const decimalPointDeficit = valueString.match(/\./u) ? -0.5 : 0 - return (valueLength + decimalPointDeficit + 0.5) + 'ch' + return `${valueLength + decimalPointDeficit + 0.5}ch` } render () { diff --git a/ui/app/contexts/metametrics.js b/ui/app/contexts/metametrics.js index 19349bb5d..111622587 100644 --- a/ui/app/contexts/metametrics.js +++ b/ui/app/contexts/metametrics.js @@ -20,7 +20,6 @@ import { sendCountIsTrackable, } from '../helpers/utils/metametrics.util' - export const MetaMetricsContext = createContext(() => { captureException( Error(`MetaMetrics context function was called from a react node that is not a descendant of a MetaMetrics context provider`), diff --git a/ui/app/ducks/app/app.js b/ui/app/ducks/app/app.js index e7672dd37..2b905a1ac 100644 --- a/ui/app/ducks/app/app.js +++ b/ui/app/ducks/app/app.js @@ -5,7 +5,7 @@ const SET_THREEBOX_LAST_UPDATED = 'metamask/app/SET_THREEBOX_LAST_UPDATED' export default function reduceApp (state = {}, action) { // default state - const appState = Object.assign({ + const appState = { shouldClose: false, menuOpen: false, modal: { @@ -51,7 +51,8 @@ export default function reduceApp (state = {}, action) { requestAccountTabs: {}, openMetaMaskTabs: {}, currentWindowTab: {}, - }, state) + ...state, + } switch (action.type) { // dropdown methods @@ -108,7 +109,6 @@ export default function reduceApp (state = {}, action) { qrCodeData: action.value, } - // modal methods: case actionConstants.MODAL_OPEN: { const { name, ...modalProps } = action.payload @@ -118,7 +118,7 @@ export default function reduceApp (state = {}, action) { modal: { open: true, modalState: { - name: name, + name, props: { ...modalProps }, }, previousModalState: { ...appState.modal.modalState }, @@ -209,17 +209,16 @@ export default function reduceApp (state = {}, action) { txId: null, warning: null, } - } else { - return { - ...appState, - // indicate notification should close - shouldClose: true, - warning: null, - txId: null, - accountDetail: { - subview: 'transactions', - }, - } + } + return { + ...appState, + // indicate notification should close + shouldClose: true, + warning: null, + txId: null, + accountDetail: { + subview: 'transactions', + }, } case actionConstants.TRANSACTION_ERROR: diff --git a/ui/app/ducks/confirm-transaction/confirm-transaction.duck.js b/ui/app/ducks/confirm-transaction/confirm-transaction.duck.js index eb8975265..2285e8bd7 100644 --- a/ui/app/ducks/confirm-transaction/confirm-transaction.duck.js +++ b/ui/app/ducks/confirm-transaction/confirm-transaction.duck.js @@ -366,7 +366,6 @@ export function setTransactionToConfirm (transactionId) { if (txParams.data) { const { data } = txParams - const tokenData = getTokenData(data) dispatch(updateTokenData(tokenData)) diff --git a/ui/app/ducks/gas/gas-duck.test.js b/ui/app/ducks/gas/gas-duck.test.js index 4a7addaf6..d7ae9b873 100644 --- a/ui/app/ducks/gas/gas-duck.test.js +++ b/ui/app/ducks/gas/gas-duck.test.js @@ -288,7 +288,7 @@ describe('Gas Duck', function () { })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok( window.fetch.getCall(0).args[0].startsWith('https://ethgasstation.info/json/ethgasAPI.json'), @@ -296,7 +296,7 @@ describe('Gas Duck', function () { ) assert.deepEqual( mockDistpatch.getCall(1).args, - [{ type: SET_BASIC_PRICE_ESTIMATES_LAST_RETRIEVED, value: 2000000 } ], + [{ type: SET_BASIC_PRICE_ESTIMATES_LAST_RETRIEVED, value: 2000000 }], ) assert.deepEqual( mockDistpatch.getCall(2).args, @@ -334,14 +334,10 @@ describe('Gas Duck', function () { safeLow: 15, }) - await fetchBasicGasEstimates()(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - {}, - ) })) + await fetchBasicGasEstimates()(mockDistpatch, () => ({ gas: { ...initState } })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok(window.fetch.notCalled) assert.deepEqual( @@ -370,14 +366,10 @@ describe('Gas Duck', function () { .withArgs('BASIC_PRICE_ESTIMATES_LAST_RETRIEVED') .returns(2000000 - 1) // one second ago from "now" - await fetchBasicGasEstimates()(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - {}, - ) })) + await fetchBasicGasEstimates()(mockDistpatch, () => ({ gas: { ...initState } })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok( window.fetch.getCall(0).args[0].startsWith('https://ethgasstation.info/json/ethgasAPI.json'), @@ -385,7 +377,7 @@ describe('Gas Duck', function () { ) assert.deepEqual( mockDistpatch.getCall(1).args, - [{ type: SET_BASIC_PRICE_ESTIMATES_LAST_RETRIEVED, value: 2000000 } ], + [{ type: SET_BASIC_PRICE_ESTIMATES_LAST_RETRIEVED, value: 2000000 }], ) assert.deepEqual( mockDistpatch.getCall(2).args, @@ -412,16 +404,16 @@ describe('Gas Duck', function () { it('should call fetch with the expected params', async function () { const mockDistpatch = sinon.spy() - await fetchBasicGasAndTimeEstimates()(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - { basicPriceAndTimeEstimatesLastRetrieved: 1000000 }, - ), - metamask: { provider: { type: 'ropsten' } }, + await fetchBasicGasAndTimeEstimates()(mockDistpatch, () => ({ + gas: { + ...initState, + basicPriceAndTimeEstimatesLastRetrieved: 1000000, + }, + metamask: { provider: { type: 'ropsten' } }, })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok( window.fetch.getCall(0).args[0].startsWith('https://ethgasstation.info/json/ethgasAPI.json'), @@ -430,7 +422,7 @@ describe('Gas Duck', function () { assert.deepEqual( mockDistpatch.getCall(1).args, - [{ type: SET_BASIC_API_ESTIMATES_LAST_RETRIEVED, value: 2000000 } ], + [{ type: SET_BASIC_API_ESTIMATES_LAST_RETRIEVED, value: 2000000 }], ) assert.deepEqual( @@ -479,16 +471,15 @@ describe('Gas Duck', function () { speed: 'mockSpeed', }) - await fetchBasicGasAndTimeEstimates()(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - {}, - ), - metamask: { provider: { type: 'ropsten' } }, + await fetchBasicGasAndTimeEstimates()(mockDistpatch, () => ({ + gas: { + ...initState, + }, + metamask: { provider: { type: 'ropsten' } }, })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok(window.fetch.notCalled) @@ -523,16 +514,15 @@ describe('Gas Duck', function () { .withArgs('BASIC_GAS_AND_TIME_API_ESTIMATES_LAST_RETRIEVED') .returns(2000000 - 1) // one second ago from "now" - await fetchBasicGasAndTimeEstimates()(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - {}, - ), - metamask: { provider: { type: 'ropsten' } }, + await fetchBasicGasAndTimeEstimates()(mockDistpatch, () => ({ + gas: { + ...initState, + }, + metamask: { provider: { type: 'ropsten' } }, })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok( window.fetch.getCall(0).args[0].startsWith('https://ethgasstation.info/json/ethgasAPI.json'), @@ -541,7 +531,7 @@ describe('Gas Duck', function () { assert.deepEqual( mockDistpatch.getCall(1).args, - [{ type: SET_BASIC_API_ESTIMATES_LAST_RETRIEVED, value: 2000000 } ], + [{ type: SET_BASIC_API_ESTIMATES_LAST_RETRIEVED, value: 2000000 }], ) assert.deepEqual( @@ -574,16 +564,16 @@ describe('Gas Duck', function () { it('should call fetch with the expected params', async function () { const mockDistpatch = sinon.spy() - await fetchGasEstimates(5)(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - { priceAndTimeEstimatesLastRetrieved: 1000000 }, - ), - metamask: { provider: { type: 'ropsten' } }, + await fetchGasEstimates(5)(mockDistpatch, () => ({ + gas: { + ...initState, + priceAndTimeEstimatesLastRetrieved: 1000000, + }, + metamask: { provider: { type: 'ropsten' } }, })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: GAS_ESTIMATE_LOADING_STARTED }], ) assert.ok( window.fetch.getCall(0).args[0].startsWith('https://ethgasstation.info/json/predictTable.json'), @@ -611,10 +601,9 @@ describe('Gas Duck', function () { it('should not call fetch if the estimates were retrieved < 75000 ms ago', async function () { const mockDistpatch = sinon.spy() - await fetchGasEstimates(5)(mockDistpatch, () => ({ gas: Object.assign( - {}, - initState, - { + await fetchGasEstimates(5)(mockDistpatch, () => ({ + gas: { + ...initState, priceAndTimeEstimatesLastRetrieved: Date.now(), priceAndTimeEstimates: [{ expectedTime: '10', @@ -622,12 +611,11 @@ describe('Gas Duck', function () { gasprice: 50, }], }, - ), - metamask: { provider: { type: 'ropsten' } }, + metamask: { provider: { type: 'ropsten' } }, })) assert.deepEqual( mockDistpatch.getCall(0).args, - [{ type: GAS_ESTIMATE_LOADING_STARTED } ], + [{ type: GAS_ESTIMATE_LOADING_STARTED }], ) assert.equal(window.fetch.callCount, 0) @@ -741,5 +729,4 @@ describe('Gas Duck', function () { ) }) }) - }) diff --git a/ui/app/ducks/gas/gas.duck.js b/ui/app/ducks/gas/gas.duck.js index 8451c800a..9d83a66e0 100644 --- a/ui/app/ducks/gas/gas.duck.js +++ b/ui/app/ducks/gas/gas.duck.js @@ -194,8 +194,8 @@ async function queryEthGasStationPredictionTable () { 'referrerPolicy': 'no-referrer-when-downgrade', 'body': null, 'method': 'GET', - 'mode': 'cors' }, - ) + 'mode': 'cors', + }) } export function fetchBasicGasEstimates () { @@ -442,8 +442,7 @@ export function fetchGasEstimates (blockTime) { }) : Promise.resolve(priceAndTimeEstimates.length ? priceAndTimeEstimates - : loadLocalStorageData('GAS_API_ESTIMATES'), - ) + : loadLocalStorageData('GAS_API_ESTIMATES')) return promiseToFetch.then((estimates) => { dispatch(setPricesAndTimeEstimates(estimates)) diff --git a/ui/app/ducks/metamask/metamask.js b/ui/app/ducks/metamask/metamask.js index 097afee7e..c2058fc06 100644 --- a/ui/app/ducks/metamask/metamask.js +++ b/ui/app/ducks/metamask/metamask.js @@ -2,7 +2,7 @@ import * as actionConstants from '../../store/actionConstants' import { ALERT_TYPES } from '../../../../app/scripts/controllers/alert' export default function reduceMetamask (state = {}, action) { - const metamaskState = Object.assign({ + const metamaskState = { isInitialized: false, isUnlocked: false, isAccountMenuOpen: false, @@ -46,7 +46,8 @@ export default function reduceMetamask (state = {}, action) { participateInMetaMetrics: null, metaMetricsSendCount: 0, nextNonce: null, - }, state) + ...state, + } switch (action.type) { @@ -88,8 +89,8 @@ export default function reduceMetamask (state = {}, action) { const { account } = action.value const name = action.value.label const id = {} - id[account] = Object.assign({}, metamaskState.identities[account], { name }) - const identities = Object.assign({}, metamaskState.identities, id) + id[account] = { ...metamaskState.identities[account], name } + const identities = { ...metamaskState.identities, ...id } return Object.assign(metamaskState, { identities }) } @@ -272,7 +273,7 @@ export default function reduceMetamask (state = {}, action) { let { currentNetworkTxList } = metamaskState currentNetworkTxList = currentNetworkTxList.map((tx) => { if (tx.id === txId) { - const newTx = Object.assign({}, tx) + const newTx = { ...tx } newTx.txParams = value return newTx } diff --git a/ui/app/helpers/utils/confirm-tx.util.js b/ui/app/helpers/utils/confirm-tx.util.js index 7f456984d..a6319ef97 100644 --- a/ui/app/helpers/utils/confirm-tx.util.js +++ b/ui/app/helpers/utils/confirm-tx.util.js @@ -11,7 +11,6 @@ import { conversionGreaterThan, } from './conversion-util' - export function increaseLastGasPrice (lastGasPrice) { return ethUtil.addHexPrefix(multiplyCurrencies(lastGasPrice || '0x0', 1.1, { multiplicandBase: 16, diff --git a/ui/app/helpers/utils/fetch-with-cache.js b/ui/app/helpers/utils/fetch-with-cache.js index 1b9693d81..470f2a8d6 100644 --- a/ui/app/helpers/utils/fetch-with-cache.js +++ b/ui/app/helpers/utils/fetch-with-cache.js @@ -24,30 +24,29 @@ const fetchWithCache = async (url, fetchOptions = {}, { cacheRefreshTime = 36000 const { cachedResponse, cachedTime } = cachedFetch[url] || {} if (cachedResponse && currentTime - cachedTime < cacheRefreshTime) { return cachedResponse - } else { - fetchOptions.headers.set('Content-Type', 'application/json') - const _fetch = timeout ? - fetchWithTimeout({ timeout }) : - window.fetch - const response = await _fetch(url, { - referrerPolicy: 'no-referrer-when-downgrade', - body: null, - method: 'GET', - mode: 'cors', - ...fetchOptions, - }) - if (!response.ok) { - throw new Error(`Fetch failed with status '${response.status}': '${response.statusText}'`) - } - const responseJson = await response.json() - const cacheEntry = { - cachedResponse: responseJson, - cachedTime: currentTime, - } - cachedFetch[url] = cacheEntry - saveLocalStorageData(cachedFetch, 'cachedFetch') - return responseJson } + fetchOptions.headers.set('Content-Type', 'application/json') + const _fetch = timeout + ? fetchWithTimeout({ timeout }) + : window.fetch + const response = await _fetch(url, { + referrerPolicy: 'no-referrer-when-downgrade', + body: null, + method: 'GET', + mode: 'cors', + ...fetchOptions, + }) + if (!response.ok) { + throw new Error(`Fetch failed with status '${response.status}': '${response.statusText}'`) + } + const responseJson = await response.json() + const cacheEntry = { + cachedResponse: responseJson, + cachedTime: currentTime, + } + cachedFetch[url] = cacheEntry + saveLocalStorageData(cachedFetch, 'cachedFetch') + return responseJson } export default fetchWithCache diff --git a/ui/app/helpers/utils/formatters.js b/ui/app/helpers/utils/formatters.js index 106a2520d..d722ef09b 100644 --- a/ui/app/helpers/utils/formatters.js +++ b/ui/app/helpers/utils/formatters.js @@ -1,3 +1,3 @@ export function formatETHFee (ethFee) { - return ethFee + ' ETH' + return `${ethFee} ETH` } diff --git a/ui/app/helpers/utils/gas-time-estimates.util.js b/ui/app/helpers/utils/gas-time-estimates.util.js index 7e143a028..5aadacf3a 100644 --- a/ui/app/helpers/utils/gas-time-estimates.util.js +++ b/ui/app/helpers/utils/gas-time-estimates.util.js @@ -47,8 +47,8 @@ export function formatTimeEstimate (totalSeconds, greaterThanMax, lessThanMin) { symbol = '> ' } - const formattedMin = `${minutes ? minutes + ' min' : ''}` - const formattedSec = `${seconds ? seconds + ' sec' : ''}` + const formattedMin = `${minutes ? `${minutes} min` : ''}` + const formattedSec = `${seconds ? `${seconds} sec` : ''}` const formattedCombined = formattedMin && formattedSec ? `${symbol}${formattedMin} ${formattedSec}` : symbol + (formattedMin || formattedSec) diff --git a/ui/app/helpers/utils/i18n-helper.test.js b/ui/app/helpers/utils/i18n-helper.test.js index 252cbe3f3..4e41f8c20 100644 --- a/ui/app/helpers/utils/i18n-helper.test.js +++ b/ui/app/helpers/utils/i18n-helper.test.js @@ -118,42 +118,42 @@ describe('i18n helper', function () { }) it('should return the correct message when a single non-react substitution is made', function () { - const result = t(TEST_KEY_2, [ TEST_SUBSTITUTION_1 ]) + const result = t(TEST_KEY_2, [TEST_SUBSTITUTION_1]) assert.equal(result, `This is a message with a single non-react substitution ${TEST_SUBSTITUTION_1}.`) }) it('should return the correct message when two non-react substitutions are made', function () { - const result = t(TEST_KEY_3, [ TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_2 ]) + const result = t(TEST_KEY_3, [TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_2]) assert.equal(result, `This is a message with two non-react substitutions ${TEST_SUBSTITUTION_1} and ${TEST_SUBSTITUTION_2}.`) }) it('should return the correct message when multiple non-react substitutions are made', function () { - const result = t(TEST_KEY_4, [ TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_2, TEST_SUBSTITUTION_3, TEST_SUBSTITUTION_4, TEST_SUBSTITUTION_5 ]) + const result = t(TEST_KEY_4, [TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_2, TEST_SUBSTITUTION_3, TEST_SUBSTITUTION_4, TEST_SUBSTITUTION_5]) assert.equal(result, `${TEST_SUBSTITUTION_1} - ${TEST_SUBSTITUTION_2} - ${TEST_SUBSTITUTION_3} - ${TEST_SUBSTITUTION_4} - ${TEST_SUBSTITUTION_5}`) }) it('should correctly render falsey substitutions', function () { - const result = t(TEST_KEY_4, [ 0, -0, '', false, NaN ]) + const result = t(TEST_KEY_4, [0, -0, '', false, NaN]) assert.equal(result, '0 - 0 - - false - NaN') }) it('should render nothing for "null" and "undefined" substitutions', function () { - const result = t(TEST_KEY_5, [ null, TEST_SUBSTITUTION_2 ]) + const result = t(TEST_KEY_5, [null, TEST_SUBSTITUTION_2]) assert.equal(result, ` - ${TEST_SUBSTITUTION_2} - `) }) it('should return the correct message when a single react substitution is made', function () { - const result = t(TEST_KEY_6, [ TEST_SUBSTITUTION_6 ]) + const result = t(TEST_KEY_6, [TEST_SUBSTITUTION_6]) assert.equal(shallow(result).html(), ' Testing a react substitution
TEST_SUBSTITUTION_1
.
') }) it('should return the correct message when two react substitutions are made', function () { - const result = t(TEST_KEY_7, [ TEST_SUBSTITUTION_7_1, TEST_SUBSTITUTION_7_2 ]) + const result = t(TEST_KEY_7, [TEST_SUBSTITUTION_7_1, TEST_SUBSTITUTION_7_2]) assert.equal(shallow(result).html(), ' Testing a react substitution
TEST_SUBSTITUTION_1
and another
TEST_SUBSTITUTION_2
.
') }) it('should return the correct message when substituting a mix of react elements and strings', function () { - const result = t(TEST_KEY_8, [ TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_8_1, TEST_SUBSTITUTION_2, TEST_SUBSTITUTION_8_2 ]) + const result = t(TEST_KEY_8, [TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_8_1, TEST_SUBSTITUTION_2, TEST_SUBSTITUTION_8_2]) assert.equal(shallow(result).html(), ' Testing a mix TEST_SUBSTITUTION_1 of react substitutions
TEST_SUBSTITUTION_3
and string substitutions TEST_SUBSTITUTION_2 +
TEST_SUBSTITUTION_4
.
') }) }) diff --git a/ui/app/helpers/utils/metametrics.util.js b/ui/app/helpers/utils/metametrics.util.js index ce76b8385..41a4bb22d 100644 --- a/ui/app/helpers/utils/metametrics.util.js +++ b/ui/app/helpers/utils/metametrics.util.js @@ -52,6 +52,7 @@ const customVariableNameIdMap = { [METAMETRICS_CUSTOM_GAS_CHANGED]: 1, [METAMETRICS_CUSTOM_ASSET_SELECTED]: 2, } + /** ********************************************************** **/ const METAMETRICS_CUSTOM_NETWORK = 'network' @@ -182,7 +183,7 @@ function composeUrl (config) { uid = `&uid=${metaMetricsId.slice(2, 18)}` } - return [ base, e_c, e_a, e_n, cvar, action_name, urlref, dimensions, url, _id, rand, pv_id, uid, new_visit ].join('') + return [base, e_c, e_a, e_n, cvar, action_name, urlref, dimensions, url, _id, rand, pv_id, uid, new_visit].join('') } export function sendMetaMetricsEvent (config) { @@ -209,9 +210,8 @@ export function verifyUserPermission (config, props) { return true } else if (allowSendMetrics && eventOpts.name === 'send') { return true - } else { - return false } + return false } const trackableSendCounts = { diff --git a/ui/app/helpers/utils/transactions.util.js b/ui/app/helpers/utils/transactions.util.js index d94bd24d8..3c6481c80 100644 --- a/ui/app/helpers/utils/transactions.util.js +++ b/ui/app/helpers/utils/transactions.util.js @@ -27,7 +27,6 @@ import { } from '../constants/transactions' import fetchWithCache from './fetch-with-cache' - import { addCurrencies } from './conversion-util' abiDecoder.addABI(abi) @@ -46,9 +45,8 @@ async function getMethodFrom4Byte (fourBytePrefix) { if (fourByteResponse.count === 1) { return fourByteResponse.results[0].text_signature - } else { - return null } + return null } let registry @@ -142,9 +140,8 @@ export function getTransactionActionKey (transaction) { return DECRYPT_REQUEST_KEY } else if (type === MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY) { return ENCRYPTION_PUBLIC_KEY_REQUEST_KEY - } else { - return SIGNATURE_REQUEST_KEY } + return SIGNATURE_REQUEST_KEY } if (isConfirmDeployContract(transaction)) { @@ -185,9 +182,8 @@ export function getLatestSubmittedTxWithNonce (transactions = [], nonce = '0x0') return current } return submittedTime > acc.submittedTime ? current : acc - } else { - return acc } + return acc }, {}) } diff --git a/ui/app/helpers/utils/util.js b/ui/app/helpers/utils/util.js index 0d2e741cf..3382104fd 100644 --- a/ui/app/helpers/utils/util.js +++ b/ui/app/helpers/utils/util.js @@ -59,7 +59,7 @@ export function addressSummary (address, firstSegLength = 10, lastSegLength = 4, if (!includeHex) { checked = ethUtil.stripHexPrefix(checked) } - return checked ? checked.slice(0, firstSegLength) + '...' + checked.slice(checked.length - lastSegLength) : '...' + return checked ? `${checked.slice(0, firstSegLength)}...${checked.slice(checked.length - lastSegLength)}` : '...' } export function isValidAddress (address) { @@ -106,7 +106,7 @@ export function parseBalance (balance) { const trailingZeros = /0+$/u const beforeDecimal = weiString.length > 18 ? weiString.slice(0, weiString.length - 18) : '0' - afterDecimal = ('000000000000000000' + wei).slice(-18).replace(trailingZeros, '') + afterDecimal = (`000000000000000000${wei}`).slice(-18).replace(trailingZeros, '') if (afterDecimal === '') { afterDecimal = '0' } @@ -127,14 +127,14 @@ export function formatBalance (balance, decimalsToKeep, needsParse = true, ticke if (sigFigs) { afterDecimal = sigFigs[0] } - formatted = '0.' + afterDecimal + ` ${ticker}` + formatted = `0.${afterDecimal} ${ticker}` } } else { - formatted = beforeDecimal + '.' + afterDecimal.slice(0, 3) + ` ${ticker}` + formatted = `${beforeDecimal}.${afterDecimal.slice(0, 3)} ${ticker}` } } else { afterDecimal += Array(decimalsToKeep).join('0') - formatted = beforeDecimal + '.' + afterDecimal.slice(0, decimalsToKeep) + ` ${ticker}` + formatted = `${beforeDecimal}.${afterDecimal.slice(0, decimalsToKeep)} ${ticker}` } return formatted } @@ -177,12 +177,10 @@ export function shortenBalance (balance, decimalsToKeep = 1) { const stringBalance = convertedBalance.toString() if (stringBalance.split('.')[1].length > 3) { return convertedBalance.toFixed(3) - } else { - return stringBalance } - } else { - return convertedBalance.toFixed(decimalsToKeep) + return stringBalance } + return convertedBalance.toFixed(decimalsToKeep) } // Takes a BN and an ethereum currency name, diff --git a/ui/app/helpers/utils/util.test.js b/ui/app/helpers/utils/util.test.js index 8a2aa1ceb..0a930e413 100644 --- a/ui/app/helpers/utils/util.test.js +++ b/ui/app/helpers/utils/util.test.js @@ -356,7 +356,7 @@ describe('util', function () { { args: ['0.0', 9], result: '0' }, { args: ['0.000000000000', 9], result: '0' }, { args: ['1', 9], result: '1' }, - { args: [1 ], result: '1' }, + { args: [1], result: '1' }, { args: ['1.0', 9], result: '1' }, { args: ['1.000000000', 9], result: '1' }, { args: ['000000001', 9], result: '1' }, diff --git a/ui/app/hooks/tests/useCancelTransaction.test.js b/ui/app/hooks/tests/useCancelTransaction.test.js index e27eb3586..a355ee5e5 100644 --- a/ui/app/hooks/tests/useCancelTransaction.test.js +++ b/ui/app/hooks/tests/useCancelTransaction.test.js @@ -8,7 +8,6 @@ import { useCancelTransaction } from '../useCancelTransaction' import { showModal } from '../../store/actions' import { increaseLastGasPrice } from '../../helpers/utils/confirm-tx.util' - describe('useCancelTransaction', function () { let useSelector const dispatch = sinon.spy() @@ -64,7 +63,6 @@ describe('useCancelTransaction', function () { }) }) - describe('when account has sufficient balance to cover gas', function () { before(function () { useSelector = sinon.stub(reactRedux, 'useSelector') @@ -108,7 +106,6 @@ describe('useCancelTransaction', function () { }) }) - after(function () { sinon.restore() }) diff --git a/ui/app/hooks/tests/useCurrencyDisplay.test.js b/ui/app/hooks/tests/useCurrencyDisplay.test.js index 7be42cd50..8b3f6910a 100644 --- a/ui/app/hooks/tests/useCurrencyDisplay.test.js +++ b/ui/app/hooks/tests/useCurrencyDisplay.test.js @@ -95,7 +95,6 @@ const tests = [ }, ] - describe('useCurrencyDisplay', function () { tests.forEach(({ input: { value, ...restProps }, result }) => { describe(`when input is { value: ${value}, decimals: ${restProps.numberOfDecimals}, denomation: ${restProps.denomination} }`, function () { @@ -111,7 +110,7 @@ describe('useCurrencyDisplay', function () { return undefined }) const hookReturn = renderHook(() => useCurrencyDisplay(value, restProps)) - const [ displayValue, parts ] = hookReturn.result.current + const [displayValue, parts] = hookReturn.result.current stub.restore() it(`should return ${result.displayValue} as displayValue`, function () { assert.equal(displayValue, result.displayValue) diff --git a/ui/app/hooks/tests/useTokenDisplayValue.test.js b/ui/app/hooks/tests/useTokenDisplayValue.test.js index ce596168f..ed0c81e4f 100644 --- a/ui/app/hooks/tests/useTokenDisplayValue.test.js +++ b/ui/app/hooks/tests/useTokenDisplayValue.test.js @@ -118,7 +118,6 @@ const tests = [ }, ] - describe('useTokenDisplayValue', function () { tests.forEach((test, idx) => { describe(`when input is decimals: ${test.token.decimals} and value: ${test.tokenValue}`, function () { diff --git a/ui/app/hooks/tests/useTransactionDisplayData.test.js b/ui/app/hooks/tests/useTransactionDisplayData.test.js index 133c9291a..a8eb15148 100644 --- a/ui/app/hooks/tests/useTransactionDisplayData.test.js +++ b/ui/app/hooks/tests/useTransactionDisplayData.test.js @@ -11,9 +11,9 @@ import * as i18nhooks from '../useI18nContext' import { getMessage } from '../../helpers/utils/i18n-helper' import messages from '../../../../app/_locales/en/messages.json' - const expectedResults = [ - { title: 'Send ETH', + { + title: 'Send ETH', category: 'send', subtitle: 'To: 0xffe5...1a97', subtitleContainsOrigin: false, @@ -23,8 +23,10 @@ const expectedResults = [ recipientAddress: '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', secondaryCurrency: '-1 ETH', isPending: false, - status: 'confirmed' }, - { title: 'Send ETH', + status: 'confirmed', + }, + { + title: 'Send ETH', category: 'send', subtitle: 'To: 0x0ccc...8848', subtitleContainsOrigin: false, @@ -34,8 +36,10 @@ const expectedResults = [ recipientAddress: '0x0ccc8aeeaf5ce790f3b448325981a143fdef8848', secondaryCurrency: '-2 ETH', isPending: false, - status: 'confirmed' }, - { title: 'Send ETH', + status: 'confirmed', + }, + { + title: 'Send ETH', category: 'send', subtitle: 'To: 0xffe5...1a97', subtitleContainsOrigin: false, @@ -45,8 +49,10 @@ const expectedResults = [ recipientAddress: '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', secondaryCurrency: '-2 ETH', isPending: false, - status: 'confirmed' }, - { title: 'Receive', + status: 'confirmed', + }, + { + title: 'Receive', category: 'receive', subtitle: 'From: 0x31b9...4523', subtitleContainsOrigin: false, @@ -56,8 +62,10 @@ const expectedResults = [ recipientAddress: '0x9eca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: '18.75 ETH', isPending: false, - status: 'confirmed' }, - { title: 'Receive', + status: 'confirmed', + }, + { + title: 'Receive', category: 'receive', subtitle: 'From: 0x9eca...a149', subtitleContainsOrigin: false, @@ -67,8 +75,10 @@ const expectedResults = [ recipientAddress: '0x9eca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: '0 ETH', isPending: false, - status: 'confirmed' }, - { title: 'Receive', + status: 'confirmed', + }, + { + title: 'Receive', category: 'receive', subtitle: 'From: 0xee01...febb', subtitleContainsOrigin: false, @@ -78,7 +88,8 @@ const expectedResults = [ recipientAddress: '0x9eca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: '1 ETH', isPending: false, - status: 'confirmed' }, + status: 'confirmed', + }, ] let useSelector, useI18nContext, useTokenFiatAmount @@ -105,9 +116,8 @@ describe('useTransactionDisplayData', function () { return 'ETH' } else if (selector === getCurrentCurrency) { return 'ETH' - } else { - return null } + return null }) }) transactions.forEach((transactionGroup, idx) => { diff --git a/ui/app/hooks/tests/useUserPreferencedCurrency.test.js b/ui/app/hooks/tests/useUserPreferencedCurrency.test.js index 65fe25c8e..b5d7b47e9 100644 --- a/ui/app/hooks/tests/useUserPreferencedCurrency.test.js +++ b/ui/app/hooks/tests/useUserPreferencedCurrency.test.js @@ -117,13 +117,11 @@ function getFakeUseSelector (state) { return state } else if (selector === getShouldShowFiat) { return state.showFiat - } else { - return state.nativeCurrency } + return state.nativeCurrency } } - describe('useUserPreferencedCurrency', function () { tests.forEach(({ params: { type, ...otherParams }, state, result }) => { describe(`when showFiat is ${state.showFiat}, useNativeCurrencyAsPrimary is ${state.useNativeCurrencyAsPrimaryCurrency} and type is ${type}`, function () { diff --git a/ui/app/hooks/useCancelTransaction.js b/ui/app/hooks/useCancelTransaction.js index 4dc19bae9..547697360 100644 --- a/ui/app/hooks/useCancelTransaction.js +++ b/ui/app/hooks/useCancelTransaction.js @@ -5,7 +5,6 @@ import { isBalanceSufficient } from '../pages/send/send.utils' import { getHexGasTotal, increaseLastGasPrice } from '../helpers/utils/confirm-tx.util' import { getConversionRate, getSelectedAccount } from '../selectors' - /** * Determine whether a transaction can be cancelled and provide a method to * kick off the process of cancellation. @@ -29,7 +28,6 @@ export function useCancelTransaction (transactionGroup) { return dispatch(showModal({ name: 'CANCEL_TRANSACTION', transactionId: id, originalGasPrice: gasPrice })) }, [dispatch, id, gasPrice]) - const hasEnoughCancelGas = primaryTransaction.txParams && isBalanceSufficient({ amount: '0x0', gasTotal: getHexGasTotal({ diff --git a/ui/app/hooks/useCurrencyDisplay.js b/ui/app/hooks/useCurrencyDisplay.js index 17568b874..4e2c99e3f 100644 --- a/ui/app/hooks/useCurrencyDisplay.js +++ b/ui/app/hooks/useCurrencyDisplay.js @@ -61,6 +61,5 @@ export function useCurrencyDisplay (inputValue, { displayValue, prefix, numberOf suffix = opts.suffix || toCurrency.toUpperCase() } - - return [`${prefix || ''}${value}${suffix ? ' ' + suffix : ''}`, { prefix, value, suffix }] + return [`${prefix || ''}${value}${suffix ? ` ${suffix}` : ''}`, { prefix, value, suffix }] } diff --git a/ui/app/hooks/useMetricEvent.js b/ui/app/hooks/useMetricEvent.js index a5a883b5f..a701bd933 100644 --- a/ui/app/hooks/useMetricEvent.js +++ b/ui/app/hooks/useMetricEvent.js @@ -1,7 +1,6 @@ import { useContext, useCallback } from 'react' import { MetaMetricsContext } from '../contexts/metametrics' - export function useMetricEvent (config = {}, overrides = {}) { const metricsEvent = useContext(MetaMetricsContext) const trackEvent = useCallback(() => metricsEvent(config, overrides), [config, metricsEvent, overrides]) diff --git a/ui/app/hooks/useRetryTransaction.js b/ui/app/hooks/useRetryTransaction.js index 9b0a9e5f5..1f3ffe701 100644 --- a/ui/app/hooks/useRetryTransaction.js +++ b/ui/app/hooks/useRetryTransaction.js @@ -10,7 +10,6 @@ import { import { increaseLastGasPrice } from '../helpers/utils/confirm-tx.util' import { useMetricEvent } from './useMetricEvent' - /** * Provides a reusable hook that, given a transactionGroup, will return * a method for beginning the retry process diff --git a/ui/app/hooks/useTokenTracker.js b/ui/app/hooks/useTokenTracker.js index fe8eba61b..55a92273b 100644 --- a/ui/app/hooks/useTokenTracker.js +++ b/ui/app/hooks/useTokenTracker.js @@ -3,7 +3,6 @@ import TokenTracker from '@metamask/eth-token-tracker' import { useSelector } from 'react-redux' import { getCurrentNetwork, getSelectedAddress } from '../selectors' - export function useTokenTracker (tokens) { const network = useSelector(getCurrentNetwork) const userAddress = useSelector(getSelectedAddress) @@ -57,7 +56,6 @@ export function useTokenTracker (tokens) { return teardownTracker }, [teardownTracker]) - // Effect to set loading state and initialize tracker when values change useEffect(() => { // This effect will only run initially and when: diff --git a/ui/app/hooks/useTransactionTimeRemaining.js b/ui/app/hooks/useTransactionTimeRemaining.js index 825d68552..10ac8545f 100644 --- a/ui/app/hooks/useTransactionTimeRemaining.js +++ b/ui/app/hooks/useTransactionTimeRemaining.js @@ -64,7 +64,7 @@ export function useTransactionTimeRemaining ( captureException(error) return NaN } - }, [ currentGasPrice, gasPrices, estimatedTimes ]) + }, [currentGasPrice, gasPrices, estimatedTimes]) useEffect(() => { if ( diff --git a/ui/app/pages/add-token/tests/add-token.test.js b/ui/app/pages/add-token/tests/add-token.test.js index 6fff131cc..8138845e7 100644 --- a/ui/app/pages/add-token/tests/add-token.test.js +++ b/ui/app/pages/add-token/tests/add-token.test.js @@ -4,7 +4,7 @@ import { Provider } from 'react-redux' import sinon from 'sinon' import configureMockStore from 'redux-mock-store' import { mountWithRouter } from '../../../../../test/lib/render-helpers' -import AddToken from '../index' +import AddToken from '..' describe('Add Token', function () { let wrapper @@ -58,7 +58,6 @@ describe('Add Token', function () { assert.equal(wrapper.find('AddToken').instance().state.customAddress, tokenAddress) }) - it('edits token symbol', function () { const tokenSymbol = 'META' const event = { target: { value: tokenSymbol } } diff --git a/ui/app/pages/add-token/token-search/token-search.component.js b/ui/app/pages/add-token/token-search/token-search.component.js index 82aaae3fc..460c7f15f 100644 --- a/ui/app/pages/add-token/token-search/token-search.component.js +++ b/ui/app/pages/add-token/token-search/token-search.component.js @@ -6,7 +6,7 @@ import InputAdornment from '@material-ui/core/InputAdornment' import TextField from '../../../components/ui/text-field' const contractList = Object.entries(contractMap) - .map(([address, tokenData]) => Object.assign({}, tokenData, { address })) + .map(([address, tokenData]) => ({ ...tokenData, address })) .filter((tokenData) => Boolean(tokenData.erc20)) const fuse = new Fuse(contractList, { diff --git a/ui/app/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js b/ui/app/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js index 876fbd761..28b04ba40 100644 --- a/ui/app/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js +++ b/ui/app/pages/confirm-add-suggested-token/confirm-add-suggested-token.component.js @@ -92,7 +92,7 @@ export default class ConfirmAddSuggestedToken extends Component {
{ Object.entries(pendingTokens) - .map(([ address, token ]) => { + .map(([address, token]) => { const { name, symbol, image } = token return ( diff --git a/ui/app/pages/confirm-add-token/confirm-add-token.component.js b/ui/app/pages/confirm-add-token/confirm-add-token.component.js index 2f98242eb..f79d962eb 100644 --- a/ui/app/pages/confirm-add-token/confirm-add-token.component.js +++ b/ui/app/pages/confirm-add-token/confirm-add-token.component.js @@ -58,7 +58,7 @@ export default class ConfirmAddToken extends Component {
{ Object.entries(pendingTokens) - .map(([ address, token ]) => { + .map(([address, token]) => { const { name, symbol } = token return ( diff --git a/ui/app/pages/confirm-decrypt-message/confirm-decrypt-message.container.js b/ui/app/pages/confirm-decrypt-message/confirm-decrypt-message.container.js index a73649484..57d00021a 100644 --- a/ui/app/pages/confirm-decrypt-message/confirm-decrypt-message.container.js +++ b/ui/app/pages/confirm-decrypt-message/confirm-decrypt-message.container.js @@ -17,7 +17,8 @@ import { getMostRecentOverviewPage } from '../../ducks/history/history' import ConfirmDecryptMessage from './confirm-decrypt-message.component' function mapStateToProps (state) { - const { confirmTransaction, + const { + confirmTransaction, metamask: { domainMetadata = {} }, } = state @@ -30,7 +31,7 @@ function mapStateToProps (state) { const fromAccount = getTargetAccountWithSendEtherInfo(state, from) return { - txData: txData, + txData, domainMetadata, fromAccount, requester: null, diff --git a/ui/app/pages/confirm-encryption-public-key/confirm-encryption-public-key.container.js b/ui/app/pages/confirm-encryption-public-key/confirm-encryption-public-key.container.js index 1c376ff5a..7a0b2c37f 100644 --- a/ui/app/pages/confirm-encryption-public-key/confirm-encryption-public-key.container.js +++ b/ui/app/pages/confirm-encryption-public-key/confirm-encryption-public-key.container.js @@ -18,7 +18,8 @@ import { getMostRecentOverviewPage } from '../../ducks/history/history' import ConfirmEncryptionPublicKey from './confirm-encryption-public-key.component' function mapStateToProps (state) { - const { confirmTransaction, + const { + confirmTransaction, metamask: { domainMetadata = {} }, } = state @@ -31,8 +32,8 @@ function mapStateToProps (state) { const fromAccount = getTargetAccountWithSendEtherInfo(state, from) return { - txData: txData, - domainMetadata: domainMetadata, + txData, + domainMetadata, fromAccount, requester: null, requesterAddress: null, diff --git a/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.component.js b/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.component.js index 8aea19663..ca690a61a 100644 --- a/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.component.js +++ b/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.component.js @@ -89,12 +89,11 @@ export default class ConfirmTokenTransactionBase extends Component { if (typeof contractExchangeRate === 'undefined') { return formatCurrency(fiatTransactionTotal, currentCurrency) - } else { - const fiatTransactionAmount = this.getFiatTransactionAmount() - const fiatTotal = addFiat(fiatTransactionAmount, fiatTransactionTotal) - const roundedFiatTotal = roundExponential(fiatTotal) - return formatCurrency(roundedFiatTotal, currentCurrency) } + const fiatTransactionAmount = this.getFiatTransactionAmount() + const fiatTotal = addFiat(fiatTransactionAmount, fiatTransactionTotal) + const roundedFiatTotal = roundExponential(fiatTotal) + return formatCurrency(roundedFiatTotal, currentCurrency) } render () { diff --git a/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.container.js b/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.container.js index f6e0a270d..8583ea238 100644 --- a/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.container.js +++ b/ui/app/pages/confirm-token-transaction-base/confirm-token-transaction-base.container.js @@ -16,7 +16,6 @@ import { } from '../../helpers/utils/token-util' import ConfirmTokenTransactionBase from './confirm-token-transaction-base.component' - const mapStateToProps = (state, ownProps) => { const { match: { params = {} } } = ownProps const { id: paramsTransactionId } = params diff --git a/ui/app/pages/confirm-transaction/conf-tx.js b/ui/app/pages/confirm-transaction/conf-tx.js index 0d7be5418..f9dbde2a5 100644 --- a/ui/app/pages/confirm-transaction/conf-tx.js +++ b/ui/app/pages/confirm-transaction/conf-tx.js @@ -105,7 +105,7 @@ class ConfirmTxScreen extends Component { log.info(`rendering a combined ${unconfTxList.length} unconf msgs & txs`) return transactionId - ? unconfTxList.find(({ id }) => id + '' === transactionId) + ? unconfTxList.find(({ id }) => `${id}` === transactionId) : unconfTxList[index] } @@ -195,7 +195,7 @@ class ConfirmTxScreen extends Component { let prevTx if (transactionId) { - prevTx = currentNetworkTxList.find(({ id }) => id + '' === transactionId) + prevTx = currentNetworkTxList.find(({ id }) => `${id}` === transactionId) } else { const { index: prevIndex, unapprovedTxs: prevUnapprovedTxs } = prevProps const prevUnconfTxList = txHelper(prevUnapprovedTxs, {}, {}, {}, network) diff --git a/ui/app/pages/confirm-transaction/confirm-transaction.component.js b/ui/app/pages/confirm-transaction/confirm-transaction.component.js index 69af2c226..087b8e8b4 100644 --- a/ui/app/pages/confirm-transaction/confirm-transaction.component.js +++ b/ui/app/pages/confirm-transaction/confirm-transaction.component.js @@ -95,13 +95,10 @@ export default class ConfirmTransaction extends Component { clearConfirmTransaction() getContractMethodData(data) setTransactionToConfirm(paramsTransactionId) - return } else if (prevProps.transactionId && !transactionId && !totalUnapprovedCount) { history.replace(mostRecentOverviewPage) - return } else if (prevProps.transactionId && transactionId && prevProps.transactionId !== transactionId) { history.replace(mostRecentOverviewPage) - return } } diff --git a/ui/app/pages/create-account/connect-hardware/account-list.js b/ui/app/pages/create-account/connect-hardware/account-list.js index cac29cdf0..f1f54ddbc 100644 --- a/ui/app/pages/create-account/connect-hardware/account-list.js +++ b/ui/app/pages/create-account/connect-hardware/account-list.js @@ -181,7 +181,6 @@ class AccountList extends Component { } - AccountList.propTypes = { onPathChange: PropTypes.func.isRequired, selectedPath: PropTypes.string.isRequired, diff --git a/ui/app/pages/create-account/connect-hardware/index.js b/ui/app/pages/create-account/connect-hardware/index.js index 689b6058d..4e537cacf 100644 --- a/ui/app/pages/create-account/connect-hardware/index.js +++ b/ui/app/pages/create-account/connect-hardware/index.js @@ -29,7 +29,6 @@ class ConnectHardwareForm extends Component { this.setState({ accounts: newAccounts }) } - componentDidMount () { this.checkIfUnlocked() } @@ -99,7 +98,6 @@ class ConnectHardwareForm extends Component { newState.selectedAccount = null } - // Map accounts with balances newState.accounts = accounts.map((account) => { const normalizedAddress = account.address.toLowerCase() @@ -148,7 +146,7 @@ class ConnectHardwareForm extends Component { eventOpts: { category: 'Accounts', action: 'Connected Hardware Wallet', - name: 'Connected Account with: ' + device, + name: `Connected Account with: ${device}`, }, }) history.push(mostRecentOverviewPage) diff --git a/ui/app/pages/create-account/connect-hardware/select-hardware.js b/ui/app/pages/create-account/connect-hardware/select-hardware.js index 5c16bd452..02c26c95e 100644 --- a/ui/app/pages/create-account/connect-hardware/select-hardware.js +++ b/ui/app/pages/create-account/connect-hardware/select-hardware.js @@ -133,7 +133,6 @@ export default class SelectHardware extends Component { ) } - scrollToTutorial = () => { if (this.referenceNode) { this.referenceNode.scrollIntoView({ behavior: 'smooth' }) diff --git a/ui/app/pages/create-account/import-account/json.js b/ui/app/pages/create-account/import-account/json.js index cd81fd8c6..1edaed355 100644 --- a/ui/app/pages/create-account/import-account/json.js +++ b/ui/app/pages/create-account/import-account/json.js @@ -107,7 +107,7 @@ class JsonImportSubview extends Component { const password = this.inputRef.current.value - importNewJsonAccount([ fileContents, password ]) + importNewJsonAccount([fileContents, password]) .then(({ selectedAddress }) => { if (selectedAddress) { history.push(mostRecentOverviewPage) diff --git a/ui/app/pages/create-account/import-account/private-key.js b/ui/app/pages/create-account/import-account/private-key.js index f23e7f418..cbc155f81 100644 --- a/ui/app/pages/create-account/import-account/private-key.js +++ b/ui/app/pages/create-account/import-account/private-key.js @@ -32,7 +32,7 @@ class PrivateKeyImportView extends Component { const privateKey = this.inputRef.current.value const { importNewAccount, history, displayWarning, mostRecentOverviewPage, setSelectedAddress, firstAddress } = this.props - importNewAccount('Private Key', [ privateKey ]) + importNewAccount('Private Key', [privateKey]) .then(({ selectedAddress }) => { if (selectedAddress) { this.context.metricsEvent({ @@ -131,7 +131,6 @@ export default compose( connect(mapStateToProps, mapDispatchToProps), )(PrivateKeyImportView) - function mapStateToProps (state) { return { error: state.appState.warning, @@ -142,8 +141,8 @@ function mapStateToProps (state) { function mapDispatchToProps (dispatch) { return { - importNewAccount: (strategy, [ privateKey ]) => { - return dispatch(actions.importNewAccount(strategy, [ privateKey ])) + importNewAccount: (strategy, [privateKey]) => { + return dispatch(actions.importNewAccount(strategy, [privateKey])) }, displayWarning: (message) => dispatch(actions.displayWarning(message || null)), setSelectedAddress: (address) => dispatch(actions.setSelectedAddress(address)), diff --git a/ui/app/pages/create-account/tests/create-account.test.js b/ui/app/pages/create-account/tests/create-account.test.js index b12ecd36b..f41aa2796 100644 --- a/ui/app/pages/create-account/tests/create-account.test.js +++ b/ui/app/pages/create-account/tests/create-account.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mountWithRouter } from '../../../../../test/lib/render-helpers' -import CreateAccountPage from '../index' +import CreateAccountPage from '..' describe('Create Account Page', function () { let wrapper diff --git a/ui/app/pages/first-time-flow/create-password/import-with-seed-phrase/tests/import-with-seed-phrase.component.test.js b/ui/app/pages/first-time-flow/create-password/import-with-seed-phrase/tests/import-with-seed-phrase.component.test.js index a464bb79e..95177e62a 100644 --- a/ui/app/pages/first-time-flow/create-password/import-with-seed-phrase/tests/import-with-seed-phrase.component.test.js +++ b/ui/app/pages/first-time-flow/create-password/import-with-seed-phrase/tests/import-with-seed-phrase.component.test.js @@ -7,7 +7,7 @@ import ImportWithSeedPhrase from '../import-with-seed-phrase.component' function shallowRender (props = {}, context = {}) { return shallow(, { context: { - t: (str) => str + '_t', + t: (str) => `${str}_t`, metricsEvent: sinon.spy(), ...context, }, diff --git a/ui/app/pages/first-time-flow/end-of-flow/end-of-flow.component.js b/ui/app/pages/first-time-flow/end-of-flow/end-of-flow.component.js index a6510553d..aa2611fc6 100644 --- a/ui/app/pages/first-time-flow/end-of-flow/end-of-flow.component.js +++ b/ui/app/pages/first-time-flow/end-of-flow/end-of-flow.component.js @@ -56,22 +56,22 @@ export default class EndOfFlowScreen extends PureComponent { { t('endOfFlowMessage2') }
- { '• ' + t('endOfFlowMessage3') } + { `• ${t('endOfFlowMessage3')}` }
- { '• ' + t('endOfFlowMessage4') } + { `• ${t('endOfFlowMessage4')}` }
- { '• ' + t('endOfFlowMessage5') } + { `• ${t('endOfFlowMessage5')}` }
- { '• ' + t('endOfFlowMessage6') } + { `• ${t('endOfFlowMessage6')}` }
- { '• ' + t('endOfFlowMessage7') } + { `• ${t('endOfFlowMessage7')}` }
- { '*' + t('endOfFlowMessage8') }  + { `*${t('endOfFlowMessage8')}` }  { t('gdprMessagePrivacyPolicy') } - ]) + ]) }
diff --git a/ui/app/pages/first-time-flow/metametrics-opt-in/tests/metametrics-opt-in.test.js b/ui/app/pages/first-time-flow/metametrics-opt-in/tests/metametrics-opt-in.test.js index c8a2491ff..2f7ade5e5 100644 --- a/ui/app/pages/first-time-flow/metametrics-opt-in/tests/metametrics-opt-in.test.js +++ b/ui/app/pages/first-time-flow/metametrics-opt-in/tests/metametrics-opt-in.test.js @@ -3,7 +3,7 @@ import React from 'react' import sinon from 'sinon' import configureMockStore from 'redux-mock-store' import { mountWithRouter } from '../../../../../../test/lib/render-helpers' -import MetaMetricsOptIn from '../index' +import MetaMetricsOptIn from '..' describe('MetaMetricsOptIn', function () { it('opt out of MetaMetrics', function () { diff --git a/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/confirm-seed-phrase.component.js b/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/confirm-seed-phrase.component.js index 8cc34e2af..318e4fcb5 100644 --- a/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/confirm-seed-phrase.component.js +++ b/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/confirm-seed-phrase.component.js @@ -247,7 +247,7 @@ export default class ConfirmSeedPhrase extends PureComponent { setDraggingSeedIndex={this.setDraggingSeedIndex} setHoveringIndex={this.setHoveringIndex} onDrop={this.onDrop} - droppable={!!word} + droppable={Boolean(word)} /> ) }) diff --git a/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/draggable-seed.component.js b/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/draggable-seed.component.js index 9eea945a5..66f227318 100644 --- a/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/draggable-seed.component.js +++ b/ui/app/pages/first-time-flow/seed-phrase/confirm-seed-phrase/draggable-seed.component.js @@ -121,5 +121,3 @@ const collectDrop = (connect, monitor) => { } export default DropTarget(SEEDWORD, seedTarget, collectDrop)(DragSource(SEEDWORD, seedSource, collectDrag)(DraggableSeed)) - - diff --git a/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/reveal-seed-phrase.component.js b/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/reveal-seed-phrase.component.js index afcd771c4..0130e3a34 100644 --- a/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/reveal-seed-phrase.component.js +++ b/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/reveal-seed-phrase.component.js @@ -82,7 +82,8 @@ export default class RevealSeedPhrase extends PureComponent { className={classnames( 'reveal-seed-phrase__secret-words notranslate', { 'reveal-seed-phrase__secret-words--hidden': !isShowingSeedPhrase, - })} + }, + )} > { seedPhrase }
diff --git a/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/tests/reveal-seed-phrase.test.js b/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/tests/reveal-seed-phrase.test.js index 62d64d5b6..152e24935 100644 --- a/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/tests/reveal-seed-phrase.test.js +++ b/ui/app/pages/first-time-flow/seed-phrase/reveal-seed-phrase/tests/reveal-seed-phrase.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import RevealSeedPhrase from '../index' +import RevealSeedPhrase from '..' describe('Reveal Seed Phrase', function () { let wrapper diff --git a/ui/app/pages/first-time-flow/seed-phrase/tests/confirm-seed-phrase-component.test.js b/ui/app/pages/first-time-flow/seed-phrase/tests/confirm-seed-phrase-component.test.js index 78c77d3a7..200d2867f 100644 --- a/ui/app/pages/first-time-flow/seed-phrase/tests/confirm-seed-phrase-component.test.js +++ b/ui/app/pages/first-time-flow/seed-phrase/tests/confirm-seed-phrase-component.test.js @@ -9,7 +9,7 @@ function shallowRender (props = {}, context = {}) { , { context: { - t: (str) => str + '_t', + t: (str) => `${str}_t`, ...context, }, }, @@ -152,7 +152,6 @@ describe('ConfirmSeedPhrase Component', function () { const sorted = root.state().sortedSeedWords const seeds = root.find('.confirm-seed-phrase__seed-word--sorted') - originalSeed.forEach((seed) => { const seedIndex = sorted.findIndex((s) => s === seed) seeds.at(seedIndex).simulate('click') diff --git a/ui/app/pages/first-time-flow/select-action/select-action.component.js b/ui/app/pages/first-time-flow/select-action/select-action.component.js index 5379952f1..f66eda3a5 100644 --- a/ui/app/pages/first-time-flow/select-action/select-action.component.js +++ b/ui/app/pages/first-time-flow/select-action/select-action.component.js @@ -45,7 +45,6 @@ export default class SelectAction extends PureComponent {
-
{ t('newToMetaMask') } diff --git a/ui/app/pages/first-time-flow/select-action/tests/select-action.test.js b/ui/app/pages/first-time-flow/select-action/tests/select-action.test.js index 6d7954276..baeda007b 100644 --- a/ui/app/pages/first-time-flow/select-action/tests/select-action.test.js +++ b/ui/app/pages/first-time-flow/select-action/tests/select-action.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mountWithRouter } from '../../../../../../test/lib/render-helpers' -import SelectAction from '../index' +import SelectAction from '..' describe('Selection Action', function () { let wrapper diff --git a/ui/app/pages/first-time-flow/welcome/tests/welcome.test.js b/ui/app/pages/first-time-flow/welcome/tests/welcome.test.js index 0e3a762a8..c3a584f0c 100644 --- a/ui/app/pages/first-time-flow/welcome/tests/welcome.test.js +++ b/ui/app/pages/first-time-flow/welcome/tests/welcome.test.js @@ -3,7 +3,7 @@ import React from 'react' import sinon from 'sinon' import configureMockStore from 'redux-mock-store' import { mountWithRouter } from '../../../../../../test/lib/render-helpers' -import Welcome from '../index' +import Welcome from '..' describe('Welcome', function () { const mockStore = { diff --git a/ui/app/pages/home/home.component.js b/ui/app/pages/home/home.component.js index 880e438e0..92af97d3b 100644 --- a/ui/app/pages/home/home.component.js +++ b/ui/app/pages/home/home.component.js @@ -158,7 +158,7 @@ export default class Home extends PureComponent { threeBoxLastUpdated && showRestorePrompt ? ( ) } + renderPopover = () => { const { setConnectedStatusPopoverHasBeenShown } = this.props const { t } = this.context diff --git a/ui/app/pages/lock/tests/lock.test.js b/ui/app/pages/lock/tests/lock.test.js index 77a1a7203..4f4c870e7 100644 --- a/ui/app/pages/lock/tests/lock.test.js +++ b/ui/app/pages/lock/tests/lock.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mountWithRouter } from '../../../../../test/lib/render-helpers' -import Lock from '../index' +import Lock from '..' describe('Lock', function () { diff --git a/ui/app/pages/mobile-sync/mobile-sync.component.js b/ui/app/pages/mobile-sync/mobile-sync.component.js index 51ad3e6b7..be0d3dbe2 100644 --- a/ui/app/pages/mobile-sync/mobile-sync.component.js +++ b/ui/app/pages/mobile-sync/mobile-sync.component.js @@ -29,7 +29,6 @@ export default class MobileSyncPage extends Component { keyrings: PropTypes.array, } - state = { screen: PASSWORD_PROMPT_SCREEN, password: '', @@ -199,7 +198,8 @@ export default class MobileSyncPage extends Component { } else { resolve() } - }) + }, + ) }) } @@ -263,7 +263,6 @@ export default class MobileSyncPage extends Component { }) } - componentWillUnmount () { this.clearTimeouts() this.disconnectWebsockets() diff --git a/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js b/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js index 76b6a5570..07b4c95f8 100644 --- a/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js +++ b/ui/app/pages/send/send-content/add-recipient/add-recipient.component.js @@ -222,7 +222,6 @@ export default class AddRecipient extends Component { ) } - if (toWarning) { return ( !!name), + contacts: addressBook.filter(({ name }) => Boolean(name)), nonContacts: addressBook.filter(({ name }) => !name), } } diff --git a/ui/app/pages/send/send-content/add-recipient/ens-input.component.js b/ui/app/pages/send/send-content/add-recipient/ens-input.component.js index 4607ebdbb..c3dce42d8 100644 --- a/ui/app/pages/send/send-content/add-recipient/ens-input.component.js +++ b/ui/app/pages/send/send-content/add-recipient/ens-input.component.js @@ -10,7 +10,6 @@ import log from 'loglevel' import { ellipsify } from '../../send.utils' import { isValidDomainName, isValidAddress, isValidAddressHead } from '../../../../helpers/utils/util' - // Local Constants const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' const ZERO_X_ERROR_ADDRESS = '0x' @@ -188,7 +187,6 @@ export default class EnsInput extends Component { const { className, selectedAddress, selectedName, contact = {} } = this.props const name = contact.name || selectedName - return (
- ), { context: { t: (str) => str + '_t' } }) + ), { context: { t: (str) => `${str}_t` } }) instance = wrapper.instance() }) @@ -94,7 +94,6 @@ describe('AddRecipient Component', function () { const xferLink = wrapper.find('.send__select-recipient-wrapper__list__link') assert.equal(xferLink.length, 1) - const groups = wrapper.find('RecipientGroup') assert.equal(groups.shallow().find('.send__select-recipient-wrapper__group').length, 1) }) diff --git a/ui/app/pages/send/send-content/send-amount-row/amount-max-button/tests/amount-max-button-component.test.js b/ui/app/pages/send/send-content/send-amount-row/amount-max-button/tests/amount-max-button-component.test.js index 7ba387c51..cc4546f58 100644 --- a/ui/app/pages/send/send-content/send-amount-row/amount-max-button/tests/amount-max-button-component.test.js +++ b/ui/app/pages/send/send-content/send-amount-row/amount-max-button/tests/amount-max-button-component.test.js @@ -32,7 +32,7 @@ describe('AmountMaxButton Component', function () { /> ), { context: { - t: (str) => str + '_t', + t: (str) => `${str}_t`, metricsEvent: () => undefined, }, }) diff --git a/ui/app/pages/send/send-content/send-amount-row/tests/send-amount-row-component.test.js b/ui/app/pages/send/send-content/send-amount-row/tests/send-amount-row-component.test.js index fa1e5a2aa..5b025e985 100644 --- a/ui/app/pages/send/send-content/send-amount-row/tests/send-amount-row-component.test.js +++ b/ui/app/pages/send/send-content/send-amount-row/tests/send-amount-row-component.test.js @@ -160,7 +160,7 @@ function shallowRenderSendAmountRow () { updateSendAmountError={updateSendAmountError} updateGas={() => undefined} /> - ), { context: { t: (str) => str + '_t' } }) + ), { context: { t: (str) => `${str}_t` } }) const instance = wrapper.instance() const updateAmount = sinon.spy(instance, 'updateAmount') const updateGas = sinon.spy(instance, 'updateGas') diff --git a/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js b/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js index 4920156f0..831bf9ac7 100644 --- a/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js +++ b/ui/app/pages/send/send-content/send-asset-row/send-asset-row.component.js @@ -124,7 +124,6 @@ export default class SendAssetRow extends Component { ) } - renderAsset (token, insideDropdown = false) { const { address, symbol } = token const { t } = this.context diff --git a/ui/app/pages/send/send-content/send-content.container.js b/ui/app/pages/send/send-content/send-content.container.js index 5cde49de9..3bbc36a49 100644 --- a/ui/app/pages/send/send-content/send-content.container.js +++ b/ui/app/pages/send/send-content/send-content.container.js @@ -12,7 +12,7 @@ function mapStateToProps (state) { const ownedAccounts = accountsWithSendEtherInfoSelector(state) const to = getSendTo(state) return { - isOwnedAccount: !!ownedAccounts.find(({ address }) => address.toLowerCase() === to.toLowerCase()), + isOwnedAccount: Boolean(ownedAccounts.find(({ address }) => address.toLowerCase() === to.toLowerCase())), contact: getAddressBookEntry(state, to), to, } diff --git a/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/tests/gas-fee-display.component.test.js b/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/tests/gas-fee-display.component.test.js index b479efb9d..d5f6716a7 100644 --- a/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/tests/gas-fee-display.component.test.js +++ b/ui/app/pages/send/send-content/send-gas-row/gas-fee-display/tests/gas-fee-display.component.test.js @@ -24,7 +24,7 @@ describe('GasFeeDisplay Component', function () { showGasButtonGroup={propsMethodSpies.showCustomizeGasModal} onReset={propsMethodSpies.onReset} /> - ), { context: { t: (str) => str + '_t' } }) + ), { context: { t: (str) => `${str}_t` } }) }) afterEach(function () { diff --git a/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js b/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js index 622bae0c4..8df7bbbfa 100644 --- a/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js +++ b/ui/app/pages/send/send-content/send-gas-row/send-gas-row.component.js @@ -151,9 +151,8 @@ export default class SendGasRow extends Component { return advancedGasInputs } else if (gasButtonGroupShown) { return gasPriceButtonGroup - } else { - return gasFeeDisplay } + return gasFeeDisplay } render () { diff --git a/ui/app/pages/send/send-content/send-gas-row/send-gas-row.container.js b/ui/app/pages/send/send-content/send-gas-row/send-gas-row.container.js index 51a17a40c..b215087fe 100644 --- a/ui/app/pages/send/send-content/send-gas-row/send-gas-row.container.js +++ b/ui/app/pages/send/send-content/send-gas-row/send-gas-row.container.js @@ -36,7 +36,6 @@ import { import { showModal, setGasPrice, setGasLimit, setGasTotal, updateSendAmount } from '../../../../store/actions' import SendGasRow from './send-gas-row.component' - export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(SendGasRow) function mapStateToProps (state) { diff --git a/ui/app/pages/send/send-content/send-gas-row/tests/send-gas-row-component.test.js b/ui/app/pages/send/send-content/send-gas-row/tests/send-gas-row-component.test.js index f80b294f7..e078ed25a 100644 --- a/ui/app/pages/send/send-content/send-gas-row/tests/send-gas-row-component.test.js +++ b/ui/app/pages/send/send-content/send-gas-row/tests/send-gas-row-component.test.js @@ -33,7 +33,7 @@ describe('SendGasRow Component', function () { anotherGasPriceButtonGroupProp: 'bar', }} /> - ), { context: { t: (str) => str + '_t', metricsEvent: () => ({}) } }) + ), { context: { t: (str) => `${str}_t`, metricsEvent: () => ({}) } }) wrapper.setProps({ isMainnet: true }) }) diff --git a/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-component.test.js b/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-component.test.js index 1255aac49..5e2b261e0 100644 --- a/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-component.test.js +++ b/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-component.test.js @@ -13,7 +13,7 @@ describe('SendRowErrorMessage Component', function () { errors={{ error1: 'abc', error2: 'def' }} errorType="error3" /> - ), { context: { t: (str) => str + '_t' } }) + ), { context: { t: (str) => `${str}_t` } }) }) it('should render null if the passed errors do not contain an error of errorType', function () { diff --git a/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-container.test.js b/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-container.test.js index 8c57cf268..5e8773529 100644 --- a/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-container.test.js +++ b/ui/app/pages/send/send-content/send-row-wrapper/send-row-error-message/tests/send-row-error-message-container.test.js @@ -20,7 +20,8 @@ describe('send-row-error-message container', function () { it('should map the correct properties to props', function () { assert.deepEqual(mapStateToProps('mockState', { errorType: 'someType' }), { errors: 'mockErrors:mockState', - errorType: 'someType' }) + errorType: 'someType', + }) }) }) diff --git a/ui/app/pages/send/send-content/tests/send-content-component.test.js b/ui/app/pages/send/send-content/tests/send-content-component.test.js index 3687e8711..dff83a610 100644 --- a/ui/app/pages/send/send-content/tests/send-content-component.test.js +++ b/ui/app/pages/send/send-content/tests/send-content-component.test.js @@ -18,7 +18,7 @@ describe('SendContent Component', function () { , - { context: { t: (str) => str + '_t' } }, + { context: { t: (str) => `${str}_t` } }, ) }) diff --git a/ui/app/pages/send/send-footer/send-footer.utils.js b/ui/app/pages/send/send-footer/send-footer.utils.js index c92c73a30..2fec545dc 100644 --- a/ui/app/pages/send/send-footer/send-footer.utils.js +++ b/ui/app/pages/send/send-footer/send-footer.utils.js @@ -61,7 +61,7 @@ export function constructUpdatedTx ({ data: ( TOKEN_TRANSFER_FUNCTION_SIGNATURE + Array.prototype.map.call( ethAbi.rawEncode(['address', 'uint256'], [to, ethUtil.addHexPrefix(amount)]), - (x) => ('00' + x.toString(16)).slice(-2), + (x) => (`00${x.toString(16)}`).slice(-2), ).join('') ), })) diff --git a/ui/app/pages/send/send-footer/tests/send-footer-component.test.js b/ui/app/pages/send/send-footer/tests/send-footer-component.test.js index ef502e0aa..0ddd961ee 100644 --- a/ui/app/pages/send/send-footer/tests/send-footer-component.test.js +++ b/ui/app/pages/send/send-footer/tests/send-footer-component.test.js @@ -83,7 +83,6 @@ describe('SendFooter Component', function () { }) }) - describe('formShouldBeDisabled()', function () { const config = { 'should return true if inError is truthy': { diff --git a/ui/app/pages/send/send-footer/tests/send-footer-container.test.js b/ui/app/pages/send/send-footer/tests/send-footer-container.test.js index 54040bfd7..314503e0d 100644 --- a/ui/app/pages/send/send-footer/tests/send-footer-container.test.js +++ b/ui/app/pages/send/send-footer/tests/send-footer-container.test.js @@ -97,7 +97,7 @@ describe('send-footer container', function () { ) assert.deepEqual( actionSpies.signTokenTx.getCall(0).args, - [ '0xabc', 'mockTo', 'mockAmount', { value: 'mockAmount' } ], + ['0xabc', 'mockTo', 'mockAmount', { value: 'mockAmount' }], ) }) @@ -125,7 +125,7 @@ describe('send-footer container', function () { ) assert.deepEqual( actionSpies.signTx.getCall(0).args, - [ { value: 'mockAmount' } ], + [{ value: 'mockAmount' }], ) }) }) @@ -168,7 +168,7 @@ describe('send-footer container', function () { assert.equal(utilsStubs.addressIsNew.getCall(0).args[0], 'mockToAccounts') assert.deepEqual( actionSpies.addToAddressBook.getCall(0).args, - [ '0xmockNewAddress', 'mockNickname' ], + ['0xmockNewAddress', 'mockNickname'], ) }) }) diff --git a/ui/app/pages/send/send-footer/tests/send-footer-utils.test.js b/ui/app/pages/send/send-footer/tests/send-footer-utils.test.js index c84856c3c..b0f5f6586 100644 --- a/ui/app/pages/send/send-footer/tests/send-footer-utils.test.js +++ b/ui/app/pages/send/send-footer/tests/send-footer-utils.test.js @@ -5,7 +5,7 @@ import { TOKEN_TRANSFER_FUNCTION_SIGNATURE } from '../../send.constants' const stubs = { rawEncode: sinon.stub().callsFake((arr1, arr2) => { - return [ ...arr1, ...arr2 ] + return [...arr1, ...arr2] }), } diff --git a/ui/app/pages/send/send.component.js b/ui/app/pages/send/send.component.js index 882c2edd6..ff6a54e58 100644 --- a/ui/app/pages/send/send.component.js +++ b/ui/app/pages/send/send.component.js @@ -14,7 +14,6 @@ import SendContent from './send-content' import SendFooter from './send-footer' import EnsInput from './send-content/add-recipient/ens-input' - export default class SendTransactionScreen extends Component { static propTypes = { diff --git a/ui/app/pages/send/send.utils.js b/ui/app/pages/send/send.utils.js index fe208f7be..32dc1939a 100644 --- a/ui/app/pages/send/send.utils.js +++ b/ui/app/pages/send/send.utils.js @@ -21,7 +21,6 @@ import { TOKEN_TRANSFER_FUNCTION_SIGNATURE, } from './send.constants' - export { addGasBuffer, calcGasTotal, @@ -69,7 +68,7 @@ function isBalanceSufficient ({ { value: totalAmount, fromNumericBase: 'hex', - conversionRate: conversionRate, + conversionRate, fromCurrency: primaryCurrency, }, ) @@ -262,9 +261,9 @@ async function estimateGas ({ if (simulationFailed) { const estimateWithBuffer = addGasBuffer(paramsForGasEstimate.gas, blockGasLimit, 1.5) return ethUtil.addHexPrefix(estimateWithBuffer) - } else { - throw error } + throw error + } } @@ -306,7 +305,7 @@ function generateTokenTransferData ({ toAddress = '0x0', amount = '0x0', sendTok } return TOKEN_TRANSFER_FUNCTION_SIGNATURE + Array.prototype.map.call( abi.rawEncode(['address', 'uint256'], [toAddress, ethUtil.addHexPrefix(amount)]), - (x) => ('00' + x.toString(16)).slice(-2), + (x) => (`00${x.toString(16)}`).slice(-2), ).join('') } diff --git a/ui/app/pages/send/tests/send-container.test.js b/ui/app/pages/send/tests/send-container.test.js index ae9cfd2d4..6cc39fe31 100644 --- a/ui/app/pages/send/tests/send-container.test.js +++ b/ui/app/pages/send/tests/send-container.test.js @@ -67,7 +67,7 @@ describe('send container', function () { it('should dispatch an updateGasData action when editingTransactionId is falsy', function () { const { gasPrice, selectedAddress, sendToken, blockGasLimit, to, value, data } = mockProps mapDispatchToPropsObject.updateAndSetGasLimit( - Object.assign({}, mockProps, { editingTransactionId: false }), + { ...mockProps, editingTransactionId: false }, ) assert(dispatchSpy.calledOnce) assert.deepEqual( @@ -85,7 +85,7 @@ describe('send container', function () { } it('should dispatch an action', function () { - mapDispatchToPropsObject.updateSendTokenBalance(Object.assign({}, mockProps)) + mapDispatchToPropsObject.updateSendTokenBalance({ ...mockProps }) assert(dispatchSpy.calledOnce) assert.deepEqual( actionSpies.updateSendTokenBalance.getCall(0).args[0], diff --git a/ui/app/pages/send/tests/send-utils.test.js b/ui/app/pages/send/tests/send-utils.test.js index 1640c8046..0d23947ff 100644 --- a/ui/app/pages/send/tests/send-utils.test.js +++ b/ui/app/pages/send/tests/send-utils.test.js @@ -22,7 +22,7 @@ const stubs = { conversionUtil: sinon.stub().callsFake((val) => parseInt(val, 16)), conversionGTE: sinon.stub().callsFake((obj1, obj2) => obj1.value >= obj2.value), multiplyCurrencies: sinon.stub().callsFake((a, b) => `${a}x${b}`), - calcTokenAmount: sinon.stub().callsFake((a, d) => 'calc:' + a + d), + calcTokenAmount: sinon.stub().callsFake((a, d) => `calc:${a}${d}`), rawEncode: sinon.stub().returns([16, 1100]), conversionGreaterThan: sinon.stub().callsFake((obj1, obj2) => obj1.value > obj2.value), conversionLessThan: sinon.stub().callsFake((obj1, obj2) => obj1.value < obj2.value), @@ -70,7 +70,7 @@ describe('send utils', function () { toNumericBase: 'hex', multiplicandBase: 16, multiplierBase: 16, - } ], + }], ) }) }) @@ -327,32 +327,32 @@ describe('send utils', function () { assert.equal(baseMockParams.estimateGasMethod.callCount, 1) assert.deepEqual( baseMockParams.estimateGasMethod.getCall(0).args[0], - Object.assign({ gasPrice: undefined, value: undefined }, baseExpectedCall), + { gasPrice: undefined, value: undefined, ...baseExpectedCall }, ) assert.equal(result, '0xabc16') }) it('should call ethQuery.estimateGas with the expected params when initialGasLimitHex is lower than the upperGasLimit', async function () { - const result = await estimateGas(Object.assign({}, baseMockParams, { blockGasLimit: '0xbcd' })) + const result = await estimateGas({ ...baseMockParams, blockGasLimit: '0xbcd' }) assert.equal(baseMockParams.estimateGasMethod.callCount, 1) assert.deepEqual( baseMockParams.estimateGasMethod.getCall(0).args[0], - Object.assign({ gasPrice: undefined, value: undefined }, baseExpectedCall, { gas: '0xbcdx0.95' }), + { gasPrice: undefined, value: undefined, ...baseExpectedCall, gas: '0xbcdx0.95' }, ) assert.equal(result, '0xabc16x1.5') }) it('should call ethQuery.estimateGas with a value of 0x0 and the expected data and to if passed a sendToken', async function () { - const result = await estimateGas(Object.assign({ data: 'mockData', sendToken: { address: 'mockAddress' } }, baseMockParams)) + const result = await estimateGas({ data: 'mockData', sendToken: { address: 'mockAddress' }, ...baseMockParams }) assert.equal(baseMockParams.estimateGasMethod.callCount, 1) assert.deepEqual( baseMockParams.estimateGasMethod.getCall(0).args[0], - Object.assign({}, baseExpectedCall, { - gasPrice: undefined, + { + ...baseExpectedCall, gasPrice: undefined, value: '0x0', data: '0xa9059cbb104c', to: 'mockAddress', - }), + }, ) assert.equal(result, '0xabc16') }) @@ -371,46 +371,40 @@ describe('send utils', function () { it(`should return ${SIMPLE_GAS_COST} if ethQuery.getCode does not return '0x'`, async function () { assert.equal(baseMockParams.estimateGasMethod.callCount, 0) - const result = await estimateGas(Object.assign({}, baseMockParams, { to: '0x123' })) + const result = await estimateGas({ ...baseMockParams, to: '0x123' }) assert.equal(result, SIMPLE_GAS_COST) }) it(`should return ${SIMPLE_GAS_COST} if not passed a sendToken or truthy to address`, async function () { assert.equal(baseMockParams.estimateGasMethod.callCount, 0) - const result = await estimateGas(Object.assign({}, baseMockParams, { to: null })) + const result = await estimateGas({ ...baseMockParams, to: null }) assert.equal(result, SIMPLE_GAS_COST) }) it(`should not return ${SIMPLE_GAS_COST} if passed a sendToken`, async function () { assert.equal(baseMockParams.estimateGasMethod.callCount, 0) - const result = await estimateGas(Object.assign({}, baseMockParams, { to: '0x123', sendToken: { address: '0x0' } })) + const result = await estimateGas({ ...baseMockParams, to: '0x123', sendToken: { address: '0x0' } }) assert.notEqual(result, SIMPLE_GAS_COST) }) it(`should return ${BASE_TOKEN_GAS_COST} if passed a sendToken but no to address`, async function () { - const result = await estimateGas(Object.assign({}, baseMockParams, { to: null, sendToken: { address: '0x0' } })) + const result = await estimateGas({ ...baseMockParams, to: null, sendToken: { address: '0x0' } }) assert.equal(result, BASE_TOKEN_GAS_COST) }) it(`should return the adjusted blockGasLimit if it fails with a 'Transaction execution error.'`, async function () { - const result = await estimateGas(Object.assign({}, baseMockParams, { - to: 'isContract willFailBecauseOf:Transaction execution error.', - })) + const result = await estimateGas({ ...baseMockParams, to: 'isContract willFailBecauseOf:Transaction execution error.' }) assert.equal(result, '0x64x0.95') }) it(`should return the adjusted blockGasLimit if it fails with a 'gas required exceeds allowance or always failing transaction.'`, async function () { - const result = await estimateGas(Object.assign({}, baseMockParams, { - to: 'isContract willFailBecauseOf:gas required exceeds allowance or always failing transaction.', - })) + const result = await estimateGas({ ...baseMockParams, to: 'isContract willFailBecauseOf:gas required exceeds allowance or always failing transaction.' }) assert.equal(result, '0x64x0.95') }) it(`should reject other errors`, async function () { try { - await estimateGas(Object.assign({}, baseMockParams, { - to: 'isContract willFailBecauseOf:some other error', - })) + await estimateGas({ ...baseMockParams, to: 'isContract willFailBecauseOf:some other error' }) } catch (err) { assert.equal(err.message, 'some other error') } diff --git a/ui/app/pages/settings/advanced-tab/advanced-tab.component.js b/ui/app/pages/settings/advanced-tab/advanced-tab.component.js index 898bfad18..055ad2977 100644 --- a/ui/app/pages/settings/advanced-tab/advanced-tab.component.js +++ b/ui/app/pages/settings/advanced-tab/advanced-tab.component.js @@ -491,7 +491,7 @@ function addUrlProtocolPrefix (urlString) { if (!urlString.match( /(^http:\/\/)|(^https:\/\/)/u, )) { - return 'https://' + urlString + return `https://${urlString}` } return urlString } diff --git a/ui/app/pages/settings/contact-list-tab/contact-list-tab.component.js b/ui/app/pages/settings/contact-list-tab/contact-list-tab.component.js index fc6dc5354..74cc1b89b 100644 --- a/ui/app/pages/settings/contact-list-tab/contact-list-tab.component.js +++ b/ui/app/pages/settings/contact-list-tab/contact-list-tab.component.js @@ -30,7 +30,7 @@ export default class ContactListTab extends Component { renderAddresses () { const { addressBook, history, selectedAddress } = this.props - const contacts = addressBook.filter(({ name }) => !!name) + const contacts = addressBook.filter(({ name }) => Boolean(name)) const nonContacts = addressBook.filter(({ name }) => !name) return ( diff --git a/ui/app/pages/settings/contact-list-tab/contact-list-tab.container.js b/ui/app/pages/settings/contact-list-tab/contact-list-tab.container.js index 8871830a8..597b74683 100644 --- a/ui/app/pages/settings/contact-list-tab/contact-list-tab.container.js +++ b/ui/app/pages/settings/contact-list-tab/contact-list-tab.container.js @@ -15,7 +15,6 @@ import { } from '../../../helpers/constants/routes' import ContactListTab from './contact-list-tab.component' - const mapStateToProps = (state, ownProps) => { const { location } = ownProps const { pathname } = location diff --git a/ui/app/pages/settings/contact-list-tab/view-contact/view-contact.component.js b/ui/app/pages/settings/contact-list-tab/view-contact/view-contact.component.js index faa670f05..6256c1134 100644 --- a/ui/app/pages/settings/contact-list-tab/view-contact/view-contact.component.js +++ b/ui/app/pages/settings/contact-list-tab/view-contact/view-contact.component.js @@ -12,11 +12,11 @@ import { useCopyToClipboard } from '../../../../hooks/useCopyToClipboard' function quadSplit (address) { return ( - '0x ' + - address - .slice(2) - .match(/.{1,4}/ug) - .join(' ') + `0x ${ + address + .slice(2) + .match(/.{1,4}/ug) + .join(' ')}` ) } diff --git a/ui/app/pages/settings/networks-tab/network-form/network-form.component.js b/ui/app/pages/settings/networks-tab/network-form/network-form.component.js index 3ca23e7f9..024af3a31 100644 --- a/ui/app/pages/settings/networks-tab/network-form/network-form.component.js +++ b/ui/app/pages/settings/networks-tab/network-form/network-form.component.js @@ -207,10 +207,9 @@ export default class NetworkForm extends PureComponent { validateChainId = (chainId) => { // eslint-disable-next-line radix - this.setErrorTo('chainId', !!chainId && Number.isNaN(parseInt(chainId)) + this.setErrorTo('chainId', Boolean(chainId) && Number.isNaN(parseInt(chainId)) ? `${this.context.t('invalidInput')} chainId` - : '', - ) + : '') } isValidWhenAppended = (url) => { diff --git a/ui/app/pages/settings/networks-tab/networks-tab.component.js b/ui/app/pages/settings/networks-tab/networks-tab.component.js index 40bbc0c36..c9450e4c5 100644 --- a/ui/app/pages/settings/networks-tab/networks-tab.component.js +++ b/ui/app/pages/settings/networks-tab/networks-tab.component.js @@ -104,7 +104,7 @@ export default class NetworksTab extends PureComponent { return (
{ setNetworksTabAddMode(false) diff --git a/ui/app/pages/settings/networks-tab/networks-tab.container.js b/ui/app/pages/settings/networks-tab/networks-tab.container.js index 282078246..5b35f3ba5 100644 --- a/ui/app/pages/settings/networks-tab/networks-tab.container.js +++ b/ui/app/pages/settings/networks-tab/networks-tab.container.js @@ -36,7 +36,7 @@ const mapStateToProps = (state) => { } }) - const networksToRender = [ ...defaultNetworks, ...frequentRpcNetworkListDetails ] + const networksToRender = [...defaultNetworks, ...frequentRpcNetworkListDetails] let selectedNetwork = networksToRender.find((network) => network.rpcUrl === networksTabSelectedRpcUrl) || {} const networkIsSelected = Boolean(selectedNetwork.rpcUrl) diff --git a/ui/app/pages/settings/security-tab/tests/security-tab.test.js b/ui/app/pages/settings/security-tab/tests/security-tab.test.js index 1fa1b2eb8..fd1b8c085 100644 --- a/ui/app/pages/settings/security-tab/tests/security-tab.test.js +++ b/ui/app/pages/settings/security-tab/tests/security-tab.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import SecurityTab from '../index' +import SecurityTab from '..' describe('Security Tab', function () { let wrapper diff --git a/ui/app/pages/settings/settings-tab/settings-tab.component.js b/ui/app/pages/settings/settings-tab/settings-tab.component.js index 2e3c7f220..c7d984f88 100644 --- a/ui/app/pages/settings/settings-tab/settings-tab.component.js +++ b/ui/app/pages/settings/settings-tab/settings-tab.component.js @@ -101,7 +101,6 @@ export default class SettingsTab extends PureComponent { ) } - renderBlockieOptIn () { const { t } = this.context const { useBlockie, setUseBlockie } = this.props diff --git a/ui/app/pages/settings/settings-tab/tests/settings-tab.test.js b/ui/app/pages/settings/settings-tab/tests/settings-tab.test.js index 290d5081a..1803ff590 100644 --- a/ui/app/pages/settings/settings-tab/tests/settings-tab.test.js +++ b/ui/app/pages/settings/settings-tab/tests/settings-tab.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import SettingsTab from '../index' +import SettingsTab from '..' describe('Settings Tab', function () { let wrapper diff --git a/ui/app/pages/unlock-page/tests/unlock-page.test.js b/ui/app/pages/unlock-page/tests/unlock-page.test.js index 33ae361ca..48bb2b78d 100644 --- a/ui/app/pages/unlock-page/tests/unlock-page.test.js +++ b/ui/app/pages/unlock-page/tests/unlock-page.test.js @@ -2,7 +2,7 @@ import assert from 'assert' import React from 'react' import sinon from 'sinon' import { mount } from 'enzyme' -import UnlockPage from '../index' +import UnlockPage from '..' describe('Unlock Page', function () { let wrapper @@ -19,7 +19,6 @@ describe('Unlock Page', function () { showOptInModal: sinon.spy(), } - beforeEach(function () { wrapper = mount( diff --git a/ui/app/selectors/confirm-transaction.js b/ui/app/selectors/confirm-transaction.js index 553a44307..93c876ef7 100644 --- a/ui/app/selectors/confirm-transaction.js +++ b/ui/app/selectors/confirm-transaction.js @@ -121,7 +121,6 @@ export const unconfirmedTransactionsCountSelector = createSelector( }, ) - export const currentCurrencySelector = (state) => state.metamask.currentCurrency export const conversionRateSelector = (state) => state.metamask.conversionRate diff --git a/ui/app/selectors/custom-gas.js b/ui/app/selectors/custom-gas.js index f8c4ecf49..b3c1b1dcd 100644 --- a/ui/app/selectors/custom-gas.js +++ b/ui/app/selectors/custom-gas.js @@ -132,7 +132,6 @@ export function getRenderableEthFee (estimate, gasLimit, numberOfDecimals = 9) { return formatETHFee(fee) } - export function getRenderableConvertedCurrencyFee (estimate, gasLimit, convertedCurrency, conversionRate) { const value = conversionUtil(estimate, { fromNumericBase: 'dec', toNumericBase: 'hex' }) const fee = basicPriceEstimateToETHTotal(value, gasLimit) @@ -164,8 +163,8 @@ export function formatTimeEstimate (totalSeconds, greaterThanMax, lessThanMin) { symbol = '> ' } - const formattedMin = `${minutes ? minutes + ' min' : ''}` - const formattedSec = `${seconds ? seconds + ' sec' : ''}` + const formattedMin = `${minutes ? `${minutes} min` : ''}` + const formattedSec = `${seconds ? `${seconds} sec` : ''}` const formattedCombined = formattedMin && formattedSec ? `${symbol}${formattedMin} ${formattedSec}` : symbol + [formattedMin, formattedSec].find((t) => t) @@ -199,7 +198,7 @@ export function getRenderableBasicEstimateData (state, gasLimit) { const { showFiatInTestnets } = getPreferences(state) const isMainnet = getIsMainnet(state) - const showFiat = (isMainnet || !!showFiatInTestnets) + const showFiat = (isMainnet || Boolean(showFiatInTestnets)) const { conversionRate } = state.metamask const currentCurrency = getCurrentCurrency(state) const { @@ -253,7 +252,7 @@ export function getRenderableEstimateDataForSmallButtonsFromGWEI (state) { const { showFiatInTestnets } = getPreferences(state) const isMainnet = getIsMainnet(state) - const showFiat = (isMainnet || !!showFiatInTestnets) + const showFiat = (isMainnet || Boolean(showFiatInTestnets)) const gasLimit = state.metamask.send.gasLimit || getCustomGasLimit(state) || '0x5208' const { conversionRate } = state.metamask const currentCurrency = getCurrentCurrency(state) diff --git a/ui/app/selectors/permissions.js b/ui/app/selectors/permissions.js index 22247e607..bc7bcabe4 100644 --- a/ui/app/selectors/permissions.js +++ b/ui/app/selectors/permissions.js @@ -249,7 +249,7 @@ export function getPermissionsForActiveTab (state) { export function getLastConnectedInfo (state) { const { permissionsHistory = {} } = state.metamask return Object.keys(permissionsHistory).reduce((acc, origin) => { - const ethAccountsHistory = JSON.parse(JSON.stringify(permissionsHistory[origin]['eth_accounts'])) + const ethAccountsHistory = JSON.parse(JSON.stringify(permissionsHistory[origin].eth_accounts)) return { ...acc, [origin]: ethAccountsHistory, diff --git a/ui/app/selectors/selectors.js b/ui/app/selectors/selectors.js index 9be3b1adc..3789e3854 100644 --- a/ui/app/selectors/selectors.js +++ b/ui/app/selectors/selectors.js @@ -63,11 +63,10 @@ export const getMetaMaskAccounts = createSelector( }, } - } else { - return { - ...selectedAccounts, - [accountID]: account, - } + } + return { + ...selectedAccounts, + [accountID]: account, } }, {}), ) @@ -119,7 +118,7 @@ export const getMetaMaskAccountsOrdered = createSelector( getMetaMaskAccounts, (keyrings, identities, accounts) => keyrings .reduce((list, keyring) => list.concat(keyring.accounts), []) - .filter((address) => !!identities[address]) + .filter((address) => Boolean(identities[address])) .map((address) => ({ ...identities[address], ...accounts[address] })), ) @@ -180,7 +179,7 @@ export function accountsWithSendEtherInfoSelector (state) { const identities = getMetaMaskIdentities(state) const accountsWithSendEtherInfo = Object.entries(identities).map(([key, identity]) => { - return Object.assign({}, identity, accounts[key]) + return { ...identity, ...accounts[key] } }) return accountsWithSendEtherInfo @@ -258,7 +257,7 @@ export function isEthereumNetwork (state) { GOERLI, } = NETWORK_TYPES - return [ KOVAN, MAINNET, RINKEBY, ROPSTEN, GOERLI].includes(networkType) + return [KOVAN, MAINNET, RINKEBY, ROPSTEN, GOERLI].includes(networkType) } export function getPreferences ({ metamask }) { diff --git a/ui/app/selectors/send.js b/ui/app/selectors/send.js index dd17f90ac..3fcd3e760 100644 --- a/ui/app/selectors/send.js +++ b/ui/app/selectors/send.js @@ -157,9 +157,8 @@ export function getTitleKey (state) { return 'edit' } else if (isToken) { return 'sendTokens' - } else { - return 'sendETH' } + return 'sendETH' } export function isSendFormInError (state) { diff --git a/ui/app/selectors/tests/custom-gas.test.js b/ui/app/selectors/tests/custom-gas.test.js index 7e3e6c085..6ae6119c4 100644 --- a/ui/app/selectors/tests/custom-gas.test.js +++ b/ui/app/selectors/tests/custom-gas.test.js @@ -52,22 +52,30 @@ describe('custom-gas selectors', function () { describe('getEstimatedGasPrices', function () { it('should return price and time estimates', function () { - const mockState = { gas: { priceAndTimeEstimates: [ - { gasprice: 12, somethingElse: 20 }, - { gasprice: 22, expectedTime: 30 }, - { gasprice: 32, somethingElse: 40 }, - ] } } + const mockState = { + gas: { + priceAndTimeEstimates: [ + { gasprice: 12, somethingElse: 20 }, + { gasprice: 22, expectedTime: 30 }, + { gasprice: 32, somethingElse: 40 }, + ], + }, + } assert.deepEqual(getEstimatedGasPrices(mockState), [12, 22, 32]) }) }) describe('getEstimatedGasTimes', function () { it('should return price and time estimates', function () { - const mockState = { gas: { priceAndTimeEstimates: [ - { somethingElse: 12, expectedTime: 20 }, - { gasPrice: 22, expectedTime: 30 }, - { somethingElse: 32, expectedTime: 40 }, - ] } } + const mockState = { + gas: { + priceAndTimeEstimates: [ + { somethingElse: 12, expectedTime: 20 }, + { gasPrice: 22, expectedTime: 30 }, + { somethingElse: 32, expectedTime: 40 }, + ], + }, + } assert.deepEqual(getEstimatedGasTimes(mockState), [20, 30, 40]) }) }) diff --git a/ui/app/selectors/tests/send.test.js b/ui/app/selectors/tests/send.test.js index d232baf1b..529e03958 100644 --- a/ui/app/selectors/tests/send.test.js +++ b/ui/app/selectors/tests/send.test.js @@ -37,11 +37,11 @@ import { import mockState from './send-selectors-test-data' describe('send selectors', function () { - const tempGlobalEth = Object.assign({}, global.eth) + const tempGlobalEth = { ...global.eth } beforeEach(function () { global.eth = { contract: sinon.stub().returns({ - at: (address) => 'mockAt:' + address, + at: (address) => `mockAt:${address}`, }), } }) @@ -217,9 +217,9 @@ describe('send selectors', function () { }) it('should return null if send token is not set', function () { - const modifiedMetamaskState = Object.assign({}, mockState.metamask, { send: {} }) + const modifiedMetamaskState = { ...mockState.metamask, send: {} } assert.equal( - getSendTokenContract(Object.assign({}, mockState, { metamask: modifiedMetamaskState })), + getSendTokenContract({ ...mockState, metamask: modifiedMetamaskState }), null, ) }) @@ -280,11 +280,12 @@ describe('send selectors', function () { it('should get the selected account balance if the send.from does not exist', function () { const editedMockState = { - metamask: Object.assign({}, mockState.metamask, { + metamask: { + ...mockState.metamask, send: { from: null, }, - }), + }, } assert.equal( getSendFromBalance(editedMockState), @@ -308,11 +309,12 @@ describe('send selectors', function () { it('should return the current account if send.from does not exist', function () { const editedMockState = { - metamask: Object.assign({}, mockState.metamask, { + metamask: { + ...mockState.metamask, send: { from: null, }, - }), + }, } assert.deepEqual( getSendFromObject(editedMockState), @@ -532,7 +534,8 @@ describe('send selectors', function () { editingTransactionId: true, token: {}, }), - ), 'edit') + ), 'edit', + ) }) it('should return the correct key when getSendEditingTransactionId is falsy and getSendToken is truthy', function () { @@ -543,7 +546,8 @@ describe('send selectors', function () { editingTransactionId: false, token: {}, }), - ), 'sendTokens') + ), 'sendTokens', + ) }) it('should return the correct key when getSendEditingTransactionId is falsy and getSendToken is falsy', function () { @@ -554,7 +558,8 @@ describe('send selectors', function () { editingTransactionId: false, token: null, }), - ), 'sendETH') + ), 'sendETH', + ) }) }) }) @@ -571,7 +576,7 @@ describe('send selectors', function () { it('should return true if any of the values of the object returned by getSendErrors are truthy', function () { assert.equal(isSendFormInError( getSendMockState({ - errors: [ true ], + errors: [true], }), ), true) }) @@ -584,7 +589,7 @@ describe('send selectors', function () { ), false) assert.equal(isSendFormInError( getSendMockState({ - errors: [ false ], + errors: [false], }), ), false) }) diff --git a/ui/app/selectors/tests/transactions.test.js b/ui/app/selectors/tests/transactions.test.js index 12a931e81..65f36b3ea 100644 --- a/ui/app/selectors/tests/transactions.test.js +++ b/ui/app/selectors/tests/transactions.test.js @@ -184,7 +184,7 @@ describe('Transaction Selectors', function () { const expectedResult = [ { nonce: '0x0', - transactions: [ tx1 ], + transactions: [tx1], initialTransaction: tx1, primaryTransaction: tx1, hasRetried: false, @@ -192,7 +192,7 @@ describe('Transaction Selectors', function () { }, { nonce: '0x1', - transactions: [ tx2 ], + transactions: [tx2], initialTransaction: tx2, primaryTransaction: tx2, hasRetried: false, @@ -273,7 +273,7 @@ describe('Transaction Selectors', function () { const expectedResult = [ { nonce: submittedTx.txParams.nonce, - transactions: [ submittedTx ], + transactions: [submittedTx], initialTransaction: submittedTx, primaryTransaction: submittedTx, hasRetried: false, @@ -281,7 +281,7 @@ describe('Transaction Selectors', function () { }, { nonce: unapprovedTx.txParams.nonce, - transactions: [ unapprovedTx ], + transactions: [unapprovedTx], initialTransaction: unapprovedTx, primaryTransaction: unapprovedTx, hasRetried: false, @@ -289,7 +289,7 @@ describe('Transaction Selectors', function () { }, { nonce: approvedTx.txParams.nonce, - transactions: [ approvedTx ], + transactions: [approvedTx], initialTransaction: approvedTx, primaryTransaction: approvedTx, hasRetried: false, @@ -305,7 +305,7 @@ describe('Transaction Selectors', function () { const expectedResult = [ { nonce: confirmedTx.txParams.nonce, - transactions: [ confirmedTx ], + transactions: [confirmedTx], initialTransaction: confirmedTx, primaryTransaction: confirmedTx, hasRetried: false, @@ -318,7 +318,7 @@ describe('Transaction Selectors', function () { it('submittedPendingTransactionsSelector', function () { - const expectedResult = [ submittedTx ] + const expectedResult = [submittedTx] assert.deepEqual(submittedPendingTransactionsSelector(state), expectedResult) }) }) diff --git a/ui/app/store/actions.js b/ui/app/store/actions.js index 4d9f7a4b3..543860f5a 100644 --- a/ui/app/store/actions.js +++ b/ui/app/store/actions.js @@ -257,7 +257,7 @@ export function resetAccount () { return } - log.info('Transaction history reset for ' + account) + log.info(`Transaction history reset for ${account}`) dispatch(showAccountsPage()) resolve(account) }) @@ -277,7 +277,6 @@ export function removeAccount (address) { return } resolve(account) - return }) }) await forceUpdateMetamaskState(dispatch) @@ -288,7 +287,7 @@ export function removeAccount (address) { dispatch(hideLoadingIndication()) } - log.info('Account removed: ' + address) + log.info(`Account removed: ${address}`) dispatch(showAccountsPage()) } } @@ -412,7 +411,6 @@ export function unlockHardwareWalletAccount (index, deviceName, hdPath) { dispatch(hideLoadingIndication()) resolve() - return }) }) } @@ -589,7 +587,6 @@ export function signTx (txData) { global.ethQuery.sendTransaction(txData, (err) => { if (err) { dispatch(displayWarning(err.message)) - return } }) dispatch(showConfTxPage()) @@ -725,7 +722,7 @@ export function updateSendAmount (amount) { export function updateCustomNonce (value) { return { type: actionConstants.UPDATE_CUSTOM_NONCE, - value: value, + value, } } @@ -1044,7 +1041,7 @@ export function cancelTxs (txDataList) { if (getEnvironmentType() === ENVIRONMENT_TYPE_NOTIFICATION) { global.platform.closeCurrentWindow() - return + } } } @@ -1059,7 +1056,7 @@ export function markPasswordForgotten () { return } resolve() - return + }) }) } finally { @@ -1322,15 +1319,15 @@ export function addTokens (tokens) { return Promise.all(tokens.map(({ address, symbol, decimals }) => ( dispatch(addToken(address, symbol, decimals)) ))) - } else { - return Promise.all( - Object - .entries(tokens) - .map(([_, { address, symbol, decimals }]) => ( - dispatch(addToken(address, symbol, decimals)) - )), - ) } + return Promise.all( + Object + .entries(tokens) + .map(([_, { address, symbol, decimals }]) => ( + dispatch(addToken(address, symbol, decimals)) + )), + ) + } } @@ -1534,7 +1531,6 @@ export function setRpcTarget (newRpc, chainId, ticker = 'ETH', nickname) { } catch (error) { log.error(error) dispatch(displayWarning('Had a problem changing networks!')) - return } } } @@ -1573,7 +1569,6 @@ export function addToAddressBook (recipient, nickname = '', memo = '') { } if (!set) { dispatch(displayWarning('Address book failed to update')) - return } } } @@ -1602,7 +1597,6 @@ export function hideNetworkDropdown () { } } - export function showModal (payload) { return { type: actionConstants.MODAL_OPEN, @@ -1735,9 +1729,7 @@ export function exportAccount (password, address) { } dispatch(showPrivateKey(result)) - resolve(result) - return }) }) }) @@ -1764,11 +1756,9 @@ export function exportAccounts (password, addresses) { return } resolve2(result) - return }), )) resolve(Promise.all(accountPromises)) - return }) }) } @@ -1800,7 +1790,6 @@ export function setAccountLabel (account, label) { type: actionConstants.SET_ACCOUNT_LABEL, value: { account, label }, }) - resolve(account) }) }) @@ -1966,7 +1955,6 @@ export function setParticipateInMetaMetrics (val) { type: actionConstants.SET_PARTICIPATE_IN_METAMETRICS, value: val, }) - resolve([val, metaMetricsId]) }) }) @@ -1988,7 +1976,6 @@ export function setMetaMetricsSendCount (val) { type: actionConstants.SET_METAMETRICS_SEND_COUNT, value: val, }) - resolve(val) }) }) @@ -2003,7 +1990,6 @@ export function setUseBlockie (val) { dispatch(hideLoadingIndication()) if (err) { dispatch(displayWarning(err.message)) - return } }) dispatch({ @@ -2021,7 +2007,6 @@ export function setUseNonceField (val) { dispatch(hideLoadingIndication()) if (err) { dispatch(displayWarning(err.message)) - return } }) dispatch({ @@ -2039,7 +2024,6 @@ export function setUsePhishDetect (val) { dispatch(hideLoadingIndication()) if (err) { dispatch(displayWarning(err.message)) - return } }) } @@ -2053,7 +2037,7 @@ export function setIpfsGateway (val) { dispatch(hideLoadingIndication()) if (err) { dispatch(displayWarning(err.message)) - return + } else { dispatch({ type: actionConstants.SET_IPFS_GATEWAY, @@ -2174,7 +2158,7 @@ export function setFirstTimeFlowType (type) { background.setFirstTimeFlowType(type, (err) => { if (err) { dispatch(displayWarning(err.message)) - return + } }) dispatch({ @@ -2203,7 +2187,7 @@ export function setLastActiveTime () { background.setLastActiveTime((err) => { if (err) { dispatch(displayWarning(err.message)) - return + } }) } @@ -2257,9 +2241,7 @@ export function getContractMethodData (data = '') { return getMethodDataAsync(fourBytePrefix) .then(({ name, params }) => { dispatch(loadingMethodDataFinished()) - background.addKnownMethodData(fourBytePrefix, { name, params }) - return { name, params } }) } @@ -2292,7 +2274,6 @@ export function getTokenParams (tokenAddress) { dispatch(loadingTokenParamsStarted()) log.debug(`loadingTokenParams`) - return fetchSymbolAndDecimals(tokenAddress, existingTokens) .then(({ symbol, decimals }) => { dispatch(addToken(tokenAddress, symbol, Number(decimals))) @@ -2476,7 +2457,6 @@ export function setCurrentWindowTab (currentWindowTab) { } } - export function getCurrentWindowTab () { return async (dispatch) => { const currentWindowTab = await global.platform.currentTab() diff --git a/ui/lib/icon-factory.js b/ui/lib/icon-factory.js index 142e7bbfd..19489819a 100644 --- a/ui/lib/icon-factory.js +++ b/ui/lib/icon-factory.js @@ -1,8 +1,9 @@ -let iconFactory import { isValidAddress } from 'ethereumjs-util' import contractMap from 'eth-contract-metadata' import { checksumAddress } from '../app/helpers/utils/util' +let iconFactory + export default function iconFactoryGenerator (jazzicon) { if (!iconFactory) { iconFactory = new IconFactory(jazzicon) diff --git a/ui/lib/webcam-utils.js b/ui/lib/webcam-utils.js index ef7da9496..c9b6c5503 100644 --- a/ui/lib/webcam-utils.js +++ b/ui/lib/webcam-utils.js @@ -25,11 +25,10 @@ class WebcamUtils { permissions: hasWebcamPermissions, environmentReady, } - } else { - const error = new Error('No webcam found') - error.type = 'NO_WEBCAM_FOUND' - throw error } + const error = new Error('No webcam found') + error.type = 'NO_WEBCAM_FOUND' + throw error } } diff --git a/yarn.lock b/yarn.lock index 6a0d5369c..0b0c471f6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1730,10 +1730,10 @@ web3 "^0.20.7" web3-provider-engine "^15.0.4" -"@metamask/eslint-config@^1.1.0": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@metamask/eslint-config/-/eslint-config-1.1.0.tgz#03c6fbec8ba3d95fa017d8b98ab5d0701f7458a4" - integrity sha512-yFFHIxFn3cBd9brIW/+0fJGq16hT0xUyElP0YxiZHaY7j2T/l+X/414L9kqBOuPfPa9bIKulIcJJOfcrMJZp9w== +"@metamask/eslint-config@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@metamask/eslint-config/-/eslint-config-3.0.0.tgz#39c4275e440cfc690524d328a0bda8227bd69326" + integrity sha512-AYnNopj+K0YyWuCXY4mflgMQzIcm/Jc+HiXzBzY8SJ3fMlnBXjQjsbu0B78zxLR9HZ2uW9IrCj0VG7hMj1b4og== "@metamask/eth-ledger-bridge-keyring@^0.2.6": version "0.2.6"