Update ESLint shared config to v3 (#9274)

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
feature/default_network_editable
Whymarrh Whitby 4 years ago committed by GitHub
parent 50c4845d05
commit b6ccd22d6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 62
      .eslintrc.js
  2. 5
      app/scripts/background.js
  3. 7
      app/scripts/contentscript.js
  4. 14
      app/scripts/controllers/alert.js
  5. 7
      app/scripts/controllers/app-state.js
  6. 5
      app/scripts/controllers/cached-balances.js
  7. 2
      app/scripts/controllers/detect-tokens.js
  8. 9
      app/scripts/controllers/incoming-transactions.js
  9. 1
      app/scripts/controllers/network/createLocalhostClient.js
  10. 10
      app/scripts/controllers/network/network.js
  11. 15
      app/scripts/controllers/onboarding.js
  12. 5
      app/scripts/controllers/permissions/index.js
  13. 10
      app/scripts/controllers/permissions/permissionsLog.js
  14. 17
      app/scripts/controllers/preferences.js
  15. 6
      app/scripts/controllers/threebox.js
  16. 2
      app/scripts/controllers/token-rates.js
  17. 21
      app/scripts/controllers/transactions/index.js
  18. 3
      app/scripts/controllers/transactions/pending-tx-tracker.js
  19. 20
      app/scripts/controllers/transactions/tx-state-manager.js
  20. 3
      app/scripts/inpage.js
  21. 1
      app/scripts/lib/ComposableObservableStore.js
  22. 2
      app/scripts/lib/cleanErrorStack.js
  23. 2
      app/scripts/lib/createStreamSink.js
  24. 6
      app/scripts/lib/decrypt-message-manager.js
  25. 4
      app/scripts/lib/encryption-public-key-manager.js
  26. 2
      app/scripts/lib/ens-ipfs/resolver.js
  27. 3
      app/scripts/lib/extractEthjsErrorMessage.js
  28. 6
      app/scripts/lib/local-store.js
  29. 9
      app/scripts/lib/message-manager.js
  30. 6
      app/scripts/lib/personal-message-manager.js
  31. 2
      app/scripts/lib/random-id.js
  32. 6
      app/scripts/lib/seed-phrase-verifier.js
  33. 5
      app/scripts/lib/typed-message-manager.js
  34. 3
      app/scripts/lib/util.js
  35. 39
      app/scripts/metamask-controller.js
  36. 5
      app/scripts/migrations/002.js
  37. 6
      app/scripts/migrations/003.js
  38. 6
      app/scripts/migrations/004.js
  39. 7
      app/scripts/migrations/005.js
  40. 8
      app/scripts/migrations/006.js
  41. 8
      app/scripts/migrations/007.js
  42. 8
      app/scripts/migrations/008.js
  43. 8
      app/scripts/migrations/009.js
  44. 8
      app/scripts/migrations/010.js
  45. 8
      app/scripts/migrations/011.js
  46. 8
      app/scripts/migrations/012.js
  47. 8
      app/scripts/migrations/013.js
  48. 8
      app/scripts/migrations/014.js
  49. 8
      app/scripts/migrations/015.js
  50. 8
      app/scripts/migrations/016.js
  51. 8
      app/scripts/migrations/017.js
  52. 7
      app/scripts/migrations/018.js
  53. 8
      app/scripts/migrations/019.js
  54. 8
      app/scripts/migrations/020.js
  55. 8
      app/scripts/migrations/021.js
  56. 8
      app/scripts/migrations/022.js
  57. 8
      app/scripts/migrations/023.js
  58. 6
      app/scripts/migrations/024.js
  59. 6
      app/scripts/migrations/025.js
  60. 6
      app/scripts/migrations/026.js
  61. 6
      app/scripts/migrations/027.js
  62. 6
      app/scripts/migrations/028.js
  63. 3
      app/scripts/migrations/029.js
  64. 8
      app/scripts/migrations/030.js
  65. 5
      app/scripts/migrations/031.js
  66. 5
      app/scripts/migrations/032.js
  67. 6
      app/scripts/migrations/033.js
  68. 5
      app/scripts/migrations/034.js
  69. 6
      app/scripts/migrations/035.js
  70. 5
      app/scripts/migrations/036.js
  71. 5
      app/scripts/migrations/037.js
  72. 5
      app/scripts/migrations/038.js
  73. 5
      app/scripts/migrations/039.js
  74. 5
      app/scripts/migrations/040.js
  75. 5
      app/scripts/migrations/041.js
  76. 5
      app/scripts/migrations/042.js
  77. 5
      app/scripts/migrations/043.js
  78. 5
      app/scripts/migrations/044.js
  79. 5
      app/scripts/migrations/045.js
  80. 5
      app/scripts/migrations/046.js
  81. 5
      app/scripts/migrations/047.js
  82. 2
      app/scripts/migrations/fail-tx.js
  83. 6
      app/scripts/migrations/template.js
  84. 8
      app/scripts/platforms/extension.js
  85. 3
      app/scripts/ui.js
  86. 6
      development/build/display.js
  87. 1
      development/build/etc.js
  88. 12
      development/build/index.js
  89. 1
      development/build/manifest.js
  90. 23
      development/build/scripts.js
  91. 1
      development/build/static.js
  92. 4
      development/build/styles.js
  93. 1
      development/build/task.js
  94. 2
      development/metamaskbot-build-announce.js
  95. 2
      development/mock-3box.js
  96. 1
      development/sourcemap-validator.js
  97. 2
      development/static-server.js
  98. 7
      development/verify-locale-strings.js
  99. 2
      package.json
  100. 6
      test/e2e/benchmark.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -41,36 +41,9 @@ module.exports = {
}, },
rules: { rules: {
/* TODO: Remove these when upgrading to `@metamask/eslint-config@2` */ 'default-param-last': 'off',
'array-callback-return': 'error', 'require-atomic-updates': 'off',
'callback-return': 'error', 'import/no-unassigned-import': 'off',
'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',
'prefer-destructuring': ['error', { 'prefer-destructuring': ['error', {
'VariableDeclarator': { 'VariableDeclarator': {
'array': false, 'array': false,
@ -83,33 +56,6 @@ module.exports = {
}, { }, {
'enforceForRenamedProperties': false, '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-prop-types': 'error',
'react/no-unused-state': 'error', 'react/no-unused-state': 'error',
'react/jsx-boolean-value': 'error', 'react/jsx-boolean-value': 'error',
@ -121,7 +67,7 @@ module.exports = {
'react/jsx-no-duplicate-props': 'error', 'react/jsx-no-duplicate-props': 'error',
'react/jsx-closing-bracket-location': 'error', 'react/jsx-closing-bracket-location': 'error',
'react/jsx-first-prop-new-line': ['error', 'multiline'], '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', { 'react/jsx-tag-spacing': ['error', {
'closingSlash': 'never', 'closingSlash': 'never',
'beforeSelfClosing': 'always', 'beforeSelfClosing': 'always',

@ -2,7 +2,7 @@
* @file The entry point for the web extension singleton process. * @file The entry point for the web extension singleton process.
*/ */
// these need to run before anything else // these need to run before anything else
/* eslint-disable import/order */ /* eslint-disable import/first,import/order */
import './lib/freezeGlobals' import './lib/freezeGlobals'
import setupFetchDebugging from './lib/setupFetchDebugging' import setupFetchDebugging from './lib/setupFetchDebugging'
/* eslint-enable import/order */ /* eslint-enable import/order */
@ -39,9 +39,10 @@ import {
ENVIRONMENT_TYPE_NOTIFICATION, ENVIRONMENT_TYPE_NOTIFICATION,
ENVIRONMENT_TYPE_FULLSCREEN, ENVIRONMENT_TYPE_FULLSCREEN,
} from './lib/enums' } from './lib/enums'
/* eslint-enable import/first */
// METAMASK_TEST_CONFIG is used in e2e tests to set the default network to localhost // 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') log.setDefaultLevel(process.env.METAMASK_DEBUG ? 'debug' : 'warn')

@ -10,7 +10,7 @@ const fs = require('fs')
const path = require('path') const path = require('path')
const inpageContent = fs.readFileSync(path.join(__dirname, '..', '..', 'dist', 'chrome', 'inpage.js'), 'utf8') 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 const inpageBundle = inpageContent + inpageSuffix
// Eventually this streaming injection could be replaced with: // Eventually this streaming injection could be replaced with:
@ -115,7 +115,7 @@ function forwardTrafficBetweenMuxers (channelName, muxA, muxB) {
function logStreamDisconnectWarning (remoteLabel, err) { function logStreamDisconnectWarning (remoteLabel, err) {
let warningMsg = `MetamaskContentscript - lost connection to ${remoteLabel}` let warningMsg = `MetamaskContentscript - lost connection to ${remoteLabel}`
if (err) { if (err) {
warningMsg += '\n' + err.stack warningMsg += `\n${err.stack}`
} }
console.warn(warningMsg) console.warn(warningMsg)
} }
@ -139,9 +139,8 @@ function doctypeCheck () {
const { doctype } = window.document const { doctype } = window.document
if (doctype) { if (doctype) {
return doctype.name === 'html' return doctype.name === 'html'
} else {
return true
} }
return true
} }
/** /**

@ -32,20 +32,18 @@ const defaultState = {
* alert related state * alert related state
*/ */
export default class AlertController { export default class AlertController {
/** /**
* @constructor * @constructor
* @param {AlertControllerOptions} [opts] - Controller configuration parameters * @param {AlertControllerOptions} [opts] - Controller configuration parameters
*/ */
constructor (opts = {}) { constructor (opts = {}) {
const { initState, preferencesStore } = opts const { initState, preferencesStore } = opts
const state = Object.assign( const state = {
{}, ...defaultState,
defaultState, ...initState,
initState, unconnectedAccountAlertShownOrigins: {},
{ }
unconnectedAccountAlertShownOrigins: {},
},
)
this.store = new ObservableStore(state) this.store = new ObservableStore(state)
this.selectedAddress = preferencesStore.getState().selectedAddress this.selectedAddress = preferencesStore.getState().selectedAddress

@ -2,6 +2,7 @@ import EventEmitter from 'events'
import ObservableStore from 'obs-store' import ObservableStore from 'obs-store'
export default class AppStateController extends EventEmitter { export default class AppStateController extends EventEmitter {
/** /**
* @constructor * @constructor
* @param opts * @param opts
@ -18,11 +19,11 @@ export default class AppStateController extends EventEmitter {
super() super()
this.onInactiveTimeout = onInactiveTimeout || (() => undefined) this.onInactiveTimeout = onInactiveTimeout || (() => undefined)
this.store = new ObservableStore(Object.assign({ this.store = new ObservableStore({
timeoutMinutes: 0, timeoutMinutes: 0,
connectedStatusPopoverHasBeenShown: true, connectedStatusPopoverHasBeenShown: true,
defaultHomeActiveTabName: null, defaultHomeActiveTabName: null, ...initState,
}, initState)) })
this.timer = null this.timer = null
this.isUnlocked = isUnlocked this.isUnlocked = isUnlocked

@ -12,6 +12,7 @@ import ObservableStore from 'obs-store'
* a cache of account balances in local storage * a cache of account balances in local storage
*/ */
export default class CachedBalancesController { export default class CachedBalancesController {
/** /**
* Creates a new controller instance * Creates a new controller instance
* *
@ -23,9 +24,7 @@ export default class CachedBalancesController {
this.accountTracker = accountTracker this.accountTracker = accountTracker
this.getNetwork = getNetwork this.getNetwork = getNetwork
const initState = Object.assign({ const initState = { cachedBalances: {}, ...opts.initState }
cachedBalances: {},
}, opts.initState)
this.store = new ObservableStore(initState) this.store = new ObservableStore(initState)
this._registerUpdates() this._registerUpdates()

@ -7,11 +7,13 @@ import { MAINNET } from './network/enums'
// By default, poll every 3 minutes // By default, poll every 3 minutes
const DEFAULT_INTERVAL = 180 * 1000 const DEFAULT_INTERVAL = 180 * 1000
const SINGLE_CALL_BALANCES_ADDRESS = '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39' const SINGLE_CALL_BALANCES_ADDRESS = '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39'
/** /**
* A controller that polls for token exchange * A controller that polls for token exchange
* rates based on a user's current token list * rates based on a user's current token list
*/ */
export default class DetectTokensController { export default class DetectTokensController {
/** /**
* Creates a DetectTokensController * Creates a DetectTokensController
* *

@ -40,7 +40,7 @@ export default class IncomingTransactionsController {
}) })
} }
const initState = Object.assign({ const initState = {
incomingTransactions: {}, incomingTransactions: {},
incomingTxLastFetchedBlocksByNetwork: { incomingTxLastFetchedBlocksByNetwork: {
[ROPSTEN]: null, [ROPSTEN]: null,
@ -48,8 +48,8 @@ export default class IncomingTransactionsController {
[KOVAN]: null, [KOVAN]: null,
[GOERLI]: null, [GOERLI]: null,
[MAINNET]: null, [MAINNET]: null,
}, }, ...opts.initState,
}, opts.initState) }
this.store = new ObservableStore(initState) this.store = new ObservableStore(initState)
this.preferencesController.store.subscribe(pairwise((prevState, currState) => { this.preferencesController.store.subscribe(pairwise((prevState, currState) => {
@ -265,9 +265,8 @@ function pairwise (fn) {
if (first) { if (first) {
first = false first = false
return fn(value, value) return fn(value, value)
} else {
return fn(cache, value)
} }
return fn(cache, value)
} finally { } finally {
cache = value cache = value
} }

@ -26,7 +26,6 @@ function delay (time) {
return new Promise((resolve) => setTimeout(resolve, time)) return new Promise((resolve) => setTimeout(resolve, time))
} }
function createEstimateGasMiddleware () { function createEstimateGasMiddleware () {
return createAsyncMiddleware(async (req, _, next) => { return createAsyncMiddleware(async (req, _, next) => {
if (req.method === 'eth_estimateGas' && inTest) { if (req.method === 'eth_estimateGas' && inTest) {

@ -12,8 +12,6 @@ import createInfuraClient from './createInfuraClient'
import createJsonRpcClient from './createJsonRpcClient' import createJsonRpcClient from './createJsonRpcClient'
import createLocalhostClient from './createLocalhostClient' import createLocalhostClient from './createLocalhostClient'
const networks = { networkList: {} }
import { import {
RINKEBY, RINKEBY,
MAINNET, MAINNET,
@ -21,6 +19,8 @@ import {
INFURA_PROVIDER_TYPES, INFURA_PROVIDER_TYPES,
} from './enums' } from './enums'
const networks = { networkList: {} }
const env = process.env.METAMASK_ENV const env = process.env.METAMASK_ENV
const { METAMASK_DEBUG } = process.env const { METAMASK_DEBUG } = process.env
@ -124,7 +124,7 @@ export default class NetworkController extends EventEmitter {
this.setNetworkState('loading') this.setNetworkState('loading')
return return
} }
log.info('web3.getNetwork returned ' + network) log.info(`web3.getNetwork returned ${network}`)
this.setNetworkState(network, type) this.setNetworkState(network, type)
} }
}) })
@ -212,7 +212,7 @@ export default class NetworkController extends EventEmitter {
log.info('NetworkController - configureStandardProvider', rpcUrl) log.info('NetworkController - configureStandardProvider', rpcUrl)
const networkClient = createJsonRpcClient({ rpcUrl }) const networkClient = createJsonRpcClient({ rpcUrl })
// hack to add a 'rpc' network with chainId // hack to add a 'rpc' network with chainId
networks.networkList['rpc'] = { networks.networkList.rpc = {
chainId, chainId,
rpcUrl, rpcUrl,
ticker: ticker || 'ETH', ticker: ticker || 'ETH',
@ -222,7 +222,7 @@ export default class NetworkController extends EventEmitter {
let settings = { let settings = {
network: chainId, network: chainId,
} }
settings = Object.assign(settings, networks.networkList['rpc']) settings = Object.assign(settings, networks.networkList.rpc)
this.networkConfig.putState(settings) this.networkConfig.putState(settings)
this._setNetworkClient(networkClient) this._setNetworkClient(networkClient)
} }

@ -17,6 +17,7 @@ import log from 'loglevel'
* state related to onboarding * state related to onboarding
*/ */
export default class OnboardingController { export default class OnboardingController {
/** /**
* Creates a new controller instance * Creates a new controller instance
* *
@ -26,13 +27,11 @@ export default class OnboardingController {
const initialTransientState = { const initialTransientState = {
onboardingTabs: {}, onboardingTabs: {},
} }
const initState = Object.assign( const initState = {
{ seedPhraseBackedUp: true,
seedPhraseBackedUp: true, ...opts.initState,
}, ...initialTransientState,
opts.initState, }
initialTransientState,
)
this.store = new ObservableStore(initState) this.store = new ObservableStore(initState)
this.preferencesController = opts.preferencesController this.preferencesController = opts.preferencesController
this.completedOnboarding = this.preferencesController.store.getState().completedOnboarding this.completedOnboarding = this.preferencesController.store.getState().completedOnboarding
@ -64,7 +63,7 @@ export default class OnboardingController {
log.debug('Ignoring registerOnboarding; user already onboarded') log.debug('Ignoring registerOnboarding; user already onboarded')
return return
} }
const onboardingTabs = Object.assign({}, this.store.getState().onboardingTabs) const onboardingTabs = { ...this.store.getState().onboardingTabs }
if (!onboardingTabs[location] || onboardingTabs[location] !== tabId) { if (!onboardingTabs[location] || onboardingTabs[location] !== tabId) {
log.debug(`Registering onboarding tab at location '${location}' with tabId '${tabId}'`) log.debug(`Registering onboarding tab at location '${location}' with tabId '${tabId}'`)
onboardingTabs[location] = tabId onboardingTabs[location] = tabId

@ -36,7 +36,8 @@ export class PermissionsController {
showPermissionRequest, showPermissionRequest,
} = {}, } = {},
restoredPermissions = {}, restoredPermissions = {},
restoredState = {}) { restoredState = {},
) {
// additional top-level store key set in _initializeMetadataStore // additional top-level store key set in _initializeMetadataStore
this.store = new ObservableStore({ this.store = new ObservableStore({
@ -334,7 +335,7 @@ export class PermissionsController {
.filter((acc) => acc !== account) .filter((acc) => acc !== account)
if (newPermittedAccounts.length === 0) { if (newPermittedAccounts.length === 0) {
this.removePermissionsFor({ [origin]: [ 'eth_accounts' ] }) this.removePermissionsFor({ [origin]: ['eth_accounts'] })
} else { } else {
this.permissions.updateCaveatFor( this.permissions.updateCaveatFor(

@ -113,7 +113,7 @@ export default class PermissionsLogController {
// eth_requestAccounts is a special case; we need to extract the accounts // eth_requestAccounts is a special case; we need to extract the accounts
// from it // from it
activityEntry = this.logRequest(req, isInternal) activityEntry = this.logRequest(req, isInternal)
requestedMethods = [ 'eth_accounts' ] requestedMethods = ['eth_accounts']
} else { } else {
// no-op // no-op
next() next()
@ -292,9 +292,9 @@ export default class PermissionsLogController {
// eth_accounts requires special handling, because of information // eth_accounts requires special handling, because of information
// we store about the accounts // we store about the accounts
const existingEthAccountsEntry = ( 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) { if (existingEthAccountsEntry && newEthAccountsEntry) {
@ -306,7 +306,7 @@ export default class PermissionsLogController {
) )
// merge old and new eth_accounts history entries // merge old and new eth_accounts history entries
newOriginHistory['eth_accounts'] = { newOriginHistory.eth_accounts = {
lastApproved, lastApproved,
accounts: { accounts: {
...existingEthAccountsEntry.accounts, ...existingEthAccountsEntry.accounts,
@ -364,7 +364,7 @@ export default class PermissionsLogController {
} }
} }
} }
return [ ...accounts ] return [...accounts]
} }
} }

@ -26,7 +26,7 @@ export default class PreferencesController {
* *
*/ */
constructor (opts = {}) { constructor (opts = {}) {
const initState = Object.assign({ const initState = {
frequentRpcListDetail: [], frequentRpcListDetail: [],
accountTokens: {}, accountTokens: {},
assetImages: {}, assetImages: {},
@ -61,8 +61,8 @@ export default class PreferencesController {
metaMetricsSendCount: 0, metaMetricsSendCount: 0,
// ENS decentralized website resolution // ENS decentralized website resolution
ipfsGateway: 'dweb.link', ipfsGateway: 'dweb.link', ...opts.initState,
}, opts.initState) }
this.diagnostics = opts.diagnostics this.diagnostics = opts.diagnostics
this.network = opts.network this.network = opts.network
@ -152,7 +152,6 @@ export default class PreferencesController {
this.store.updateState({ firstTimeFlowType: type }) this.store.updateState({ firstTimeFlowType: type })
} }
getSuggestedTokens () { getSuggestedTokens () {
return this.store.getState().suggestedTokens return this.store.getState().suggestedTokens
} }
@ -215,7 +214,6 @@ export default class PreferencesController {
} }
next() next()
return
} }
/** /**
@ -228,7 +226,7 @@ export default class PreferencesController {
const textDirection = (['ar', 'dv', 'fa', 'he', 'ku'].includes(key)) ? 'rtl' : 'auto' const textDirection = (['ar', 'dv', 'fa', 'he', 'ku'].includes(key)) ? 'rtl' : 'auto'
this.store.updateState({ this.store.updateState({
currentLocale: key, currentLocale: key,
textDirection: textDirection, textDirection,
}) })
return textDirection return textDirection
} }
@ -282,7 +280,6 @@ export default class PreferencesController {
return address return address
} }
/** /**
* Adds addresses to the identities object without removing identities * Adds addresses to the identities object without removing identities
* *
@ -470,7 +467,7 @@ export default class PreferencesController {
*/ */
setAccountLabel (account, label) { setAccountLabel (account, label) {
if (!account) { 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 address = normalizeAddress(account)
const { identities } = this.store.getState() const { identities } = this.store.getState()
@ -491,7 +488,6 @@ export default class PreferencesController {
* *
*/ */
updateRpc (newRpcDetails) { updateRpc (newRpcDetails) {
const rpcList = this.getFrequentRpcListDetail() const rpcList = this.getFrequentRpcListDetail()
const index = rpcList.findIndex((element) => { const index = rpcList.findIndex((element) => {
@ -508,6 +504,7 @@ export default class PreferencesController {
} }
return Promise.resolve(rpcList) return Promise.resolve(rpcList)
} }
/** /**
* Adds custom RPC url to state. * Adds custom RPC url to state.
* *
@ -529,7 +526,7 @@ export default class PreferencesController {
if (url !== 'http://localhost:8545') { if (url !== 'http://localhost:8545') {
let checkedChainId let checkedChainId
// eslint-disable-next-line radix // eslint-disable-next-line radix
if (!!chainId && !Number.isNaN(parseInt(chainId))) { if (Boolean(chainId) && !Number.isNaN(parseInt(chainId))) {
checkedChainId = chainId checkedChainId = chainId
} }
rpcList.push({ rpcUrl: url, chainId: checkedChainId, ticker, nickname, rpcPrefs }) rpcList.push({ rpcUrl: url, chainId: checkedChainId, ticker, nickname, rpcPrefs })

@ -1,6 +1,6 @@
import ObservableStore from 'obs-store' import ObservableStore from 'obs-store'
/* eslint-disable import/order */ /* eslint-disable import/first,import/order */
const Box = process.env.IN_TEST const Box = process.env.IN_TEST
? require('../../../development/mock-3box') ? require('../../../development/mock-3box')
: require('3box') : require('3box')
@ -13,6 +13,7 @@ import Migrator from '../lib/migrator'
import migrations from '../migrations' import migrations from '../migrations'
import createOriginMiddleware from '../lib/createOriginMiddleware' import createOriginMiddleware from '../lib/createOriginMiddleware'
import createMetamaskMiddleware from './network/createMetamaskMiddleware' import createMetamaskMiddleware from './network/createMetamaskMiddleware'
/* eslint-enable import/first */
const SYNC_TIMEOUT = 60 * 1000 // one minute const SYNC_TIMEOUT = 60 * 1000 // one minute
@ -42,9 +43,8 @@ export default class ThreeBoxController {
if (isUnlocked && accounts[0]) { if (isUnlocked && accounts[0]) {
const appKeyAddress = await this.keyringController.getAppKeyAddress(accounts[0], 'wallet://3box.metamask.io') const appKeyAddress = await this.keyringController.getAppKeyAddress(accounts[0], 'wallet://3box.metamask.io')
return [appKeyAddress] return [appKeyAddress]
} else {
return []
} }
return []
}, },
processPersonalMessage: async (msgParams) => { processPersonalMessage: async (msgParams) => {
const accounts = await this.keyringController.getAccounts() const accounts = await this.keyringController.getAccounts()

@ -3,7 +3,6 @@ import log from 'loglevel'
import { normalize as normalizeAddress } from 'eth-sig-util' import { normalize as normalizeAddress } from 'eth-sig-util'
import ethUtil from 'ethereumjs-util' import ethUtil from 'ethereumjs-util'
// By default, poll every 3 minutes // By default, poll every 3 minutes
const DEFAULT_INTERVAL = 180 * 1000 const DEFAULT_INTERVAL = 180 * 1000
@ -12,6 +11,7 @@ const DEFAULT_INTERVAL = 180 * 1000
* rates based on a user's current token list * rates based on a user's current token list
*/ */
export default class TokenRatesController { export default class TokenRatesController {
/** /**
* Creates a TokenRatesController * Creates a TokenRatesController
* *

@ -6,9 +6,6 @@ import EthQuery from 'ethjs-query'
import { ethErrors } from 'eth-json-rpc-errors' import { ethErrors } from 'eth-json-rpc-errors'
import abi from 'human-standard-token-abi' import abi from 'human-standard-token-abi'
import abiDecoder from 'abi-decoder' import abiDecoder from 'abi-decoder'
abiDecoder.addABI(abi)
import NonceTracker from 'nonce-tracker' import NonceTracker from 'nonce-tracker'
import log from 'loglevel' import log from 'loglevel'
import { import {
@ -19,7 +16,6 @@ import {
DEPLOY_CONTRACT_ACTION_KEY, DEPLOY_CONTRACT_ACTION_KEY,
CONTRACT_INTERACTION_KEY, CONTRACT_INTERACTION_KEY,
} from '../../../../ui/app/helpers/constants/transactions' } from '../../../../ui/app/helpers/constants/transactions'
import cleanErrorStack from '../../lib/cleanErrorStack' import cleanErrorStack from '../../lib/cleanErrorStack'
import { hexToBn, bnToHex, BnMultiplyByFraction } from '../../lib/util' import { hexToBn, bnToHex, BnMultiplyByFraction } from '../../lib/util'
import { TRANSACTION_NO_CONTRACT_ERROR_KEY } from '../../../../ui/app/helpers/constants/error-keys' 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 TxGasUtil from './tx-gas-utils'
import PendingTransactionTracker from './pending-tx-tracker' import PendingTransactionTracker from './pending-tx-tracker'
import * as txUtils from './lib/util' import * as txUtils from './lib/util'
import { import {
TRANSACTION_TYPE_CANCEL, TRANSACTION_TYPE_CANCEL,
TRANSACTION_TYPE_RETRY, TRANSACTION_TYPE_RETRY,
@ -35,6 +30,7 @@ import {
TRANSACTION_STATUS_APPROVED, TRANSACTION_STATUS_APPROVED,
} from './enums' } from './enums'
abiDecoder.addABI(abi)
const SIMPLE_GAS_COST = '0x5208' // Hex for 21000, cost of a simple send. 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 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
<br>- nonceTracker <br>- nonceTracker
calculating nonces calculating nonces
@class @class
@param {Object} - opts @param {Object} - opts
@param {Object} opts.initState - initial transaction list default is an empty array @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) const integerChainId = parseInt(networkState)
if (Number.isNaN(integerChainId)) { if (Number.isNaN(integerChainId)) {
return 0 return 0
} else {
return integerChainId
} }
return integerChainId
} }
/** /**
@ -201,6 +195,7 @@ export default class TransactionController extends EventEmitter {
const normalizedTxParams = txUtils.normalizeTxParams(txParams) const normalizedTxParams = txUtils.normalizeTxParams(txParams)
txUtils.validateTxParams(normalizedTxParams) txUtils.validateTxParams(normalizedTxParams)
/** /**
`generateTxMeta` adds the default txMeta properties to the passed object. `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 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) const { transactionCategory, getCodeResponse } = await this._determineTransactionCategory(txParams)
txMeta.transactionCategory = transactionCategory txMeta.transactionCategory = transactionCategory
@ -497,7 +492,7 @@ export default class TransactionController extends EventEmitter {
const txMeta = this.txStateManager.getTx(txId) const txMeta = this.txStateManager.getTx(txId)
// add network/chain id // add network/chain id
const chainId = this.getChainId() const chainId = this.getChainId()
const txParams = Object.assign({}, txMeta.txParams, { chainId }) const txParams = { ...txMeta.txParams, chainId }
// sign tx // sign tx
const fromAddress = txParams.from const fromAddress = txParams.from
const ethTx = new Transaction(txParams) const ethTx = new Transaction(txParams)
@ -606,19 +601,25 @@ export default class TransactionController extends EventEmitter {
// //
/** maps methods for convenience*/ /** maps methods for convenience*/
_mapMethods () { _mapMethods () {
/** @returns {Object} - the state in transaction controller */ /** @returns {Object} - the state in transaction controller */
this.getState = () => this.memStore.getState() this.getState = () => this.memStore.getState()
/** @returns {string|number} - the network number stored in networkStore */ /** @returns {string|number} - the network number stored in networkStore */
this.getNetwork = () => this.networkStore.getState() this.getNetwork = () => this.networkStore.getState()
/** @returns {string} - the user selected address */ /** @returns {string} - the user selected address */
this.getSelectedAddress = () => this.preferencesStore.getState().selectedAddress this.getSelectedAddress = () => this.preferencesStore.getState().selectedAddress
/** @returns {array} - transactions whos status is unapproved */ /** @returns {array} - transactions whos status is unapproved */
this.getUnapprovedTxCount = () => Object.keys(this.txStateManager.getUnapprovedTxList()).length this.getUnapprovedTxCount = () => Object.keys(this.txStateManager.getUnapprovedTxList()).length
/** /**
@returns {number} - number of transactions that have the status submitted @returns {number} - number of transactions that have the status submitted
@param {string} account - hex prefixed account @param {string} account - hex prefixed account
*/ */
this.getPendingTxCount = (account) => this.txStateManager.getPendingTransactions(account).length this.getPendingTxCount = (account) => this.txStateManager.getPendingTransactions(account).length
/** see txStateManager */ /** see txStateManager */
this.getFilteredTxList = (opts) => this.txStateManager.getFilteredTxList(opts) this.getFilteredTxList = (opts) => this.txStateManager.getFilteredTxList(opts)
} }

@ -15,11 +15,11 @@ import EthQuery from 'ethjs-query'
@param {function} config.getPendingTransactions a function for getting an array of transactions, @param {function} config.getPendingTransactions a function for getting an array of transactions,
@param {function} config.publishTransaction a async function for publishing raw transactions, @param {function} config.publishTransaction a async function for publishing raw transactions,
@class @class
*/ */
export default class PendingTransactionTracker extends EventEmitter { export default class PendingTransactionTracker extends EventEmitter {
/** /**
* We wait this many blocks before emitting a 'tx:dropped' event * 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)) { if (await this._checkIfTxWasDropped(txMeta)) {
this.emit('tx:dropped', txId) this.emit('tx:dropped', txId)
return
} }
} }

@ -4,6 +4,7 @@ import log from 'loglevel'
import createId from '../../lib/random-id' import createId from '../../lib/random-id'
import { generateHistoryEntry, replayHistory, snapshotFromTxMeta } from './lib/tx-state-history-helpers' import { generateHistoryEntry, replayHistory, snapshotFromTxMeta } from './lib/tx-state-history-helpers'
import { getFinalStates, normalizeTxParams } from './lib/util' import { getFinalStates, normalizeTxParams } from './lib/util'
/** /**
TransactionStateManager is responsible for the state of a transaction and TransactionStateManager is responsible for the state of a transaction and
storing the transaction storing the transaction
@ -31,9 +32,8 @@ export default class TransactionStateManager extends EventEmitter {
super() super()
this.store = new ObservableStore( this.store = new ObservableStore(
Object.assign({ { transactions: [], ...initState },
transactions: [], )
}, initState))
this.txHistoryLimit = txHistoryLimit this.txHistoryLimit = txHistoryLimit
this.getNetwork = getNetwork this.getNetwork = getNetwork
} }
@ -47,13 +47,13 @@ export default class TransactionStateManager extends EventEmitter {
if (netId === 'loading') { if (netId === 'loading') {
throw new Error('MetaMask is having trouble connecting to the network') throw new Error('MetaMask is having trouble connecting to the network')
} }
return Object.assign({ return {
id: createId(), id: createId(),
time: (new Date()).getTime(), time: (new Date()).getTime(),
status: 'unapproved', status: 'unapproved',
metamaskNetworkId: netId, metamaskNetworkId: netId,
loadingDefaults: true, loadingDefaults: true, ...opts,
}, opts) }
} }
/** /**
@ -202,6 +202,7 @@ export default class TransactionStateManager extends EventEmitter {
this._saveTxList(transactions) this._saveTxList(transactions)
return txMeta return txMeta
} }
/** /**
@param {number} txId @param {number} txId
@returns {Object} - the txMeta who matches the given id if none found @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) this._saveTxList(txList)
} }
/** /**
merges txParams obj onto txMeta.txParams merges txParams obj onto txMeta.txParams
use extend to ensure that all fields are filled use extend to ensure that all fields are filled
@ -326,6 +326,7 @@ export default class TransactionStateManager extends EventEmitter {
}) })
return filteredTxList return filteredTxList
} }
/** /**
@param {string} key - the key to check @param {string} key - the key to check
@ -340,9 +341,8 @@ export default class TransactionStateManager extends EventEmitter {
return txList.filter((txMeta) => { return txList.filter((txMeta) => {
if (key in txMeta.txParams) { if (key in txMeta.txParams) {
return filter(txMeta.txParams[key]) 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) { setTxStatusUnapproved (txId) {
this._setTxStatus(txId, 'unapproved') this._setTxStatus(txId, 'unapproved')
} }
/** /**
should update the status of the tx to 'approved'. should update the status of the tx to 'approved'.
@param {number} txId - the txMeta Id @param {number} txId - the txMeta Id
@ -417,7 +418,6 @@ export default class TransactionStateManager extends EventEmitter {
this._setTxStatus(txId, 'dropped') this._setTxStatus(txId, 'dropped')
} }
/** /**
should update the status of the tx to 'failed'. should update the status of the tx to 'failed'.
and put the error on the txMeta and put the error on the txMeta

@ -30,12 +30,14 @@ const restoreContextAfterImports = () => {
cleanContextForImports() cleanContextForImports()
/* eslint-disable import/first */
import log from 'loglevel' import log from 'loglevel'
import LocalMessageDuplexStream from 'post-message-stream' import LocalMessageDuplexStream from 'post-message-stream'
import { initProvider } from '@metamask/inpage-provider' import { initProvider } from '@metamask/inpage-provider'
// TODO:deprecate:2020 // TODO:deprecate:2020
import setupWeb3 from './lib/setupWeb3' import setupWeb3 from './lib/setupWeb3'
/* eslint-enable import/first */
restoreContextAfterImports() restoreContextAfterImports()
@ -58,7 +60,6 @@ initProvider({
// TODO:deprecate:2020 // TODO:deprecate:2020
// Setup web3 // Setup web3
if (typeof window.web3 !== 'undefined') { if (typeof window.web3 !== 'undefined') {
throw new Error(`MetaMask detected another web3. throw new Error(`MetaMask detected another web3.
MetaMask will not work reliably with another web3 extension. MetaMask will not work reliably with another web3 extension.

@ -5,6 +5,7 @@ import ObservableStore from 'obs-store'
* structure of child stores based on configuration * structure of child stores based on configuration
*/ */
export default class ComposableObservableStore extends ObservableStore { export default class ComposableObservableStore extends ObservableStore {
/** /**
* Create a new store * Create a new store
* *

@ -15,7 +15,7 @@ export default function cleanErrorStack (err) {
} else if (msg === '') { } else if (msg === '') {
err.stack = err.name err.stack = err.name
} else { } else {
err.stack = err.name + ': ' + err.message err.stack = `${err.name}: ${err.message}`
} }
return err return err

@ -4,7 +4,7 @@ import promiseToCallback from 'promise-to-callback'
class AsyncWritableStream extends WritableStream { class AsyncWritableStream extends WritableStream {
constructor (asyncWriteFn, _opts) { constructor (asyncWriteFn, _opts) {
const opts = Object.assign({ objectMode: true }, _opts) const opts = { objectMode: true, ..._opts }
super(opts) super(opts)
this._asyncWriteFn = asyncWriteFn this._asyncWriteFn = asyncWriteFn
} }

@ -26,6 +26,7 @@ const hexRe = /^[0-9A-Fa-f]+$/ug
*/ */
export default class DecryptMessageManager extends EventEmitter { export default class DecryptMessageManager extends EventEmitter {
/** /**
* Controller in charge of managing - storing, adding, removing, updating - DecryptMessage. * Controller in charge of managing - storing, adding, removing, updating - DecryptMessage.
* *
@ -100,7 +101,6 @@ export default class DecryptMessageManager extends EventEmitter {
return return
default: default:
reject(new Error(`MetaMask Decryption: Unknown problem: ${JSON.stringify(msgParams)}`)) 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 msgId = createId()
const msgData = { const msgData = {
id: msgId, id: msgId,
msgParams: msgParams, msgParams,
time: time, time,
status: 'unapproved', status: 'unapproved',
type: MESSAGE_TYPE.ETH_DECRYPT, type: MESSAGE_TYPE.ETH_DECRYPT,
} }

@ -23,6 +23,7 @@ import { MESSAGE_TYPE } from './enums'
*/ */
export default class EncryptionPublicKeyManager extends EventEmitter { export default class EncryptionPublicKeyManager extends EventEmitter {
/** /**
* Controller in charge of managing - storing, adding, removing, updating - EncryptionPublicKey. * Controller in charge of managing - storing, adding, removing, updating - EncryptionPublicKey.
* *
@ -94,7 +95,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
return return
default: default:
reject(new Error(`MetaMask EncryptionPublicKey: Unknown problem: ${JSON.stringify(address)}`)) reject(new Error(`MetaMask EncryptionPublicKey: Unknown problem: ${JSON.stringify(address)}`))
return
} }
}) })
}) })
@ -118,7 +118,7 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
const msgData = { const msgData = {
id: msgId, id: msgId,
msgParams: address, msgParams: address,
time: time, time,
status: 'unapproved', status: 'unapproved',
type: MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY, type: MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY,
} }

@ -36,7 +36,7 @@ export default async function resolveEnsToIpfsContentId ({ provider, name }) {
decodedContentHash = contentHash.helpers.cidV0ToV1Base32(decodedContentHash) decodedContentHash = contentHash.helpers.cidV0ToV1Base32(decodedContentHash)
} }
return { type: type, hash: decodedContentHash } return { type, hash: decodedContentHash }
} }
if (isLegacyResolver[0]) { if (isLegacyResolver[0]) {
// lookup content id // lookup content id

@ -19,7 +19,6 @@ export default function extractEthjsErrorMessage (errorMessage) {
const payloadAndError = errorMessage.slice(ethJsRpcSlug.length) const payloadAndError = errorMessage.slice(ethJsRpcSlug.length)
const originalError = payloadAndError.slice(payloadAndError.indexOf(errorLabelPrefix) + errorLabelPrefix.length) const originalError = payloadAndError.slice(payloadAndError.indexOf(errorLabelPrefix) + errorLabelPrefix.length)
return originalError return originalError
} else {
return errorMessage
} }
return errorMessage
} }

@ -6,11 +6,12 @@ import { checkForError } from './util'
* A wrapper around the extension's storage local API * A wrapper around the extension's storage local API
*/ */
export default class ExtensionStore { export default class ExtensionStore {
/** /**
* @constructor * @constructor
*/ */
constructor () { constructor () {
this.isSupported = !!(extension.storage.local) this.isSupported = Boolean(extension.storage.local)
if (!this.isSupported) { if (!this.isSupported) {
log.error('Storage local API not available.') 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 the object is empty, treat it as undefined
if (isEmpty(result)) { if (isEmpty(result)) {
return undefined return undefined
} else {
return result
} }
return result
} }
/** /**

@ -115,8 +115,8 @@ export default class MessageManager extends EventEmitter {
const msgId = createId() const msgId = createId()
const msgData = { const msgData = {
id: msgId, id: msgId,
msgParams: msgParams, msgParams,
time: time, time,
status: 'unapproved', status: 'unapproved',
type: MESSAGE_TYPE.ETH_SIGN, type: MESSAGE_TYPE.ETH_SIGN,
} }
@ -279,8 +279,7 @@ function normalizeMsgData (data) {
if (data.slice(0, 2) === '0x') { if (data.slice(0, 2) === '0x') {
// data is already hex // data is already hex
return data 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'))
} }

@ -28,6 +28,7 @@ const hexRe = /^[0-9A-Fa-f]+$/ug
*/ */
export default class PersonalMessageManager extends EventEmitter { export default class PersonalMessageManager extends EventEmitter {
/** /**
* Controller in charge of managing - storing, adding, removing, updating - PersonalMessage. * Controller in charge of managing - storing, adding, removing, updating - PersonalMessage.
* *
@ -100,7 +101,6 @@ export default class PersonalMessageManager extends EventEmitter {
return return
default: default:
reject(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) 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 msgId = createId()
const msgData = { const msgData = {
id: msgId, id: msgId,
msgParams: msgParams, msgParams,
time: time, time,
status: 'unapproved', status: 'unapproved',
type: MESSAGE_TYPE.PERSONAL_SIGN, type: MESSAGE_TYPE.PERSONAL_SIGN,
} }

@ -2,7 +2,7 @@ const MAX = Number.MAX_SAFE_INTEGER
let idCounter = Math.round(Math.random() * MAX) let idCounter = Math.round(Math.random() * MAX)
export default function createRandomId () { export default function createRandomId () {
idCounter = idCounter % MAX idCounter %= MAX
// eslint-disable-next-line no-plusplus // eslint-disable-next-line no-plusplus
return idCounter++ return idCounter++
} }

@ -30,8 +30,8 @@ const seedPhraseVerifier = {
const keyring = new Keyring(opts) const keyring = new Keyring(opts)
const restoredAccounts = await keyring.getAccounts() const restoredAccounts = await keyring.getAccounts()
log.debug('Created accounts: ' + JSON.stringify(createdAccounts)) log.debug(`Created accounts: ${JSON.stringify(createdAccounts)}`)
log.debug('Restored accounts: ' + JSON.stringify(restoredAccounts)) log.debug(`Restored accounts: ${JSON.stringify(restoredAccounts)}`)
if (restoredAccounts.length !== createdAccounts.length) { if (restoredAccounts.length !== createdAccounts.length) {
// this should not happen... // this should not happen...
@ -40,7 +40,7 @@ const seedPhraseVerifier = {
for (let i = 0; i < restoredAccounts.length; i++) { for (let i = 0; i < restoredAccounts.length; i++) {
if (restoredAccounts[i].toLowerCase() !== createdAccounts[i].toLowerCase()) { 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]}`)
} }
} }
}, },

@ -28,6 +28,7 @@ import { MESSAGE_TYPE } from './enums'
*/ */
export default class TypedMessageManager extends EventEmitter { export default class TypedMessageManager extends EventEmitter {
/** /**
* Controller in charge of managing - storing, adding, removing, updating - TypedMessage. * Controller in charge of managing - storing, adding, removing, updating - TypedMessage.
*/ */
@ -119,8 +120,8 @@ export default class TypedMessageManager extends EventEmitter {
const msgId = createId() const msgId = createId()
const msgData = { const msgData = {
id: msgId, id: msgId,
msgParams: msgParams, msgParams,
time: time, time,
status: 'unapproved', status: 'unapproved',
type: MESSAGE_TYPE.ETH_SIGN_TYPED_DATA, type: MESSAGE_TYPE.ETH_SIGN_TYPED_DATA,
} }

@ -27,9 +27,8 @@ const getEnvironmentTypeMemo = memoize((url) => {
return ENVIRONMENT_TYPE_FULLSCREEN return ENVIRONMENT_TYPE_FULLSCREEN
} else if (parsedUrl.pathname === '/notification.html') { } else if (parsedUrl.pathname === '/notification.html') {
return ENVIRONMENT_TYPE_NOTIFICATION return ENVIRONMENT_TYPE_NOTIFICATION
} else {
return ENVIRONMENT_TYPE_BACKGROUND
} }
return ENVIRONMENT_TYPE_BACKGROUND
}) })
/** /**

@ -63,7 +63,6 @@ import accountImporter from './account-import-strategies'
import selectChainId from './lib/select-chain-id' import selectChainId from './lib/select-chain-id'
import seedPhraseVerifier from './lib/seed-phrase-verifier' import seedPhraseVerifier from './lib/seed-phrase-verifier'
import backgroundMetaMetricsEvent from './lib/background-metametrics' import backgroundMetaMetricsEvent from './lib/background-metametrics'
export default class MetamaskController extends EventEmitter { export default class MetamaskController extends EventEmitter {
@ -274,7 +273,6 @@ export default class MetamaskController extends EventEmitter {
this.encryptionPublicKeyManager = new EncryptionPublicKeyManager() this.encryptionPublicKeyManager = new EncryptionPublicKeyManager()
this.typedMessageManager = new TypedMessageManager({ networkController: this.networkController }) this.typedMessageManager = new TypedMessageManager({ networkController: this.networkController })
this.store.updateStructure({ this.store.updateStructure({
AppStateController: this.appStateController.store, AppStateController: this.appStateController.store,
TransactionController: this.txController.store, TransactionController: this.txController.store,
@ -407,7 +405,7 @@ export default class MetamaskController extends EventEmitter {
*/ */
getState () { getState () {
const { vault } = this.keyringController.store.getState() const { vault } = this.keyringController.store.getState()
const isInitialized = !!vault const isInitialized = Boolean(vault)
return { return {
...{ isInitialized }, ...{ isInitialized },
@ -929,7 +927,6 @@ export default class MetamaskController extends EventEmitter {
return { ...keyState, identities } return { ...keyState, identities }
} }
// //
// Account Management // Account Management
// //
@ -1029,7 +1026,6 @@ export default class MetamaskController extends EventEmitter {
return address return address
} }
/** /**
* Imports an account with the specified import strategy. * Imports an account with the specified import strategy.
* These are defined in app/scripts/account-import-strategies * These are defined in app/scripts/account-import-strategies
@ -1041,7 +1037,7 @@ export default class MetamaskController extends EventEmitter {
*/ */
async importAccountWithStrategy (strategy, args) { async importAccountWithStrategy (strategy, args) {
const privateKey = await accountImporter.importAccount(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() const accounts = await keyring.getAccounts()
// update accounts in preferences controller // update accounts in preferences controller
const allAccounts = await this.keyringController.getAccounts() const allAccounts = await this.keyringController.getAccounts()
@ -1116,10 +1112,10 @@ export default class MetamaskController extends EventEmitter {
cancelMessage (msgId, cb) { cancelMessage (msgId, cb) {
const { messageManager } = this const { messageManager } = this
messageManager.rejectMsg(msgId) messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') { if (!cb || typeof cb !== 'function') {
cb(null, this.getState())
return return
} }
cb(null, this.getState())
} }
// personal_sign methods: // personal_sign methods:
@ -1175,10 +1171,10 @@ export default class MetamaskController extends EventEmitter {
cancelPersonalMessage (msgId, cb) { cancelPersonalMessage (msgId, cb) {
const messageManager = this.personalMessageManager const messageManager = this.personalMessageManager
messageManager.rejectMsg(msgId) messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') { if (!cb || typeof cb !== 'function') {
cb(null, this.getState())
return return
} }
cb(null, this.getState())
} }
// eth_decrypt methods // eth_decrypt methods
@ -1260,10 +1256,10 @@ export default class MetamaskController extends EventEmitter {
cancelDecryptMessage (msgId, cb) { cancelDecryptMessage (msgId, cb) {
const messageManager = this.decryptMessageManager const messageManager = this.decryptMessageManager
messageManager.rejectMsg(msgId) messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') { if (!cb || typeof cb !== 'function') {
cb(null, this.getState())
return return
} }
cb(null, this.getState())
} }
// eth_getEncryptionPublicKey methods // eth_getEncryptionPublicKey methods
@ -1318,10 +1314,10 @@ export default class MetamaskController extends EventEmitter {
cancelEncryptionPublicKey (msgId, cb) { cancelEncryptionPublicKey (msgId, cb) {
const messageManager = this.encryptionPublicKeyManager const messageManager = this.encryptionPublicKeyManager
messageManager.rejectMsg(msgId) messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') { if (!cb || typeof cb !== 'function') {
cb(null, this.getState())
return return
} }
cb(null, this.getState())
} }
// eth_signTypedData methods // eth_signTypedData methods
@ -1379,10 +1375,10 @@ export default class MetamaskController extends EventEmitter {
cancelTypedMessage (msgId, cb) { cancelTypedMessage (msgId, cb) {
const messageManager = this.typedMessageManager const messageManager = this.typedMessageManager
messageManager.rejectMsg(msgId) messageManager.rejectMsg(msgId)
if (cb && typeof cb === 'function') { if (!cb || typeof cb !== 'function') {
cb(null, this.getState())
return return
} }
cb(null, this.getState())
} }
//============================================================================= //=============================================================================
@ -1872,6 +1868,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -1892,7 +1889,6 @@ export default class MetamaskController extends EventEmitter {
return rpcUrl return rpcUrl
} }
/** /**
* A method for selecting a custom URL for an ethereum RPC provider. * A method for selecting a custom URL for an ethereum RPC provider.
* @param {string} rpcTarget - A URL for a valid Ethereum RPC API. * @param {string} rpcTarget - A URL for a valid Ethereum RPC API.
@ -1938,6 +1934,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -1954,6 +1951,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -1970,6 +1968,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -1986,6 +1985,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -2002,6 +2002,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -2013,6 +2014,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -2029,11 +2031,11 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }
/** /**
* A method for setting a user's current locale, affecting the language rendered. * A method for setting a user's current locale, affecting the language rendered.
* @param {string} key - Locale identifier. * @param {string} key - Locale identifier.
@ -2046,6 +2048,7 @@ export default class MetamaskController extends EventEmitter {
return return
} catch (err) { } catch (err) {
cb(err) cb(err)
// eslint-disable-next-line no-useless-return
return return
} }
} }

@ -1,12 +1,11 @@
const version = 2
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 2
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {

@ -1,13 +1,13 @@
import { cloneDeep } from 'lodash'
const version = 3 const version = 3
const oldTestRpc = 'https://rawtestrpc.metamask.io/' const oldTestRpc = 'https://rawtestrpc.metamask.io/'
const newTestRpc = 'https://testrpc.metamask.io/' const newTestRpc = 'https://testrpc.metamask.io/'
import { cloneDeep } from 'lodash'
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {

@ -1,11 +1,11 @@
const version = 4
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 4
export default { export default {
version, version,
migrate: function (versionedData) { migrate (versionedData) {
const safeVersionedData = cloneDeep(versionedData) const safeVersionedData = cloneDeep(versionedData)
safeVersionedData.meta.version = version safeVersionedData.meta.version = version
try { try {

@ -1,5 +1,3 @@
const version = 5
/* /*
This migration moves state from the flat state trie into KeyringController substate 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' import { cloneDeep } from 'lodash'
const version = 5
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -20,7 +19,7 @@ export default {
const newState = selectSubstateForKeyringController(state) const newState = selectSubstateForKeyringController(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn('MetaMask Migration #5' + err.stack) console.warn(`MetaMask Migration #5${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 6
/* /*
This migration moves KeyringController.selectedAddress to PreferencesController.selectedAddress This migration moves KeyringController.selectedAddress to PreferencesController.selectedAddress
@ -8,10 +6,12 @@ This migration moves KeyringController.selectedAddress to PreferencesController.
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 6
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = migrateState(state) const newState = migrateState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 7
/* /*
This migration breaks out the TransactionManager substate This migration breaks out the TransactionManager substate
@ -8,10 +6,12 @@ This migration breaks out the TransactionManager substate
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 7
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 8
/* /*
This migration breaks out the NoticeController substate This migration breaks out the NoticeController substate
@ -8,10 +6,12 @@ This migration breaks out the NoticeController substate
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 8
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 9
/* /*
This migration breaks out the CurrencyController substate This migration breaks out the CurrencyController substate
@ -8,10 +6,12 @@ This migration breaks out the CurrencyController substate
import { cloneDeep, merge } from 'lodash' import { cloneDeep, merge } from 'lodash'
const version = 9
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 10
/* /*
This migration breaks out the ShapeShiftController substate This migration breaks out the ShapeShiftController substate
@ -8,10 +6,12 @@ This migration breaks out the ShapeShiftController substate
import { cloneDeep, merge } from 'lodash' import { cloneDeep, merge } from 'lodash'
const version = 10
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 11
/* /*
This migration removes the discaimer state from our app, which was integrated into our notices. 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' import { cloneDeep } from 'lodash'
const version = 11
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 12
/* /*
This migration modifies our notices to delete their body after being read. 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' import { cloneDeep } from 'lodash'
const version = 12
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 13
/* /*
This migration modifies the network config from ambiguous 'testnet' to explicit 'ropsten' 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' import { cloneDeep } from 'lodash'
const version = 13
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 14
/* /*
This migration removes provider from config and moves it too NetworkController. 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' import { cloneDeep } from 'lodash'
const version = 14
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 15
/* /*
This migration sets transactions with the 'Gave up submitting tx.' err message This migration sets transactions with the 'Gave up submitting tx.' err message
@ -9,10 +7,12 @@ to a 'failed' stated
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 15
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -20,7 +20,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 16
/* /*
This migration sets transactions with the 'Gave up submitting tx.' err message This migration sets transactions with the 'Gave up submitting tx.' err message
@ -9,10 +7,12 @@ to a 'failed' stated
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 16
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -20,7 +20,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 17
/* /*
This migration sets transactions who were retried and marked as failed to submitted 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' import { cloneDeep } from 'lodash'
const version = 17
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 18
/* /*
This migration updates "transaction state history" to diffs style This migration updates "transaction state history" to diffs style
@ -12,11 +10,12 @@ import {
migrateFromSnapshotsToDiffs, migrateFromSnapshotsToDiffs,
} from '../controllers/transactions/lib/tx-state-history-helpers' } from '../controllers/transactions/lib/tx-state-history-helpers'
const version = 18
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -24,7 +23,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,6 +1,4 @@
const version = 19
/* /*
This migration sets transactions as failed This migration sets transactions as failed
@ -10,10 +8,12 @@ whos nonce is too high
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 19
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -21,7 +21,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 20
/* /*
This migration ensures previous installations This migration ensures previous installations
@ -10,10 +8,12 @@ so that we can version notices in the future.
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 20
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -21,7 +21,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,5 +1,3 @@
const version = 21
/* /*
This migration removes the BlackListController from disk state This migration removes the BlackListController from disk state
@ -8,10 +6,12 @@ This migration removes the BlackListController from disk state
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 21
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -19,7 +19,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,6 +1,4 @@
const version = 22
/* /*
This migration adds submittedTime to the txMeta if it is not their 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' import { cloneDeep } from 'lodash'
const version = 22
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -20,7 +20,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,6 +1,4 @@
const version = 23
/* /*
This migration removes transactions that are no longer usefull down to 40 total 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' import { cloneDeep } from 'lodash'
const version = 23
export default { export default {
version, version,
migrate: function (originalVersionedData) { migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
try { try {
@ -20,7 +20,7 @@ export default {
const newState = transformState(state) const newState = transformState(state)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)
}, },

@ -1,6 +1,4 @@
const version = 24
/* /*
This migration ensures that the from address in txParams is to lower case for 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' import { cloneDeep } from 'lodash'
const version = 24
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,6 +1,4 @@
// next version number // next version number
const version = 25
/* /*
normalizes txParams on unconfirmed txs normalizes txParams on unconfirmed txs
@ -10,10 +8,12 @@ import ethUtil from 'ethereumjs-util'
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 25
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,5 +1,3 @@
const version = 26
/* /*
This migration moves the identities stored in the KeyringController 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' import { cloneDeep } from 'lodash'
const version = 26
export default { export default {
version, version,
migrate (originalVersionedData) { migrate (originalVersionedData) {
@ -18,7 +18,7 @@ export default {
const state = versionedData.data const state = versionedData.data
versionedData.data = transformState(state) versionedData.data = transformState(state)
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
return Promise.reject(err) return Promise.reject(err)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)

@ -1,6 +1,4 @@
// next version number // next version number
const version = 27
/* /*
normalizes txParams on unconfirmed txs normalizes txParams on unconfirmed txs
@ -8,10 +6,12 @@ normalizes txParams on unconfirmed txs
*/ */
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 27
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,6 +1,4 @@
// next version number // next version number
const version = 28
/* /*
normalizes txParams on unconfirmed txs normalizes txParams on unconfirmed txs
@ -8,10 +6,12 @@ normalizes txParams on unconfirmed txs
*/ */
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 28
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,7 +1,8 @@
// next version number // next version number
const version = 29
import failTxsThat from './fail-tx' import failTxsThat from './fail-tx'
const version = 29
// time // time
const seconds = 1000 const seconds = 1000
const minutes = 60 * seconds const minutes = 60 * seconds

@ -1,6 +1,4 @@
// next version number // next version number
const version = 30
/* /*
removes invalid chaids from preferences and networkController for custom rpcs 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' import { cloneDeep } from 'lodash'
const version = 30
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data
@ -29,7 +29,7 @@ function transformState (state) {
if (frequentRpcListDetail) { if (frequentRpcListDetail) {
frequentRpcListDetail.forEach((rpc, index) => { frequentRpcListDetail.forEach((rpc, index) => {
// eslint-disable-next-line radix // 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 delete frequentRpcListDetail[index].chainId
} }
}) })

@ -1,7 +1,8 @@
// next version number // next version number
const version = 31
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 31
/* /*
* The purpose of this migration is to properly set the completedOnboarding flag based on the state * The purpose of this migration is to properly set the completedOnboarding flag based on the state
* of the KeyringController. * of the KeyringController.
@ -9,7 +10,7 @@ import { cloneDeep } from 'lodash'
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 32
import { cloneDeep } from 'lodash' 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 * The purpose of this migration is to set the {@code completedUiMigration} flag based on the user's UI preferences
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,6 +1,4 @@
// next version number // next version number
const version = 33
/* /*
Cleans up notices and assocated notice controller code Cleans up notices and assocated notice controller code
@ -9,10 +7,12 @@ Cleans up notices and assocated notice controller code
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 33
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,13 +1,14 @@
const version = 34
import { cloneDeep } from 'lodash' 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 * 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}. * if it was {@code false}.
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,6 +1,4 @@
// next version number // next version number
const version = 35
/* /*
Removes the deprecated 'seedWords' state Removes the deprecated 'seedWords' state
@ -9,10 +7,12 @@ Removes the deprecated 'seedWords' state
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 35
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
versionedData.data = transformState(versionedData.data) versionedData.data = transformState(versionedData.data)

@ -1,12 +1,13 @@
const version = 36
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 36
/** /**
* The purpose of this migration is to remove the {@code privacyMode} feature flag. * The purpose of this migration is to remove the {@code privacyMode} feature flag.
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,7 +1,8 @@
const version = 37
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
import { util } from '@metamask/controllers' import { util } from '@metamask/controllers'
const version = 37
/** /**
* The purpose of this migration is to update the address book state * The purpose of this migration is to update the address book state
* to the new schema with chainId as a key. * to the new schema with chainId as a key.
@ -9,7 +10,7 @@ import { util } from '@metamask/controllers'
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 38
import { cloneDeep } from 'lodash' 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 * The purpose of this migration is to assign all users to a test group for the fullScreenVsPopup a/b test
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,7 +1,8 @@
const version = 39
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
import ethUtil from 'ethereumjs-util' import ethUtil from 'ethereumjs-util'
const version = 39
const DAI_V1_CONTRACT_ADDRESS = '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359' const DAI_V1_CONTRACT_ADDRESS = '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359'
const DAI_V1_TOKEN_SYMBOL = 'DAI' const DAI_V1_TOKEN_SYMBOL = 'DAI'
const SAI_TOKEN_SYMBOL = 'SAI' const SAI_TOKEN_SYMBOL = 'SAI'
@ -21,7 +22,7 @@ function isOldDai (token = {}) {
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,6 +1,7 @@
const version = 40
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 40
/** /**
* Site connections are now managed by the PermissionsController, and the * Site connections are now managed by the PermissionsController, and the
* ProviderApprovalController is removed. This migration deletes all * ProviderApprovalController is removed. This migration deletes all
@ -8,7 +9,7 @@ import { cloneDeep } from 'lodash'
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 41
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 41
/** /**
* PreferencesController.autoLogoutTimeLimit -> autoLockTimeLimit * PreferencesController.autoLogoutTimeLimit -> autoLockTimeLimit
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,13 +1,14 @@
const version = 42
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 42
/** /**
* Initialize `connectedStatusPopoverHasBeenShown` to `false` if it hasn't yet been set, * Initialize `connectedStatusPopoverHasBeenShown` to `false` if it hasn't yet been set,
* so that existing users are introduced to the new connected status indicator * so that existing users are introduced to the new connected status indicator
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 43
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 43
/** /**
* Remove unused 'currentAccountTab' state * Remove unused 'currentAccountTab' state
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 44
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 44
/** /**
* Remove unused 'mkrMigrationReminderTimestamp' state from the `AppStateController` * Remove unused 'mkrMigrationReminderTimestamp' state from the `AppStateController`
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 45
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 45
/** /**
* Replaces {@code PreferencesController.ipfsGateway} with 'dweb.link' if set * Replaces {@code PreferencesController.ipfsGateway} with 'dweb.link' if set
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 46
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 46
/** /**
* Delete {@code ABTestController} state * Delete {@code ABTestController} state
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -1,12 +1,13 @@
const version = 47
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 47
/** /**
* Stringify the `metamaskNetworkId` property of all transactions * Stringify the `metamaskNetworkId` property of all transactions
*/ */
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -9,7 +9,7 @@ export default function failTxsThat (version, reason, condition) {
const newState = transformState(state, condition, reason) const newState = transformState(state, condition, reason)
versionedData.data = newState versionedData.data = newState
} catch (err) { } catch (err) {
console.warn(`MetaMask Migration #${version}` + err.stack) console.warn(`MetaMask Migration #${version}${err.stack}`)
} }
return Promise.resolve(versionedData) return Promise.resolve(versionedData)

@ -1,6 +1,4 @@
// next version number // next version number
const version = 0
/* /*
description of migration and what it does description of migration and what it does
@ -9,10 +7,12 @@ description of migration and what it does
import { cloneDeep } from 'lodash' import { cloneDeep } from 'lodash'
const version = 0
export default { export default {
version, version,
migrate: async function (originalVersionedData) { async migrate (originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData) const versionedData = cloneDeep(originalVersionedData)
versionedData.meta.version = version versionedData.meta.version = version
const state = versionedData.data const state = versionedData.data

@ -105,6 +105,7 @@ export default class ExtensionPlatform {
}) })
} catch (e) { } catch (e) {
cb(e) cb(e)
// eslint-disable-next-line no-useless-return
return return
} }
} }
@ -210,10 +211,11 @@ export default class ExtensionPlatform {
url, url,
{ {
'type': 'basic', 'type': 'basic',
'title': title, title,
'iconUrl': extension.extension.getURL('../../images/icon-64.png'), 'iconUrl': extension.extension.getURL('../../images/icon-64.png'),
'message': message, message,
}) },
)
} }
_subscribeToNotificationClicked () { _subscribeToNotificationClicked () {

@ -9,7 +9,6 @@ import '@formatjs/intl-relativetimeformat/polyfill'
import { EventEmitter } from 'events' import { EventEmitter } from 'events'
import PortStream from 'extension-port-stream' import PortStream from 'extension-port-stream'
import extension from 'extensionizer' import extension from 'extensionizer'
import Dnode from 'dnode' import Dnode from 'dnode'
@ -151,7 +150,7 @@ function setupWeb3Connection (connectionStream) {
function setupControllerConnection (connectionStream, cb) { function setupControllerConnection (connectionStream, cb) {
const eventEmitter = new EventEmitter() const eventEmitter = new EventEmitter()
const backgroundDnode = Dnode({ const backgroundDnode = Dnode({
sendUpdate: function (state) { sendUpdate (state) {
eventEmitter.emit('update', state) eventEmitter.emit('update', state)
}, },
}) })

@ -123,9 +123,8 @@ function getSymbolNormal (value) {
return SYMBOLS.ThreeQuarters return SYMBOLS.ThreeQuarters
} else if (rounded === 7 / 8) { } else if (rounded === 7 / 8) {
return SYMBOLS.SevenEighths return SYMBOLS.SevenEighths
} else {
return SYMBOLS.Full
} }
return SYMBOLS.Full
} }
// get partial block char for value (right-adjusted) // get partial block char for value (right-adjusted)
@ -144,7 +143,6 @@ function getSymbolNormalRight (value) {
return SYMBOLS.RightEighth return SYMBOLS.RightEighth
} else if (rounded === 1) { } else if (rounded === 1) {
return SYMBOLS.Space return SYMBOLS.Space
} else {
throw new Error('getSymbolNormalRight got unexpected result')
} }
throw new Error('getSymbolNormalRight got unexpected result')
} }

@ -9,7 +9,6 @@ const { createTask, composeParallel } = require('./task')
module.exports = createEtcTasks module.exports = createEtcTasks
function createEtcTasks ({ browserPlatforms, livereload }) { function createEtcTasks ({ browserPlatforms, livereload }) {
const clean = createTask('clean', async function clean () { const clean = createTask('clean', async function clean () {

@ -31,7 +31,8 @@ function defineAllTasks () {
const { clean, reload, zip } = createEtcTasks({ livereload, browserPlatforms }) const { clean, reload, zip } = createEtcTasks({ livereload, browserPlatforms })
// build for development (livereload) // build for development (livereload)
createTask('dev', createTask(
'dev',
composeSeries( composeSeries(
clean, clean,
styleTasks.dev, styleTasks.dev,
@ -45,7 +46,8 @@ function defineAllTasks () {
) )
// build for test development (livereload) // build for test development (livereload)
createTask('testDev', createTask(
'testDev',
composeSeries( composeSeries(
clean, clean,
styleTasks.dev, styleTasks.dev,
@ -59,7 +61,8 @@ function defineAllTasks () {
) )
// build for prod release // build for prod release
createTask('prod', createTask(
'prod',
composeSeries( composeSeries(
clean, clean,
styleTasks.prod, styleTasks.prod,
@ -73,7 +76,8 @@ function defineAllTasks () {
) )
// build for CI testing // build for CI testing
createTask('test', createTask(
'test',
composeSeries( composeSeries(
clean, clean,
styleTasks.prod, styleTasks.prod,

@ -7,7 +7,6 @@ const { createTask, composeSeries } = require('./task')
module.exports = createManifestTasks module.exports = createManifestTasks
const scriptsToExcludeFromBackgroundDevBuild = { const scriptsToExcludeFromBackgroundDevBuild = {
'bg-libs.js': true, 'bg-libs.js': true,
} }

@ -22,7 +22,6 @@ const { createTask, composeParallel, composeSeries, runInChildProcess } = requir
module.exports = createScriptTasks module.exports = createScriptTasks
const dependencies = Object.keys((packageJSON && packageJSON.dependencies) || {}) const dependencies = Object.keys((packageJSON && packageJSON.dependencies) || {})
const materialUIDependencies = ['@material-ui/core'] const materialUIDependencies = ['@material-ui/core']
const reactDepenendencies = dependencies.filter((dep) => dep.match(/react/u)) const reactDepenendencies = dependencies.filter((dep) => dep.match(/react/u))
@ -72,7 +71,6 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
return { prod, dev, testDev, test } return { prod, dev, testDev, test }
function createTasksForBuildJsDeps ({ key, filename }) { function createTasksForBuildJsDeps ({ key, filename }) {
return createTask(`scripts:deps:${key}`, bundleTask({ return createTask(`scripts:deps:${key}`, bundleTask({
label: filename, label: filename,
@ -83,7 +81,6 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
})) }))
} }
function createTasksForBuildJsExtension ({ taskPrefix, devMode, testing }) { function createTasksForBuildJsExtension ({ taskPrefix, devMode, testing }) {
const standardBundles = [ const standardBundles = [
'background', 'background',
@ -93,14 +90,12 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
const standardSubtasks = standardBundles.map((filename) => { const standardSubtasks = standardBundles.map((filename) => {
return createTask(`${taskPrefix}:${filename}`, return createTask(`${taskPrefix}:${filename}`,
createBundleTaskForBuildJsExtensionNormal({ filename, devMode, testing }), createBundleTaskForBuildJsExtensionNormal({ filename, devMode, testing }))
)
}) })
// inpage must be built before contentscript // inpage must be built before contentscript
// because inpage bundle result is included inside contentscript // because inpage bundle result is included inside contentscript
const contentscriptSubtask = createTask(`${taskPrefix}:contentscript`, const contentscriptSubtask = createTask(`${taskPrefix}:contentscript`,
createTaskForBuildJsExtensionContentscript({ devMode, testing }), createTaskForBuildJsExtensionContentscript({ devMode, testing }))
)
// task for initiating livereload // task for initiating livereload
const initiateLiveReload = async () => { const initiateLiveReload = async () => {
@ -159,7 +154,6 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
) )
} }
function bundleTask (opts) { function bundleTask (opts) {
let bundler let bundler
@ -203,7 +197,7 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
buildStream = buildStream buildStream = buildStream
.pipe(terser({ .pipe(terser({
mangle: { mangle: {
reserved: [ 'MetamaskInpageProvider' ], reserved: ['MetamaskInpageProvider'],
}, },
sourceMap: { sourceMap: {
content: true, content: true,
@ -287,9 +281,9 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
if (!opts.buildLib) { if (!opts.buildLib) {
if (opts.devMode && opts.filename === 'ui.js') { 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 { } else {
browserifyOpts['entries'] = [opts.filepath] browserifyOpts.entries = [opts.filepath]
} }
} }
@ -348,10 +342,8 @@ function createScriptTasks ({ browserPlatforms, livereload }) {
return bundler return bundler
} }
} }
function beep () { function beep () {
process.stdout.write('\x07') process.stdout.write('\x07')
} }
@ -364,13 +356,12 @@ function getEnvironment ({ devMode, test }) {
return 'testing' return 'testing'
} else if (process.env.CIRCLE_BRANCH === 'master') { } else if (process.env.CIRCLE_BRANCH === 'master') {
return 'production' 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' return 'release-candidate'
} else if (process.env.CIRCLE_BRANCH === 'develop') { } else if (process.env.CIRCLE_BRANCH === 'develop') {
return 'staging' return 'staging'
} else if (process.env.CIRCLE_PULL_REQUEST) { } else if (process.env.CIRCLE_PULL_REQUEST) {
return 'pull-request' return 'pull-request'
} else {
return 'other'
} }
return 'other'
} }

@ -9,7 +9,6 @@ const { createTask, composeSeries } = require('./task')
module.exports = createStaticAssetTasks module.exports = createStaticAssetTasks
const copyTargets = [ const copyTargets = [
{ {
src: `./app/_locales/`, src: `./app/_locales/`,

@ -11,11 +11,9 @@ const rename = require('gulp-rename')
const pump = pify(require('pump')) const pump = pify(require('pump'))
const { createTask } = require('./task') const { createTask } = require('./task')
// scss compilation and autoprefixing tasks // scss compilation and autoprefixing tasks
module.exports = createStyleTasks module.exports = createStyleTasks
function createStyleTasks ({ livereload }) { function createStyleTasks ({ livereload }) {
const prod = createTask('styles:prod', createScssBuildTask({ const prod = createTask('styles:prod', createScssBuildTask({
@ -44,7 +42,6 @@ function createStyleTasks ({ livereload }) {
return { prod, dev, lint } return { prod, dev, lint }
function createScssBuildTask ({ src, dest, devMode, pattern }) { function createScssBuildTask ({ src, dest, devMode, pattern }) {
return async function () { return async function () {
if (devMode) { if (devMode) {
@ -75,5 +72,4 @@ function createStyleTasks ({ livereload }) {
} }
} }
} }

@ -8,7 +8,6 @@ module.exports = { detectAndRunEntryTask, tasks, taskEvents, createTask, runTask
const { setupTaskDisplay } = require('./display') const { setupTaskDisplay } = require('./display')
function detectAndRunEntryTask () { function detectAndRunEntryTask () {
// get requested task name and execute // get requested task name and execute
const taskName = process.argv[2] const taskName = process.argv[2]

@ -57,7 +57,7 @@ async function start () {
`dep viz: ${depVizLink}`, `dep viz: ${depVizLink}`,
`<a href="${allArtifactsUrl}">all artifacts</a>`, `<a href="${allArtifactsUrl}">all artifacts</a>`,
] ]
const hiddenContent = `<ul>` + contentRows.map((row) => `<li>${row}</li>`).join('\n') + `</ul>` const hiddenContent = `<ul>${contentRows.map((row) => `<li>${row}</li>`).join('\n')}</ul>`
const exposedContent = `Builds ready [${SHORT_SHA1}]` const exposedContent = `Builds ready [${SHORT_SHA1}]`
const artifactsBody = `<details><summary>${exposedContent}</summary>${hiddenContent}</details>` const artifactsBody = `<details><summary>${exposedContent}</summary>${hiddenContent}</details>`

@ -3,7 +3,7 @@ function delay (time) {
} }
async function loadFromMock3Box (key) { 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() const text = await res.text()
return text.length ? JSON.parse(text) : null return text.length ? JSON.parse(text) : null
} }

@ -18,7 +18,6 @@ start().catch((error) => {
process.exit(1) process.exit(1)
}) })
async function start () { async function start () {
const targetFiles = [ const targetFiles = [
`background.js`, `background.js`,

@ -61,7 +61,7 @@ const main = async () => {
} }
while (args.length) { while (args.length) {
if (/^(--port|-p)$/u.test(args[0])) { if ((/^(--port|-p)$/u).test(args[0])) {
if (args[1] === undefined) { if (args[1] === undefined) {
throw new Error('Missing port argument') throw new Error('Missing port argument')
} }

@ -104,7 +104,7 @@ async function getLocale (code) {
async function writeLocale (code, locale) { async function writeLocale (code, locale) {
try { try {
const localeFilePath = getLocalePath(code) 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) { } catch (e) {
if (e.code === 'ENOENT') { if (e.code === 'ENOENT') {
log.error('Locale file not found') log.error('Locale file not found')
@ -150,7 +150,7 @@ async function verifyLocale (code) {
if (extraItems.length > 0) { if (extraItems.length > 0) {
if (fix) { if (fix) {
const newLocale = Object.assign({}, targetLocale) const newLocale = { ...targetLocale }
for (const item of extraItems) { for (const item of extraItems) {
delete newLocale[item] delete newLocale[item]
} }
@ -215,7 +215,7 @@ async function verifyEnglishLocale () {
} }
if (unusedMessages.length > 0 && fix) { if (unusedMessages.length > 0 && fix) {
const newLocale = Object.assign({}, englishLocale) const newLocale = { ...englishLocale }
for (const key of unusedMessages) { for (const key of unusedMessages) {
delete newLocale[key] delete newLocale[key]
} }
@ -244,7 +244,6 @@ async function * getFileContents (filenames) {
} }
} }
function compareLocalesForMissingItems ({ base, subject }) { function compareLocalesForMissingItems ({ base, subject }) {
return Object.keys(base).filter((key) => !subject[key]) return Object.keys(base).filter((key) => !subject[key])
} }

@ -179,7 +179,7 @@
"@babel/preset-env": "^7.5.5", "@babel/preset-env": "^7.5.5",
"@babel/preset-react": "^7.0.0", "@babel/preset-react": "^7.0.0",
"@babel/register": "^7.5.5", "@babel/register": "^7.5.5",
"@metamask/eslint-config": "^1.1.0", "@metamask/eslint-config": "^3.0.0",
"@metamask/forwarder": "^1.1.0", "@metamask/forwarder": "^1.1.0",
"@metamask/test-dapp": "^3.1.0", "@metamask/test-dapp": "^3.1.0",
"@sentry/cli": "^1.49.0", "@sentry/cli": "^1.49.0",

@ -118,7 +118,7 @@ async function main () {
let existingParentDirectory let existingParentDirectory
while (args.length) { while (args.length) {
if (/^(--pages|-p)$/u.test(args[0])) { if ((/^(--pages|-p)$/u).test(args[0])) {
if (args[1] === undefined) { if (args[1] === undefined) {
throw new Error('Missing pages argument') throw new Error('Missing pages argument')
} }
@ -129,7 +129,7 @@ async function main () {
} }
} }
args.splice(0, 2) args.splice(0, 2)
} else if (/^(--samples|-s)$/u.test(args[0])) { } else if ((/^(--samples|-s)$/u).test(args[0])) {
if (args[1] === undefined) { if (args[1] === undefined) {
throw new Error('Missing number of samples') throw new Error('Missing number of samples')
} }
@ -138,7 +138,7 @@ async function main () {
throw new Error(`Invalid 'samples' argument given: '${args[1]}'`) throw new Error(`Invalid 'samples' argument given: '${args[1]}'`)
} }
args.splice(0, 2) args.splice(0, 2)
} else if (/^(--out|-o)$/u.test(args[0])) { } else if ((/^(--out|-o)$/u).test(args[0])) {
if (args[1] === undefined) { if (args[1] === undefined) {
throw new Error('Missing output filename') throw new Error('Missing output filename')
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save