aboutsummaryrefslogtreecommitdiffstats
path: root/app
diff options
context:
space:
mode:
Diffstat (limited to 'app')
-rw-r--r--app/_locales/en/messages.json33
-rw-r--r--app/images/copy-to-clipboard.svg24
-rw-r--r--app/images/download.svg41
-rw-r--r--app/images/warning.svg22
-rw-r--r--app/manifest.json2
-rw-r--r--app/scripts/background.js6
-rw-r--r--app/scripts/contentscript.js1
-rw-r--r--app/scripts/controllers/network/network.js2
-rw-r--r--app/scripts/controllers/token-rates.js8
-rw-r--r--app/scripts/controllers/transactions/README.md92
-rw-r--r--app/scripts/controllers/transactions/index.js (renamed from app/scripts/controllers/transactions.js)332
-rw-r--r--app/scripts/controllers/transactions/lib/tx-state-history-helper.js (renamed from app/scripts/lib/tx-state-history-helper.js)27
-rw-r--r--app/scripts/controllers/transactions/lib/util.js99
-rw-r--r--app/scripts/controllers/transactions/nonce-tracker.js (renamed from app/scripts/lib/nonce-tracker.js)44
-rw-r--r--app/scripts/controllers/transactions/pending-tx-tracker.js (renamed from app/scripts/lib/pending-tx-tracker.js)77
-rw-r--r--app/scripts/controllers/transactions/tx-gas-utils.js (renamed from app/scripts/lib/tx-gas-utils.js)36
-rw-r--r--app/scripts/controllers/transactions/tx-state-manager.js (renamed from app/scripts/lib/tx-state-manager.js)207
-rw-r--r--app/scripts/lib/config-manager.js22
-rw-r--r--app/scripts/lib/setupRaven.js61
-rw-r--r--app/scripts/metamask-controller.js2
-rw-r--r--app/scripts/migrations/018.js2
21 files changed, 853 insertions, 287 deletions
diff --git a/app/_locales/en/messages.json b/app/_locales/en/messages.json
index 3b20ab49a..a40c2635c 100644
--- a/app/_locales/en/messages.json
+++ b/app/_locales/en/messages.json
@@ -98,6 +98,9 @@
"clickCopy": {
"message": "Click to Copy"
},
+ "close": {
+ "message": "Close"
+ },
"confirm": {
"message": "Confirm"
},
@@ -259,6 +262,9 @@
"enterPasswordConfirm": {
"message": "Enter your password to confirm"
},
+ "enterPasswordContinue": {
+ "message": "Enter password to continue"
+ },
"passwordNotLongEnough": {
"message": "Password not long enough"
},
@@ -331,6 +337,9 @@
"gasPriceRequired": {
"message": "Gas Price Required"
},
+ "generatingTransaction": {
+ "message": "Generating transaction"
+ },
"getEther": {
"message": "Get Ether"
},
@@ -476,6 +485,9 @@
"metamaskDescription": {
"message": "MetaMask is a secure identity vault for Ethereum."
},
+ "metamaskSeedWords": {
+ "message": "MetaMask Seed Words"
+ },
"min": {
"message": "Minimum"
},
@@ -549,6 +561,9 @@
"message": "or",
"description": "choice between creating or importing a new account"
},
+ "password": {
+ "message": "Password"
+ },
"passwordCorrect": {
"message": "Please make sure your password is correct."
},
@@ -634,8 +649,17 @@
"revealSeedWords": {
"message": "Reveal Seed Words"
},
+ "revealSeedWordsTitle": {
+ "message": "Seed Phrase"
+ },
+ "revealSeedWordsDescription": {
+ "message": "If you ever change browsers or move computers, you will need this seed phrase to access your accounts. Save them somewhere safe and secret."
+ },
+ "revealSeedWordsWarningTitle": {
+ "message": "DO NOT share this phrase with anyone!"
+ },
"revealSeedWordsWarning": {
- "message": "Do not recover your seed words in a public place! These words can be used to steal all your accounts."
+ "message": "These words can be used to steal all your accounts."
},
"revert": {
"message": "Revert"
@@ -677,6 +701,9 @@
"reprice_subtitle": {
"message": "Increase your gas price to attempt to overwrite and speed up your transaction"
},
+ "saveAsCsvFile": {
+ "message": "Save as CSV File"
+ },
"saveAsFile": {
"message": "Save as File",
"description": "Account export process"
@@ -909,7 +936,7 @@
"youSign": {
"message": "You are signing"
},
- "generatingTransaction": {
- "message": "Generating transaction"
+ "yourPrivateSeedPhrase": {
+ "message": "Your private seed phrase"
}
}
diff --git a/app/images/copy-to-clipboard.svg b/app/images/copy-to-clipboard.svg
new file mode 100644
index 000000000..c67c2aa84
--- /dev/null
+++ b/app/images/copy-to-clipboard.svg
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="18px" height="17px" viewBox="0 0 18 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: sketchtool 49.3 (51167) - http://www.bohemiancoding.com/sketch -->
+ <title>374E58A5-C29E-4921-83E7-889FA06D6408</title>
+ <desc>Created with sketchtool.</desc>
+ <defs></defs>
+ <g id="Reveal-Seedphrase" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Seed-phrase-2" transform="translate(-39.000000, -379.000000)">
+ <g id="Group-2">
+ <g id="Group-8" transform="translate(16.000000, 248.000000)">
+ <g id="Group-6" transform="translate(23.336478, 120.000000)">
+ <g id="Group-5" transform="translate(0.408805, 11.000000)">
+ <g id="copy-to-clipboard">
+ <rect id="Rectangle-18" stroke="#3098DC" stroke-width="2" x="1" y="1" width="12.0220126" height="12"></rect>
+ <rect id="Rectangle-18-Copy-2" fill="#FFFFFF" x="2.1572327" y="2" width="14.0220126" height="14"></rect>
+ <rect id="Rectangle-18-Copy" stroke="#3098DC" stroke-width="2" x="4.23584906" y="4" width="12.0220126" height="12"></rect>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/download.svg b/app/images/download.svg
index 137a1190e..b55066414 100644
--- a/app/images/download.svg
+++ b/app/images/download.svg
@@ -1,15 +1,26 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
- width="24.088px" height="24px" viewBox="138.01 0 24.088 24" enable-background="new 138.01 0 24.088 24" xml:space="preserve" fill="#F7861C">
-<g>
- <polygon fill="#F7861C" points="157.551,17.075 156.55,17.075 156.55,19.149 142.569,19.149 142.569,17.075 141.568,17.075
- 141.568,20.145 141.955,20.145 141.955,20.15 157.006,20.15 157.006,20.145 157.551,20.145 "/>
- <polygon fill="#F7861C" points="152.555,10.275 152.555,11.26 152.555,11.268 151.562,11.268 151.562,12.252 150.565,12.252
- 150.565,4.171 149.564,4.171 149.564,12.236 148.564,12.236 148.564,11.252 147.564,11.252 147.564,11.236 147.564,11.221
- 147.564,10.236 146.563,10.236 146.563,11.221 146.563,11.236 146.563,12.221 147.563,12.221 147.563,12.236 147.563,12.252
- 147.563,13.236 148.563,13.236 148.563,14.221 149.564,14.221 149.564,15.725 150.565,15.725 150.565,14.236 151.563,14.236
- 151.563,13.252 152.563,13.252 152.563,12.268 152.563,12.26 153.556,12.26 153.556,11.275 153.556,11.26 153.556,10.275 "/>
-</g>
-</svg>
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="20px" height="18px" viewBox="0 0 20 18" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: sketchtool 49.3 (51167) - http://www.bohemiancoding.com/sketch -->
+ <title>50559280-0739-419A-8E87-3CDD16A6996A</title>
+ <desc>Created with sketchtool.</desc>
+ <defs></defs>
+ <g id="Reveal-Seedphrase" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Seed-phrase-2" transform="translate(-212.000000, -379.000000)" stroke="#259DE5" stroke-width="2">
+ <g id="Group-2">
+ <g id="Group-8" transform="translate(16.000000, 248.000000)">
+ <g id="Group-6" transform="translate(23.336478, 120.000000)">
+ <g id="Group-3" transform="translate(174.000000, 11.000000)">
+ <g id="Group-4">
+ <g id="download">
+ <polyline id="Path-5" points="0 11 0 17 17 17 17 11"></polyline>
+ <path d="M8.5,0 L8.5,11" id="Path-6"></path>
+ <polyline id="Path-7" points="3.1875 7 8.5 11 13.8125 7"></polyline>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/images/warning.svg b/app/images/warning.svg
new file mode 100644
index 000000000..9c8d697d7
--- /dev/null
+++ b/app/images/warning.svg
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="33px" height="32px" viewBox="0 0 33 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 49.3 (51167) - http://www.bohemiancoding.com/sketch -->
+ <title>Group 7</title>
+ <desc>Created with Sketch.</desc>
+ <defs></defs>
+ <g id="Reveal-Seedphrase" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Seed-phrase-2" transform="translate(-29.000000, -155.000000)">
+ <g id="Group-2" transform="translate(0.000000, 132.000000)">
+ <g id="Group" transform="translate(28.000000, 19.000000)">
+ <g id="Group-19-Copy-2" transform="translate(0.000000, 3.000000)">
+ <g id="Group-7">
+ <path d="M20.1321134,3.85444772 L32.5721829,26.6020033 C33.367162,28.0556794 32.8331826,29.8785746 31.3795065,30.6735537 C30.9381289,30.9149321 30.4431378,31.0414403 29.9400695,31.0414403 L5.05993054,31.0414403 C3.40307629,31.0414403 2.05993054,29.6982946 2.05993054,28.0414403 C2.05993054,27.538372 2.18643873,27.0433809 2.42781712,26.6020033 L14.8678866,3.85444772 C15.6628657,2.40077162 17.4857609,1.86679221 18.939437,2.66177133 C19.442875,2.93708896 19.8567958,3.35100977 20.1321134,3.85444772 Z" id="Triangle-2-Copy" stroke="#FF001F" stroke-width="2"></path>
+ <rect id="Rectangle-5" fill="#FF001F" x="16" y="9" width="3" height="13"></rect>
+ <rect id="Rectangle-5-Copy" fill="#FF001F" x="16" y="24" width="3" height="3"></rect>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+ </g>
+</svg> \ No newline at end of file
diff --git a/app/manifest.json b/app/manifest.json
index dc46f1ca4..3e5eed205 100644
--- a/app/manifest.json
+++ b/app/manifest.json
@@ -1,7 +1,7 @@
{
"name": "__MSG_appName__",
"short_name": "__MSG_appName__",
- "version": "4.5.5",
+ "version": "4.6.0",
"manifest_version": 2,
"author": "https://metamask.io",
"description": "__MSG_appDescription__",
diff --git a/app/scripts/background.js b/app/scripts/background.js
index 38b871bb5..69d549c85 100644
--- a/app/scripts/background.js
+++ b/app/scripts/background.js
@@ -261,7 +261,11 @@ function setupController (initState, initLangCode) {
controller.txController.on(`tx:status-update`, (txId, status) => {
if (status !== 'failed') return
const txMeta = controller.txController.txStateManager.getTx(txId)
- reportFailedTxToSentry({ raven, txMeta })
+ try {
+ reportFailedTxToSentry({ raven, txMeta })
+ } catch (e) {
+ console.error(e)
+ }
})
// setup state persistence
diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js
index dbf1c6d4c..ddf1a9432 100644
--- a/app/scripts/contentscript.js
+++ b/app/scripts/contentscript.js
@@ -174,6 +174,7 @@ function blacklistedDomainCheck () {
'uscourts.gov',
'dropbox.com',
'webbyawards.com',
+ 'cdn.shopify.com/s/javascripts/tricorder/xtld-read-only-frame.html',
]
var currentUrl = window.location.href
var currentRegex
diff --git a/app/scripts/controllers/network/network.js b/app/scripts/controllers/network/network.js
index 6fd983bb2..2f5b81cd2 100644
--- a/app/scripts/controllers/network/network.js
+++ b/app/scripts/controllers/network/network.js
@@ -1,7 +1,7 @@
const assert = require('assert')
const EventEmitter = require('events')
const createMetamaskProvider = require('web3-provider-engine/zero.js')
-const SubproviderFromProvider = require('web3-provider-engine/subproviders/web3.js')
+const SubproviderFromProvider = require('web3-provider-engine/subproviders/provider.js')
const createInfuraProvider = require('eth-json-rpc-infura/src/createProvider')
const ObservableStore = require('obs-store')
const ComposedStore = require('obs-store/lib/composed')
diff --git a/app/scripts/controllers/token-rates.js b/app/scripts/controllers/token-rates.js
index 21384f262..87d716aa6 100644
--- a/app/scripts/controllers/token-rates.js
+++ b/app/scripts/controllers/token-rates.js
@@ -1,4 +1,5 @@
const ObservableStore = require('obs-store')
+const { warn } = require('loglevel')
// By default, poll every 3 minutes
const DEFAULT_INTERVAL = 180 * 1000
@@ -39,10 +40,13 @@ class TokenRatesController {
*/
async fetchExchangeRate (address) {
try {
- const response = await fetch(`https://metamask.dev.balanc3.net/prices?from=${address}&to=ETH&autoConversion=false&summaryOnly=true`)
+ const response = await fetch(`https://metamask.balanc3.net/prices?from=${address}&to=ETH&autoConversion=false&summaryOnly=true`)
const json = await response.json()
return json && json.length ? json[0].averagePrice : 0
- } catch (error) { }
+ } catch (error) {
+ warn(`MetaMask - TokenRatesController exchange rate fetch failed for ${address}.`, error)
+ return 0
+ }
}
/**
diff --git a/app/scripts/controllers/transactions/README.md b/app/scripts/controllers/transactions/README.md
new file mode 100644
index 000000000..b414762dc
--- /dev/null
+++ b/app/scripts/controllers/transactions/README.md
@@ -0,0 +1,92 @@
+# Transaction Controller
+
+Transaction Controller is an aggregate of sub-controllers and trackers
+exposed to the MetaMask controller.
+
+- txStateManager
+ responsible for the state of a transaction and
+ storing the transaction
+- pendingTxTracker
+ watching blocks for transactions to be include
+ and emitting confirmed events
+- txGasUtil
+ gas calculations and safety buffering
+- nonceTracker
+ calculating nonces
+
+## Flow diagram of processing a transaction
+
+![transaction-flow](../../../../docs/transaction-flow.png)
+
+## txMeta's & txParams
+
+A txMeta is the "meta" object it has all the random bits of info we need about a transaction on it. txParams are sacred every thing on txParams gets signed so it must
+be a valid key and be hex prefixed except for the network number. Extra stuff must go on the txMeta!
+
+Here is a txMeta too look at:
+
+```js
+txMeta = {
+ "id": 2828415030114568, // unique id for this txMeta used for look ups
+ "time": 1524094064821, // time of creation
+ "status": "confirmed",
+ "metamaskNetworkId": "1524091532133", //the network id for the transaction
+ "loadingDefaults": false, // used to tell the ui when we are done calculatyig gass defaults
+ "txParams": { // the txParams object
+ "from": "0x8acce2391c0d510a6c5e5d8f819a678f79b7e675",
+ "to": "0x8acce2391c0d510a6c5e5d8f819a678f79b7e675",
+ "value": "0x0",
+ "gasPrice": "0x3b9aca00",
+ "gas": "0x7b0c",
+ "nonce": "0x0"
+ },
+ "history": [{ //debug
+ "id": 2828415030114568,
+ "time": 1524094064821,
+ "status": "unapproved",
+ "metamaskNetworkId": "1524091532133",
+ "loadingDefaults": true,
+ "txParams": {
+ "from": "0x8acce2391c0d510a6c5e5d8f819a678f79b7e675",
+ "to": "0x8acce2391c0d510a6c5e5d8f819a678f79b7e675",
+ "value": "0x0"
+ }
+ },
+ [
+ {
+ "op": "add",
+ "path": "/txParams/gasPrice",
+ "value": "0x3b9aca00"
+ },
+ ...], // I've removed most of history for this
+ "gasPriceSpecified": false, //whether or not the user/dapp has specified gasPrice
+ "gasLimitSpecified": false, //whether or not the user/dapp has specified gas
+ "estimatedGas": "5208",
+ "origin": "MetaMask", //debug
+ "nonceDetails": {
+ "params": {
+ "highestLocallyConfirmed": 0,
+ "highestSuggested": 0,
+ "nextNetworkNonce": 0
+ },
+ "local": {
+ "name": "local",
+ "nonce": 0,
+ "details": {
+ "startPoint": 0,
+ "highest": 0
+ }
+ },
+ "network": {
+ "name": "network",
+ "nonce": 0,
+ "details": {
+ "baseCount": 0
+ }
+ }
+ },
+ "rawTx": "0xf86980843b9aca00827b0c948acce2391c0d510a6c5e5d8f819a678f79b7e67580808602c5b5de66eea05c01a320b96ac730cb210ca56d2cb71fa360e1fc2c21fa5cf333687d18eb323fa02ed05987a6e5fd0f2459fcff80710b76b83b296454ad9a37594a0ccb4643ea90", // used for rebroadcast
+ "hash": "0xa45ba834b97c15e6ff4ed09badd04ecd5ce884b455eb60192cdc73bcc583972a",
+ "submittedTime": 1524094077902 // time of the attempt to submit the raw tx to the network, used in the ui to show the retry button
+}
+```
diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions/index.js
index c8211ebd7..541f1db73 100644
--- a/app/scripts/controllers/transactions.js
+++ b/app/scripts/controllers/transactions/index.js
@@ -3,28 +3,42 @@ const ObservableStore = require('obs-store')
const ethUtil = require('ethereumjs-util')
const Transaction = require('ethereumjs-tx')
const EthQuery = require('ethjs-query')
-const TransactionStateManager = require('../lib/tx-state-manager')
-const TxGasUtil = require('../lib/tx-gas-utils')
-const PendingTransactionTracker = require('../lib/pending-tx-tracker')
-const NonceTracker = require('../lib/nonce-tracker')
+const TransactionStateManager = require('./tx-state-manager')
+const TxGasUtil = require('./tx-gas-utils')
+const PendingTransactionTracker = require('./pending-tx-tracker')
+const NonceTracker = require('./nonce-tracker')
+const txUtils = require('./lib/util')
const log = require('loglevel')
-/*
+/**
Transaction Controller is an aggregate of sub-controllers and trackers
composing them in a way to be exposed to the metamask controller
- - txStateManager
+ <br>- txStateManager
responsible for the state of a transaction and
storing the transaction
- - pendingTxTracker
+ <br>- pendingTxTracker
watching blocks for transactions to be include
and emitting confirmed events
- - txGasUtil
+ <br>- txGasUtil
gas calculations and safety buffering
- - nonceTracker
+ <br>- nonceTracker
calculating nonces
+
+
+ @class
+ @param {object} - opts
+ @param {object} opts.initState - initial transaction list default is an empty array
+ @param {Object} opts.networkStore - an observable store for network number
+ @param {Object} opts.blockTracker - An instance of eth-blocktracker
+ @param {Object} opts.provider - A network provider.
+ @param {Function} opts.signTransaction - function the signs an ethereumjs-tx
+ @param {Function} [opts.getGasPrice] - optional gas price calculator
+ @param {Function} opts.signTransaction - ethTx signer that returns a rawTx
+ @param {Number} [opts.txHistoryLimit] - number *optional* for limiting how many transactions are in state
+ @param {Object} opts.preferencesStore
*/
-module.exports = class TransactionController extends EventEmitter {
+class TransactionController extends EventEmitter {
constructor (opts) {
super()
this.networkStore = opts.networkStore || new ObservableStore({})
@@ -38,45 +52,19 @@ module.exports = class TransactionController extends EventEmitter {
this.query = new EthQuery(this.provider)
this.txGasUtil = new TxGasUtil(this.provider)
+ this._mapMethods()
this.txStateManager = new TransactionStateManager({
initState: opts.initState,
txHistoryLimit: opts.txHistoryLimit,
getNetwork: this.getNetwork.bind(this),
})
-
- this.txStateManager.getFilteredTxList({
- status: 'unapproved',
- loadingDefaults: true,
- }).forEach((tx) => {
- this.addTxDefaults(tx)
- .then((txMeta) => {
- txMeta.loadingDefaults = false
- this.txStateManager.updateTx(txMeta, 'transactions: gas estimation for tx on boot')
- }).catch((error) => {
- this.txStateManager.setTxStatusFailed(tx.id, error)
- })
- })
-
- this.txStateManager.getFilteredTxList({
- status: 'approved',
- }).forEach((txMeta) => {
- const txSignError = new Error('Transaction found as "approved" during boot - possibly stuck during signing')
- this.txStateManager.setTxStatusFailed(txMeta.id, txSignError)
- })
-
+ this._onBootCleanUp()
this.store = this.txStateManager.store
- this.txStateManager.on('tx:status-update', this.emit.bind(this, 'tx:status-update'))
this.nonceTracker = new NonceTracker({
provider: this.provider,
getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager),
- getConfirmedTransactions: (address) => {
- return this.txStateManager.getFilteredTxList({
- from: address,
- status: 'confirmed',
- err: undefined,
- })
- },
+ getConfirmedTransactions: this.txStateManager.getConfirmedTransactions.bind(this.txStateManager),
})
this.pendingTxTracker = new PendingTransactionTracker({
@@ -88,60 +76,14 @@ module.exports = class TransactionController extends EventEmitter {
})
this.txStateManager.store.subscribe(() => this.emit('update:badge'))
-
- this.pendingTxTracker.on('tx:warning', (txMeta) => {
- this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:warning')
- })
- this.pendingTxTracker.on('tx:confirmed', (txId) => this._markNonceDuplicatesDropped(txId))
- this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager))
- this.pendingTxTracker.on('tx:block-update', (txMeta, latestBlockNumber) => {
- if (!txMeta.firstRetryBlockNumber) {
- txMeta.firstRetryBlockNumber = latestBlockNumber
- this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:block-update')
- }
- })
- this.pendingTxTracker.on('tx:retry', (txMeta) => {
- if (!('retryCount' in txMeta)) txMeta.retryCount = 0
- txMeta.retryCount++
- this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:retry')
- })
-
- this.blockTracker.on('block', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker))
- // this is a little messy but until ethstore has been either
- // removed or redone this is to guard against the race condition
- this.blockTracker.on('latest', this.pendingTxTracker.resubmitPendingTxs.bind(this.pendingTxTracker))
- this.blockTracker.on('sync', this.pendingTxTracker.queryPendingTxs.bind(this.pendingTxTracker))
+ this._setupListners()
// memstore is computed from a few different stores
this._updateMemstore()
this.txStateManager.store.subscribe(() => this._updateMemstore())
this.networkStore.subscribe(() => this._updateMemstore())
this.preferencesStore.subscribe(() => this._updateMemstore())
}
-
- getState () {
- return this.memStore.getState()
- }
-
- getNetwork () {
- return this.networkStore.getState()
- }
-
- getSelectedAddress () {
- return this.preferencesStore.getState().selectedAddress
- }
-
- getUnapprovedTxCount () {
- return Object.keys(this.txStateManager.getUnapprovedTxList()).length
- }
-
- getPendingTxCount (account) {
- return this.txStateManager.getPendingTransactions(account).length
- }
-
- getFilteredTxList (opts) {
- return this.txStateManager.getFilteredTxList(opts)
- }
-
+ /** @returns {number} the chainId*/
getChainId () {
const networkState = this.networkStore.getState()
const getChainId = parseInt(networkState)
@@ -152,16 +94,30 @@ module.exports = class TransactionController extends EventEmitter {
}
}
- wipeTransactions (address) {
- this.txStateManager.wipeTransactions(address)
- }
-
- // Adds a tx to the txlist
+/**
+ Adds a tx to the txlist
+ @emits ${txMeta.id}:unapproved
+*/
addTx (txMeta) {
this.txStateManager.addTx(txMeta)
this.emit(`${txMeta.id}:unapproved`, txMeta)
}
+ /**
+ Wipes the transactions for a given account
+ @param {string} address - hex string of the from address for txs being removed
+ */
+ wipeTransactions (address) {
+ this.txStateManager.wipeTransactions(address)
+ }
+
+ /**
+ add a new unapproved transaction to the pipeline
+
+ @returns {Promise<string>} the hash of the transaction after being submitted to the network
+ @param txParams {object} - txParams for the transaction
+ @param opts {object} - with the key origin to put the origin on the txMeta
+ */
async newUnapprovedTransaction (txParams, opts = {}) {
log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
const initialTxMeta = await this.addUnapprovedTransaction(txParams)
@@ -184,17 +140,24 @@ module.exports = class TransactionController extends EventEmitter {
})
}
+ /**
+ Validates and generates a txMeta with defaults and puts it in txStateManager
+ store
+
+ @returns {txMeta}
+ */
+
async addUnapprovedTransaction (txParams) {
// validate
- const normalizedTxParams = this._normalizeTxParams(txParams)
- this._validateTxParams(normalizedTxParams)
+ const normalizedTxParams = txUtils.normalizeTxParams(txParams)
+ txUtils.validateTxParams(normalizedTxParams)
// construct txMeta
let txMeta = this.txStateManager.generateTxMeta({ txParams: normalizedTxParams })
this.addTx(txMeta)
this.emit('newUnapprovedTx', txMeta)
// add default tx params
try {
- txMeta = await this.addTxDefaults(txMeta)
+ txMeta = await this.addTxGasDefaults(txMeta)
} catch (error) {
console.log(error)
this.txStateManager.setTxStatusFailed(txMeta.id, error)
@@ -206,21 +169,33 @@ module.exports = class TransactionController extends EventEmitter {
return txMeta
}
-
- async addTxDefaults (txMeta) {
+/**
+ adds the tx gas defaults: gas && gasPrice
+ @param txMeta {Object} - the txMeta object
+ @returns {Promise<object>} resolves with txMeta
+*/
+ async addTxGasDefaults (txMeta) {
const txParams = txMeta.txParams
// ensure value
+ txParams.value = txParams.value ? ethUtil.addHexPrefix(txParams.value) : '0x0'
txMeta.gasPriceSpecified = Boolean(txParams.gasPrice)
let gasPrice = txParams.gasPrice
if (!gasPrice) {
gasPrice = this.getGasPrice ? this.getGasPrice() : await this.query.gasPrice()
}
txParams.gasPrice = ethUtil.addHexPrefix(gasPrice.toString(16))
- txParams.value = txParams.value || '0x0'
// set gasLimit
return await this.txGasUtil.analyzeGasUsage(txMeta)
}
+ /**
+ Creates a new txMeta with the same txParams as the original
+ to allow the user to resign the transaction with a higher gas values
+ @param originalTxId {number} - the id of the txMeta that
+ you want to attempt to retry
+ @return {txMeta}
+ */
+
async retryTransaction (originalTxId) {
const originalTxMeta = this.txStateManager.getTx(originalTxId)
const lastGasPrice = originalTxMeta.txParams.gasPrice
@@ -234,15 +209,31 @@ module.exports = class TransactionController extends EventEmitter {
return txMeta
}
+ /**
+ updates the txMeta in the txStateManager
+ @param txMeta {Object} - the updated txMeta
+ */
async updateTransaction (txMeta) {
this.txStateManager.updateTx(txMeta, 'confTx: user updated transaction')
}
+ /**
+ updates and approves the transaction
+ @param txMeta {Object}
+ */
async updateAndApproveTransaction (txMeta) {
this.txStateManager.updateTx(txMeta, 'confTx: user approved transaction')
await this.approveTransaction(txMeta.id)
}
+ /**
+ sets the tx status to approved
+ auto fills the nonce
+ signs the transaction
+ publishes the transaction
+ if any of these steps fails the tx status will be set to failed
+ @param txId {number} - the tx's Id
+ */
async approveTransaction (txId) {
let nonceLock
try {
@@ -274,7 +265,11 @@ module.exports = class TransactionController extends EventEmitter {
throw err
}
}
-
+ /**
+ adds the chain id and signs the transaction and set the status to signed
+ @param txId {number} - the tx's Id
+ @returns - rawTx {string}
+ */
async signTransaction (txId) {
const txMeta = this.txStateManager.getTx(txId)
// add network/chain id
@@ -290,6 +285,12 @@ module.exports = class TransactionController extends EventEmitter {
return rawTx
}
+ /**
+ publishes the raw tx and sets the txMeta to submitted
+ @param txId {number} - the tx's Id
+ @param rawTx {string} - the hex string of the serialized signed transaction
+ @returns {Promise<void>}
+ */
async publishTransaction (txId, rawTx) {
const txMeta = this.txStateManager.getTx(txId)
txMeta.rawTx = rawTx
@@ -299,11 +300,20 @@ module.exports = class TransactionController extends EventEmitter {
this.txStateManager.setTxStatusSubmitted(txId)
}
+ /**
+ Convenience method for the ui thats sets the transaction to rejected
+ @param txId {number} - the tx's Id
+ @returns {Promise<void>}
+ */
async cancelTransaction (txId) {
this.txStateManager.setTxStatusRejected(txId)
}
- // receives a txHash records the tx as signed
+ /**
+ Sets the txHas on the txMeta
+ @param txId {number} - the tx's Id
+ @param txHash {string} - the hash for the txMeta
+ */
setTxHash (txId, txHash) {
// Add the tx hash to the persisted meta-tx object
const txMeta = this.txStateManager.getTx(txId)
@@ -314,63 +324,92 @@ module.exports = class TransactionController extends EventEmitter {
//
// PRIVATE METHODS
//
+ /** maps methods for convenience*/
+ _mapMethods () {
+ /** @returns the state in transaction controller */
+ this.getState = () => this.memStore.getState()
+ /** @returns the network number stored in networkStore */
+ this.getNetwork = () => this.networkStore.getState()
+ /** @returns the user selected address */
+ this.getSelectedAddress = () => this.preferencesStore.getState().selectedAddress
+ /** Returns an array of transactions whos status is unapproved */
+ this.getUnapprovedTxCount = () => Object.keys(this.txStateManager.getUnapprovedTxList()).length
+ /**
+ @returns a number that represents how many transactions have the status submitted
+ @param account {String} - hex prefixed account
+ */
+ this.getPendingTxCount = (account) => this.txStateManager.getPendingTransactions(account).length
+ /** see txStateManager */
+ this.getFilteredTxList = (opts) => this.txStateManager.getFilteredTxList(opts)
+ }
- _normalizeTxParams (txParams) {
- // functions that handle normalizing of that key in txParams
- const whiteList = {
- from: from => ethUtil.addHexPrefix(from).toLowerCase(),
- to: to => ethUtil.addHexPrefix(txParams.to).toLowerCase(),
- nonce: nonce => ethUtil.addHexPrefix(nonce),
- value: value => ethUtil.addHexPrefix(value),
- data: data => ethUtil.addHexPrefix(data),
- gas: gas => ethUtil.addHexPrefix(gas),
- gasPrice: gasPrice => ethUtil.addHexPrefix(gasPrice),
- }
+ /**
+ If transaction controller was rebooted with transactions that are uncompleted
+ in steps of the transaction signing or user confirmation process it will either
+ transition txMetas to a failed state or try to redo those tasks.
+ */
- // apply only keys in the whiteList
- const normalizedTxParams = {}
- Object.keys(whiteList).forEach((key) => {
- if (txParams[key]) normalizedTxParams[key] = whiteList[key](txParams[key])
+ _onBootCleanUp () {
+ this.txStateManager.getFilteredTxList({
+ status: 'unapproved',
+ loadingDefaults: true,
+ }).forEach((tx) => {
+ this.addTxGasDefaults(tx)
+ .then((txMeta) => {
+ txMeta.loadingDefaults = false
+ this.txStateManager.updateTx(txMeta, 'transactions: gas estimation for tx on boot')
+ }).catch((error) => {
+ this.txStateManager.setTxStatusFailed(tx.id, error)
+ })
})
- return normalizedTxParams
+ this.txStateManager.getFilteredTxList({
+ status: 'approved',
+ }).forEach((txMeta) => {
+ const txSignError = new Error('Transaction found as "approved" during boot - possibly stuck during signing')
+ this.txStateManager.setTxStatusFailed(txMeta.id, txSignError)
+ })
}
- _validateTxParams (txParams) {
- this._validateFrom(txParams)
- this._validateRecipient(txParams)
- if ('value' in txParams) {
- const value = txParams.value.toString()
- if (value.includes('-')) {
- throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`)
+ /**
+ is called in constructor applies the listeners for pendingTxTracker txStateManager
+ and blockTracker
+ */
+ _setupListners () {
+ this.txStateManager.on('tx:status-update', this.emit.bind(this, 'tx:status-update'))
+ this.pendingTxTracker.on('tx:warning', (txMeta) => {
+ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:warning')
+ })
+ this.pendingTxTracker.on('tx:confirmed', (txId) => this.txStateManager.setTxStatusConfirmed(txId))
+ this.pendingTxTracker.on('tx:confirmed', (txId) => this._markNonceDuplicatesDropped(txId))
+ this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager))
+ this.pendingTxTracker.on('tx:block-update', (txMeta, latestBlockNumber) => {
+ if (!txMeta.firstRetryBlockNumber) {
+ txMeta.firstRetryBlockNumber = latestBlockNumber
+ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:block-update')
}
+ })
+ this.pendingTxTracker.on('tx:retry', (txMeta) => {
+ if (!('retryCount' in txMeta)) txMeta.retryCount = 0
+ txMeta.retryCount++
+ this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:retry')
+ })
- if (value.includes('.')) {
- throw new Error(`Invalid transaction value of ${txParams.value} number must be in wei`)
- }
- }
- }
+ this.blockTracker.on('block', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker))
+ // this is a little messy but until ethstore has been either
+ // removed or redone this is to guard against the race condition
+ this.blockTracker.on('latest', this.pendingTxTracker.resubmitPendingTxs.bind(this.pendingTxTracker))
+ this.blockTracker.on('sync', this.pendingTxTracker.queryPendingTxs.bind(this.pendingTxTracker))
- _validateFrom (txParams) {
- if ( !(typeof txParams.from === 'string') ) throw new Error(`Invalid from address ${txParams.from} not a string`)
- if (!ethUtil.isValidAddress(txParams.from)) throw new Error('Invalid from address')
}
- _validateRecipient (txParams) {
- if (txParams.to === '0x' || txParams.to === null ) {
- if (txParams.data) {
- delete txParams.to
- } else {
- throw new Error('Invalid recipient address')
- }
- } else if ( txParams.to !== undefined && !ethUtil.isValidAddress(txParams.to) ) {
- throw new Error('Invalid recipient address')
- }
- return txParams
- }
+ /**
+ Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions
+ in the list have the same nonce
+ @param txId {Number} - the txId of the transaction that has been confirmed in a block
+ */
_markNonceDuplicatesDropped (txId) {
- this.txStateManager.setTxStatusConfirmed(txId)
// get the confirmed transactions nonce and from address
const txMeta = this.txStateManager.getTx(txId)
const { nonce, from } = txMeta.txParams
@@ -385,6 +424,9 @@ module.exports = class TransactionController extends EventEmitter {
})
}
+ /**
+ Updates the memStore in transaction controller
+ */
_updateMemstore () {
const unapprovedTxs = this.txStateManager.getUnapprovedTxList()
const selectedAddressTxList = this.txStateManager.getFilteredTxList({
@@ -394,3 +436,5 @@ module.exports = class TransactionController extends EventEmitter {
this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
}
}
+
+module.exports = TransactionController
diff --git a/app/scripts/lib/tx-state-history-helper.js b/app/scripts/controllers/transactions/lib/tx-state-history-helper.js
index 94c7b6792..59a4b562c 100644
--- a/app/scripts/lib/tx-state-history-helper.js
+++ b/app/scripts/controllers/transactions/lib/tx-state-history-helper.js
@@ -1,6 +1,6 @@
const jsonDiffer = require('fast-json-patch')
const clone = require('clone')
-
+/** @module*/
module.exports = {
generateHistoryEntry,
replayHistory,
@@ -8,7 +8,11 @@ module.exports = {
migrateFromSnapshotsToDiffs,
}
-
+/**
+ converts non-initial history entries into diffs
+ @param longHistory {array}
+ @returns {array}
+*/
function migrateFromSnapshotsToDiffs (longHistory) {
return (
longHistory
@@ -20,6 +24,17 @@ function migrateFromSnapshotsToDiffs (longHistory) {
)
}
+/**
+ generates an array of history objects sense the previous state.
+ The object has the keys opp(the operation preformed),
+ path(the key and if a nested object then each key will be seperated with a `/`)
+ value
+ with the first entry having the note
+ @param previousState {object} - the previous state of the object
+ @param newState {object} - the update object
+ @param note {string} - a optional note for the state change
+ @reurns {array}
+*/
function generateHistoryEntry (previousState, newState, note) {
const entry = jsonDiffer.compare(previousState, newState)
// Add a note to the first op, since it breaks if we append it to the entry
@@ -27,11 +42,19 @@ function generateHistoryEntry (previousState, newState, note) {
return entry
}
+/**
+ Recovers previous txMeta state obj
+ @return {object}
+*/
function replayHistory (_shortHistory) {
const shortHistory = clone(_shortHistory)
return shortHistory.reduce((val, entry) => jsonDiffer.applyPatch(val, entry).newDocument)
}
+/**
+ @param txMeta {Object}
+ @returns {object} a clone object of the txMeta with out history
+*/
function snapshotFromTxMeta (txMeta) {
// create txMeta snapshot for history
const snapshot = clone(txMeta)
diff --git a/app/scripts/controllers/transactions/lib/util.js b/app/scripts/controllers/transactions/lib/util.js
new file mode 100644
index 000000000..84f7592a0
--- /dev/null
+++ b/app/scripts/controllers/transactions/lib/util.js
@@ -0,0 +1,99 @@
+const {
+ addHexPrefix,
+ isValidAddress,
+} = require('ethereumjs-util')
+
+/**
+@module
+*/
+module.exports = {
+ normalizeTxParams,
+ validateTxParams,
+ validateFrom,
+ validateRecipient,
+ getFinalStates,
+}
+
+
+// functions that handle normalizing of that key in txParams
+const normalizers = {
+ from: from => addHexPrefix(from).toLowerCase(),
+ to: to => addHexPrefix(to).toLowerCase(),
+ nonce: nonce => addHexPrefix(nonce),
+ value: value => addHexPrefix(value),
+ data: data => addHexPrefix(data),
+ gas: gas => addHexPrefix(gas),
+ gasPrice: gasPrice => addHexPrefix(gasPrice),
+}
+
+ /**
+ normalizes txParams
+ @param txParams {object}
+ @returns {object} normalized txParams
+ */
+function normalizeTxParams (txParams) {
+ // apply only keys in the normalizers
+ const normalizedTxParams = {}
+ for (const key in normalizers) {
+ if (txParams[key]) normalizedTxParams[key] = normalizers[key](txParams[key])
+ }
+ return normalizedTxParams
+}
+
+ /**
+ validates txParams
+ @param txParams {object}
+ */
+function validateTxParams (txParams) {
+ validateFrom(txParams)
+ validateRecipient(txParams)
+ if ('value' in txParams) {
+ const value = txParams.value.toString()
+ if (value.includes('-')) {
+ throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`)
+ }
+
+ if (value.includes('.')) {
+ throw new Error(`Invalid transaction value of ${txParams.value} number must be in wei`)
+ }
+ }
+}
+
+ /**
+ validates the from field in txParams
+ @param txParams {object}
+ */
+function validateFrom (txParams) {
+ if (!(typeof txParams.from === 'string')) throw new Error(`Invalid from address ${txParams.from} not a string`)
+ if (!isValidAddress(txParams.from)) throw new Error('Invalid from address')
+}
+
+ /**
+ validates the to field in txParams
+ @param txParams {object}
+ */
+function validateRecipient (txParams) {
+ if (txParams.to === '0x' || txParams.to === null) {
+ if (txParams.data) {
+ delete txParams.to
+ } else {
+ throw new Error('Invalid recipient address')
+ }
+ } else if (txParams.to !== undefined && !isValidAddress(txParams.to)) {
+ throw new Error('Invalid recipient address')
+ }
+ return txParams
+}
+
+ /**
+ @returns an {array} of states that can be considered final
+ */
+function getFinalStates () {
+ return [
+ 'rejected', // the user has responded no!
+ 'confirmed', // the tx has been included in a block.
+ 'failed', // the tx failed for some reason, included on tx data.
+ 'dropped', // the tx nonce was already used
+ ]
+}
+
diff --git a/app/scripts/lib/nonce-tracker.js b/app/scripts/controllers/transactions/nonce-tracker.js
index 5b1cd7f43..f8cdc5523 100644
--- a/app/scripts/lib/nonce-tracker.js
+++ b/app/scripts/controllers/transactions/nonce-tracker.js
@@ -1,7 +1,15 @@
const EthQuery = require('ethjs-query')
const assert = require('assert')
const Mutex = require('await-semaphore').Mutex
-
+/**
+ @param opts {Object}
+ @param {Object} opts.provider a ethereum provider
+ @param {Function} opts.getPendingTransactions a function that returns an array of txMeta
+ whosee status is `submitted`
+ @param {Function} opts.getConfirmedTransactions a function that returns an array of txMeta
+ whose status is `confirmed`
+ @class
+*/
class NonceTracker {
constructor ({ provider, getPendingTransactions, getConfirmedTransactions }) {
@@ -12,6 +20,9 @@ class NonceTracker {
this.lockMap = {}
}
+ /**
+ @returns {Promise<Object>} with the key releaseLock (the gloabl mutex)
+ */
async getGlobalLock () {
const globalMutex = this._lookupMutex('global')
// await global mutex free
@@ -19,8 +30,20 @@ class NonceTracker {
return { releaseLock }
}
- // releaseLock must be called
- // releaseLock must be called after adding signed tx to pending transactions (or discarding)
+ /**
+ * @typedef NonceDetails
+ * @property {number} highestLocallyConfirmed - A hex string of the highest nonce on a confirmed transaction.
+ * @property {number} nextNetworkNonce - The next nonce suggested by the eth_getTransactionCount method.
+ * @property {number} highetSuggested - The maximum between the other two, the number returned.
+ */
+
+ /**
+ this will return an object with the `nextNonce` `nonceDetails` of type NonceDetails, and the releaseLock
+ Note: releaseLock must be called after adding a signed tx to pending transactions (or discarding).
+
+ @param address {string} the hex string for the address whose nonce we are calculating
+ @returns {Promise<NonceDetails>}
+ */
async getNonceLock (address) {
// await global mutex free
await this._globalMutexFree()
@@ -123,6 +146,17 @@ class NonceTracker {
return highestNonce
}
+ /**
+ @typedef {object} highestContinuousFrom
+ @property {string} - name the name for how the nonce was calculated based on the data used
+ @property {number} - nonce the next suggested nonce
+ @property {object} - details the provided starting nonce that was used (for debugging)
+ */
+ /**
+ @param txList {array} - list of txMeta's
+ @param startPoint {number} - the highest known locally confirmed nonce
+ @returns {highestContinuousFrom}
+ */
_getHighestContinuousFrom (txList, startPoint) {
const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce
@@ -140,6 +174,10 @@ class NonceTracker {
// this is a hotfix for the fact that the blockTracker will
// change when the network changes
+
+ /**
+ @returns {Object} the current blockTracker
+ */
_getBlockTracker () {
return this.provider._blockTracker
}
diff --git a/app/scripts/lib/pending-tx-tracker.js b/app/scripts/controllers/transactions/pending-tx-tracker.js
index e8869e6b8..6e2fcb40b 100644
--- a/app/scripts/lib/pending-tx-tracker.js
+++ b/app/scripts/controllers/transactions/pending-tx-tracker.js
@@ -1,23 +1,24 @@
const EventEmitter = require('events')
+const log = require('loglevel')
const EthQuery = require('ethjs-query')
-/*
-
- Utility class for tracking the transactions as they
- go from a pending state to a confirmed (mined in a block) state
+/**
+ Event emitter utility class for tracking the transactions as they<br>
+ go from a pending state to a confirmed (mined in a block) state<br>
+<br>
As well as continues broadcast while in the pending state
+<br>
+@param config {object} - non optional configuration object consists of:
+ @param {Object} config.provider - A network provider.
+ @param {Object} config.nonceTracker see nonce tracker
+ @param {function} config.getPendingTransactions a function for getting an array of transactions,
+ @param {function} config.publishTransaction a async function for publishing raw transactions,
- ~config is not optional~
- requires a: {
- provider: //,
- nonceTracker: //see nonce tracker,
- getPendingTransactions: //() a function for getting an array of transactions,
- publishTransaction: //(rawTx) a async function for publishing raw transactions,
- }
+@class
*/
-module.exports = class PendingTransactionTracker extends EventEmitter {
+class PendingTransactionTracker extends EventEmitter {
constructor (config) {
super()
this.query = new EthQuery(config.provider)
@@ -29,8 +30,13 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
this._checkPendingTxs()
}
- // checks if a signed tx is in a block and
- // if included sets the tx status as 'confirmed'
+ /**
+ checks if a signed tx is in a block and
+ if it is included emits tx status as 'confirmed'
+ @param block {object}, a full block
+ @emits tx:confirmed
+ @emits tx:failed
+ */
checkForTxInBlock (block) {
const signedTxList = this.getPendingTransactions()
if (!signedTxList.length) return
@@ -52,6 +58,11 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
})
}
+ /**
+ asks the network for the transaction to see if a block number is included on it
+ if we have skipped/missed blocks
+ @param object - oldBlock newBlock
+ */
queryPendingTxs ({ oldBlock, newBlock }) {
// check pending transactions on start
if (!oldBlock) {
@@ -63,7 +74,11 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
if (diff > 1) this._checkPendingTxs()
}
-
+ /**
+ Will resubmit any transactions who have not been confirmed in a block
+ @param block {object} - a block object
+ @emits tx:warning
+ */
resubmitPendingTxs (block) {
const pending = this.getPendingTransactions()
// only try resubmitting if their are transactions to resubmit
@@ -100,6 +115,13 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
}))
}
+ /**
+ resubmits the individual txMeta used in resubmitPendingTxs
+ @param txMeta {Object} - txMeta object
+ @param latestBlockNumber {string} - hex string for the latest block number
+ @emits tx:retry
+ @returns txHash {string}
+ */
async _resubmitTx (txMeta, latestBlockNumber) {
if (!txMeta.firstRetryBlockNumber) {
this.emit('tx:block-update', txMeta, latestBlockNumber)
@@ -123,7 +145,13 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
this.emit('tx:retry', txMeta)
return txHash
}
-
+ /**
+ Ask the network for the transaction to see if it has been include in a block
+ @param txMeta {Object} - the txMeta object
+ @emits tx:failed
+ @emits tx:confirmed
+ @emits tx:warning
+ */
async _checkPendingTx (txMeta) {
const txHash = txMeta.hash
const txId = txMeta.id
@@ -162,8 +190,9 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
}
}
- // checks the network for signed txs and
- // if confirmed sets the tx status as 'confirmed'
+ /**
+ checks the network for signed txs and releases the nonce global lock if it is
+ */
async _checkPendingTxs () {
const signedTxList = this.getPendingTransactions()
// in order to keep the nonceTracker accurate we block it while updating pending transactions
@@ -171,12 +200,17 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
try {
await Promise.all(signedTxList.map((txMeta) => this._checkPendingTx(txMeta)))
} catch (err) {
- console.error('PendingTransactionWatcher - Error updating pending transactions')
- console.error(err)
+ log.error('PendingTransactionWatcher - Error updating pending transactions')
+ log.error(err)
}
nonceGlobalLock.releaseLock()
}
+ /**
+ checks to see if a confirmed txMeta has the same nonce
+ @param txMeta {Object} - txMeta object
+ @returns {boolean}
+ */
async _checkIfNonceIsTaken (txMeta) {
const address = txMeta.txParams.from
const completed = this.getCompletedTransactions(address)
@@ -185,5 +219,6 @@ module.exports = class PendingTransactionTracker extends EventEmitter {
})
return sameNonce.length > 0
}
-
}
+
+module.exports = PendingTransactionTracker
diff --git a/app/scripts/lib/tx-gas-utils.js b/app/scripts/controllers/transactions/tx-gas-utils.js
index c579e462a..36b5cdbc9 100644
--- a/app/scripts/lib/tx-gas-utils.js
+++ b/app/scripts/controllers/transactions/tx-gas-utils.js
@@ -3,22 +3,27 @@ const {
hexToBn,
BnMultiplyByFraction,
bnToHex,
-} = require('./util')
+} = require('../../lib/util')
const { addHexPrefix } = require('ethereumjs-util')
const SIMPLE_GAS_COST = '0x5208' // Hex for 21000, cost of a simple send.
-/*
-tx-utils are utility methods for Transaction manager
+/**
+tx-gas-utils are gas utility methods for Transaction manager
its passed ethquery
and used to do things like calculate gas of a tx.
+@param {Object} provider - A network provider.
*/
-module.exports = class TxGasUtil {
+class TxGasUtil {
constructor (provider) {
this.query = new EthQuery(provider)
}
+ /**
+ @param txMeta {Object} - the txMeta object
+ @returns {object} the txMeta object with the gas written to the txParams
+ */
async analyzeGasUsage (txMeta) {
const block = await this.query.getBlockByNumber('latest', true)
let estimatedGasHex
@@ -38,6 +43,12 @@ module.exports = class TxGasUtil {
return txMeta
}
+ /**
+ Estimates the tx's gas usage
+ @param txMeta {Object} - the txMeta object
+ @param blockGasLimitHex {string} - hex string of the block's gas limit
+ @returns {string} the estimated gas limit as a hex string
+ */
async estimateTxGas (txMeta, blockGasLimitHex) {
const txParams = txMeta.txParams
@@ -70,6 +81,12 @@ module.exports = class TxGasUtil {
return await this.query.estimateGas(txParams)
}
+ /**
+ Writes the gas on the txParams in the txMeta
+ @param txMeta {Object} - the txMeta object to write to
+ @param blockGasLimitHex {string} - the block gas limit hex
+ @param estimatedGasHex {string} - the estimated gas hex
+ */
setTxGas (txMeta, blockGasLimitHex, estimatedGasHex) {
txMeta.estimatedGas = addHexPrefix(estimatedGasHex)
const txParams = txMeta.txParams
@@ -87,6 +104,13 @@ module.exports = class TxGasUtil {
return
}
+ /**
+ Adds a gas buffer with out exceeding the block gas limit
+
+ @param initialGasLimitHex {string} - the initial gas limit to add the buffer too
+ @param blockGasLimitHex {string} - the block gas limit
+ @returns {string} the buffered gas limit as a hex string
+ */
addGasBuffer (initialGasLimitHex, blockGasLimitHex) {
const initialGasLimitBn = hexToBn(initialGasLimitHex)
const blockGasLimitBn = hexToBn(blockGasLimitHex)
@@ -100,4 +124,6 @@ module.exports = class TxGasUtil {
// otherwise use blockGasLimit
return bnToHex(upperGasLimitBn)
}
-} \ No newline at end of file
+}
+
+module.exports = TxGasUtil \ No newline at end of file
diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/controllers/transactions/tx-state-manager.js
index c6d10ee62..53428c333 100644
--- a/app/scripts/lib/tx-state-manager.js
+++ b/app/scripts/controllers/transactions/tx-state-manager.js
@@ -1,22 +1,33 @@
const extend = require('xtend')
const EventEmitter = require('events')
const ObservableStore = require('obs-store')
-const createId = require('./random-id')
const ethUtil = require('ethereumjs-util')
-const txStateHistoryHelper = require('./tx-state-history-helper')
-
-// STATUS METHODS
- // statuses:
- // - `'unapproved'` the user has not responded
- // - `'rejected'` the user has responded no!
- // - `'approved'` the user has approved the tx
- // - `'signed'` the tx is signed
- // - `'submitted'` the tx is sent to a server
- // - `'confirmed'` the tx has been included in a block.
- // - `'failed'` the tx failed for some reason, included on tx data.
- // - `'dropped'` the tx nonce was already used
-
-module.exports = class TransactionStateManager extends EventEmitter {
+const txStateHistoryHelper = require('./lib/tx-state-history-helper')
+const createId = require('../../lib/random-id')
+const { getFinalStates } = require('./lib/util')
+/**
+ TransactionStateManager is responsible for the state of a transaction and
+ storing the transaction
+ it also has some convenience methods for finding subsets of transactions
+ *
+ *STATUS METHODS
+ <br>statuses:
+ <br> - `'unapproved'` the user has not responded
+ <br> - `'rejected'` the user has responded no!
+ <br> - `'approved'` the user has approved the tx
+ <br> - `'signed'` the tx is signed
+ <br> - `'submitted'` the tx is sent to a server
+ <br> - `'confirmed'` the tx has been included in a block.
+ <br> - `'failed'` the tx failed for some reason, included on tx data.
+ <br> - `'dropped'` the tx nonce was already used
+ @param opts {object}
+ @param {object} [opts.initState={ transactions: [] }] initial transactions list with the key transaction {array}
+ @param {number} [opts.txHistoryLimit] limit for how many finished
+ transactions can hang around in state
+ @param {function} opts.getNetwork return network number
+ @class
+*/
+class TransactionStateManager extends EventEmitter {
constructor ({ initState, txHistoryLimit, getNetwork }) {
super()
@@ -28,6 +39,10 @@ module.exports = class TransactionStateManager extends EventEmitter {
this.getNetwork = getNetwork
}
+ /**
+ @param opts {object} - the object to use when overwriting defaults
+ @returns {txMeta} the default txMeta object
+ */
generateTxMeta (opts) {
return extend({
id: createId(),
@@ -38,17 +53,25 @@ module.exports = class TransactionStateManager extends EventEmitter {
}, opts)
}
+ /**
+ @returns {array} of txMetas that have been filtered for only the current network
+ */
getTxList () {
const network = this.getNetwork()
const fullTxList = this.getFullTxList()
return fullTxList.filter((txMeta) => txMeta.metamaskNetworkId === network)
}
+ /**
+ @returns {array} of all the txMetas in store
+ */
getFullTxList () {
return this.store.getState().transactions
}
- // Returns the tx list
+ /**
+ @returns {array} the tx list whos status is unapproved
+ */
getUnapprovedTxList () {
const txList = this.getTxsByMetaData('status', 'unapproved')
return txList.reduce((result, tx) => {
@@ -57,18 +80,37 @@ module.exports = class TransactionStateManager extends EventEmitter {
}, {})
}
+ /**
+ @param [address] {string} - hex prefixed address to sort the txMetas for [optional]
+ @returns {array} the tx list whos status is submitted if no address is provide
+ returns all txMetas who's status is submitted for the current network
+ */
getPendingTransactions (address) {
const opts = { status: 'submitted' }
if (address) opts.from = address
return this.getFilteredTxList(opts)
}
+ /**
+ @param [address] {string} - hex prefixed address to sort the txMetas for [optional]
+ @returns {array} the tx list whos status is confirmed if no address is provide
+ returns all txMetas who's status is confirmed for the current network
+ */
getConfirmedTransactions (address) {
const opts = { status: 'confirmed' }
if (address) opts.from = address
return this.getFilteredTxList(opts)
}
+ /**
+ Adds the txMeta to the list of transactions in the store.
+ if the list is over txHistoryLimit it will remove a transaction that
+ is in its final state
+ it will allso add the key `history` to the txMeta with the snap shot of the original
+ object
+ @param txMeta {Object}
+ @returns {object} the txMeta
+ */
addTx (txMeta) {
this.once(`${txMeta.id}:signed`, function (txId) {
this.removeAllListeners(`${txMeta.id}:rejected`)
@@ -92,7 +134,9 @@ module.exports = class TransactionStateManager extends EventEmitter {
// or rejected tx's.
// not tx's that are pending or unapproved
if (txCount > txHistoryLimit - 1) {
- let index = transactions.findIndex((metaTx) => metaTx.status === 'confirmed' || metaTx.status === 'rejected')
+ const index = transactions.findIndex((metaTx) => {
+ return getFinalStates().includes(metaTx.status)
+ })
if (index !== -1) {
transactions.splice(index, 1)
}
@@ -101,12 +145,21 @@ module.exports = class TransactionStateManager extends EventEmitter {
this._saveTxList(transactions)
return txMeta
}
- // gets tx by Id and returns it
+ /**
+ @param txId {number}
+ @returns {object} the txMeta who matches the given id if none found
+ for the network returns undefined
+ */
getTx (txId) {
const txMeta = this.getTxsByMetaData('id', txId)[0]
return txMeta
}
+ /**
+ updates the txMeta in the list and adds a history entry
+ @param txMeta {Object} - the txMeta to update
+ @param [note] {string} - a not about the update for history
+ */
updateTx (txMeta, note) {
// validate txParams
if (txMeta.txParams) {
@@ -134,16 +187,23 @@ module.exports = class TransactionStateManager extends EventEmitter {
}
- // merges txParams obj onto txData.txParams
- // use extend to ensure that all fields are filled
+ /**
+ merges txParams obj onto txMeta.txParams
+ use extend to ensure that all fields are filled
+ @param txId {number} - the id of the txMeta
+ @param txParams {object} - the updated txParams
+ */
updateTxParams (txId, txParams) {
const txMeta = this.getTx(txId)
txMeta.txParams = extend(txMeta.txParams, txParams)
this.updateTx(txMeta, `txStateManager#updateTxParams`)
}
- // validates txParams members by type
- validateTxParams(txParams) {
+ /**
+ validates txParams members by type
+ @param txParams {object} - txParams to validate
+ */
+ validateTxParams (txParams) {
Object.keys(txParams).forEach((key) => {
const value = txParams[key]
// validate types
@@ -159,17 +219,19 @@ module.exports = class TransactionStateManager extends EventEmitter {
})
}
-/*
- Takes an object of fields to search for eg:
- let thingsToLookFor = {
- to: '0x0..',
- from: '0x0..',
- status: 'signed',
- err: undefined,
- }
- and returns a list of tx with all
+/**
+ @param opts {object} - an object of fields to search for eg:<br>
+ let <code>thingsToLookFor = {<br>
+ to: '0x0..',<br>
+ from: '0x0..',<br>
+ status: 'signed',<br>
+ err: undefined,<br>
+ }<br></code>
+ @param [initialList=this.getTxList()]
+ @returns a {array} of txMeta with all
options matching
-
+ */
+ /*
****************HINT****************
| `err: undefined` is like looking |
| for a tx with no err |
@@ -190,7 +252,14 @@ module.exports = class TransactionStateManager extends EventEmitter {
})
return filteredTxList
}
+ /**
+ @param key {string} - the key to check
+ @param value - the value your looking for
+ @param [txList=this.getTxList()] {array} - the list to search. default is the txList
+ from txStateManager#getTxList
+ @returns {array} a list of txMetas who matches the search params
+ */
getTxsByMetaData (key, value, txList = this.getTxList()) {
return txList.filter((txMeta) => {
if (txMeta.txParams[key]) {
@@ -203,33 +272,51 @@ module.exports = class TransactionStateManager extends EventEmitter {
// get::set status
- // should return the status of the tx.
+ /**
+ @param txId {number} - the txMeta Id
+ @return {string} the status of the tx.
+ */
getTxStatus (txId) {
const txMeta = this.getTx(txId)
return txMeta.status
}
- // should update the status of the tx to 'rejected'.
+ /**
+ should update the status of the tx to 'rejected'.
+ @param txId {number} - the txMeta Id
+ */
setTxStatusRejected (txId) {
this._setTxStatus(txId, 'rejected')
}
- // should update the status of the tx to 'unapproved'.
+ /**
+ should update the status of the tx to 'unapproved'.
+ @param txId {number} - the txMeta Id
+ */
setTxStatusUnapproved (txId) {
this._setTxStatus(txId, 'unapproved')
}
- // should update the status of the tx to 'approved'.
+ /**
+ should update the status of the tx to 'approved'.
+ @param txId {number} - the txMeta Id
+ */
setTxStatusApproved (txId) {
this._setTxStatus(txId, 'approved')
}
- // should update the status of the tx to 'signed'.
+ /**
+ should update the status of the tx to 'signed'.
+ @param txId {number} - the txMeta Id
+ */
setTxStatusSigned (txId) {
this._setTxStatus(txId, 'signed')
}
- // should update the status of the tx to 'submitted'.
- // and add a time stamp for when it was called
+ /**
+ should update the status of the tx to 'submitted'.
+ and add a time stamp for when it was called
+ @param txId {number} - the txMeta Id
+ */
setTxStatusSubmitted (txId) {
const txMeta = this.getTx(txId)
txMeta.submittedTime = (new Date()).getTime()
@@ -237,17 +324,29 @@ module.exports = class TransactionStateManager extends EventEmitter {
this._setTxStatus(txId, 'submitted')
}
- // should update the status of the tx to 'confirmed'.
+ /**
+ should update the status of the tx to 'confirmed'.
+ @param txId {number} - the txMeta Id
+ */
setTxStatusConfirmed (txId) {
this._setTxStatus(txId, 'confirmed')
}
- // should update the status dropped
+ /**
+ should update the status of the tx to 'dropped'.
+ @param txId {number} - the txMeta Id
+ */
setTxStatusDropped (txId) {
this._setTxStatus(txId, 'dropped')
}
+ /**
+ should update the status of the tx to 'failed'.
+ and put the error on the txMeta
+ @param txId {number} - the txMeta Id
+ @param err {erroObject} - error object
+ */
setTxStatusFailed (txId, err) {
const txMeta = this.getTx(txId)
txMeta.err = {
@@ -258,6 +357,11 @@ module.exports = class TransactionStateManager extends EventEmitter {
this._setTxStatus(txId, 'failed')
}
+ /**
+ Removes transaction from the given address for the current network
+ from the txList
+ @param address {string} - hex string of the from address on the txParams to remove
+ */
wipeTransactions (address) {
// network only tx
const txs = this.getFullTxList()
@@ -273,9 +377,8 @@ module.exports = class TransactionStateManager extends EventEmitter {
// PRIVATE METHODS
//
- // Should find the tx in the tx list and
- // update it.
- // should set the status in txData
+ // STATUS METHODS
+ // statuses:
// - `'unapproved'` the user has not responded
// - `'rejected'` the user has responded no!
// - `'approved'` the user has approved the tx
@@ -283,6 +386,15 @@ module.exports = class TransactionStateManager extends EventEmitter {
// - `'submitted'` the tx is sent to a server
// - `'confirmed'` the tx has been included in a block.
// - `'failed'` the tx failed for some reason, included on tx data.
+ // - `'dropped'` the tx nonce was already used
+
+ /**
+ @param txId {number} - the txMeta Id
+ @param status {string} - the status to set on the txMeta
+ @emits tx:status-update - passes txId and status
+ @emits ${txMeta.id}:finished - if it is a finished state. Passes the txMeta
+ @emits update:badge
+ */
_setTxStatus (txId, status) {
const txMeta = this.getTx(txId)
txMeta.status = status
@@ -295,9 +407,14 @@ module.exports = class TransactionStateManager extends EventEmitter {
this.emit('update:badge')
}
- // Saves the new/updated txList.
+ /**
+ Saves the new/updated txList.
+ @param transactions {array} - the list of transactions to save
+ */
// Function is intended only for internal use
_saveTxList (transactions) {
this.store.updateState({ transactions })
}
}
+
+module.exports = TransactionStateManager
diff --git a/app/scripts/lib/config-manager.js b/app/scripts/lib/config-manager.js
index c10ff2f4e..221746467 100644
--- a/app/scripts/lib/config-manager.js
+++ b/app/scripts/lib/config-manager.js
@@ -101,6 +101,7 @@ ConfigManager.prototype.setShowSeedWords = function (should) {
this.setData(data)
}
+
ConfigManager.prototype.getShouldShowSeedWords = function () {
var data = this.getData()
return data.showSeedWords
@@ -116,27 +117,6 @@ 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/setupRaven.js b/app/scripts/lib/setupRaven.js
index 9ec9a256f..b1b67f771 100644
--- a/app/scripts/lib/setupRaven.js
+++ b/app/scripts/lib/setupRaven.js
@@ -23,22 +23,16 @@ function setupRaven(opts) {
release,
transport: function(opts) {
const report = opts.data
- // simplify certain complex error messages
- report.exception.values.forEach(item => {
- let errorMessage = item.value
- // simplify ethjs error messages
- errorMessage = extractEthjsErrorMessage(errorMessage)
- // simplify 'Transaction Failed: known transaction'
- if (errorMessage.indexOf('Transaction Failed: known transaction') === 0) {
- // cut the hash from the error message
- errorMessage = 'Transaction Failed: known transaction'
- }
- // finalize
- item.value = errorMessage
- })
-
- // modify report urls
- rewriteReportUrls(report)
+ try {
+ // handle error-like non-error exceptions
+ nonErrorException(report)
+ // simplify certain complex error messages (e.g. Ethjs)
+ simplifyErrorMessages(report)
+ // modify report urls
+ rewriteReportUrls(report)
+ } catch (err) {
+ console.warn(err)
+ }
// make request normally
client._makeRequest(opts)
},
@@ -48,15 +42,42 @@ function setupRaven(opts) {
return Raven
}
+function nonErrorException(report) {
+ // handle errors that lost their error-ness in serialization
+ if (report.message.includes('Non-Error exception captured with keys: message')) {
+ if (!(report.extra && report.extra.__serialized__)) return
+ report.message = `Non-Error Exception: ${report.extra.__serialized__.message}`
+ }
+}
+
+function simplifyErrorMessages(report) {
+ if (report.exception && report.exception.values) {
+ report.exception.values.forEach(item => {
+ let errorMessage = item.value
+ // simplify ethjs error messages
+ errorMessage = extractEthjsErrorMessage(errorMessage)
+ // simplify 'Transaction Failed: known transaction'
+ if (errorMessage.indexOf('Transaction Failed: known transaction') === 0) {
+ // cut the hash from the error message
+ errorMessage = 'Transaction Failed: known transaction'
+ }
+ // finalize
+ item.value = errorMessage
+ })
+ }
+}
+
function rewriteReportUrls(report) {
// update request url
report.request.url = toMetamaskUrl(report.request.url)
// update exception stack trace
- report.exception.values.forEach(item => {
- item.stacktrace.frames.forEach(frame => {
- frame.filename = toMetamaskUrl(frame.filename)
+ if (report.exception && report.exception.values) {
+ report.exception.values.forEach(item => {
+ item.stacktrace.frames.forEach(frame => {
+ frame.filename = toMetamaskUrl(frame.filename)
+ })
})
- })
+ }
}
function toMetamaskUrl(origUrl) {
diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index edde38819..c4a73d8ea 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -309,7 +309,6 @@ module.exports = class MetamaskController extends EventEmitter {
lostAccounts: this.configManager.getLostAccounts(),
seedWords: this.configManager.getSeedWords(),
forgottenPassword: this.configManager.getPasswordForgotten(),
- isRevealingSeedWords: Boolean(this.configManager.getIsRevealingSeedWords()),
},
}
}
@@ -351,7 +350,6 @@ 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/migrations/018.js b/app/scripts/migrations/018.js
index bea1fe3da..ffbf24a4b 100644
--- a/app/scripts/migrations/018.js
+++ b/app/scripts/migrations/018.js
@@ -7,7 +7,7 @@ This migration updates "transaction state history" to diffs style
*/
const clone = require('clone')
-const txStateHistoryHelper = require('../lib/tx-state-history-helper')
+const txStateHistoryHelper = require('../controllers/transactions/lib/tx-state-history-helper')
module.exports = {