aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md1
-rw-r--r--app/_locales/en/messages.json3
-rw-r--r--app/scripts/controllers/address-book.js66
-rw-r--r--app/scripts/controllers/currency.js67
-rw-r--r--app/scripts/controllers/preferences.js124
-rw-r--r--app/scripts/controllers/shapeshift.js74
-rw-r--r--app/scripts/lib/buy-eth-url.js11
-rw-r--r--app/scripts/lib/config-manager.js22
-rw-r--r--app/scripts/lib/createLoggerMiddleware.js14
-rw-r--r--app/scripts/lib/createOriginMiddleware.js12
-rw-r--r--app/scripts/lib/events-proxy.js25
-rw-r--r--app/scripts/lib/get-first-preferred-lang-code.js7
-rw-r--r--app/scripts/lib/hex-to-bn.js7
-rw-r--r--app/scripts/lib/local-store.js37
-rw-r--r--app/scripts/lib/migrator/index.js35
-rw-r--r--app/scripts/lib/nodeify.js8
-rw-r--r--app/scripts/lib/stream-utils.js18
-rw-r--r--app/scripts/lib/util.js49
-rw-r--r--app/scripts/metamask-controller.js2
-rw-r--r--app/scripts/platforms/sw.js27
-rw-r--r--app/scripts/platforms/window.js23
-rw-r--r--mascara/src/app/first-time/confirm-seed-screen.js14
-rw-r--r--mascara/src/app/first-time/seed-screen.js71
-rw-r--r--test/integration/lib/tx-list-items.js2
-rw-r--r--ui/app/actions.js34
-rw-r--r--ui/app/app.js27
-rw-r--r--ui/app/components/account-dropdowns.js5
-rw-r--r--ui/app/components/dropdowns/components/account-dropdowns.js5
-rw-r--r--ui/app/components/loading.js18
-rw-r--r--ui/app/components/modals/export-private-key-modal.js7
-rw-r--r--ui/app/components/pages/settings/info.js10
-rw-r--r--ui/app/components/pending-tx/index.js31
-rw-r--r--ui/app/components/qr-code.js13
-rw-r--r--ui/app/components/send/account-list-item.js3
-rw-r--r--ui/app/components/tx-list-item.js5
-rw-r--r--ui/app/components/tx-view.js4
-rw-r--r--ui/app/components/wallet-view.js9
-rw-r--r--ui/app/css/itcss/components/loading-overlay.scss12
-rw-r--r--ui/app/util.js15
-rw-r--r--ui/lib/icon-factory.js4
40 files changed, 777 insertions, 144 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9537657ec..3e2b481de 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@
- Improved performance of 3D fox logo.
- Fetch token prices based on contract address, not symbol
- Fix bug that prevents setting language locale in settings.
+- Show checksum addresses throughout the UI
## 4.5.5 Fri Apr 06 2018
diff --git a/app/_locales/en/messages.json b/app/_locales/en/messages.json
index b372326ee..3b20ab49a 100644
--- a/app/_locales/en/messages.json
+++ b/app/_locales/en/messages.json
@@ -908,5 +908,8 @@
},
"youSign": {
"message": "You are signing"
+ },
+ "generatingTransaction": {
+ "message": "Generating transaction"
}
}
diff --git a/app/scripts/controllers/address-book.js b/app/scripts/controllers/address-book.js
index 6fb4ee114..c91e6b2e4 100644
--- a/app/scripts/controllers/address-book.js
+++ b/app/scripts/controllers/address-book.js
@@ -4,9 +4,22 @@ const extend = require('xtend')
class AddressBookController {
- // Controller in charge of managing the address book functionality from the
- // recipients field on the send screen. Manages a history of all saved
- // addresses and all currently owned addresses.
+ /**
+ * Controller in charge of managing the address book functionality from the
+ * recipients field on the send screen. Manages a history of all saved
+ * addresses and all currently owned addresses.
+ *
+ * @typedef {Object} AddressBookController
+ * @param {object} opts Overrides the defaults for the initial state of this.store
+ * @property {array} opts.initState initializes the the state of the AddressBookController. Can contain an
+ * addressBook property to initialize the addressBook array
+ * @param {KeyringController} keyringController (Soon to be deprecated) The keyringController used in the current
+ * MetamaskController. Contains the identities used in this AddressBookController.
+ * @property {object} store The the store of the current users address book
+ * @property {array} store.addressBook An array of addresses and nicknames. These are set by the user when sending
+ * to a new address.
+ *
+ */
constructor (opts = {}, keyringController) {
const initState = extend({
addressBook: [],
@@ -19,7 +32,14 @@ class AddressBookController {
// PUBLIC METHODS
//
- // Sets a new address book in store by accepting a new address and nickname.
+ /**
+ * Sets a new address book in store by accepting a new address and nickname.
+ *
+ * @param {string} address A hex address of a new account that the user is sending to.
+ * @param {string} name The name the user wishes to associate with the new account
+ * @returns {Promise<void>} Promise resolves with undefined
+ *
+ */
setAddressBook (address, name) {
return this._addToAddressBook(address, name)
.then((addressBook) => {
@@ -30,14 +50,16 @@ class AddressBookController {
})
}
- //
- // PRIVATE METHODS
- //
-
-
- // Performs the logic to add the address and name into the address book. The
- // pushed object is an object of two fields. Current behavior does not set an
- // upper limit to the number of addresses.
+ /**
+ * Performs the logic to add the address and name into the address book. The pushed object is an object of two
+ * fields. Current behavior does not set an upper limit to the number of addresses.
+ *
+ * @private
+ * @param {string} address A hex address of a new account that the user is sending to.
+ * @param {string} name The name the user wishes to associate with the new account
+ * @returns {Promise<array>} Promises the updated addressBook array
+ *
+ */
_addToAddressBook (address, name) {
const addressBook = this._getAddressBook()
const identities = this._getIdentities()
@@ -62,14 +84,26 @@ class AddressBookController {
return Promise.resolve(addressBook)
}
- // Internal method to get the address book. Current persistence behavior
- // should not require that this method be called from the UI directly.
+ /**
+ * Internal method to get the address book. Current persistence behavior should not require that this method be
+ * called from the UI directly.
+ *
+ * @private
+ * @returns {array} The addressBook array from the store.
+ *
+ */
_getAddressBook () {
return this.store.getState().addressBook
}
- // Retrieves identities from the keyring controller in order to avoid
- // duplication
+ /**
+ * Retrieves identities from the keyring controller in order to avoid
+ * duplication
+ *
+ * @deprecated
+ * @returns {array} Returns the identies array from the keyringContoller's state
+ *
+ */
_getIdentities () {
return this.keyringController.memStore.getState().identities
}
diff --git a/app/scripts/controllers/currency.js b/app/scripts/controllers/currency.js
index d9e0a3e34..480c08b1c 100644
--- a/app/scripts/controllers/currency.js
+++ b/app/scripts/controllers/currency.js
@@ -1,4 +1,4 @@
-const ObservableStore = require('obs-store')
+ const ObservableStore = require('obs-store')
const extend = require('xtend')
const log = require('loglevel')
@@ -7,6 +7,22 @@ const POLLING_INTERVAL = 600000
class CurrencyController {
+ /**
+ * Controller responsible for managing data associated with the currently selected currency.
+ *
+ * @typedef {Object} CurrencyController
+ * @param {object} opts Overrides the defaults for the initial state of this.store
+ * @property {array} opts.initState initializes the the state of the CurrencyController. Can contain an
+ * currentCurrency, conversionRate and conversionDate properties
+ * @property {string} currentCurrency A 2-4 character shorthand that describes a specific currency, currently
+ * selected by the user
+ * @property {number} conversionRate The conversion rate from ETH to the selected currency.
+ * @property {string} conversionDate The date at which the conversion rate was set. Expressed in in milliseconds
+ * since midnight of January 1, 1970
+ * @property {number} conversionInterval The id of the interval created by the scheduleConversionInterval method.
+ * Used to clear an existing interval on subsequent calls of that method.
+ *
+ */
constructor (opts = {}) {
const initState = extend({
currentCurrency: 'usd',
@@ -20,30 +36,73 @@ class CurrencyController {
// PUBLIC METHODS
//
+ /**
+ * A getter for the currentCurrency property
+ *
+ * @returns {string} A 2-4 character shorthand that describes a specific currency, currently selected by the user
+ *
+ */
getCurrentCurrency () {
return this.store.getState().currentCurrency
}
+ /**
+ * A setter for the currentCurrency property
+ *
+ * @param {string} currentCurrency The new currency to set as the currentCurrency in the store
+ *
+ */
setCurrentCurrency (currentCurrency) {
this.store.updateState({ currentCurrency })
}
+ /**
+ * A getter for the conversionRate property
+ *
+ * @returns {string} The conversion rate from ETH to the selected currency.
+ *
+ */
getConversionRate () {
return this.store.getState().conversionRate
}
+ /**
+ * A setter for the conversionRate property
+ *
+ * @param {number} conversionRate The new rate to set as the conversionRate in the store
+ *
+ */
setConversionRate (conversionRate) {
this.store.updateState({ conversionRate })
}
+ /**
+ * A getter for the conversionDate property
+ *
+ * @returns {string} The date at which the conversion rate was set. Expressed in milliseconds since midnight of
+ * January 1, 1970
+ *
+ */
getConversionDate () {
return this.store.getState().conversionDate
}
+ /**
+ * A setter for the conversionDate property
+ *
+ * @param {number} conversionDate The date, expressed in milliseconds since midnight of January 1, 1970, that the
+ * conversionRate was set
+ *
+ */
setConversionDate (conversionDate) {
this.store.updateState({ conversionDate })
}
+ /**
+ * Updates the conversionRate and conversionDate properties associated with the currentCurrency. Updated info is
+ * fetched from an external API
+ *
+ */
async updateConversionRate () {
let currentCurrency
try {
@@ -59,6 +118,12 @@ class CurrencyController {
}
}
+ /**
+ * Creates a new poll, using setInterval, to periodically call updateConversionRate. The id of the interval is
+ * stored at the controller's conversionInterval property. If it is called and such an id already exists, the
+ * previous interval is clear and a new one is created.
+ *
+ */
scheduleConversionInterval () {
if (this.conversionInterval) {
clearInterval(this.conversionInterval)
diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js
index b4819d951..d4d508026 100644
--- a/app/scripts/controllers/preferences.js
+++ b/app/scripts/controllers/preferences.js
@@ -4,6 +4,21 @@ const extend = require('xtend')
class PreferencesController {
+ /**
+ *
+ * @typedef {Object} PreferencesController
+ * @param {object} opts Overrides the defaults for the initial state of this.store
+ * @property {object} store The an object containing a users preferences, stored in local storage
+ * @property {array} store.frequentRpcList A list of custom rpcs to provide the user
+ * @property {string} store.currentAccountTab Indicates the selected tab in the ui
+ * @property {array} store.tokens The tokens the user wants display in their token lists
+ * @property {boolean} store.useBlockie The users preference for blockie identicons within the UI
+ * @property {object} store.featureFlags A key-boolean map, where keys refer to features and booleans to whether the
+ * user wishes to see that feature
+ * @property {string} store.currentLocale The preferred language locale key
+ * @property {string} store.selectedAddress A hex string that matches the currently selected address in the app
+ *
+ */
constructor (opts = {}) {
const initState = extend({
frequentRpcList: [],
@@ -17,18 +32,43 @@ class PreferencesController {
}
// PUBLIC METHODS
+ /**
+ * Setter for the `useBlockie` property
+ *
+ * @param {boolean} val Whether or not the user prefers blockie indicators
+ *
+ */
setUseBlockie (val) {
this.store.updateState({ useBlockie: val })
}
+ /**
+ * Getter for the `useBlockie` property
+ *
+ * @returns {boolean} this.store.useBlockie
+ *
+ */
getUseBlockie () {
return this.store.getState().useBlockie
}
+ /**
+ * Setter for the `currentLocale` property
+ *
+ * @param {string} key he preferred language locale key
+ *
+ */
setCurrentLocale (key) {
this.store.updateState({ currentLocale: key })
}
+ /**
+ * Setter for the `selectedAddress` property
+ *
+ * @param {string} _address A new hex address for an account
+ * @returns {Promise<void>} Promise resolves with undefined
+ *
+ */
setSelectedAddress (_address) {
return new Promise((resolve, reject) => {
const address = normalizeAddress(_address)
@@ -37,10 +77,37 @@ class PreferencesController {
})
}
+ /**
+ * Getter for the `selectedAddress` property
+ *
+ * @returns {string} The hex address for the currently selected account
+ *
+ */
getSelectedAddress () {
return this.store.getState().selectedAddress
}
+ /**
+ * Contains data about tokens users add to their account.
+ * @typedef {Object} AddedToken
+ * @property {string} address - The hex address for the token contract. Will be all lower cased and hex-prefixed.
+ * @property {string} symbol - The symbol of the token, usually 3 or 4 capitalized letters
+ * {@link https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol}
+ * @property {boolean} decimals - The number of decimals the token uses.
+ * {@link https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals}
+ */
+
+ /**
+ * Adds a new token to the token array, or updates the token if passed an address that already exists.
+ * Modifies the existing tokens array from the store. All objects in the tokens array array AddedToken objects.
+ * @see AddedToken {@link AddedToken}
+ *
+ * @param {string} rawAddress Hex address of the token contract. May or may not be a checksum address.
+ * @param {string} symbol The symbol of the token
+ * @param {number} decimals The number of decimals the token uses.
+ * @returns {Promise<array>} Promises the new array of AddedToken objects.
+ *
+ */
async addToken (rawAddress, symbol, decimals) {
const address = normalizeAddress(rawAddress)
const newEntry = { address, symbol, decimals }
@@ -62,6 +129,13 @@ class PreferencesController {
return Promise.resolve(tokens)
}
+ /**
+ * Removes a specified token from the tokens array.
+ *
+ * @param {string} rawAddress Hex address of the token contract to remove.
+ * @returns {Promise<array>} The new array of AddedToken objects
+ *
+ */
removeToken (rawAddress) {
const tokens = this.store.getState().tokens
@@ -71,10 +145,23 @@ class PreferencesController {
return Promise.resolve(updatedTokens)
}
+ /**
+ * A getter for the `tokens` property
+ *
+ * @returns {array} The current array of AddedToken objects
+ *
+ */
getTokens () {
return this.store.getState().tokens
}
+ /**
+ * Gets an updated rpc list from this.addToFrequentRpcList() and sets the `frequentRpcList` to this update list.
+ *
+ * @param {string} _url The the new rpc url to add to the updated list
+ * @returns {Promise<void>} Promise resolves with undefined
+ *
+ */
updateFrequentRpcList (_url) {
return this.addToFrequentRpcList(_url)
.then((rpcList) => {
@@ -83,6 +170,13 @@ class PreferencesController {
})
}
+ /**
+ * Setter for the `currentAccountTab` property
+ *
+ * @param {string} currentAccountTab Specifies the new tab to be marked as current
+ * @returns {Promise<void>} Promise resolves with undefined
+ *
+ */
setCurrentAccountTab (currentAccountTab) {
return new Promise((resolve, reject) => {
this.store.updateState({ currentAccountTab })
@@ -90,6 +184,15 @@ class PreferencesController {
})
}
+ /**
+ * Returns an updated rpcList based on the passed url and the current list.
+ * The returned list will have a max length of 2. If the _url currently exists it the list, it will be moved to the
+ * end of the list. The current list is modified and returned as a promise.
+ *
+ * @param {string} _url The rpc url to add to the frequentRpcList.
+ * @returns {Promise<array>} The updated frequentRpcList.
+ *
+ */
addToFrequentRpcList (_url) {
const rpcList = this.getFrequentRpcList()
const index = rpcList.findIndex((element) => { return element === _url })
@@ -105,10 +208,24 @@ class PreferencesController {
return Promise.resolve(rpcList)
}
+ /**
+ * Getter for the `frequentRpcList` property.
+ *
+ * @returns {array<string>} An array of one or two rpc urls.
+ *
+ */
getFrequentRpcList () {
return this.store.getState().frequentRpcList
}
+ /**
+ * Updates the `featureFlags` property, which is an object. One property within that object will be set to a boolean.
+ *
+ * @param {string} feature A key that corresponds to a UI feature.
+ * @param {boolean} activated Indicates whether or not the UI feature should be displayed
+ * @returns {Promise<object>} Promises a new object; the updated featureFlags object.
+ *
+ */
setFeatureFlag (feature, activated) {
const currentFeatureFlags = this.store.getState().featureFlags
const updatedFeatureFlags = {
@@ -121,6 +238,13 @@ class PreferencesController {
return Promise.resolve(updatedFeatureFlags)
}
+ /**
+ * A getter for the `featureFlags` property
+ *
+ * @returns {object} A key-boolean map, where keys refer to features and booleans to whether the
+ * user wishes to see that feature
+ *
+ */
getFeatureFlags () {
return this.store.getState().featureFlags
}
diff --git a/app/scripts/controllers/shapeshift.js b/app/scripts/controllers/shapeshift.js
index b38b3812d..b2a1462c2 100644
--- a/app/scripts/controllers/shapeshift.js
+++ b/app/scripts/controllers/shapeshift.js
@@ -7,6 +7,17 @@ const POLLING_INTERVAL = 3000
class ShapeshiftController {
+ /**
+ * Controller responsible for managing the list of shapeshift transactions. On construction, it initiates a poll
+ * that queries a shapeshift.io API for updates to any pending shapeshift transactions
+ *
+ * @typedef {Object} ShapeshiftController
+ * @param {object} opts Overrides the defaults for the initial state of this.store
+ * @property {array} opts.initState initializes the the state of the ShapeshiftController. Can contain an
+ * shapeShiftTxList array.
+ * @property {array} shapeShiftTxList An array of ShapeShiftTx objects
+ *
+ */
constructor (opts = {}) {
const initState = extend({
shapeShiftTxList: [],
@@ -15,21 +26,54 @@ class ShapeshiftController {
this.pollForUpdates()
}
+ /**
+ * Represents, and contains data about, a single shapeshift transaction.
+ * @typedef {Object} ShapeShiftTx
+ * @property {string} depositAddress - An address at which to send a crypto deposit, so that eth can be sent to the
+ * user's Metamask account
+ * @property {string} depositType - An abbreviation of the type of crypto currency to be deposited.
+ * @property {string} key - The 'shapeshift' key differentiates this from other types of txs in Metamask
+ * @property {number} time - The time at which the tx was created
+ * @property {object} response - Initiated as an empty object, which will be replaced by a Response object. @see {@link
+ * https://developer.mozilla.org/en-US/docs/Web/API/Response}
+ */
+
//
// PUBLIC METHODS
//
+ /**
+ * A getter for the shapeShiftTxList property
+ *
+ * @returns {array<ShapeShiftTx>}
+ *
+ */
getShapeShiftTxList () {
const shapeShiftTxList = this.store.getState().shapeShiftTxList
return shapeShiftTxList
}
+ /**
+ * A getter for all ShapeShiftTx in the shapeShiftTxList that have not successfully completed a deposit.
+ *
+ * @returns {array<ShapeShiftTx>} Only includes ShapeShiftTx which has a response property with a status !== complete
+ *
+ */
getPendingTxs () {
const txs = this.getShapeShiftTxList()
const pending = txs.filter(tx => tx.response && tx.response.status !== 'complete')
return pending
}
+ /**
+ * A poll that exists as long as there are pending transactions. Each call attempts to update the data of any
+ * pendingTxs, and then calls itself again. If there are no pending txs, the recursive call is not made and
+ * the polling stops.
+ *
+ * this.updateTx is used to attempt the update to the pendingTxs in the ShapeShiftTxList, and that updated data
+ * is saved with saveTx.
+ *
+ */
pollForUpdates () {
const pendingTxs = this.getPendingTxs()
@@ -46,6 +90,15 @@ class ShapeshiftController {
})
}
+ /**
+ * Attempts to update a ShapeShiftTx with data from a shapeshift.io API. Both the response and time properties
+ * can be updated. The response property is updated with every call, but the time property is only updated when
+ * the response status updates to 'complete'. This will occur once the user makes a deposit as the ShapeShiftTx
+ * depositAddress
+ *
+ * @param {ShapeShiftTx} tx The tx to update
+ *
+ */
async updateTx (tx) {
try {
const url = `https://shapeshift.io/txStat/${tx.depositAddress}`
@@ -61,6 +114,13 @@ class ShapeshiftController {
}
}
+ /**
+ * Saves an updated to a ShapeShiftTx in the shapeShiftTxList. If the passed ShapeShiftTx is not in the
+ * shapeShiftTxList, nothing happens.
+ *
+ * @param {ShapeShiftTx} tx The updated tx to save, if it exists in the current shapeShiftTxList
+ *
+ */
saveTx (tx) {
const { shapeShiftTxList } = this.store.getState()
const index = shapeShiftTxList.indexOf(tx)
@@ -70,6 +130,12 @@ class ShapeshiftController {
}
}
+ /**
+ * Removes a ShapeShiftTx from the shapeShiftTxList
+ *
+ * @param {ShapeShiftTx} tx The tx to remove
+ *
+ */
removeShapeShiftTx (tx) {
const { shapeShiftTxList } = this.store.getState()
const index = shapeShiftTxList.indexOf(index)
@@ -79,6 +145,14 @@ class ShapeshiftController {
this.updateState({ shapeShiftTxList })
}
+ /**
+ * Creates a new ShapeShiftTx, adds it to the shapeShiftTxList, and initiates a new poll for updates of pending txs
+ *
+ * @param {string} depositAddress - An address at which to send a crypto deposit, so that eth can be sent to the
+ * user's Metamask account
+ * @param {string} depositType - An abbreviation of the type of crypto currency to be deposited.
+ *
+ */
createShapeShiftTx (depositAddress, depositType) {
const state = this.store.getState()
let { shapeShiftTxList } = state
diff --git a/app/scripts/lib/buy-eth-url.js b/app/scripts/lib/buy-eth-url.js
index b9dde3c28..4e2d0bc79 100644
--- a/app/scripts/lib/buy-eth-url.js
+++ b/app/scripts/lib/buy-eth-url.js
@@ -1,5 +1,16 @@
module.exports = getBuyEthUrl
+/**
+ * Gives the caller a url at which the user can acquire eth, depending on the network they are in
+ *
+ * @param {object} opts Options required to determine the correct url
+ * @param {string} opts.network The network for which to return a url
+ * @param {string} opts.amount The amount of ETH to buy on coinbase. Only relevant if network === '1'.
+ * @param {string} opts.address The address the bought ETH should be sent to. Only relevant if network === '1'.
+ * @returns {string|undefined} The url at which the user can access ETH, while in the given network. If the passed
+ * network does not match any of the specified cases, or if no network is given, returns undefined.
+ *
+ */
function getBuyEthUrl ({ network, amount, address }) {
let url
switch (network) {
diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js
index 34b603b96..63d27c40e 100644
--- a/app/scripts/lib/config-manager.js
+++ b/app/scripts/lib/config-manager.js
@@ -102,7 +102,6 @@ ConfigManager.prototype.setShowSeedWords = function (should) {
this.setData(data)
}
-
ConfigManager.prototype.getShouldShowSeedWords = function () {
var data = this.getData()
return data.showSeedWords
@@ -118,6 +117,27 @@ ConfigManager.prototype.getSeedWords = function () {
var data = this.getData()
return data.seedWords
}
+
+/**
+ * Called to set the isRevealingSeedWords flag. This happens only when the user chooses to reveal
+ * the seed words and not during the first time flow.
+ * @param {boolean} reveal - Value to set the isRevealingSeedWords flag.
+ */
+ConfigManager.prototype.setIsRevealingSeedWords = function (reveal = false) {
+ const data = this.getData()
+ data.isRevealingSeedWords = reveal
+ this.setData(data)
+}
+
+/**
+ * Returns the isRevealingSeedWords flag.
+ * @returns {boolean|undefined}
+ */
+ConfigManager.prototype.getIsRevealingSeedWords = function () {
+ const data = this.getData()
+ return data.isRevealingSeedWords
+}
+
ConfigManager.prototype.setRpcTarget = function (rpcUrl) {
var config = this.getConfig()
config.provider = {
diff --git a/app/scripts/lib/createLoggerMiddleware.js b/app/scripts/lib/createLoggerMiddleware.js
index fc6abf828..996c3477c 100644
--- a/app/scripts/lib/createLoggerMiddleware.js
+++ b/app/scripts/lib/createLoggerMiddleware.js
@@ -1,16 +1,20 @@
const log = require('loglevel')
-// log rpc activity
module.exports = createLoggerMiddleware
-function createLoggerMiddleware ({ origin }) {
- return function loggerMiddleware (req, res, next, end) {
- next((cb) => {
+/**
+ * Returns a middleware that logs RPC activity
+ * @param {{ origin: string }} opts - The middleware options
+ * @returns {Function}
+ */
+function createLoggerMiddleware (opts) {
+ return function loggerMiddleware (/** @type {any} */ req, /** @type {any} */ res, /** @type {Function} */ next) {
+ next((/** @type {Function} */ cb) => {
if (res.error) {
log.error('Error in RPC response:\n', res)
}
if (req.isMetamaskInternal) return
- log.info(`RPC (${origin}):`, req, '->', res)
+ log.info(`RPC (${opts.origin}):`, req, '->', res)
cb()
})
}
diff --git a/app/scripts/lib/createOriginMiddleware.js b/app/scripts/lib/createOriginMiddleware.js
index f8bdb2dc2..98bb0e3b3 100644
--- a/app/scripts/lib/createOriginMiddleware.js
+++ b/app/scripts/lib/createOriginMiddleware.js
@@ -1,9 +1,13 @@
-// append dapp origin domain to request
module.exports = createOriginMiddleware
-function createOriginMiddleware ({ origin }) {
- return function originMiddleware (req, res, next, end) {
- req.origin = origin
+/**
+ * Returns a middleware that appends the DApp origin to request
+ * @param {{ origin: string }} opts - The middleware options
+ * @returns {Function}
+ */
+function createOriginMiddleware (opts) {
+ return function originMiddleware (/** @type {any} */ req, /** @type {any} */ _, /** @type {Function} */ next) {
+ req.origin = opts.origin
next()
}
}
diff --git a/app/scripts/lib/events-proxy.js b/app/scripts/lib/events-proxy.js
index c0a490b05..f83773ccc 100644
--- a/app/scripts/lib/events-proxy.js
+++ b/app/scripts/lib/events-proxy.js
@@ -1,26 +1,37 @@
+/**
+ * Returns an EventEmitter that proxies events from the given event emitter
+ * @param {any} eventEmitter
+ * @param {object} listeners - The listeners to proxy to
+ * @returns {any}
+ */
module.exports = function createEventEmitterProxy (eventEmitter, listeners) {
let target = eventEmitter
const eventHandlers = listeners || {}
- const proxy = new Proxy({}, {
- get: (obj, name) => {
+ const proxy = /** @type {any} */ (new Proxy({}, {
+ get: (_, name) => {
// intercept listeners
if (name === 'on') return addListener
if (name === 'setTarget') return setTarget
if (name === 'proxyEventHandlers') return eventHandlers
- return target[name]
+ return (/** @type {any} */ (target))[name]
},
- set: (obj, name, value) => {
+ set: (_, name, value) => {
target[name] = value
return true
},
- })
- function setTarget (eventEmitter) {
+ }))
+ function setTarget (/** @type {EventEmitter} */ eventEmitter) {
target = eventEmitter
// migrate listeners
Object.keys(eventHandlers).forEach((name) => {
- eventHandlers[name].forEach((handler) => target.on(name, handler))
+ /** @type {Array<Function>} */ (eventHandlers[name]).forEach((handler) => target.on(name, handler))
})
}
+ /**
+ * Attaches a function to be called whenever the specified event is emitted
+ * @param {string} name
+ * @param {Function} handler
+ */
function addListener (name, handler) {
if (!eventHandlers[name]) eventHandlers[name] = []
eventHandlers[name].push(handler)
diff --git a/app/scripts/lib/get-first-preferred-lang-code.js b/app/scripts/lib/get-first-preferred-lang-code.js
index e3635434e..5473fccf0 100644
--- a/app/scripts/lib/get-first-preferred-lang-code.js
+++ b/app/scripts/lib/get-first-preferred-lang-code.js
@@ -4,6 +4,13 @@ const allLocales = require('../../_locales/index.json')
const existingLocaleCodes = allLocales.map(locale => locale.code.toLowerCase().replace('_', '-'))
+/**
+ * Returns a preferred language code, based on settings within the user's browser. If we have no translations for the
+ * users preferred locales, 'en' is returned.
+ *
+ * @returns {Promise<string>} Promises a locale code, either one from the user's preferred list that we have a translation for, or 'en'
+ *
+ */
async function getFirstPreferredLangCode () {
const userPreferredLocaleCodes = await promisify(
extension.i18n.getAcceptLanguages,
diff --git a/app/scripts/lib/hex-to-bn.js b/app/scripts/lib/hex-to-bn.js
index 184217279..b28746920 100644
--- a/app/scripts/lib/hex-to-bn.js
+++ b/app/scripts/lib/hex-to-bn.js
@@ -1,6 +1,11 @@
-const ethUtil = require('ethereumjs-util')
+const ethUtil = (/** @type {object} */ (require('ethereumjs-util')))
const BN = ethUtil.BN
+/**
+ * Returns a [BinaryNumber]{@link BN} representation of the given hex value
+ * @param {string} hex
+ * @return {any}
+ */
module.exports = function hexToBn (hex) {
return new BN(ethUtil.stripHexPrefix(hex), 16)
}
diff --git a/app/scripts/lib/local-store.js b/app/scripts/lib/local-store.js
index 2dda0ba1f..139ff86bd 100644
--- a/app/scripts/lib/local-store.js
+++ b/app/scripts/lib/local-store.js
@@ -1,11 +1,13 @@
-// We should not rely on local storage in an extension!
-// We should use this instead!
-// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/local
-
const extension = require('extensionizer')
const log = require('loglevel')
+/**
+ * A wrapper around the extension's storage local API
+ */
module.exports = class ExtensionStore {
+ /**
+ * @constructor
+ */
constructor() {
this.isSupported = !!(extension.storage.local)
if (!this.isSupported) {
@@ -13,6 +15,10 @@ module.exports = class ExtensionStore {
}
}
+ /**
+ * Returns all of the keys currently saved
+ * @return {Promise<*>}
+ */
async get() {
if (!this.isSupported) return undefined
const result = await this._get()
@@ -25,14 +31,24 @@ module.exports = class ExtensionStore {
}
}
+ /**
+ * Sets the key in local state
+ * @param {object} state - The state to set
+ * @return {Promise<void>}
+ */
async set(state) {
return this._set(state)
}
+ /**
+ * Returns all of the keys currently saved
+ * @private
+ * @return {object} the key-value map from local storage
+ */
_get() {
const local = extension.storage.local
return new Promise((resolve, reject) => {
- local.get(null, (result) => {
+ local.get(null, (/** @type {any} */ result) => {
const err = extension.runtime.lastError
if (err) {
reject(err)
@@ -43,6 +59,12 @@ module.exports = class ExtensionStore {
})
}
+ /**
+ * Sets the key in local state
+ * @param {object} obj - The key to set
+ * @return {Promise<void>}
+ * @private
+ */
_set(obj) {
const local = extension.storage.local
return new Promise((resolve, reject) => {
@@ -58,6 +80,11 @@ module.exports = class ExtensionStore {
}
}
+/**
+ * Returns whether or not the given object contains no keys
+ * @param {object} obj - The object to check
+ * @returns {boolean}
+ */
function isEmpty(obj) {
return Object.keys(obj).length === 0
}
diff --git a/app/scripts/lib/migrator/index.js b/app/scripts/lib/migrator/index.js
index 85c2717ea..345ca8001 100644
--- a/app/scripts/lib/migrator/index.js
+++ b/app/scripts/lib/migrator/index.js
@@ -1,7 +1,23 @@
const EventEmitter = require('events')
+/**
+ * @typedef {object} Migration
+ * @property {number} version - The migration version
+ * @property {Function} migrate - Returns a promise of the migrated data
+ */
+
+/**
+ * @typedef {object} MigratorOptions
+ * @property {Array<Migration>} [migrations] - The list of migrations to apply
+ * @property {number} [defaultVersion] - The version to use in the initial state
+ */
+
class Migrator extends EventEmitter {
+ /**
+ * @constructor
+ * @param {MigratorOptions} opts
+ */
constructor (opts = {}) {
super()
const migrations = opts.migrations || []
@@ -42,19 +58,30 @@ class Migrator extends EventEmitter {
return versionedData
- // migration is "pending" if it has a higher
- // version number than currentVersion
+ /**
+ * Returns whether or not the migration is pending
+ *
+ * A migration is considered "pending" if it has a higher
+ * version number than the current version.
+ * @param {Migration} migration
+ * @returns {boolean}
+ */
function migrationIsPending (migration) {
return migration.version > versionedData.meta.version
}
}
- generateInitialState (initState) {
+ /**
+ * Returns the initial state for the migrator
+ * @param {object} [data] - The data for the initial state
+ * @returns {{meta: {version: number}, data: any}}
+ */
+ generateInitialState (data) {
return {
meta: {
version: this.defaultVersion,
},
- data: initState,
+ data,
}
}
diff --git a/app/scripts/lib/nodeify.js b/app/scripts/lib/nodeify.js
index 9b595d93c..25be6537b 100644
--- a/app/scripts/lib/nodeify.js
+++ b/app/scripts/lib/nodeify.js
@@ -1,6 +1,14 @@
const promiseToCallback = require('promise-to-callback')
const noop = function () {}
+/**
+ * A generator that returns a function which, when passed a promise, can treat that promise as a node style callback.
+ * The prime advantage being that callbacks are better for error handling.
+ *
+ * @param {Function} fn The function to handle as a callback
+ * @param {Object} context The context in which the fn is to be called, most often a this reference
+ *
+ */
module.exports = function nodeify (fn, context) {
return function () {
const args = [].slice.call(arguments)
diff --git a/app/scripts/lib/stream-utils.js b/app/scripts/lib/stream-utils.js
index 8bb0b4f3c..3dbc064b5 100644
--- a/app/scripts/lib/stream-utils.js
+++ b/app/scripts/lib/stream-utils.js
@@ -8,20 +8,34 @@ module.exports = {
setupMultiplex: setupMultiplex,
}
+/**
+ * Returns a stream transform that parses JSON strings passing through
+ * @return {stream.Transform}
+ */
function jsonParseStream () {
- return Through.obj(function (serialized, encoding, cb) {
+ return Through.obj(function (serialized, _, cb) {
this.push(JSON.parse(serialized))
cb()
})
}
+/**
+ * Returns a stream transform that calls {@code JSON.stringify}
+ * on objects passing through
+ * @return {stream.Transform} the stream transform
+ */
function jsonStringifyStream () {
- return Through.obj(function (obj, encoding, cb) {
+ return Through.obj(function (obj, _, cb) {
this.push(JSON.stringify(obj))
cb()
})
}
+/**
+ * Sets up stream multiplexing for the given stream
+ * @param {any} connectionStream - the stream to mux
+ * @return {stream.Stream} the multiplexed stream
+ */
function setupMultiplex (connectionStream) {
const mux = new ObjectMultiplex()
pump(
diff --git a/app/scripts/lib/util.js b/app/scripts/lib/util.js
index df815906f..431d1e59c 100644
--- a/app/scripts/lib/util.js
+++ b/app/scripts/lib/util.js
@@ -7,11 +7,26 @@ const {
ENVIRONMENT_TYPE_FULLSCREEN,
} = require('./enums')
+/**
+ * Generates an example stack trace
+ *
+ * @returns {string} A stack trace
+ *
+ */
function getStack () {
const stack = new Error('Stack trace generator - not an error').stack
return stack
}
+/**
+ * Used to determine the window type through which the app is being viewed.
+ * - 'popup' refers to the extension opened through the browser app icon (in top right corner in chrome and firefox)
+ * - 'responsive' refers to the main browser window
+ * - 'notification' refers to the popup that appears in its own window when taking action outside of metamask
+ *
+ * @returns {string} A single word label that represents the type of window through which the app is being viewed
+ *
+ */
const getEnvironmentType = (url = window.location.href) => {
if (url.match(/popup.html(?:\?.+)*$/)) {
return ENVIRONMENT_TYPE_POPUP
@@ -22,6 +37,17 @@ const getEnvironmentType = (url = window.location.href) => {
}
}
+/**
+ * Checks whether a given balance of ETH, represented as a hex string, is sufficient to pay a value plus a gas fee
+ *
+ * @param {object} txParams Contains data about a transaction
+ * @param {string} txParams.gas The gas for a transaction
+ * @param {string} txParams.gasPrice The price per gas for the transaction
+ * @param {string} txParams.value The value of ETH to send
+ * @param {string} hexBalance A balance of ETH represented as a hex string
+ * @returns {boolean} Whether the balance is greater than or equal to the value plus the value of gas times gasPrice
+ *
+ */
function sufficientBalance (txParams, hexBalance) {
// validate hexBalance is a hex string
assert.equal(typeof hexBalance, 'string', 'sufficientBalance - hexBalance is not a hex string')
@@ -36,14 +62,37 @@ function sufficientBalance (txParams, hexBalance) {
return balance.gte(maxCost)
}
+/**
+ * Converts a BN object to a hex string with a '0x' prefix
+ *
+ * @param {BN} inputBn The BN to convert to a hex string
+ * @returns {string} A '0x' prefixed hex string
+ *
+ */
function bnToHex (inputBn) {
return ethUtil.addHexPrefix(inputBn.toString(16))
}
+/**
+ * Converts a hex string to a BN object
+ *
+ * @param {string} inputHex A number represented as a hex string
+ * @returns {Object} A BN object
+ *
+ */
function hexToBn (inputHex) {
return new BN(ethUtil.stripHexPrefix(inputHex), 16)
}
+/**
+ * Used to multiply a BN by a fraction
+ *
+ * @param {BN} targetBN The number to multiply by a fraction
+ * @param {number|string} numerator The numerator of the fraction multiplier
+ * @param {number|string} denominator The denominator of the fraction multiplier
+ * @returns {BN} The product of the multiplication
+ *
+ */
function BnMultiplyByFraction (targetBN, numerator, denominator) {
const numBN = new BN(numerator)
const denomBN = new BN(denominator)
diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index a12b6776e..782bc50ac 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -308,6 +308,7 @@ module.exports = class MetamaskController extends EventEmitter {
lostAccounts: this.configManager.getLostAccounts(),
seedWords: this.configManager.getSeedWords(),
forgottenPassword: this.configManager.getPasswordForgotten(),
+ isRevealingSeedWords: Boolean(this.configManager.getIsRevealingSeedWords()),
},
}
}
@@ -347,6 +348,7 @@ module.exports = class MetamaskController extends EventEmitter {
clearSeedWordCache: this.clearSeedWordCache.bind(this),
resetAccount: nodeify(this.resetAccount, this),
importAccountWithStrategy: this.importAccountWithStrategy.bind(this),
+ setIsRevealingSeedWords: this.configManager.setIsRevealingSeedWords.bind(this.configManager),
// vault management
submitPassword: nodeify(keyringController.submitPassword, keyringController),
diff --git a/app/scripts/platforms/sw.js b/app/scripts/platforms/sw.js
index 007d8dc5b..56c5f2774 100644
--- a/app/scripts/platforms/sw.js
+++ b/app/scripts/platforms/sw.js
@@ -1,20 +1,25 @@
-
class SwPlatform {
-
- //
- // Public
- //
-
+ /**
+ * Reloads the platform
+ */
reload () {
- // you cant actually do this
- global.location.reload()
+ // TODO: you can't actually do this
+ /** @type {any} */ (global).location.reload()
}
- openWindow ({ url }) {
- // this doesnt actually work
- global.open(url, '_blank')
+ /**
+ * Opens a window
+ * @param {{url: string}} opts - The window options
+ */
+ openWindow (opts) {
+ // TODO: this doesn't actually work
+ /** @type {any} */ (global).open(opts.url, '_blank')
}
+ /**
+ * Returns the platform version
+ * @returns {string}
+ */
getVersion () {
return '<unable to read version>'
}
diff --git a/app/scripts/platforms/window.js b/app/scripts/platforms/window.js
index 1527c008b..943b2a703 100644
--- a/app/scripts/platforms/window.js
+++ b/app/scripts/platforms/window.js
@@ -1,18 +1,23 @@
-
class WindowPlatform {
-
- //
- // Public
- //
-
+ /**
+ * Reload the platform
+ */
reload () {
- global.location.reload()
+ /** @type {any} */ (global).location.reload()
}
- openWindow ({ url }) {
- global.open(url, '_blank')
+ /**
+ * Opens a window
+ * @param {{url: string}} opts - The window options
+ */
+ openWindow (opts) {
+ /** @type {any} */ (global).open(opts.url, '_blank')
}
+ /**
+ * Returns the platform version
+ * @returns {string}
+ */
getVersion () {
return '<unable to read version>'
}
diff --git a/mascara/src/app/first-time/confirm-seed-screen.js b/mascara/src/app/first-time/confirm-seed-screen.js
index 438f383b1..7c0431431 100644
--- a/mascara/src/app/first-time/confirm-seed-screen.js
+++ b/mascara/src/app/first-time/confirm-seed-screen.js
@@ -9,7 +9,7 @@ import Identicon from '../../../../ui/app/components/identicon'
import { confirmSeedWords, showModal } from '../../../../ui/app/actions'
import Breadcrumbs from './breadcrumbs'
import LoadingScreen from './loading-screen'
-import { DEFAULT_ROUTE } from '../../../../ui/app/routes'
+import { DEFAULT_ROUTE, INITIALIZE_BACKUP_PHRASE_ROUTE } from '../../../../ui/app/routes'
class ConfirmSeedScreen extends Component {
static propTypes = {
@@ -53,7 +53,7 @@ class ConfirmSeedScreen extends Component {
}
render () {
- const { seedWords } = this.props
+ const { seedWords, history } = this.props
const { selectedSeeds, shuffledSeeds } = this.state
const isValid = seedWords === selectedSeeds.map(([_, seed]) => seed).join(' ')
@@ -66,6 +66,16 @@ class ConfirmSeedScreen extends Component {
<div className="first-view-main-wrapper">
<div className="first-view-main">
<div className="backup-phrase">
+ <a
+ className="backup-phrase__back-button"
+ onClick={e => {
+ e.preventDefault()
+ history.push(INITIALIZE_BACKUP_PHRASE_ROUTE)
+ }}
+ href="#"
+ >
+ {`< Back`}
+ </a>
<Identicon address={this.props.address} diameter={70} />
<div className="backup-phrase__content-wrapper">
<div>
diff --git a/mascara/src/app/first-time/seed-screen.js b/mascara/src/app/first-time/seed-screen.js
index d004be77b..9af9ca3be 100644
--- a/mascara/src/app/first-time/seed-screen.js
+++ b/mascara/src/app/first-time/seed-screen.js
@@ -8,6 +8,7 @@ import Identicon from '../../../../ui/app/components/identicon'
import Breadcrumbs from './breadcrumbs'
import LoadingScreen from './loading-screen'
import { DEFAULT_ROUTE, INITIALIZE_CONFIRM_SEED_ROUTE } from '../../../../ui/app/routes'
+import { confirmSeedWords } from '../../../../ui/app/actions'
const LockIcon = props => (
<svg
@@ -44,6 +45,8 @@ class BackupPhraseScreen extends Component {
address: PropTypes.string.isRequired,
seedWords: PropTypes.string,
history: PropTypes.object,
+ isRevealingSeedWords: PropTypes.bool,
+ clearSeedWords: PropTypes.func,
};
static defaultProps = {
@@ -58,6 +61,14 @@ class BackupPhraseScreen extends Component {
}
componentWillMount () {
+ this.checkSeedWords()
+ }
+
+ componentDidUpdate () {
+ this.checkSeedWords()
+ }
+
+ checkSeedWords () {
const { seedWords, history } = this.props
if (!seedWords) {
@@ -92,9 +103,29 @@ class BackupPhraseScreen extends Component {
)
}
- renderSecretScreen () {
+ renderSubmitButton () {
+ const { isRevealingSeedWords, clearSeedWords, history } = this.props
const { isShowingSecret } = this.state
- const { history } = this.props
+
+ return isRevealingSeedWords
+ ? <button
+ className="first-time-flow__button"
+ onClick={() => clearSeedWords().then(() => history.push(DEFAULT_ROUTE))}
+ disabled={!isShowingSecret}
+ >
+ Done
+ </button>
+ : <button
+ className="first-time-flow__button"
+ onClick={() => isShowingSecret && history.push(INITIALIZE_CONFIRM_SEED_ROUTE)}
+ disabled={!isShowingSecret}
+ >
+ Next
+ </button>
+ }
+
+ renderSecretScreen () {
+ const { isRevealingSeedWords } = this.props
return (
<div className="backup-phrase__content-wrapper">
@@ -121,14 +152,8 @@ class BackupPhraseScreen extends Component {
</div>
</div>
<div className="backup-phrase__next-button">
- <button
- className="first-time-flow__button"
- onClick={() => isShowingSecret && history.push(INITIALIZE_CONFIRM_SEED_ROUTE)}
- disabled={!isShowingSecret}
- >
- Next
- </button>
- <Breadcrumbs total={3} currentIndex={1} />
+ { this.renderSubmitButton() }
+ { !isRevealingSeedWords && <Breadcrumbs total={3} currentIndex={1} />}
</div>
</div>
)
@@ -150,13 +175,25 @@ class BackupPhraseScreen extends Component {
}
}
+const mapStateToProps = ({ metamask, appState }) => {
+ const { selectedAddress, seedWords, isRevealingSeedWords } = metamask
+ const { isLoading } = appState
+
+ return {
+ seedWords,
+ isRevealingSeedWords,
+ isLoading,
+ address: selectedAddress,
+ }
+}
+
+const mapDispatchToProps = dispatch => {
+ return {
+ clearSeedWords: () => dispatch(confirmSeedWords()),
+ }
+}
+
export default compose(
withRouter,
- connect(
- ({ metamask: { selectedAddress, seedWords }, appState: { isLoading } }) => ({
- seedWords,
- isLoading,
- address: selectedAddress,
- })
- )
+ connect(mapStateToProps, mapDispatchToProps),
)(BackupPhraseScreen)
diff --git a/test/integration/lib/tx-list-items.js b/test/integration/lib/tx-list-items.js
index d0056eb94..0c0c5a77f 100644
--- a/test/integration/lib/tx-list-items.js
+++ b/test/integration/lib/tx-list-items.js
@@ -53,7 +53,7 @@ async function runTxListItemsTest(assert, done) {
const confirmedTokenTx = txListItems[6]
const confirmedTokenTxAddress = await findAsync($(confirmedTokenTx), '.tx-list-account')
- assert.equal(confirmedTokenTxAddress[0].textContent, '0xe7884118...81a9', 'confirmedTokenTx has correct address')
+ assert.equal(confirmedTokenTxAddress[0].textContent, '0xE7884118...81a9', 'confirmedTokenTx has correct address')
const rejectedTx = txListItems[7]
const rejectedTxRenderedStatus = await findAsync($(rejectedTx), '.tx-list-status')
diff --git a/ui/app/actions.js b/ui/app/actions.js
index f5cdd32bc..81d9c333b 100644
--- a/ui/app/actions.js
+++ b/ui/app/actions.js
@@ -345,13 +345,11 @@ function transitionBackward () {
}
}
-function confirmSeedWords () {
+function clearSeedWordCache () {
+ log.debug(`background.clearSeedWordCache`)
return dispatch => {
- dispatch(actions.showLoadingIndication())
- log.debug(`background.clearSeedWordCache`)
return new Promise((resolve, reject) => {
background.clearSeedWordCache((err, account) => {
- dispatch(actions.hideLoadingIndication())
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
@@ -365,6 +363,22 @@ function confirmSeedWords () {
}
}
+function confirmSeedWords () {
+ return async dispatch => {
+ dispatch(actions.showLoadingIndication())
+ const account = await dispatch(clearSeedWordCache())
+ return dispatch(setIsRevealingSeedWords(false))
+ .then(() => {
+ dispatch(actions.hideLoadingIndication())
+ return account
+ })
+ .catch(() => {
+ dispatch(actions.hideLoadingIndication())
+ return account
+ })
+ }
+}
+
function createNewVaultAndRestore (password, seed) {
return (dispatch) => {
dispatch(actions.showLoadingIndication())
@@ -446,11 +460,13 @@ function requestRevealSeed (password) {
}
dispatch(actions.showNewVaultSeed(result))
- dispatch(actions.hideLoadingIndication())
resolve()
})
})
})
+ .then(() => dispatch(setIsRevealingSeedWords(true)))
+ .then(() => dispatch(actions.hideLoadingIndication()))
+ .catch(() => dispatch(actions.hideLoadingIndication()))
}
}
@@ -1907,3 +1923,11 @@ function updateNetworkEndpointType (networkEndpointType) {
value: networkEndpointType,
}
}
+
+function setIsRevealingSeedWords (reveal) {
+ return dispatch => {
+ log.debug(`background.setIsRevealingSeedWords`)
+ background.setIsRevealingSeedWords(reveal)
+ return forceUpdateMetamaskState(dispatch)
+ }
+}
diff --git a/ui/app/app.js b/ui/app/app.js
index 827b4e9ce..0b38b1326 100644
--- a/ui/app/app.js
+++ b/ui/app/app.js
@@ -56,11 +56,20 @@ const {
class App extends Component {
componentWillMount () {
- const { currentCurrency, setCurrentCurrencyToUSD } = this.props
+ const {
+ currentCurrency,
+ setCurrentCurrencyToUSD,
+ isRevealingSeedWords,
+ clearSeedWords,
+ } = this.props
if (!currentCurrency) {
setCurrentCurrencyToUSD()
}
+
+ if (isRevealingSeedWords) {
+ clearSeedWords()
+ }
}
renderRoutes () {
@@ -137,8 +146,6 @@ class App extends Component {
loadingMessage: loadMessage,
}),
- // this.renderLoadingIndicator({ isLoading, isLoadingNetwork, loadMessage }),
-
// content
this.renderRoutes(),
])
@@ -302,17 +309,6 @@ class App extends Component {
)
}
- renderLoadingIndicator ({ isLoading, isLoadingNetwork, loadMessage }) {
- const { isMascara } = this.props
-
- return isMascara
- ? null
- : h(Loading, {
- isLoading: isLoading || isLoadingNetwork,
- loadingMessage: loadMessage,
- })
- }
-
toggleMetamaskActive () {
if (!this.props.isUnlocked) {
// currently inactive: redirect to password box
@@ -406,6 +402,8 @@ App.propTypes = {
isMouseUser: PropTypes.bool,
setMouseUserState: PropTypes.func,
t: PropTypes.func,
+ isRevealingSeedWords: PropTypes.bool,
+ clearSeedWords: PropTypes.func,
}
function mapStateToProps (state) {
@@ -486,6 +484,7 @@ function mapDispatchToProps (dispatch, ownProps) {
setCurrentCurrencyToUSD: () => dispatch(actions.setCurrentCurrency('usd')),
toggleAccountMenu: () => dispatch(actions.toggleAccountMenu()),
setMouseUserState: (isMouseUser) => dispatch(actions.setMouseUserState(isMouseUser)),
+ clearSeedWords: () => dispatch(actions.confirmSeedWords()),
}
}
diff --git a/ui/app/components/account-dropdowns.js b/ui/app/components/account-dropdowns.js
index 03955e077..043008a36 100644
--- a/ui/app/components/account-dropdowns.js
+++ b/ui/app/components/account-dropdowns.js
@@ -7,8 +7,8 @@ const connect = require('react-redux').connect
const Dropdown = require('./dropdown').Dropdown
const DropdownMenuItem = require('./dropdown').DropdownMenuItem
const Identicon = require('./identicon')
-const ethUtil = require('ethereumjs-util')
const copyToClipboard = require('copy-to-clipboard')
+const { checksumAddress } = require('../util')
class AccountDropdowns extends Component {
constructor (props) {
@@ -212,8 +212,7 @@ class AccountDropdowns extends Component {
closeMenu: () => {},
onClick: () => {
const { selected } = this.props
- const checkSumAddress = selected && ethUtil.toChecksumAddress(selected)
- copyToClipboard(checkSumAddress)
+ copyToClipboard(checksumAddress(selected))
},
},
this.context.t('copyAddress'),
diff --git a/ui/app/components/dropdowns/components/account-dropdowns.js b/ui/app/components/dropdowns/components/account-dropdowns.js
index a133f0e29..179b6617f 100644
--- a/ui/app/components/dropdowns/components/account-dropdowns.js
+++ b/ui/app/components/dropdowns/components/account-dropdowns.js
@@ -7,7 +7,7 @@ const connect = require('react-redux').connect
const Dropdown = require('./dropdown').Dropdown
const DropdownMenuItem = require('./dropdown').DropdownMenuItem
const Identicon = require('../../identicon')
-const ethUtil = require('ethereumjs-util')
+const { checksumAddress } = require('../../../util')
const copyToClipboard = require('copy-to-clipboard')
const { formatBalance } = require('../../../util')
@@ -311,8 +311,7 @@ class AccountDropdowns extends Component {
closeMenu: () => {},
onClick: () => {
const { selected } = this.props
- const checkSumAddress = selected && ethUtil.toChecksumAddress(selected)
- copyToClipboard(checkSumAddress)
+ copyToClipboard(checksumAddress(selected))
},
style: Object.assign(
dropdownMenuItemStyle,
diff --git a/ui/app/components/loading.js b/ui/app/components/loading.js
index cb6fa51fb..b9afc550f 100644
--- a/ui/app/components/loading.js
+++ b/ui/app/components/loading.js
@@ -1,6 +1,7 @@
const { Component } = require('react')
const h = require('react-hyperscript')
const PropTypes = require('prop-types')
+const classnames = require('classnames')
class LoadingIndicator extends Component {
renderMessage () {
@@ -10,14 +11,16 @@ class LoadingIndicator extends Component {
render () {
return (
- h('.full-flex-height.loading-overlay', {}, [
- h('img', {
- src: 'images/loading.svg',
- }),
+ h('.loading-overlay', {
+ className: classnames({ 'loading-overlay--full-screen': this.props.fullScreen }),
+ }, [
+ h('.flex-center.flex-column', [
+ h('img', {
+ src: 'images/loading.svg',
+ }),
- h('br'),
-
- this.renderMessage(),
+ this.renderMessage(),
+ ]),
])
)
}
@@ -25,6 +28,7 @@ class LoadingIndicator extends Component {
LoadingIndicator.propTypes = {
loadingMessage: PropTypes.string,
+ fullScreen: PropTypes.bool,
}
module.exports = LoadingIndicator
diff --git a/ui/app/components/modals/export-private-key-modal.js b/ui/app/components/modals/export-private-key-modal.js
index 1f80aed39..447e43b7a 100644
--- a/ui/app/components/modals/export-private-key-modal.js
+++ b/ui/app/components/modals/export-private-key-modal.js
@@ -3,12 +3,13 @@ const PropTypes = require('prop-types')
const h = require('react-hyperscript')
const inherits = require('util').inherits
const connect = require('react-redux').connect
-const ethUtil = require('ethereumjs-util')
+const { stripHexPrefix } = require('ethereumjs-util')
const actions = require('../../actions')
const AccountModalContainer = require('./account-modal-container')
const { getSelectedIdentity } = require('../../selectors')
const ReadOnlyInput = require('../readonly-input')
const copyToClipboard = require('copy-to-clipboard')
+const { checksumAddress } = require('../../util')
function mapStateToProps (state) {
return {
@@ -60,7 +61,7 @@ ExportPrivateKeyModal.prototype.renderPasswordLabel = function (privateKey) {
}
ExportPrivateKeyModal.prototype.renderPasswordInput = function (privateKey) {
- const plainKey = privateKey && ethUtil.stripHexPrefix(privateKey)
+ const plainKey = privateKey && stripHexPrefix(privateKey)
return privateKey
? h(ReadOnlyInput, {
@@ -121,7 +122,7 @@ ExportPrivateKeyModal.prototype.render = function () {
h(ReadOnlyInput, {
wrapperClass: 'ellip-address-wrapper',
inputClass: 'qr-ellip-address ellip-address',
- value: address,
+ value: checksumAddress(address),
}),
h('div.account-modal-divider'),
diff --git a/ui/app/components/pages/settings/info.js b/ui/app/components/pages/settings/info.js
index eb9be66e6..bd9040499 100644
--- a/ui/app/components/pages/settings/info.js
+++ b/ui/app/components/pages/settings/info.js
@@ -3,6 +3,14 @@ const PropTypes = require('prop-types')
const h = require('react-hyperscript')
class Info extends Component {
+ constructor (props) {
+ super(props)
+
+ this.state = {
+ version: global.platform.getVersion(),
+ }
+ }
+
renderLogo () {
return (
h('div.settings__info-logo-wrapper', [
@@ -76,7 +84,7 @@ class Info extends Component {
this.renderLogo(),
h('div.settings__info-item', [
h('div.settings__info-version-header', 'MetaMask Version'),
- h('div.settings__info-version-number', '4.0.0'),
+ h('div.settings__info-version-number', this.state.version),
]),
h('div.settings__info-item', [
h(
diff --git a/ui/app/components/pending-tx/index.js b/ui/app/components/pending-tx/index.js
index acdd99364..6ee83ba7e 100644
--- a/ui/app/components/pending-tx/index.js
+++ b/ui/app/components/pending-tx/index.js
@@ -1,6 +1,7 @@
const Component = require('react').Component
const connect = require('react-redux').connect
const h = require('react-hyperscript')
+const PropTypes = require('prop-types')
const clone = require('clone')
const abi = require('human-standard-token-abi')
const abiDecoder = require('abi-decoder')
@@ -11,6 +12,7 @@ const util = require('../../util')
const ConfirmSendEther = require('./confirm-send-ether')
const ConfirmSendToken = require('./confirm-send-token')
const ConfirmDeployContract = require('./confirm-deploy-contract')
+const Loading = require('../loading')
const TX_TYPES = {
DEPLOY_CONTRACT: 'deploy_contract',
@@ -53,10 +55,24 @@ function PendingTx () {
}
}
-PendingTx.prototype.componentWillMount = async function () {
+PendingTx.prototype.componentDidMount = function () {
+ this.setTokenData()
+}
+
+PendingTx.prototype.componentDidUpdate = function (prevProps, prevState) {
+ if (prevState.isFetching) {
+ this.setTokenData()
+ }
+}
+
+PendingTx.prototype.setTokenData = async function () {
const txMeta = this.gatherTxMeta()
const txParams = txMeta.txParams || {}
+ if (txMeta.loadingDefaults) {
+ return
+ }
+
if (!txParams.to) {
return this.setState({
transactionType: TX_TYPES.DEPLOY_CONTRACT,
@@ -125,7 +141,10 @@ PendingTx.prototype.render = function () {
const { sendTransaction } = this.props
if (isFetching) {
- return h('noscript')
+ return h(Loading, {
+ fullScreen: true,
+ loadingMessage: this.context.t('generatingTransaction'),
+ })
}
switch (transactionType) {
@@ -150,6 +169,12 @@ PendingTx.prototype.render = function () {
sendTransaction,
})
default:
- return h('noscript')
+ return h(Loading, {
+ fullScreen: true,
+ })
}
}
+
+PendingTx.contextTypes = {
+ t: PropTypes.func,
+}
diff --git a/ui/app/components/qr-code.js b/ui/app/components/qr-code.js
index 83885539c..3b2c62f49 100644
--- a/ui/app/components/qr-code.js
+++ b/ui/app/components/qr-code.js
@@ -3,8 +3,9 @@ const h = require('react-hyperscript')
const qrCode = require('qrcode-npm').qrcode
const inherits = require('util').inherits
const connect = require('react-redux').connect
-const isHexPrefixed = require('ethereumjs-util').isHexPrefixed
+const { isHexPrefixed } = require('ethereumjs-util')
const ReadOnlyInput = require('./readonly-input')
+const { checksumAddress } = require('../util')
module.exports = connect(mapStateToProps)(QrCodeView)
@@ -24,16 +25,16 @@ function QrCodeView () {
QrCodeView.prototype.render = function () {
const props = this.props
- const Qr = props.Qr
- const address = `${isHexPrefixed(Qr.data) ? 'ethereum:' : ''}${Qr.data}`
+ const { message, data } = props.Qr
+ const address = `${isHexPrefixed(data) ? 'ethereum:' : ''}${data}`
const qrImage = qrCode(4, 'M')
qrImage.addData(address)
qrImage.make()
return h('.div.flex-column.flex-center', [
- Array.isArray(Qr.message)
+ Array.isArray(message)
? h('.message-container', this.renderMultiMessage())
- : Qr.message && h('.qr-header', Qr.message),
+ : message && h('.qr-header', message),
this.props.warning ? this.props.warning && h('span.error.flex-center', {
style: {
@@ -50,7 +51,7 @@ QrCodeView.prototype.render = function () {
h(ReadOnlyInput, {
wrapperClass: 'ellip-address-wrapper',
inputClass: 'qr-ellip-address',
- value: Qr.data,
+ value: checksumAddress(data),
}),
])
}
diff --git a/ui/app/components/send/account-list-item.js b/ui/app/components/send/account-list-item.js
index 1ad3f69c1..b5e604a6e 100644
--- a/ui/app/components/send/account-list-item.js
+++ b/ui/app/components/send/account-list-item.js
@@ -2,6 +2,7 @@ const Component = require('react').Component
const h = require('react-hyperscript')
const inherits = require('util').inherits
const connect = require('react-redux').connect
+const { checksumAddress } = require('../../util')
const Identicon = require('../identicon')
const CurrencyDisplay = require('./currency-display')
const { conversionRateSelector, getCurrentCurrency } = require('../../selectors')
@@ -56,7 +57,7 @@ AccountListItem.prototype.render = function () {
]),
- displayAddress && name && h('div.account-list-item__account-address', address),
+ displayAddress && name && h('div.account-list-item__account-address', checksumAddress(address)),
displayBalance && h(CurrencyDisplay, {
primaryCurrency: 'ETH',
diff --git a/ui/app/components/tx-list-item.js b/ui/app/components/tx-list-item.js
index 403f83ab9..bd4ea80a6 100644
--- a/ui/app/components/tx-list-item.js
+++ b/ui/app/components/tx-list-item.js
@@ -9,6 +9,7 @@ const abiDecoder = require('abi-decoder')
abiDecoder.addABI(abi)
const Identicon = require('./identicon')
const contractMap = require('eth-contract-metadata')
+const { checksumAddress } = require('../util')
const actions = require('../actions')
const { conversionUtil, multiplyCurrencies } = require('../conversion-util')
@@ -74,10 +75,12 @@ TxListItem.prototype.getAddressText = function () {
const decodedData = txParams.data && abiDecoder.decodeMethod(txParams.data)
const { name: txDataName, params = [] } = decodedData || {}
const { value } = params[0] || {}
+ const checksummedAddress = checksumAddress(address)
+ const checksummedValue = checksumAddress(value)
let addressText
if (txDataName === 'transfer' || address) {
- const addressToRender = txDataName === 'transfer' ? value : address
+ const addressToRender = txDataName === 'transfer' ? checksummedValue : checksummedAddress
addressText = `${addressToRender.slice(0, 10)}...${addressToRender.slice(-4)}`
} else if (isMsg) {
addressText = this.context.t('sigRequest')
diff --git a/ui/app/components/tx-view.js b/ui/app/components/tx-view.js
index 80aac35c4..263f992c0 100644
--- a/ui/app/components/tx-view.js
+++ b/ui/app/components/tx-view.js
@@ -2,13 +2,13 @@ const Component = require('react').Component
const PropTypes = require('prop-types')
const connect = require('react-redux').connect
const h = require('react-hyperscript')
-const ethUtil = require('ethereumjs-util')
const inherits = require('util').inherits
const { withRouter } = require('react-router-dom')
const { compose } = require('recompose')
const actions = require('../actions')
const selectors = require('../selectors')
const { SEND_ROUTE } = require('../routes')
+const { checksumAddress: toChecksumAddress } = require('../util')
const BalanceComponent = require('./balance-component')
const TxList = require('./tx-list')
@@ -32,7 +32,7 @@ function mapStateToProps (state) {
const network = state.metamask.network
const selectedTokenAddress = state.metamask.selectedTokenAddress
const selectedAddress = state.metamask.selectedAddress || Object.keys(accounts)[0]
- const checksumAddress = selectedAddress && ethUtil.toChecksumAddress(selectedAddress)
+ const checksumAddress = toChecksumAddress(selectedAddress)
const identity = identities[selectedAddress]
return {
diff --git a/ui/app/components/wallet-view.js b/ui/app/components/wallet-view.js
index e3e1b8903..9e430f87b 100644
--- a/ui/app/components/wallet-view.js
+++ b/ui/app/components/wallet-view.js
@@ -6,6 +6,7 @@ const { withRouter } = require('react-router-dom')
const { compose } = require('recompose')
const inherits = require('util').inherits
const classnames = require('classnames')
+const { checksumAddress } = require('../util')
const Identicon = require('./identicon')
// const AccountDropdowns = require('./dropdowns/index.js').AccountDropdowns
const Tooltip = require('./tooltip-v2.js')
@@ -107,6 +108,8 @@ WalletView.prototype.render = function () {
// temporary logs + fake extra wallets
// console.log('walletview, selectedAccount:', selectedAccount)
+ const checksummedAddress = checksumAddress(selectedAddress)
+
const keyring = keyrings.find((kr) => {
return kr.accounts.includes(selectedAddress) ||
kr.accounts.includes(selectedIdentity.address)
@@ -135,7 +138,7 @@ WalletView.prototype.render = function () {
}, [
h(Identicon, {
diameter: 54,
- address: selectedAddress,
+ address: checksummedAddress,
}),
h('span.account-name', {
@@ -158,7 +161,7 @@ WalletView.prototype.render = function () {
'wallet-view__address__pressed': this.state.copyToClipboardPressed,
}),
onClick: () => {
- copyToClipboard(selectedAddress)
+ copyToClipboard(checksummedAddress)
this.setState({ hasCopied: true })
setTimeout(() => this.setState({ hasCopied: false }), 3000)
},
@@ -169,7 +172,7 @@ WalletView.prototype.render = function () {
this.setState({ copyToClipboardPressed: false })
},
}, [
- `${selectedAddress.slice(0, 4)}...${selectedAddress.slice(-4)}`,
+ `${checksummedAddress.slice(0, 4)}...${checksummedAddress.slice(-4)}`,
h('i.fa.fa-clipboard', { style: { marginLeft: '8px' } }),
]),
]),
diff --git a/ui/app/css/itcss/components/loading-overlay.scss b/ui/app/css/itcss/components/loading-overlay.scss
index 15009c1e6..a92fffec5 100644
--- a/ui/app/css/itcss/components/loading-overlay.scss
+++ b/ui/app/css/itcss/components/loading-overlay.scss
@@ -1,13 +1,14 @@
.loading-overlay {
- left: 0px;
+ left: 0;
z-index: 50;
position: absolute;
flex-direction: column;
display: flex;
justify-content: center;
align-items: center;
+ flex: 1 1 auto;
width: 100%;
- background: rgba(255, 255, 255, 0.8);
+ background: rgba(255, 255, 255, .8);
@media screen and (max-width: 575px) {
margin-top: 56px;
@@ -18,4 +19,11 @@
margin-top: 75px;
height: calc(100% - 75px);
}
+
+ &--full-screen {
+ position: fixed;
+ height: 100vh;
+ width: 100vw;
+ margin-top: 0;
+ }
}
diff --git a/ui/app/util.js b/ui/app/util.js
index bbe2bb09e..8e9390dfb 100644
--- a/ui/app/util.js
+++ b/ui/app/util.js
@@ -57,6 +57,7 @@ module.exports = {
isInvalidChecksumAddress,
allNull,
getTokenAddressFromTokenObject,
+ checksumAddress,
}
function valuesFor (obj) {
@@ -67,7 +68,7 @@ function valuesFor (obj) {
function addressSummary (address, firstSegLength = 10, lastSegLength = 4, includeHex = true) {
if (!address) return ''
- let checked = ethUtil.toChecksumAddress(address)
+ let checked = checksumAddress(address)
if (!includeHex) {
checked = ethUtil.stripHexPrefix(checked)
}
@@ -76,7 +77,7 @@ function addressSummary (address, firstSegLength = 10, lastSegLength = 4, includ
function miniAddressSummary (address) {
if (!address) return ''
- var checked = ethUtil.toChecksumAddress(address)
+ var checked = checksumAddress(address)
return checked ? checked.slice(0, 4) + '...' + checked.slice(-4) : '...'
}
@@ -287,3 +288,13 @@ function allNull (obj) {
function getTokenAddressFromTokenObject (token) {
return Object.values(token)[0].address.toLowerCase()
}
+
+/**
+ * Safely checksumms a potentially-null address
+ *
+ * @param {String} [address] - address to checksum
+ * @returns {String} - checksummed address
+ */
+function checksumAddress (address) {
+ return address ? ethUtil.toChecksumAddress(address) : ''
+}
diff --git a/ui/lib/icon-factory.js b/ui/lib/icon-factory.js
index 31498a3a9..7fadbceff 100644
--- a/ui/lib/icon-factory.js
+++ b/ui/lib/icon-factory.js
@@ -1,6 +1,6 @@
var iconFactory
const isValidAddress = require('ethereumjs-util').isValidAddress
-const toChecksumAddress = require('ethereumjs-util').toChecksumAddress
+const { checksumAddress } = require('../app/util')
const contractMap = require('eth-contract-metadata')
module.exports = function (jazzicon) {
@@ -16,7 +16,7 @@ function IconFactory (jazzicon) {
}
IconFactory.prototype.iconForAddress = function (address, diameter) {
- const addr = toChecksumAddress(address)
+ const addr = checksumAddress(address)
if (iconExistsFor(addr)) {
return imageElFor(addr)
}