Merge branch 'master' into i18n

feature/default_network_editable
Thomas Huang 7 years ago committed by GitHub
commit b7c7083a11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 152
      .circleci/config.yml
  2. 1
      .gitignore
  3. 3
      .nsprc
  4. 1
      CHANGELOG.md
  5. 4
      app/scripts/controllers/transactions.js
  6. 48
      app/scripts/lib/seed-phrase-verifier.js
  7. 2
      app/scripts/lib/tx-state-manager.js
  8. 51
      app/scripts/metamask-controller.js
  9. 17
      circle.yml
  10. 1
      mock-dev.js
  11. 62
      old-ui/app/accounts/import/json.js
  12. 22241
      package-lock.json
  13. 16
      package.json
  14. 4
      test/unit/message-manager-test.js
  15. 10
      test/unit/network-contoller-test.js
  16. 133
      test/unit/seed-phrase-verifier-test.js
  17. 2
      test/unit/tx-state-manager-test.js
  18. 80
      ui/app/accounts/import/json.js
  19. 103
      ui/app/actions.js
  20. 16
      ui/app/add-token.js
  21. 8
      ui/app/components/dropdowns/network-dropdown.js
  22. 4
      ui/app/components/pending-tx/confirm-send-token.js
  23. 2
      ui/app/css/itcss/components/new-account.scss
  24. 4
      ui/app/css/itcss/settings/variables.scss
  25. 19
      ui/app/keychains/hd/restore-vault.js
  26. 14
      ui/app/reducers/app.js
  27. 2
      ui/app/reducers/metamask.js
  28. 809
      yarn.lock

@ -0,0 +1,152 @@
version: 2
workflows:
version: 2
full_test:
jobs:
- prep-deps-npm
- prep-deps-firefox
- prep-scss:
requires:
- prep-deps-npm
- test-lint:
requires:
- prep-deps-npm
- test-unit:
requires:
- prep-deps-npm
- test-integration-mascara:
requires:
- prep-deps-npm
- prep-deps-firefox
- prep-scss
- test-integration-flat:
requires:
- prep-deps-npm
- prep-deps-firefox
- prep-scss
jobs:
prep-deps-npm:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: Install deps via npm
command: npm install
- save_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
paths:
- node_modules
prep-deps-firefox:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- run:
name: Download Firefox
command: >
wget https://ftp.mozilla.org/pub/firefox/releases/58.0/linux-x86_64/en-US/firefox-58.0.tar.bz2
&& tar xjf firefox-58.0.tar.bz2
- save_cache:
key: dependency-cache-firefox-{{ .Revision }}
paths:
- firefox
prep-scss:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: Get Scss Cache key
# this allows us to checksum against a whole directory
command: find ui/app/css -type f -exec md5sum {} \; | sort -k 2 > scss_checksum
- run:
name: Build for integration tests
command: npm run test:integration:build
- save_cache:
key: scss-cache-{{ checksum "scss_checksum" }}
paths:
- ui/app/css/output
test-lint:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: Test
command: npm run lint
test-unit:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: test:coverage
command: npm run test:coverage
test-integration-flat:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-firefox-{{ .Revision }}
- run:
name: Install firefox
command: >
sudo rm -r /opt/firefox
&& sudo mv firefox /opt/firefox58
&& sudo mv /usr/bin/firefox /usr/bin/firefox-old
&& sudo ln -s /opt/firefox58/firefox /usr/bin/firefox
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: Get Scss Cache key
# this allows us to checksum against a whole directory
command: find ui/app/css -type f -exec md5sum {} \; | sort -k 2 > scss_checksum
- restore_cache:
key: scss-cache-{{ checksum "scss_checksum" }}
- run:
name: test:integration:flat
command: npm run test:flat
test-integration-mascara:
docker:
- image: circleci/node:8-browsers
steps:
- checkout
- restore_cache:
key: dependency-cache-firefox-{{ .Revision }}
- run:
name: Install firefox
command: >
sudo rm -r /opt/firefox
&& sudo mv firefox /opt/firefox58
&& sudo mv /usr/bin/firefox /usr/bin/firefox-old
&& sudo ln -s /opt/firefox58/firefox /usr/bin/firefox
- restore_cache:
key: dependency-cache-{{ checksum "package-lock.json" }}
- run:
name: Get Scss Cache key
# this allows us to checksum against a whole directory
command: find ui/app/css -type f -exec md5sum {} \; | sort -k 2 > scss_checksum
- restore_cache:
key: scss-cache-{{ checksum "scss_checksum" }}
- run:
name: test:integration:mascara
command: npm run test:mascara

1
.gitignore vendored

@ -1,6 +1,5 @@
npm-debug.log
node_modules
package-lock.json
app/bower_components
test/bower_components

@ -0,0 +1,3 @@
{
"exceptions": ["https://nodesecurity.io/advisories/566"]
}

@ -1,6 +1,7 @@
# Changelog
## Current Master
- Fix flashing to Log in screen after logging in or restoring from seed phrase.
## 4.2.0 Tue Mar 06 2018

@ -3,7 +3,7 @@ const ObservableStore = require('obs-store')
const ethUtil = require('ethereumjs-util')
const Transaction = require('ethereumjs-tx')
const EthQuery = require('ethjs-query')
const TransactionStateManger = require('../lib/tx-state-manager')
const TransactionStateManager = require('../lib/tx-state-manager')
const TxGasUtil = require('../lib/tx-gas-utils')
const PendingTransactionTracker = require('../lib/pending-tx-tracker')
const createId = require('../lib/random-id')
@ -38,7 +38,7 @@ module.exports = class TransactionController extends EventEmitter {
this.query = new EthQuery(this.provider)
this.txGasUtil = new TxGasUtil(this.provider)
this.txStateManager = new TransactionStateManger({
this.txStateManager = new TransactionStateManager({
initState: opts.initState,
txHistoryLimit: opts.txHistoryLimit,
getNetwork: this.getNetwork.bind(this),

@ -0,0 +1,48 @@
const KeyringController = require('eth-keyring-controller')
const seedPhraseVerifier = {
// Verifies if the seed words can restore the accounts.
//
// The seed words can recreate the primary keyring and the accounts belonging to it.
// The created accounts in the primary keyring are always the same.
// The keyring always creates the accounts in the same sequence.
verifyAccounts (createdAccounts, seedWords) {
return new Promise((resolve, reject) => {
if (!createdAccounts || createdAccounts.length < 1) {
return reject(new Error('No created accounts defined.'))
}
const keyringController = new KeyringController({})
const Keyring = keyringController.getKeyringClassForType('HD Key Tree')
const opts = {
mnemonic: seedWords,
numberOfAccounts: createdAccounts.length,
}
const keyring = new Keyring(opts)
keyring.getAccounts()
.then((restoredAccounts) => {
log.debug('Created accounts: ' + JSON.stringify(createdAccounts))
log.debug('Restored accounts: ' + JSON.stringify(restoredAccounts))
if (restoredAccounts.length !== createdAccounts.length) {
// this should not happen...
return reject(new Error('Wrong number of accounts'))
}
for (let i = 0; i < restoredAccounts.length; i++) {
if (restoredAccounts[i].toLowerCase() !== createdAccounts[i].toLowerCase()) {
return reject(new Error('Not identical accounts! Original: ' + createdAccounts[i] + ', Restored: ' + restoredAccounts[i]))
}
}
return resolve()
})
})
},
}
module.exports = seedPhraseVerifier

@ -4,7 +4,7 @@ const ObservableStore = require('obs-store')
const ethUtil = require('ethereumjs-util')
const txStateHistoryHelper = require('./tx-state-history-helper')
module.exports = class TransactionStateManger extends EventEmitter {
module.exports = class TransactionStateManager extends EventEmitter {
constructor ({ initState, txHistoryLimit, getNetwork }) {
super()

@ -37,6 +37,7 @@ const version = require('../manifest.json').version
const BN = require('ethereumjs-util').BN
const GWEI_BN = new BN('1000000000')
const percentile = require('percentile')
const seedPhraseVerifier = require('./lib/seed-phrase-verifier')
module.exports = class MetamaskController extends EventEmitter {
@ -344,6 +345,7 @@ module.exports = class MetamaskController extends EventEmitter {
// primary HD keyring management
addNewAccount: nodeify(this.addNewAccount, this),
placeSeedWords: this.placeSeedWords.bind(this),
verifySeedPhrase: nodeify(this.verifySeedPhrase, this),
clearSeedWordCache: this.clearSeedWordCache.bind(this),
resetAccount: this.resetAccount.bind(this),
importAccountWithStrategy: this.importAccountWithStrategy.bind(this),
@ -565,14 +567,18 @@ module.exports = class MetamaskController extends EventEmitter {
// Opinionated Keyring Management
//
async addNewAccount (cb) {
async addNewAccount () {
const primaryKeyring = this.keyringController.getKeyringsByType('HD Key Tree')[0]
if (!primaryKeyring) return cb(new Error('MetamaskController - No HD Key Tree found'))
if (!primaryKeyring) {
throw new Error('MetamaskController - No HD Key Tree found')
}
const keyringController = this.keyringController
const oldAccounts = await keyringController.getAccounts()
const keyState = await keyringController.addNewAccount(primaryKeyring)
const newAccounts = await keyringController.getAccounts()
await this.verifySeedPhrase()
newAccounts.forEach((address) => {
if (!oldAccounts.includes(address)) {
this.preferencesController.setSelectedAddress(address)
@ -587,16 +593,45 @@ module.exports = class MetamaskController extends EventEmitter {
// Used when creating a first vault, to allow confirmation.
// Also used when revealing the seed words in the confirmation view.
placeSeedWords (cb) {
const primaryKeyring = this.keyringController.getKeyringsByType('HD Key Tree')[0]
if (!primaryKeyring) return cb(new Error('MetamaskController - No HD Key Tree found'))
primaryKeyring.serialize()
.then((serialized) => {
const seedWords = serialized.mnemonic
this.verifySeedPhrase()
.then((seedWords) => {
this.configManager.setSeedWords(seedWords)
cb(null, seedWords)
return cb(null, seedWords)
})
.catch((err) => {
return cb(err)
})
}
// Verifies the current vault's seed words if they can restore the
// accounts belonging to the current vault.
//
// Called when the first account is created and on unlocking the vault.
async verifySeedPhrase () {
const primaryKeyring = this.keyringController.getKeyringsByType('HD Key Tree')[0]
if (!primaryKeyring) {
throw new Error('MetamaskController - No HD Key Tree found')
}
const serialized = await primaryKeyring.serialize()
const seedWords = serialized.mnemonic
const accounts = await primaryKeyring.getAccounts()
if (accounts.length < 1) {
throw new Error('MetamaskController - No accounts found')
}
try {
await seedPhraseVerifier.verifyAccounts(accounts, seedWords)
return seedWords
} catch (err) {
log.error(err.message)
throw err
}
}
// ClearSeedWordCache
//
// Removes the primary account's seed words from the UI's state tree,

@ -1,17 +0,0 @@
machine:
node:
version: 8.1.4
test:
override:
- "npm test"
dependencies:
pre:
- sudo apt-get update
# get latest stable firefox
- sudo apt-get install firefox
- firefox_cmd=`which firefox`; sudo rm -f $firefox_cmd; sudo ln -s `which firefox.ubuntu` $firefox_cmd
# get latest stable chrome
- wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
- sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
- sudo apt-get update
- sudo apt-get install google-chrome-stable

@ -15,7 +15,6 @@
const extend = require('xtend')
const render = require('react-dom').render
const h = require('react-hyperscript')
const pipe = require('mississippi').pipe
const Root = require('./ui/app/root')
const configureStore = require('./ui/app/store')
const actions = require('./ui/app/actions')

@ -1,26 +1,23 @@
const inherits = require('util').inherits
const Component = require('react').Component
const h = require('react-hyperscript')
const connect = require('react-redux').connect
const actions = require('../../../../ui/app/actions')
const FileInput = require('react-simple-file-input').default
const PropTypes = require('prop-types')
const HELP_LINK = 'https://github.com/MetaMask/faq/blob/master/README.md#q-i-cant-use-the-import-feature-for-uploading-a-json-file-the-window-keeps-closing-when-i-try-to-select-a-file'
module.exports = connect(mapStateToProps)(JsonImportSubview)
class JsonImportSubview extends Component {
constructor (props) {
super(props)
function mapStateToProps (state) {
return {
error: state.appState.warning,
this.state = {
file: null,
fileContents: '',
}
}
inherits(JsonImportSubview, Component)
function JsonImportSubview () {
Component.call(this)
}
JsonImportSubview.prototype.render = function () {
render () {
const { error } = this.props
return (
@ -34,7 +31,10 @@ JsonImportSubview.prototype.render = function () {
}, [
h('p', 'Used by a variety of different clients'),
h('a.warning', { href: HELP_LINK, target: '_blank' }, 'File import not working? Click here!'),
h('a.warning', {
href: HELP_LINK,
target: '_blank',
}, 'File import not working? Click here!'),
h(FileInput, {
readAs: 'text',
@ -68,24 +68,23 @@ JsonImportSubview.prototype.render = function () {
)
}
JsonImportSubview.prototype.onLoad = function (event, file) {
onLoad (event, file) {
this.setState({file: file, fileContents: event.target.result})
}
JsonImportSubview.prototype.createKeyringOnEnter = function (event) {
createKeyringOnEnter (event) {
if (event.key === 'Enter') {
event.preventDefault()
this.createNewKeychain()
}
}
JsonImportSubview.prototype.createNewKeychain = function () {
const state = this.state
const { fileContents } = state
createNewKeychain () {
const { fileContents } = this.state
if (!fileContents) {
const message = 'You must select a file to import.'
return this.props.dispatch(actions.displayWarning(message))
return this.props.displayWarning(message)
}
const passwordInput = document.getElementById('json-password-box')
@ -93,8 +92,31 @@ JsonImportSubview.prototype.createNewKeychain = function () {
if (!password) {
const message = 'You must enter a password for the selected file.'
return this.props.dispatch(actions.displayWarning(message))
return this.props.displayWarning(message)
}
this.props.dispatch(actions.importNewAccount('JSON File', [ fileContents, password ]))
this.props.importNewAccount([ fileContents, password ])
}
}
JsonImportSubview.propTypes = {
error: PropTypes.string,
displayWarning: PropTypes.func,
importNewAccount: PropTypes.func,
}
const mapStateToProps = state => {
return {
error: state.appState.warning,
}
}
const mapDispatchToProps = dispatch => {
return {
goHome: () => dispatch(actions.goHome()),
displayWarning: warning => dispatch(actions.displayWarning(warning)),
importNewAccount: options => dispatch(actions.importNewAccount('JSON File', options)),
}
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(JsonImportSubview)

22241
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -15,7 +15,8 @@
"test": "npm run lint && npm run test:coverage && npm run test:integration",
"test:unit": "METAMASK_ENV=test mocha --exit --require babel-core/register --require test/helper.js --recursive \"test/unit/**/*.js\"",
"test:single": "METAMASK_ENV=test mocha --require test/helper.js",
"test:integration": "gulp build:scss && npm run test:flat && npm run test:mascara",
"test:integration": "npm run test:integration:build && npm run test:flat && npm run test:mascara",
"test:integration:build": "gulp build:scss",
"test:coverage": "nyc npm run test:unit && npm run test:coveralls-upload",
"test:coveralls-upload": "if [ $COVERALLS_REPO_TOKEN ]; then nyc report --reporter=text-lcov | coveralls; fi",
"test:flat": "npm run test:flat:build && karma start test/flat.conf.js",
@ -105,7 +106,7 @@
"fast-levenshtein": "^2.0.6",
"fuse.js": "^3.2.0",
"gulp": "github:gulpjs/gulp#4.0",
"gulp-autoprefixer": "^4.0.0",
"gulp-autoprefixer": "^5.0.0",
"gulp-eslint": "^4.0.0",
"gulp-sass": "^3.1.0",
"hat": "0.0.3",
@ -125,7 +126,6 @@
"loglevel": "^1.4.1",
"metamascara": "^2.0.0",
"metamask-logo": "^2.1.2",
"mississippi": "^1.2.0",
"mkdirp": "^0.5.1",
"multiplex": "^6.7.0",
"number-to-bn": "^1.7.0",
@ -139,7 +139,7 @@
"post-message-stream": "^3.0.0",
"promise-filter": "^1.1.0",
"promise-to-callback": "^1.0.0",
"pump": "^1.0.2",
"pump": "^3.0.0",
"pumpify": "^1.3.4",
"qrcode-npm": "0.0.3",
"ramda": "^0.24.1",
@ -189,7 +189,7 @@
"babelify": "^8.0.0",
"beefy": "^2.1.5",
"brfs": "^1.4.3",
"browserify": "^14.4.0",
"browserify": "^16.1.1",
"chai": "^4.1.0",
"compression": "^1.7.1",
"coveralls": "^3.0.0",
@ -212,7 +212,7 @@
"gulp-replace": "^0.6.1",
"gulp-sourcemaps": "^2.6.0",
"gulp-stylefmt": "^1.1.0",
"gulp-stylelint": "^4.0.0",
"gulp-stylelint": "^7.0.0",
"gulp-uglify": "^3.0.0",
"gulp-uglify-es": "^1.0.1",
"gulp-util": "^3.0.7",
@ -222,7 +222,7 @@
"jsdom": "^11.1.0",
"jsdom-global": "^3.0.2",
"jshint-stylish": "~2.2.1",
"karma": "^1.7.1",
"karma": "^2.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
"karma-firefox-launcher": "^1.0.1",
@ -244,7 +244,7 @@
"react-testutils-additions": "^15.2.0",
"redux-test-utils": "^0.2.2",
"sinon": "^4.0.0",
"stylelint-config-standard": "^17.0.0",
"stylelint-config-standard": "^18.2.0",
"tape": "^4.5.1",
"testem": "^2.0.0",
"uglifyify": "^4.0.2",

@ -1,11 +1,11 @@
const assert = require('assert')
const MessageManger = require('../../app/scripts/lib/message-manager')
const MessageManager = require('../../app/scripts/lib/message-manager')
describe('Message Manager', function () {
let messageManager
beforeEach(function () {
messageManager = new MessageManger()
messageManager = new MessageManager()
})
describe('#getMsgList', function () {

@ -15,11 +15,8 @@ describe('# Network Controller', function () {
beforeEach(function () {
nock('https://api.infura.io')
.get('/*/')
.reply(200)
nock('https://rinkeby.infura.io')
.persist()
.post('/metamask')
.reply(200)
@ -29,6 +26,11 @@ describe('# Network Controller', function () {
networkController.initializeProvider(networkControllerProviderInit, provider)
})
afterEach(function () {
nock.cleanAll()
})
describe('network', function () {
describe('#provider', function () {
it('provider should be updatable without reassignment', function () {

@ -0,0 +1,133 @@
const assert = require('assert')
const clone = require('clone')
const KeyringController = require('eth-keyring-controller')
const firstTimeState = require('../../app/scripts/first-time-state')
const seedPhraseVerifier = require('../../app/scripts/lib/seed-phrase-verifier')
const mockEncryptor = require('../lib/mock-encryptor')
describe('SeedPhraseVerifier', function () {
describe('verifyAccounts', function () {
let password = 'passw0rd1'
let hdKeyTree = 'HD Key Tree'
let keyringController
let vault
let primaryKeyring
beforeEach(async function () {
keyringController = new KeyringController({
initState: clone(firstTimeState),
encryptor: mockEncryptor,
})
assert(keyringController)
vault = await keyringController.createNewVaultAndKeychain(password)
primaryKeyring = keyringController.getKeyringsByType(hdKeyTree)[0]
})
it('should be able to verify created account with seed words', async function () {
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
let serialized = await primaryKeyring.serialize()
let seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
let result = await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
})
it('should be able to verify created account (upper case) with seed words', async function () {
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
let upperCaseAccounts = [createdAccounts[0].toUpperCase()]
let serialized = await primaryKeyring.serialize()
let seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
let result = await seedPhraseVerifier.verifyAccounts(upperCaseAccounts, seedWords)
})
it('should be able to verify created account (lower case) with seed words', async function () {
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
let lowerCaseAccounts = [createdAccounts[0].toLowerCase()]
let serialized = await primaryKeyring.serialize()
let seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
let result = await seedPhraseVerifier.verifyAccounts(lowerCaseAccounts, seedWords)
})
it('should return error with good but different seed words', async function () {
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
let serialized = await primaryKeyring.serialize()
let seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
try {
let result = await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
assert.fail("Should reject")
} catch (err) {
assert.ok(err.message.indexOf('Not identical accounts!') >= 0, 'Wrong error message')
}
})
it('should return error with undefined existing accounts', async function () {
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
let serialized = await primaryKeyring.serialize()
let seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
try {
let result = await seedPhraseVerifier.verifyAccounts(undefined, seedWords)
assert.fail("Should reject")
} catch (err) {
assert.equal(err.message, 'No created accounts defined.')
}
})
it('should return error with empty accounts array', async function () {
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
let serialized = await primaryKeyring.serialize()
let seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
try {
let result = await seedPhraseVerifier.verifyAccounts([], seedWords)
assert.fail("Should reject")
} catch (err) {
assert.equal(err.message, 'No created accounts defined.')
}
})
it('should be able to verify more than one created account with seed words', async function () {
const keyState = await keyringController.addNewAccount(primaryKeyring)
const keyState2 = await keyringController.addNewAccount(primaryKeyring)
let createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 3)
let serialized = await primaryKeyring.serialize()
let seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
let result = await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
})
})
})

@ -5,7 +5,7 @@ const TxStateManager = require('../../app/scripts/lib/tx-state-manager')
const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper')
const noop = () => true
describe('TransactionStateManger', function () {
describe('TransactionStateManager', function () {
let txStateManager
const currentNetworkId = 42
const otherNetworkId = 2

@ -1,5 +1,5 @@
const inherits = require('util').inherits
const Component = require('react').Component
const PropTypes = require('prop-types')
const h = require('react-hyperscript')
const connect = require('react-redux').connect
const actions = require('../../actions')
@ -8,27 +8,27 @@ const t = require('../../../i18n')
const HELP_LINK = 'https://support.metamask.io/kb/article/7-importing-accounts'
module.exports = connect(mapStateToProps)(JsonImportSubview)
class JsonImportSubview extends Component {
constructor (props) {
super(props)
function mapStateToProps (state) {
return {
error: state.appState.warning,
this.state = {
file: null,
fileContents: '',
}
}
inherits(JsonImportSubview, Component)
function JsonImportSubview () {
Component.call(this)
}
JsonImportSubview.prototype.render = function () {
render () {
const { error } = this.props
return (
h('div.new-account-import-form__json', [
h('p', t('usedByClients')),
h('a.warning', { href: HELP_LINK, target: '_blank' }, t('fileImportFail')),
h('p', 'Used by a variety of different clients'),
h('a.warning', {
href: HELP_LINK,
target: '_blank',
}, 'File import not working? Click here!'),
h(FileInput, {
readAs: 'text',
@ -43,23 +43,23 @@ JsonImportSubview.prototype.render = function () {
h('input.new-account-import-form__input-password', {
type: 'password',
placeholder: t('enterPassword'),
placeholder: 'Enter password',
id: 'json-password-box',
onKeyPress: this.createKeyringOnEnter.bind(this),
}),
h('div.new-account-create-form__buttons', {}, [
h('button.new-account-create-form__button-cancel.allcaps', {
h('button.new-account-create-form__button-cancel', {
onClick: () => this.props.goHome(),
}, [
t('cancel'),
'CANCEL',
]),
h('button.new-account-create-form__button-create.allcaps', {
onClick: () => this.createNewKeychain.bind(this),
h('button.new-account-create-form__button-create', {
onClick: () => this.createNewKeychain(),
}, [
t('import'),
'IMPORT',
]),
]),
@ -69,39 +69,63 @@ JsonImportSubview.prototype.render = function () {
)
}
JsonImportSubview.prototype.onLoad = function (event, file) {
onLoad (event, file) {
this.setState({file: file, fileContents: event.target.result})
}
JsonImportSubview.prototype.createKeyringOnEnter = function (event) {
createKeyringOnEnter (event) {
if (event.key === 'Enter') {
event.preventDefault()
this.createNewKeychain()
}
}
JsonImportSubview.prototype.createNewKeychain = function () {
createNewKeychain () {
const state = this.state
if (!state) {
const message = 'You must select a valid file to import.'
return this.props.dispatch(actions.displayWarning(message))
return this.props.displayWarning(message)
}
const { fileContents } = state
if (!fileContents) {
const message = t('needImportFile')
return this.props.dispatch(actions.displayWarning(message))
const message = 'You must select a file to import.'
return this.props.displayWarning(message)
}
const passwordInput = document.getElementById('json-password-box')
const password = passwordInput.value
if (!password) {
const message = t('needImportPassword')
return this.props.dispatch(actions.displayWarning(message))
const message = 'You must enter a password for the selected file.'
return this.props.displayWarning(message)
}
this.props.dispatch(actions.importNewAccount('JSON File', [ fileContents, password ]))
this.props.importNewJsonAccount([ fileContents, password ])
}
}
JsonImportSubview.propTypes = {
error: PropTypes.string,
goHome: PropTypes.func,
displayWarning: PropTypes.func,
importNewJsonAccount: PropTypes.func,
}
const mapStateToProps = state => {
return {
error: state.appState.warning,
}
}
const mapDispatchToProps = dispatch => {
return {
goHome: () => dispatch(actions.goHome()),
displayWarning: warning => dispatch(actions.displayWarning(warning)),
importNewJsonAccount: options => dispatch(actions.importNewAccount('JSON File', options)),
}
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(JsonImportSubview)

@ -284,19 +284,42 @@ function goHome () {
// async actions
function tryUnlockMetamask (password) {
return (dispatch) => {
return dispatch => {
dispatch(actions.showLoadingIndication())
dispatch(actions.unlockInProgress())
log.debug(`background.submitPassword`)
background.submitPassword(password, (err) => {
dispatch(actions.hideLoadingIndication())
if (err) {
dispatch(actions.unlockFailed(err.message))
} else {
return new Promise((resolve, reject) => {
background.submitPassword(password, error => {
if (error) {
return reject(error)
}
resolve()
})
})
.then(() => {
dispatch(actions.unlockSucceeded())
dispatch(actions.transitionForward())
forceUpdateMetamaskState(dispatch)
return forceUpdateMetamaskState(dispatch)
})
.then(() => {
return new Promise((resolve, reject) => {
background.verifySeedPhrase(err => {
if (err) {
dispatch(actions.displayWarning(err.message))
}
resolve()
})
})
})
.then(() => {
dispatch(actions.transitionForward())
dispatch(actions.hideLoadingIndication())
})
.catch(err => {
dispatch(actions.unlockFailed(err.message))
dispatch(actions.hideLoadingIndication())
})
}
}
@ -339,46 +362,53 @@ function createNewVaultAndRestore (password, seed) {
log.debug(`background.createNewVaultAndRestore`)
return new Promise((resolve, reject) => {
background.createNewVaultAndRestore(password, seed, (err) => {
dispatch(actions.hideLoadingIndication())
background.createNewVaultAndRestore(password, seed, err => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
dispatch(actions.showAccountsPage())
resolve()
})
})
.then(() => dispatch(actions.unMarkPasswordForgotten()))
.then(() => {
dispatch(actions.showAccountsPage())
dispatch(actions.hideLoadingIndication())
})
.catch(err => {
dispatch(actions.displayWarning(err.message))
dispatch(actions.hideLoadingIndication())
})
}
}
function createNewVaultAndKeychain (password) {
return (dispatch) => {
return dispatch => {
dispatch(actions.showLoadingIndication())
log.debug(`background.createNewVaultAndKeychain`)
return new Promise((resolve, reject) => {
background.createNewVaultAndKeychain(password, (err) => {
background.createNewVaultAndKeychain(password, err => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
log.debug(`background.placeSeedWords`)
background.placeSeedWords((err) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
dispatch(actions.hideLoadingIndication())
forceUpdateMetamaskState(dispatch)
resolve()
})
})
})
.then(() => forceUpdateMetamaskState(dispatch))
.then(() => dispatch(actions.hideLoadingIndication()))
.catch(() => dispatch(actions.hideLoadingIndication()))
}
}
@ -389,18 +419,27 @@ function revealSeedConfirmation () {
}
function requestRevealSeed (password) {
return (dispatch) => {
return dispatch => {
dispatch(actions.showLoadingIndication())
log.debug(`background.submitPassword`)
background.submitPassword(password, (err) => {
return new Promise((resolve, reject) => {
background.submitPassword(password, err => {
if (err) {
return dispatch(actions.displayWarning(err.message))
dispatch(actions.displayWarning(err.message))
return reject(err)
}
log.debug(`background.placeSeedWords`)
background.placeSeedWords((err, result) => {
if (err) return dispatch(actions.displayWarning(err.message))
dispatch(actions.hideLoadingIndication())
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
dispatch(actions.showNewVaultSeed(result))
dispatch(actions.hideLoadingIndication())
resolve()
})
})
})
}
@ -851,11 +890,14 @@ function markPasswordForgotten () {
}
function unMarkPasswordForgotten () {
return (dispatch) => {
return background.unMarkPasswordForgotten(() => {
return dispatch => {
return new Promise(resolve => {
background.unMarkPasswordForgotten(() => {
dispatch(actions.forgotPassword(false))
forceUpdateMetamaskState(dispatch)
resolve()
})
})
.then(() => forceUpdateMetamaskState(dispatch))
}
}
@ -1704,11 +1746,16 @@ function callBackgroundThenUpdate (method, ...args) {
function forceUpdateMetamaskState (dispatch) {
log.debug(`background.getState`)
return new Promise((resolve, reject) => {
background.getState((err, newState) => {
if (err) {
return dispatch(actions.displayWarning(err.message))
dispatch(actions.displayWarning(err.message))
return reject(err)
}
dispatch(actions.updateMetamaskState(newState))
resolve()
})
})
}

@ -71,13 +71,17 @@ AddTokenScreen.prototype.componentWillMount = function () {
}
AddTokenScreen.prototype.toggleToken = function (address, token) {
const { selectedTokens, errors } = this.state
const { [address]: selectedToken } = selectedTokens
const { selectedTokens = {}, errors } = this.state
const selectedTokensCopy = { ...selectedTokens }
if (address in selectedTokensCopy) {
delete selectedTokensCopy[address]
} else {
selectedTokensCopy[address] = token
}
this.setState({
selectedTokens: {
...selectedTokens,
[address]: selectedToken ? null : token,
},
selectedTokens: selectedTokensCopy,
errors: {
...errors,
tokenSelector: null,

@ -115,7 +115,7 @@ NetworkDropdown.prototype.render = function () {
[
providerType === 'mainnet' ? h('i.fa.fa-check') : h('.network-check__transparent', '✓'),
h(NetworkDropdownIcon, {
backgroundColor: '#038789', // $blue-lagoon
backgroundColor: '#29B6AF', // $java
isSelected: providerType === 'mainnet',
}),
h('span.network-name-item', {
@ -137,7 +137,7 @@ NetworkDropdown.prototype.render = function () {
[
providerType === 'ropsten' ? h('i.fa.fa-check') : h('.network-check__transparent', '✓'),
h(NetworkDropdownIcon, {
backgroundColor: '#e91550', // $crimson
backgroundColor: '#ff4a8d', // $wild-strawberry
isSelected: providerType === 'ropsten',
}),
h('span.network-name-item', {
@ -159,7 +159,7 @@ NetworkDropdown.prototype.render = function () {
[
providerType === 'kovan' ? h('i.fa.fa-check') : h('.network-check__transparent', '✓'),
h(NetworkDropdownIcon, {
backgroundColor: '#690496', // $purple
backgroundColor: '#7057ff', // $cornflower-blue
isSelected: providerType === 'kovan',
}),
h('span.network-name-item', {
@ -181,7 +181,7 @@ NetworkDropdown.prototype.render = function () {
[
providerType === 'rinkeby' ? h('i.fa.fa-check') : h('.network-check__transparent', '✓'),
h(NetworkDropdownIcon, {
backgroundColor: '#ebb33f', // $tulip-tree
backgroundColor: '#f6c343', // $saffron
isSelected: providerType === 'rinkeby',
}),
h('span.network-name-item', {

@ -64,8 +64,8 @@ function mapDispatchToProps (dispatch, ownProps) {
updateTokenExchangeRate: () => dispatch(actions.updateTokenExchangeRate(symbol)),
editTransaction: txMeta => {
const { token: { address } } = ownProps
const { txParams, id } = txMeta
const tokenData = txParams.data && abiDecoder.decodeMethod(txParams.data)
const { txParams = {}, id } = txMeta
const tokenData = txParams.data && abiDecoder.decodeMethod(txParams.data) || {}
const { params = [] } = tokenData
const { value: to } = params[0] || {}
const { value: tokenAmountInDec } = params[1] || {}

@ -190,7 +190,7 @@
margin-top: 39px;
display: flex;
width: 100%;
justify-content: space-evenly;
justify-content: space-between;
}
&__button-cancel,

@ -46,6 +46,10 @@ $manatee: #93949d;
$spindle: #c7ddec;
$mid-gray: #5b5d67;
$cape-cod: #38393a;
$java: #29b6af;
$wild-strawberry: #ff4a8d;
$cornflower-blue: #7057ff;
$saffron: #f6c343;
/*
Z-Indicies

@ -107,12 +107,15 @@ RestoreVaultScreen.prototype.render = function () {
}
RestoreVaultScreen.prototype.showInitializeMenu = function () {
this.props.dispatch(actions.unMarkPasswordForgotten())
if (this.props.forgottenPassword) {
this.props.dispatch(actions.backToUnlockView())
const { dispatch, forgottenPassword } = this.props
dispatch(actions.unMarkPasswordForgotten())
.then(() => {
if (forgottenPassword) {
dispatch(actions.backToUnlockView())
} else {
this.props.dispatch(actions.showInitializeMenu())
dispatch(actions.showInitializeMenu())
}
})
}
RestoreVaultScreen.prototype.createOnEnter = function (event) {
@ -150,11 +153,5 @@ RestoreVaultScreen.prototype.createNewVaultAndRestore = function () {
this.warning = null
this.props.dispatch(actions.displayWarning(this.warning))
this.props.dispatch(actions.createNewVaultAndRestore(password, seed))
.then(() => {
this.props.dispatch(actions.unMarkPasswordForgotten())
})
.catch((err) => {
log.error(err.message)
})
.catch(err => log.error(err.message))
}

@ -138,14 +138,18 @@ function reduceApp (state, action) {
})
case actions.FORGOT_PASSWORD:
return extend(appState, {
currentView: {
name: action.value ? 'restoreVault' : 'accountDetail',
},
transForward: false,
const newState = extend(appState, {
forgottenPassword: action.value,
})
if (action.value) {
newState.currentView = {
name: 'restoreVault',
}
}
return newState
case actions.SHOW_INIT_MENU:
return extend(appState, {
currentView: defaultView,

@ -130,8 +130,6 @@ function reduceMetamask (state, action) {
case actions.SHOW_NEW_VAULT_SEED:
return extend(metamaskState, {
isUnlocked: true,
isInitialized: false,
isRevealingSeedWords: true,
seedWords: action.value,
})

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save