From e9712a13ecd96db0bcc9d22998fc4df2ecdeeebc Mon Sep 17 00:00:00 2001 From: frankiebee Date: Fri, 11 Aug 2017 14:19:35 -0700 Subject: Create tests for TxStateManager --- app/scripts/controllers/transactions.js | 209 +++-------------------------- app/scripts/lib/tx-state-manager.js | 201 ++++++++++++++++++++++++++++ test/unit/tx-controller-test.js | 222 ++++--------------------------- test/unit/tx-state-manager-test.js | 227 ++++++++++++++++++++++++++++++++ 4 files changed, 471 insertions(+), 388 deletions(-) create mode 100644 app/scripts/lib/tx-state-manager.js create mode 100644 test/unit/tx-state-manager-test.js diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 58c468e22..48a882a71 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -4,6 +4,7 @@ const clone = require('clone') const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') const EthQuery = require('ethjs-query') +const TransactionStateManger = require('../lib/tx-state-manager') const TxProviderUtil = require('../lib/tx-utils') const PendingTransactionTracker = require('../lib/pending-tx-tracker') const createId = require('../lib/random-id') @@ -12,18 +13,23 @@ const NonceTracker = require('../lib/nonce-tracker') module.exports = class TransactionController extends EventEmitter { constructor (opts) { super() - this.store = new ObservableStore(extend({ - transactions: [], - }, opts.initState)) - this.memStore = new ObservableStore({}) this.networkStore = opts.networkStore || new ObservableStore({}) this.preferencesStore = opts.preferencesStore || new ObservableStore({}) - this.txHistoryLimit = opts.txHistoryLimit this.provider = opts.provider this.blockTracker = opts.blockTracker this.signEthTx = opts.signTransaction this.ethStore = opts.ethStore + this.memStore = new ObservableStore({}) + this.query = new EthQuery(this.provider) + this.txProviderUtil = new TxProviderUtil(this.provider) + + this.txStateManager = new TransactionStateManger(extend({ + transactions: [], + txHistoryLimit: opts.txHistoryLimit, + getNetwork: this.getNetwork.bind(this), + }, opts.initState)) + this.nonceTracker = new NonceTracker({ provider: this.provider, getPendingTransactions: (address) => { @@ -34,8 +40,6 @@ module.exports = class TransactionController extends EventEmitter { }) }, }) - this.query = new EthQuery(this.provider) - this.txProviderUtil = new TxProviderUtil(this.provider) this.pendingTxTracker = new PendingTransactionTracker({ provider: this.provider, @@ -69,7 +73,7 @@ module.exports = class TransactionController extends EventEmitter { this.blockTracker.on('sync', this.pendingTxTracker.queryPendingTxs.bind(this.pendingTxTracker)) // memstore is computed from a few different stores this._updateMemstore() - this.store.subscribe(() => this._updateMemstore()) + this.txStateManager.subscribe(() => this._updateMemstore()) this.networkStore.subscribe(() => this._updateMemstore()) this.preferencesStore.subscribe(() => this._updateMemstore()) } @@ -86,84 +90,27 @@ module.exports = class TransactionController extends EventEmitter { return this.preferencesStore.getState().selectedAddress } - // Returns the number of txs for the current network. - getTxCount () { - return this.getTxList().length - } - - // Returns the full tx list across all networks - getFullTxList () { - return this.store.getState().transactions - } - getUnapprovedTxCount () { return Object.keys(this.getUnapprovedTxList()).length } getPendingTxCount () { - return this.getTxsByMetaData('status', 'signed').length + return this.txStateManager.getTxsByMetaData('status', 'signed').length } // Returns the tx list - getTxList () { - const network = this.getNetwork() - const fullTxList = this.getFullTxList() - return this.getTxsByMetaData('metamaskNetworkId', network, fullTxList) - } - // gets tx by Id and returns it - getTx (txId) { - const txList = this.getTxList() - const txMeta = txList.find(txData => txData.id === txId) - return txMeta - } getUnapprovedTxList () { - const txList = this.getTxList() - return txList.filter((txMeta) => txMeta.status === 'unapproved') - .reduce((result, tx) => { + const txList = this.txStateManager.getTxsByMetaData('status', 'unapproved') + return txList.reduce((result, tx) => { result[tx.id] = tx return result }, {}) } - updateTx (txMeta) { - // create txMeta snapshot for history - const txMetaForHistory = clone(txMeta) - // dont include previous history in this snapshot - delete txMetaForHistory.history - // add snapshot to tx history - if (!txMeta.history) txMeta.history = [] - txMeta.history.push(txMetaForHistory) - - const txId = txMeta.id - const txList = this.getFullTxList() - const index = txList.findIndex(txData => txData.id === txId) - if (!txMeta.history) txMeta.history = [] - txMeta.history.push(txMetaForHistory) - - txList[index] = txMeta - this._saveTxList(txList) - this.emit('update') - } - // Adds a tx to the txlist addTx (txMeta) { - const txCount = this.getTxCount() - const network = this.getNetwork() - const fullTxList = this.getFullTxList() - const txHistoryLimit = this.txHistoryLimit - - // checks if the length of the tx history is - // longer then desired persistence limit - // and then if it is removes only confirmed - // or rejected tx's. - // not tx's that are pending or unapproved - if (txCount > txHistoryLimit - 1) { - const index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId)) - fullTxList.splice(index, 1) - } - fullTxList.push(txMeta) - this._saveTxList(fullTxList) + this.txStateManager.addTx(txMeta) this.emit('update') this.once(`${txMeta.id}:signed`, function (txId) { @@ -211,7 +158,7 @@ module.exports = class TransactionController extends EventEmitter { // add default tx params await this.addTxDefaults(txMeta) // save txMeta - this.addTx(txMeta) + this.txStateManager.addTx(txMeta) return txMeta } @@ -306,133 +253,11 @@ module.exports = class TransactionController extends EventEmitter { this.updateTx(txMeta) } - /* - 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 - options matching - - ****************HINT**************** - | `err: undefined` is like looking | - | for a tx with no err | - | so you can also search txs that | - | dont have something as well by | - | setting the value as undefined | - ************************************ - - this is for things like filtering a the tx list - for only tx's from 1 account - or for filltering for all txs from one account - and that have been 'confirmed' - */ - getFilteredTxList (opts) { - let filteredTxList - Object.keys(opts).forEach((key) => { - filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList) - }) - return filteredTxList - } - - getTxsByMetaData (key, value, txList = this.getTxList()) { - return txList.filter((txMeta) => { - if (txMeta.txParams[key]) { - return txMeta.txParams[key] === value - } else { - return txMeta[key] === value - } - }) - } - - // STATUS METHODS - // get::set status - - // should return the status of the tx. - getTxStatus (txId) { - const txMeta = this.getTx(txId) - return txMeta.status - } - - // should update the status of the tx to 'rejected'. - setTxStatusRejected (txId) { - this._setTxStatus(txId, 'rejected') - } - - // should update the status of the tx to 'approved'. - setTxStatusApproved (txId) { - this._setTxStatus(txId, 'approved') - } - - // should update the status of the tx to 'signed'. - setTxStatusSigned (txId) { - this._setTxStatus(txId, 'signed') - } - - // should update the status of the tx to 'submitted'. - setTxStatusSubmitted (txId) { - this._setTxStatus(txId, 'submitted') - } - - // should update the status of the tx to 'confirmed'. - setTxStatusConfirmed (txId) { - this._setTxStatus(txId, 'confirmed') - } - - setTxStatusFailed (txId, err) { - const txMeta = this.getTx(txId) - txMeta.err = { - message: err.toString(), - stack: err.stack, - } - this.updateTx(txMeta) - this._setTxStatus(txId, 'failed') - } - - // merges txParams obj onto txData.txParams - // use extend to ensure that all fields are filled - updateTxParams (txId, txParams) { - const txMeta = this.getTx(txId) - txMeta.txParams = extend(txMeta.txParams, txParams) - this.updateTx(txMeta) - } - /* _____________________________________ | | | PRIVATE METHODS | |______________________________________*/ - - // Should find the tx in the tx list and - // update it. - // should set the status in txData - // - `'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. - _setTxStatus (txId, status) { - const txMeta = this.getTx(txId) - txMeta.status = status - this.emit(`${txMeta.id}:${status}`, txId) - if (status === 'submitted' || status === 'rejected') { - this.emit(`${txMeta.id}:finished`, txMeta) - } - this.updateTx(txMeta) - this.emit('updateBadge') - } - - // Saves the new/updated txList. - // Function is intended only for internal use - _saveTxList (transactions) { - this.store.updateState({ transactions }) - } - _updateMemstore () { const unapprovedTxs = this.getUnapprovedTxList() const selectedAddressTxList = this.getFilteredTxList({ diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js new file mode 100644 index 000000000..91271cc4a --- /dev/null +++ b/app/scripts/lib/tx-state-manager.js @@ -0,0 +1,201 @@ +const clone = require('clone') +const extend = require('xtend') +const ObservableStore = require('obs-store') + +module.exports = class TransactionStateManger extends ObservableStore { + constructor ({initState, txHistoryLimit, getNetwork}) { + super(initState) + this.txHistoryLimit = txHistoryLimit + this.getNetwork = getNetwork + } + // Returns the number of txs for the current network. + getTxCount () { + return this.getTxList().length + } + + getTxList () { + const network = this.getNetwork() + const fullTxList = this.getFullTxList() + return fullTxList.filter((txMeta) => txMeta.metamaskNetworkId === network) + } + + getFullTxList () { + return this.getState().transactions + } + + addTx (txMeta) { + const transactions = this.getFullTxList() + const txCount = this.getTxCount() + const txHistoryLimit = this.txHistoryLimit + + // checks if the length of the tx history is + // longer then desired persistence limit + // and then if it is removes only confirmed + // or rejected tx's. + // not tx's that are pending or unapproved + if (txCount > txHistoryLimit - 1) { + const index = transactions.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected'))) + transactions.splice(index, 1) + } + transactions.push(txMeta) + transactions.push(txMeta) + this._saveTxList(transactions) + } + // gets tx by Id and returns it + getTx (txId) { + const txMeta = this.getTxsByMetaData('id', txId)[0] + return txMeta + } + + updateTx (txMeta) { + // create txMeta snapshot for history + const txMetaForHistory = clone(txMeta) + // dont include previous history in this snapshot + delete txMetaForHistory.history + // add snapshot to tx history + if (!txMeta.history) txMeta.history = [] + txMeta.history.push(txMetaForHistory) + + const txId = txMeta.id + const txList = this.getFullTxList() + const index = txList.findIndex(txData => txData.id === txId) + if (!txMeta.history) txMeta.history = [] + txMeta.history.push(txMetaForHistory) + + txList[index] = txMeta + this._saveTxList(txList) + } + + + // merges txParams obj onto txData.txParams + // use extend to ensure that all fields are filled + updateTxParams (txId, txParams) { + const txMeta = this.getTx(txId) + txMeta.txParams = extend(txMeta.txParams, txParams) + this.updateTx(txMeta) + } + +/* + 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 + options matching + + ****************HINT**************** + | `err: undefined` is like looking | + | for a tx with no err | + | so you can also search txs that | + | dont have something as well by | + | setting the value as undefined | + ************************************ + + this is for things like filtering a the tx list + for only tx's from 1 account + or for filltering for all txs from one account + and that have been 'confirmed' + */ + getFilteredTxList (opts, initialList) { + let filteredTxList = initialList + Object.keys(opts).forEach((key) => { + filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList) + }) + return filteredTxList + } + + getTxsByMetaData (key, value, txList = this.getTxList()) { + return txList.filter((txMeta) => { + if (txMeta.txParams[key]) { + return txMeta.txParams[key] === value + } else { + return txMeta[key] === value + } + }) + } + + // 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. + + // get::set status + + // should return the status of the tx. + getTxStatus (txId) { + const txMeta = this.getTx(txId) + return txMeta.status + } + + // should update the status of the tx to 'rejected'. + setTxStatusRejected (txId) { + this._setTxStatus(txId, 'rejected') + } + + // should update the status of the tx to 'approved'. + setTxStatusApproved (txId) { + this._setTxStatus(txId, 'approved') + } + + // should update the status of the tx to 'signed'. + setTxStatusSigned (txId) { + this._setTxStatus(txId, 'signed') + } + + // should update the status of the tx to 'submitted'. + setTxStatusSubmitted (txId) { + this._setTxStatus(txId, 'submitted') + } + + // should update the status of the tx to 'confirmed'. + setTxStatusConfirmed (txId) { + this._setTxStatus(txId, 'confirmed') + } + + setTxStatusFailed (txId, reason) { + const txMeta = this.getTx(txId) + txMeta.err = reason + this.updateTx(txMeta) + this._setTxStatus(txId, 'failed') + } + +/* _____________________________________ +| | +| PRIVATE METHODS | +|______________________________________*/ + + // Should find the tx in the tx list and + // update it. + // should set the status in txData + // - `'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. + _setTxStatus (txId, status) { + const txMeta = this.getTx(txId) + txMeta.status = status + this.emit(`${txMeta.id}:${status}`, txId) + if (status === 'submitted' || status === 'rejected') { + this.emit(`${txMeta.id}:finished`, txMeta) + } + this.updateTx(txMeta) + this.emit('updateBadge') + } + + // Saves the new/updated txList. + // Function is intended only for internal use + _saveTxList (transactions) { + this.updateState({ transactions }) + } +} \ No newline at end of file diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index 57d7deccd..40be490c0 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -47,11 +47,12 @@ describe('Transaction Controller', function () { metamaskNetworkId: currentNetworkId, txParams, } - txController._saveTxList([txMeta]) + txController.txStateManager._saveTxList([txMeta]) stub = sinon.stub(txController, 'addUnapprovedTransaction').returns(Promise.resolve(txMeta)) }) afterEach(function () { + txController.txStateManager._saveTxList([]) stub.restore() }) @@ -69,7 +70,7 @@ describe('Transaction Controller', function () { txController.once('newUnaprovedTx', (txMetaFromEmit) => { setTimeout(() => { txController.setTxHash(txMetaFromEmit.id, '0x0') - txController.setTxStatusSubmitted(txMetaFromEmit.id) + txController.txStateManager.setTxStatusSubmitted(txMetaFromEmit.id) }, 10) }) @@ -84,7 +85,7 @@ describe('Transaction Controller', function () { it('should reject when finished and status is rejected', function (done) { txController.once('newUnaprovedTx', (txMetaFromEmit) => { setTimeout(() => { - txController.setTxStatusRejected(txMetaFromEmit.id) + txController.txStateManager.setTxStatusRejected(txMetaFromEmit.id) }, 10) }) @@ -107,7 +108,7 @@ describe('Transaction Controller', function () { assert(('txParams' in txMeta), 'should have a txParams') assert(('history' in txMeta), 'should have a history') - const memTxMeta = txController.getTx(txMeta.id) + const memTxMeta = txController.txStateManager.getTx(txMeta.id) assert.deepEqual(txMeta, memTxMeta, `txMeta should be stored in txController after adding it\n expected: ${txMeta} \n got: ${memTxMeta}`) addTxDefaultsStub.restore() done() @@ -160,202 +161,31 @@ describe('Transaction Controller', function () { }) }) - describe('#getTxList', function () { - it('when new should return empty array', function () { - var result = txController.getTxList() - assert.ok(Array.isArray(result)) - assert.equal(result.length, 0) - }) - }) - describe('#addTx', function () { - it('adds a tx returned in getTxList', function () { - var tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx, noop) - var result = txController.getTxList() - assert.ok(Array.isArray(result)) - assert.equal(result.length, 1) - assert.equal(result[0].id, 1) - }) - - it('does not override txs from other networks', function () { - var tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } - var tx2 = { id: 2, status: 'confirmed', metamaskNetworkId: otherNetworkId, txParams: {} } - txController.addTx(tx, noop) - txController.addTx(tx2, noop) - var result = txController.getFullTxList() - var result2 = txController.getTxList() - assert.equal(result.length, 2, 'txs were deleted') - assert.equal(result2.length, 1, 'incorrect number of txs on network.') - }) - - it('cuts off early txs beyond a limit', function () { - const limit = txController.txHistoryLimit - for (let i = 0; i < limit + 1; i++) { - const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx, noop) - } - var result = txController.getTxList() - assert.equal(result.length, limit, `limit of ${limit} txs enforced`) - assert.equal(result[0].id, 1, 'early txs truncted') - }) - - it('cuts off early txs beyond a limit whether or not it is confirmed or rejected', function () { - const limit = txController.txHistoryLimit - for (let i = 0; i < limit + 1; i++) { - const tx = { id: i, time: new Date(), status: 'rejected', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx, noop) - } - var result = txController.getTxList() - assert.equal(result.length, limit, `limit of ${limit} txs enforced`) - assert.equal(result[0].id, 1, 'early txs truncted') - }) - - it('cuts off early txs beyond a limit but does not cut unapproved txs', function () { - var unconfirmedTx = { id: 0, time: new Date(), status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(unconfirmedTx, noop) - const limit = txController.txHistoryLimit - for (let i = 1; i < limit + 1; i++) { - const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx, noop) - } - var result = txController.getTxList() - assert.equal(result.length, limit, `limit of ${limit} txs enforced`) - assert.equal(result[0].id, 0, 'first tx should still be there') - assert.equal(result[0].status, 'unapproved', 'first tx should be unapproved') - assert.equal(result[1].id, 2, 'early txs truncted') - }) - }) - - describe('#setTxStatusSigned', function () { - it('sets the tx status to signed', function () { - var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx, noop) - txController.setTxStatusSigned(1) - var result = txController.getTxList() - assert.ok(Array.isArray(result)) - assert.equal(result.length, 1) - assert.equal(result[0].status, 'signed') - }) - - it('should emit a signed event to signal the exciton of callback', (done) => { - this.timeout(10000) - var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } - const noop = function () { - assert(true, 'event listener has been triggered and noop executed') - done() - } - txController.addTx(tx) - txController.on('1:signed', noop) - txController.setTxStatusSigned(1) - }) - }) - - describe('#setTxStatusRejected', function () { - it('sets the tx status to rejected', function () { - var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx) - txController.setTxStatusRejected(1) - var result = txController.getTxList() - assert.ok(Array.isArray(result)) - assert.equal(result.length, 1) - assert.equal(result[0].status, 'rejected') - }) - - it('should emit a rejected event to signal the exciton of callback', (done) => { - this.timeout(10000) - var tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } - txController.addTx(tx) - const noop = function (err, txId) { - assert(true, 'event listener has been triggered and noop executed') - done() - } - txController.on('1:rejected', noop) - txController.setTxStatusRejected(1) - }) - }) - - describe('#updateTx', function () { - it('replaces the tx with the same id', function () { - txController.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - txController.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - txController.updateTx({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: currentNetworkId, txParams: {} }) - var result = txController.getTx('1') - assert.equal(result.hash, 'foo') - }) - - it('updates gas price', function () { - const originalGasPrice = '0x01' - const desiredGasPrice = '0x02' - - const txMeta = { - id: '1', + it('should emit updates', function (done) { + txMeta = { status: 'unapproved', + id: 1, metamaskNetworkId: currentNetworkId, - txParams: { - gasPrice: originalGasPrice, - }, + txParams: {} } - const updatedMeta = clone(txMeta) - + const eventNames = ['update', 'updateBadge', '1:unapproved'] + const listeners = [] + eventNames.forEach((eventName) => { + listeners.push(new Promise((resolve) => { + txController.once(eventName, (arg) => { + resolve(arg) + }) + })) + }) + Promise.all(listeners) + .then((returnValues) => { + assert.deepEqual(returnValues.pop(), txMeta, 'last event 1:unapproved should return txMeta') + done() + }) + .catch(done) txController.addTx(txMeta) - updatedMeta.txParams.gasPrice = desiredGasPrice - txController.updateTx(updatedMeta) - var result = txController.getTx('1') - assert.equal(result.txParams.gasPrice, desiredGasPrice, 'gas price updated') - }) - }) - - describe('#getUnapprovedTxList', function () { - it('returns unapproved txs in a hash', function () { - txController.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - txController.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - const result = txController.getUnapprovedTxList() - assert.equal(typeof result, 'object') - assert.equal(result['1'].status, 'unapproved') - assert.equal(result['2'], undefined) - }) - }) - - describe('#getTx', function () { - it('returns a tx with the requested id', function () { - txController.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - txController.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - assert.equal(txController.getTx('1').status, 'unapproved') - assert.equal(txController.getTx('2').status, 'confirmed') - }) - }) - - describe('#getFilteredTxList', function () { - it('returns a tx with the requested data', function () { - const txMetas = [ - { id: 0, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, - { id: 1, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, - { id: 2, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, - { id: 3, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, - { id: 4, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, - { id: 5, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, - { id: 6, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, - { id: 7, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, - { id: 8, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, - { id: 9, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, - ] - txMetas.forEach((txMeta) => txController.addTx(txMeta, noop)) - let filterParams - - filterParams = { status: 'unapproved', from: '0xaa' } - assert.equal(txController.getFilteredTxList(filterParams).length, 3, `getFilteredTxList - ${JSON.stringify(filterParams)}`) - filterParams = { status: 'unapproved', to: '0xaa' } - assert.equal(txController.getFilteredTxList(filterParams).length, 2, `getFilteredTxList - ${JSON.stringify(filterParams)}`) - filterParams = { status: 'confirmed', from: '0xbb' } - assert.equal(txController.getFilteredTxList(filterParams).length, 3, `getFilteredTxList - ${JSON.stringify(filterParams)}`) - filterParams = { status: 'confirmed' } - assert.equal(txController.getFilteredTxList(filterParams).length, 5, `getFilteredTxList - ${JSON.stringify(filterParams)}`) - filterParams = { from: '0xaa' } - assert.equal(txController.getFilteredTxList(filterParams).length, 5, `getFilteredTxList - ${JSON.stringify(filterParams)}`) - filterParams = { to: '0xaa' } - assert.equal(txController.getFilteredTxList(filterParams).length, 5, `getFilteredTxList - ${JSON.stringify(filterParams)}`) }) }) @@ -389,11 +219,11 @@ describe('Transaction Controller', function () { const pubStub = sinon.stub(txController, 'publishTransaction').callsFake(() => { txController.setTxHash('1', originalValue) - txController.setTxStatusSubmitted('1') + txController.txStateManager.setTxStatusSubmitted('1') }) txController.approveTransaction(txMeta.id).then(() => { - const result = txController.getTx(txMeta.id) + const result = txController.txStateManager.getTx(txMeta.id) const params = result.txParams assert.equal(params.gas, originalValue, 'gas unmodified') diff --git a/test/unit/tx-state-manager-test.js b/test/unit/tx-state-manager-test.js new file mode 100644 index 000000000..0b35465d6 --- /dev/null +++ b/test/unit/tx-state-manager-test.js @@ -0,0 +1,227 @@ +const assert = require('assert') +const clone = require('clone') +const ObservableStore = require('obs-store') +const TxStateManager = require('../../app/scripts/lib/tx-state-manager') +const noop = () => true + +describe('TransactionStateManger', function () { + let txStateManager + const currentNetworkId = 42 + const otherNetworkId = 2 + + beforeEach(function () { + txStateManager = new TxStateManager({ + initState: { + transactions: [], + }, + txHistoryLimit: 10, + getNetwork: () => currentNetworkId + }) + }) + + describe('#setTxStatusSigned', function () { + it('sets the tx status to signed', function () { + let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx, noop) + txStateManager.setTxStatusSigned(1) + let result = txStateManager.getTxList() + assert.ok(Array.isArray(result)) + assert.equal(result.length, 1) + assert.equal(result[0].status, 'signed') + }) + + it('should emit a signed event to signal the exciton of callback', (done) => { + let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } + const noop = function () { + assert(true, 'event listener has been triggered and noop executed') + done() + } + txStateManager.addTx(tx) + txStateManager.on('1:signed', noop) + txStateManager.setTxStatusSigned(1) + + }) + }) + + describe('#setTxStatusRejected', function () { + it('sets the tx status to rejected', function () { + let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx) + txStateManager.setTxStatusRejected(1) + let result = txStateManager.getTxList() + assert.ok(Array.isArray(result)) + assert.equal(result.length, 1) + assert.equal(result[0].status, 'rejected') + }) + + it('should emit a rejected event to signal the exciton of callback', (done) => { + let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx) + const noop = function (err, txId) { + assert(true, 'event listener has been triggered and noop executed') + done() + } + txStateManager.on('1:rejected', noop) + txStateManager.setTxStatusRejected(1) + }) + }) + + describe('#getFullTxList', function () { + it('when new should return empty array', function () { + let result = txStateManager.getTxList() + assert.ok(Array.isArray(result)) + assert.equal(result.length, 0) + }) + }) + + describe('#getTxList', function () { + it('when new should return empty array', function () { + let result = txStateManager.getTxList() + assert.ok(Array.isArray(result)) + assert.equal(result.length, 0) + }) + }) + + describe('#addTx', function () { + it('adds a tx returned in getTxList', function () { + let tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx, noop) + let result = txStateManager.getTxList() + assert.ok(Array.isArray(result)) + assert.equal(result.length, 1) + assert.equal(result[0].id, 1) + }) + + it('does not override txs from other networks', function () { + let tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } + let tx2 = { id: 2, status: 'confirmed', metamaskNetworkId: otherNetworkId, txParams: {} } + txStateManager.addTx(tx, noop) + txStateManager.addTx(tx2, noop) + let result = txStateManager.getFullTxList() + let result2 = txStateManager.getTxList() + assert.equal(result.length, 2, 'txs were deleted') + assert.equal(result2.length, 1, 'incorrect number of txs on network.') + }) + + it('cuts off early txs beyond a limit', function () { + const limit = txStateManager.txHistoryLimit + for (let i = 0; i < limit + 1; i++) { + const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx, noop) + } + let result = txStateManager.getTxList() + assert.equal(result.length, limit, `limit of ${limit} txs enforced`) + assert.equal(result[0].id, 1, 'early txs truncted') + }) + + it('cuts off early txs beyond a limit whether or not it is confirmed or rejected', function () { + const limit = txStateManager.txHistoryLimit + for (let i = 0; i < limit + 1; i++) { + const tx = { id: i, time: new Date(), status: 'rejected', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx, noop) + } + let result = txStateManager.getTxList() + assert.equal(result.length, limit, `limit of ${limit} txs enforced`) + assert.equal(result[0].id, 1, 'early txs truncted') + }) + + it('cuts off early txs beyond a limit but does not cut unapproved txs', function () { + let unconfirmedTx = { id: 0, time: new Date(), status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(unconfirmedTx, noop) + const limit = txStateManager.txHistoryLimit + for (let i = 1; i < limit + 1; i++) { + const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} } + txStateManager.addTx(tx, noop) + } + let result = txStateManager.getTxList() + assert.equal(result.length, limit, `limit of ${limit} txs enforced`) + assert.equal(result[0].id, 0, 'first tx should still be there') + assert.equal(result[0].status, 'unapproved', 'first tx should be unapproved') + assert.equal(result[1].id, 2, 'early txs truncted') + }) + }) + + describe('#updateTx', function () { + it('replaces the tx with the same id', function () { + txStateManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) + txStateManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) + txStateManager.updateTx({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: currentNetworkId, txParams: {} }) + let result = txStateManager.getTx('1') + assert.equal(result.hash, 'foo') + }) + + it('updates gas price', function () { + const originalGasPrice = '0x01' + const desiredGasPrice = '0x02' + + const txMeta = { + id: '1', + status: 'unapproved', + metamaskNetworkId: currentNetworkId, + txParams: { + gasPrice: originalGasPrice, + }, + } + + const updatedMeta = clone(txMeta) + + txStateManager.addTx(txMeta) + updatedMeta.txParams.gasPrice = desiredGasPrice + txStateManager.updateTx(updatedMeta) + let result = txStateManager.getTx('1') + assert.equal(result.txParams.gasPrice, desiredGasPrice, 'gas price updated') + }) + }) + + describe('#getUnapprovedTxList', function () { + it('returns unapproved txs in a hash', function () { + txStateManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) + txStateManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) + const result = txStateManager.getUnapprovedTxList() + assert.equal(typeof result, 'object') + assert.equal(result['1'].status, 'unapproved') + assert.equal(result['2'], undefined) + }) + }) + + describe('#getTx', function () { + it('returns a tx with the requested id', function () { + txStateManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) + txStateManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) + assert.equal(txStateManager.getTx('1').status, 'unapproved') + assert.equal(txStateManager.getTx('2').status, 'confirmed') + }) + }) + + describe('#getFilteredTxList', function () { + it('returns a tx with the requested data', function () { + const txMetas = [ + { id: 0, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, + { id: 1, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, + { id: 2, status: 'unapproved', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, + { id: 3, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, + { id: 4, status: 'unapproved', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, + { id: 5, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, + { id: 6, status: 'confirmed', txParams: { from: '0xaa', to: '0xbb' }, metamaskNetworkId: currentNetworkId }, + { id: 7, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, + { id: 8, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, + { id: 9, status: 'confirmed', txParams: { from: '0xbb', to: '0xaa' }, metamaskNetworkId: currentNetworkId }, + ] + txMetas.forEach((txMeta) => txStateManager.addTx(txMeta, noop)) + let filterParams + + filterParams = { status: 'unapproved', from: '0xaa' } + assert.equal(txStateManager.getFilteredTxList(filterParams).length, 3, `getFilteredTxList - ${JSON.stringify(filterParams)}`) + filterParams = { status: 'unapproved', to: '0xaa' } + assert.equal(txStateManager.getFilteredTxList(filterParams).length, 2, `getFilteredTxList - ${JSON.stringify(filterParams)}`) + filterParams = { status: 'confirmed', from: '0xbb' } + assert.equal(txStateManager.getFilteredTxList(filterParams).length, 3, `getFilteredTxList - ${JSON.stringify(filterParams)}`) + filterParams = { status: 'confirmed' } + assert.equal(txStateManager.getFilteredTxList(filterParams).length, 5, `getFilteredTxList - ${JSON.stringify(filterParams)}`) + filterParams = { from: '0xaa' } + assert.equal(txStateManager.getFilteredTxList(filterParams).length, 5, `getFilteredTxList - ${JSON.stringify(filterParams)}`) + filterParams = { to: '0xaa' } + assert.equal(txStateManager.getFilteredTxList(filterParams).length, 5, `getFilteredTxList - ${JSON.stringify(filterParams)}`) + }) + }) +}) \ No newline at end of file -- cgit v1.2.3 From 7ea83b6bae34dcf652d85474fe1d82893d592d55 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Fri, 18 Aug 2017 12:23:35 -0700 Subject: Create TxStateManager --- app/scripts/controllers/transactions.js | 73 +++++++++++++-------------------- app/scripts/lib/tx-state-manager.js | 19 ++++++++- app/scripts/metamask-controller.js | 2 +- 3 files changed, 47 insertions(+), 47 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 48a882a71..b044948d7 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -1,6 +1,5 @@ const EventEmitter = require('events') const extend = require('xtend') -const clone = require('clone') const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') const EthQuery = require('ethjs-query') @@ -24,16 +23,18 @@ module.exports = class TransactionController extends EventEmitter { this.query = new EthQuery(this.provider) this.txProviderUtil = new TxProviderUtil(this.provider) - this.txStateManager = new TransactionStateManger(extend({ - transactions: [], + this.txStateManager = new TransactionStateManger({ + initState: extend({ + transactions: [], + }, opts.initState), txHistoryLimit: opts.txHistoryLimit, getNetwork: this.getNetwork.bind(this), - }, opts.initState)) + }) this.nonceTracker = new NonceTracker({ provider: this.provider, getPendingTransactions: (address) => { - return this.getFilteredTxList({ + return this.txStateManager.getFilteredTxList({ from: address, status: 'submitted', err: undefined, @@ -52,16 +53,16 @@ module.exports = class TransactionController extends EventEmitter { publishTransaction: this.txProviderUtil.publishTransaction.bind(this.txProviderUtil), getPendingTransactions: () => { const network = this.getNetwork() - return this.getFilteredTxList({ + return this.txStateManager.getFilteredTxList({ status: 'submitted', metamaskNetworkId: network, }) }, }) - this.pendingTxTracker.on('txWarning', this.updateTx.bind(this)) - this.pendingTxTracker.on('txFailed', this.setTxStatusFailed.bind(this)) - this.pendingTxTracker.on('txConfirmed', this.setTxStatusConfirmed.bind(this)) + this.pendingTxTracker.on('txWarning', this.txStateManager.updateTx.bind(this.txStateManager)) + this.pendingTxTracker.on('txFailed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) + this.pendingTxTracker.on('txConfirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager)) this.blockTracker.on('rawBlock', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker)) // this is a little messy but until ethstore has been either @@ -91,35 +92,17 @@ module.exports = class TransactionController extends EventEmitter { } getUnapprovedTxCount () { - return Object.keys(this.getUnapprovedTxList()).length + return Object.keys(this.txStateManager.getUnapprovedTxList()).length } getPendingTxCount () { return this.txStateManager.getTxsByMetaData('status', 'signed').length } - // Returns the tx list - - getUnapprovedTxList () { - const txList = this.txStateManager.getTxsByMetaData('status', 'unapproved') - return txList.reduce((result, tx) => { - result[tx.id] = tx - return result - }, {}) - } - // Adds a tx to the txlist addTx (txMeta) { this.txStateManager.addTx(txMeta) this.emit('update') - - this.once(`${txMeta.id}:signed`, function (txId) { - this.removeAllListeners(`${txMeta.id}:rejected`) - }) - this.once(`${txMeta.id}:rejected`, function (txId) { - this.removeAllListeners(`${txMeta.id}:signed`) - }) - this.emit('updateBadge') this.emit(`${txMeta.id}:unapproved`, txMeta) } @@ -130,7 +113,7 @@ module.exports = class TransactionController extends EventEmitter { this.emit('newUnaprovedTx', txMeta) // listen for tx completion (success, fail) return new Promise((resolve, reject) => { - this.once(`${txMeta.id}:finished`, (completedTx) => { + this.txStateManager.once(`${txMeta.id}:finished`, (completedTx) => { switch (completedTx.status) { case 'submitted': return resolve(completedTx.hash) @@ -158,7 +141,7 @@ module.exports = class TransactionController extends EventEmitter { // add default tx params await this.addTxDefaults(txMeta) // save txMeta - this.txStateManager.addTx(txMeta) + this.addTx(txMeta) return txMeta } @@ -175,7 +158,7 @@ module.exports = class TransactionController extends EventEmitter { } async updateAndApproveTransaction (txMeta) { - this.updateTx(txMeta) + this.txStateManager.updateTx(txMeta) await this.approveTransaction(txMeta.id) } @@ -183,9 +166,9 @@ module.exports = class TransactionController extends EventEmitter { let nonceLock try { // approve - this.setTxStatusApproved(txId) + this.txStateManager.setTxStatusApproved(txId) // get next nonce - const txMeta = this.getTx(txId) + const txMeta = this.txStateManager.getTx(txId) const fromAddress = txMeta.txParams.from // wait for a nonce nonceLock = await this.nonceTracker.getNonceLock(fromAddress) @@ -193,14 +176,14 @@ module.exports = class TransactionController extends EventEmitter { txMeta.txParams.nonce = nonceLock.nextNonce // add nonce debugging information to txMeta txMeta.nonceDetails = nonceLock.nonceDetails - this.updateTx(txMeta) + this.txStateManager.updateTx(txMeta) // sign transaction const rawTx = await this.signTransaction(txId) await this.publishTransaction(txId, rawTx) // must set transaction to submitted/failed before releasing lock nonceLock.releaseLock() } catch (err) { - this.setTxStatusFailed(txId, err) + this.txStateManager.setTxStatusFailed(txId, err) // must set transaction to submitted/failed before releasing lock if (nonceLock) nonceLock.releaseLock() // continue with error chain @@ -209,29 +192,29 @@ module.exports = class TransactionController extends EventEmitter { } async signTransaction (txId) { - const txMeta = this.getTx(txId) + const txMeta = this.txStateManager.getTx(txId) const txParams = txMeta.txParams const fromAddress = txParams.from // add network/chain id txParams.chainId = this.getChainId() const ethTx = this.txProviderUtil.buildEthTxFromParams(txParams) await this.signEthTx(ethTx, fromAddress) - this.setTxStatusSigned(txMeta.id) + this.txStateManager.setTxStatusSigned(txMeta.id) const rawTx = ethUtil.bufferToHex(ethTx.serialize()) return rawTx } async publishTransaction (txId, rawTx) { - const txMeta = this.getTx(txId) + const txMeta = this.txStateManager.getTx(txId) txMeta.rawTx = rawTx - this.updateTx(txMeta) + this.txStateManager.updateTx(txMeta) const txHash = await this.txProviderUtil.publishTransaction(rawTx) this.setTxHash(txId, txHash) - this.setTxStatusSubmitted(txId) + this.txStateManager.setTxStatusSubmitted(txId) } async cancelTransaction (txId) { - this.setTxStatusRejected(txId) + this.txStateManager.setTxStatusRejected(txId) } @@ -248,9 +231,9 @@ module.exports = class TransactionController extends EventEmitter { // receives a txHash records the tx as signed setTxHash (txId, txHash) { // Add the tx hash to the persisted meta-tx object - const txMeta = this.getTx(txId) + const txMeta = this.txStateManager.getTx(txId) txMeta.hash = txHash - this.updateTx(txMeta) + this.txStateManager.updateTx(txMeta) } /* _____________________________________ @@ -259,8 +242,8 @@ module.exports = class TransactionController extends EventEmitter { |______________________________________*/ _updateMemstore () { - const unapprovedTxs = this.getUnapprovedTxList() - const selectedAddressTxList = this.getFilteredTxList({ + const unapprovedTxs = this.txStateManager.getUnapprovedTxList() + const selectedAddressTxList = this.txStateManager.getFilteredTxList({ from: this.getSelectedAddress(), metamaskNetworkId: this.getNetwork(), }) diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index 91271cc4a..378ea38ab 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -23,7 +23,25 @@ module.exports = class TransactionStateManger extends ObservableStore { return this.getState().transactions } + // Returns the tx list + + getUnapprovedTxList () { + const txList = this.getTxsByMetaData('status', 'unapproved') + return txList.reduce((result, tx) => { + result[tx.id] = tx + return result + }, {}) + } + + addTx (txMeta) { + this.once(`${txMeta.id}:signed`, function (txId) { + this.removeAllListeners(`${txMeta.id}:rejected`) + }) + this.once(`${txMeta.id}:rejected`, function (txId) { + this.removeAllListeners(`${txMeta.id}:signed`) + }) + const transactions = this.getFullTxList() const txCount = this.getTxCount() const txHistoryLimit = this.txHistoryLimit @@ -38,7 +56,6 @@ module.exports = class TransactionStateManger extends ObservableStore { transactions.splice(index, 1) } transactions.push(txMeta) - transactions.push(txMeta) this._saveTxList(transactions) } // gets tx by Id and returns it diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index a007d6fc5..7137190ac 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -133,7 +133,7 @@ module.exports = class MetamaskController extends EventEmitter { this.publicConfigStore = this.initPublicConfigStore() // manual disk state subscriptions - this.txController.store.subscribe((state) => { + this.txController.txStateManager.subscribe((state) => { this.store.updateState({ TransactionController: state }) }) this.keyringController.store.subscribe((state) => { -- cgit v1.2.3 From 474a4e941f7bb5c19ac50d61c6c681a19278b52f Mon Sep 17 00:00:00 2001 From: frankiebee Date: Mon, 21 Aug 2017 11:51:34 -0700 Subject: fix tests --- test/unit/tx-state-manager-test.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/test/unit/tx-state-manager-test.js b/test/unit/tx-state-manager-test.js index 998bbe152..464e50ee4 100644 --- a/test/unit/tx-state-manager-test.js +++ b/test/unit/tx-state-manager-test.js @@ -2,6 +2,7 @@ const assert = require('assert') const clone = require('clone') const ObservableStore = require('obs-store') const TxStateManager = require('../../app/scripts/lib/tx-state-manager') +const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper') const noop = () => true describe('TransactionStateManger', function () { @@ -145,7 +146,9 @@ describe('TransactionStateManger', function () { it('replaces the tx with the same id', function () { txStateManager.addTx({ id: '1', status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) txStateManager.addTx({ id: '2', status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }, noop) - txStateManager.updateTx({ id: '1', status: 'blah', hash: 'foo', metamaskNetworkId: currentNetworkId, txParams: {} }) + const txMeta = txStateManager.getTx('1') + txMeta.hash = 'foo' + txStateManager.updateTx(txMeta) let result = txStateManager.getTx('1') assert.equal(result.hash, 'foo') }) @@ -166,16 +169,16 @@ describe('TransactionStateManger', function () { const updatedMeta = clone(txMeta) txStateManager.addTx(txMeta) - const updatedTx = txController.getTx('1') + const updatedTx = txStateManager.getTx('1') // verify tx was initialized correctly assert.equal(updatedTx.history.length, 1, 'one history item (initial)') assert.equal(Array.isArray(updatedTx.history[0]), false, 'first history item is initial state') assert.deepEqual(updatedTx.history[0], txStateHistoryHelper.snapshotFromTxMeta(updatedTx), 'first history item is initial state') // modify value and updateTx updatedTx.txParams.gasPrice = desiredGasPrice - txController.updateTx(updatedTx) + txStateManager.updateTx(updatedTx) // check updated value - const result = txController.getTx('1') + const result = txStateManager.getTx('1') assert.equal(result.txParams.gasPrice, desiredGasPrice, 'gas price updated') // validate history was updated assert.equal(result.history.length, 2, 'two history items (initial + diff)') -- cgit v1.2.3 From 4c554f32eca5ceda2d525b967075ec2b6ff41809 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 5 Sep 2017 20:13:43 -0700 Subject: remove #buildEthTxFromParams --- app/scripts/lib/tx-utils.js | 17 ----------------- test/unit/tx-utils-test.js | 4 +++- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/app/scripts/lib/tx-utils.js b/app/scripts/lib/tx-utils.js index 5af078dc4..618f69e1c 100644 --- a/app/scripts/lib/tx-utils.js +++ b/app/scripts/lib/tx-utils.js @@ -1,5 +1,4 @@ const EthQuery = require('ethjs-query') -const Transaction = require('ethereumjs-tx') const normalize = require('eth-sig-util').normalize const { hexToBn, @@ -78,22 +77,6 @@ module.exports = class txProvideUtil { return bnToHex(upperGasLimitBn) } - // builds ethTx from txParams object - buildEthTxFromParams (txParams) { - // normalize values - txParams.to = normalize(txParams.to) - txParams.from = normalize(txParams.from) - txParams.value = normalize(txParams.value) - txParams.data = normalize(txParams.data) - txParams.gas = normalize(txParams.gas || txParams.gasLimit) - txParams.gasPrice = normalize(txParams.gasPrice) - txParams.nonce = normalize(txParams.nonce) - // build ethTx - log.info(`Prepared tx for signing: ${JSON.stringify(txParams)}`) - const ethTx = new Transaction(txParams) - return ethTx - } - async publishTransaction (rawTx) { return await this.query.sendRawTransaction(rawTx) } diff --git a/test/unit/tx-utils-test.js b/test/unit/tx-utils-test.js index 43128b977..dcfb9fb3d 100644 --- a/test/unit/tx-utils-test.js +++ b/test/unit/tx-utils-test.js @@ -1,6 +1,8 @@ const assert = require('assert') +const Transaction = require('ethereumjs-tx') const BN = require('bn.js') + const { hexToBn, bnToHex } = require('../../app/scripts/lib/util') const TxUtils = require('../../app/scripts/lib/tx-utils') @@ -28,7 +30,7 @@ describe('txUtils', function () { nonce: '0x3', chainId: 42, } - const ethTx = txUtils.buildEthTxFromParams(txParams) + const ethTx = new Transaction(txParams) assert.equal(ethTx.getChainId(), 42, 'chainId is set from tx params') }) }) -- cgit v1.2.3 From 00bd5b143ffc13ac0a48f2049f61f26082af12c8 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 5 Sep 2017 20:33:50 -0700 Subject: rename tx-utils.js -> tx-gas-utils.js --- app/scripts/lib/tx-gas-utils.js | 85 +++++++++++++++++++++++++++++++++++++++ app/scripts/lib/tx-utils.js | 89 ----------------------------------------- test/unit/tx-utils-test.js | 2 +- 3 files changed, 86 insertions(+), 90 deletions(-) create mode 100644 app/scripts/lib/tx-gas-utils.js delete mode 100644 app/scripts/lib/tx-utils.js diff --git a/app/scripts/lib/tx-gas-utils.js b/app/scripts/lib/tx-gas-utils.js new file mode 100644 index 000000000..246c94ccd --- /dev/null +++ b/app/scripts/lib/tx-gas-utils.js @@ -0,0 +1,85 @@ +const EthQuery = require('ethjs-query') +const normalize = require('eth-sig-util').normalize +const { + hexToBn, + BnMultiplyByFraction, + bnToHex, +} = require('./util') + +/* +tx-utils are utility methods for Transaction manager +its passed ethquery +and used to do things like calculate gas of a tx. +*/ + +module.exports = class txProvideUtil { + constructor (provider) { + this.query = new EthQuery(provider) + } + + async analyzeGasUsage (txMeta) { + const block = await this.query.getBlockByNumber('latest', true) + let estimatedGasHex + try { + estimatedGasHex = await this.estimateTxGas(txMeta, block.gasLimit) + } catch (err) { + if (err.message.includes('Transaction execution error.')) { + txMeta.simulationFails = true + return txMeta + } + } + this.setTxGas(txMeta, block.gasLimit, estimatedGasHex) + return txMeta + } + + async estimateTxGas (txMeta, blockGasLimitHex) { + const txParams = txMeta.txParams + // check if gasLimit is already specified + txMeta.gasLimitSpecified = Boolean(txParams.gas) + // if not, fallback to block gasLimit + if (!txMeta.gasLimitSpecified) { + const blockGasLimitBN = hexToBn(blockGasLimitHex) + const saferGasLimitBN = BnMultiplyByFraction(blockGasLimitBN, 19, 20) + txParams.gas = bnToHex(saferGasLimitBN) + } + // run tx + return await this.query.estimateGas(txParams) + } + + setTxGas (txMeta, blockGasLimitHex, estimatedGasHex) { + txMeta.estimatedGas = estimatedGasHex + const txParams = txMeta.txParams + + // if gasLimit was specified and doesnt OOG, + // use original specified amount + if (txMeta.gasLimitSpecified) { + txMeta.estimatedGas = txParams.gas + return + } + // if gasLimit not originally specified, + // try adding an additional gas buffer to our estimation for safety + const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex) + txParams.gas = recommendedGasHex + return + } + + addGasBuffer (initialGasLimitHex, blockGasLimitHex) { + const initialGasLimitBn = hexToBn(initialGasLimitHex) + const blockGasLimitBn = hexToBn(blockGasLimitHex) + const upperGasLimitBn = blockGasLimitBn.muln(0.9) + const bufferedGasLimitBn = initialGasLimitBn.muln(1.5) + + // if initialGasLimit is above blockGasLimit, dont modify it + if (initialGasLimitBn.gt(upperGasLimitBn)) return bnToHex(initialGasLimitBn) + // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit + if (bufferedGasLimitBn.lt(upperGasLimitBn)) return bnToHex(bufferedGasLimitBn) + // otherwise use blockGasLimit + return bnToHex(upperGasLimitBn) + } + + async validateTxParams (txParams) { + if (('value' in txParams) && txParams.value.indexOf('-') === 0) { + throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`) + } + } +} \ No newline at end of file diff --git a/app/scripts/lib/tx-utils.js b/app/scripts/lib/tx-utils.js deleted file mode 100644 index 618f69e1c..000000000 --- a/app/scripts/lib/tx-utils.js +++ /dev/null @@ -1,89 +0,0 @@ -const EthQuery = require('ethjs-query') -const normalize = require('eth-sig-util').normalize -const { - hexToBn, - BnMultiplyByFraction, - bnToHex, -} = require('./util') - -/* -tx-utils are utility methods for Transaction manager -its passed ethquery -and used to do things like calculate gas of a tx. -*/ - -module.exports = class txProvideUtil { - constructor (provider) { - this.query = new EthQuery(provider) - } - - async analyzeGasUsage (txMeta) { - const block = await this.query.getBlockByNumber('latest', true) - let estimatedGasHex - try { - estimatedGasHex = await this.estimateTxGas(txMeta, block.gasLimit) - } catch (err) { - if (err.message.includes('Transaction execution error.')) { - txMeta.simulationFails = true - return txMeta - } - } - this.setTxGas(txMeta, block.gasLimit, estimatedGasHex) - return txMeta - } - - async estimateTxGas (txMeta, blockGasLimitHex) { - const txParams = txMeta.txParams - // check if gasLimit is already specified - txMeta.gasLimitSpecified = Boolean(txParams.gas) - // if not, fallback to block gasLimit - if (!txMeta.gasLimitSpecified) { - const blockGasLimitBN = hexToBn(blockGasLimitHex) - const saferGasLimitBN = BnMultiplyByFraction(blockGasLimitBN, 19, 20) - txParams.gas = bnToHex(saferGasLimitBN) - } - // run tx - return await this.query.estimateGas(txParams) - } - - setTxGas (txMeta, blockGasLimitHex, estimatedGasHex) { - txMeta.estimatedGas = estimatedGasHex - const txParams = txMeta.txParams - - // if gasLimit was specified and doesnt OOG, - // use original specified amount - if (txMeta.gasLimitSpecified) { - txMeta.estimatedGas = txParams.gas - return - } - // if gasLimit not originally specified, - // try adding an additional gas buffer to our estimation for safety - const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex) - txParams.gas = recommendedGasHex - return - } - - addGasBuffer (initialGasLimitHex, blockGasLimitHex) { - const initialGasLimitBn = hexToBn(initialGasLimitHex) - const blockGasLimitBn = hexToBn(blockGasLimitHex) - const upperGasLimitBn = blockGasLimitBn.muln(0.9) - const bufferedGasLimitBn = initialGasLimitBn.muln(1.5) - - // if initialGasLimit is above blockGasLimit, dont modify it - if (initialGasLimitBn.gt(upperGasLimitBn)) return bnToHex(initialGasLimitBn) - // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit - if (bufferedGasLimitBn.lt(upperGasLimitBn)) return bnToHex(bufferedGasLimitBn) - // otherwise use blockGasLimit - return bnToHex(upperGasLimitBn) - } - - async publishTransaction (rawTx) { - return await this.query.sendRawTransaction(rawTx) - } - - async validateTxParams (txParams) { - if (('value' in txParams) && txParams.value.indexOf('-') === 0) { - throw new Error(`Invalid transaction value of ${txParams.value} not a positive number.`) - } - } -} \ No newline at end of file diff --git a/test/unit/tx-utils-test.js b/test/unit/tx-utils-test.js index dcfb9fb3d..8ca13412e 100644 --- a/test/unit/tx-utils-test.js +++ b/test/unit/tx-utils-test.js @@ -4,7 +4,7 @@ const BN = require('bn.js') const { hexToBn, bnToHex } = require('../../app/scripts/lib/util') -const TxUtils = require('../../app/scripts/lib/tx-utils') +const TxUtils = require('../../app/scripts/lib/tx-gas-utils') describe('txUtils', function () { -- cgit v1.2.3 From 15c12ca4bb6996f43518630ded12c0d7be2d571b Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 5 Sep 2017 21:50:36 -0700 Subject: add better comments --- app/scripts/controllers/transactions.js | 72 +++++++++++++++++++-------------- app/scripts/lib/tx-state-manager.js | 1 - test/unit/tx-controller-test.js | 4 +- 3 files changed, 43 insertions(+), 34 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 2349be1ad..6c4701283 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -2,13 +2,29 @@ const EventEmitter = require('events') const extend = require('xtend') const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') +const Transaction = require('ethereumjs-tx') const EthQuery = require('ethjs-query') const TransactionStateManger = require('../lib/tx-state-manager') -const TxProviderUtil = require('../lib/tx-utils') +const TxGasUtil = require('../lib/tx-gas-utils') const PendingTransactionTracker = require('../lib/pending-tx-tracker') const createId = require('../lib/random-id') const NonceTracker = require('../lib/nonce-tracker') +/* + Transaction Controller is an aggregate of sub-controllers and trackers + composing them in a way to be 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 +*/ + module.exports = class TransactionController extends EventEmitter { constructor (opts) { super() @@ -21,7 +37,7 @@ module.exports = class TransactionController extends EventEmitter { this.memStore = new ObservableStore({}) this.query = new EthQuery(this.provider) - this.txProviderUtil = new TxProviderUtil(this.provider) + this.txGasUtil = new TxGasUtil(this.provider) this.txStateManager = new TransactionStateManger({ initState: extend({ @@ -37,7 +53,6 @@ module.exports = class TransactionController extends EventEmitter { return this.txStateManager.getFilteredTxList({ from: address, status: 'submitted', - err: undefined, }) }, }) @@ -50,16 +65,17 @@ module.exports = class TransactionController extends EventEmitter { if (!account) return return account.balance }, - publishTransaction: this.txProviderUtil.publishTransaction.bind(this.txProviderUtil), + publishTransaction: this.query.sendRawTransaction, getPendingTransactions: () => { - const network = this.getNetwork() - return this.txStateManager.getFilteredTxList({ - status: 'submitted', - metamaskNetworkId: network, - }) + return this.txStateManager.getFilteredTxList({ status: 'submitted' }) }, }) + this.txStateManager.subscribe(() => { + this.emit('update') + this.emit('updateBadge') + }) + this.pendingTxTracker.on('txWarning', this.txStateManager.updateTx.bind(this.txStateManager)) this.pendingTxTracker.on('txFailed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) this.pendingTxTracker.on('txConfirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager)) @@ -99,11 +115,19 @@ module.exports = class TransactionController extends EventEmitter { return this.txStateManager.getTxsByMetaData('status', 'signed').length } + getChainId () { + const networkState = this.networkStore.getState() + const getChainId = parseInt(networkState) + if (Number.isNaN(getChainId)) { + return 0 + } else { + return getChainId + } + } + // Adds a tx to the txlist addTx (txMeta) { this.txStateManager.addTx(txMeta) - this.emit('update') - this.emit('updateBadge') this.emit(`${txMeta.id}:unapproved`, txMeta) } @@ -114,7 +138,6 @@ module.exports = class TransactionController extends EventEmitter { // listen for tx completion (success, fail) return new Promise((resolve, reject) => { this.txStateManager.once(`${txMeta.id}:finished`, (completedTx) => { - this.emit('updateBadge') switch (completedTx.status) { case 'submitted': return resolve(completedTx.hash) @@ -129,7 +152,7 @@ module.exports = class TransactionController extends EventEmitter { async addUnapprovedTransaction (txParams) { // validate - await this.txProviderUtil.validateTxParams(txParams) + await this.txGasUtil.validateTxParams(txParams) // construct txMeta const txMeta = { id: createId(), @@ -148,13 +171,11 @@ module.exports = class TransactionController extends EventEmitter { async addTxDefaults (txMeta) { const txParams = txMeta.txParams // ensure value + const gasPrice = txParams.gasPrice || await this.query.gasPrice() txParams.value = txParams.value || '0x0' - if (!txParams.gasPrice) { - const gasPrice = await this.query.gasPrice() - txParams.gasPrice = gasPrice - } + txParams.gasPrice = ethUtil.addHexPrefix(gasPrice.toString(16)) // set gasLimit - return await this.txProviderUtil.analyzeGasUsage(txMeta) + return await this.txGasUtil.analyzeGasUsage(txMeta) } async updateAndApproveTransaction (txMeta) { @@ -197,7 +218,7 @@ module.exports = class TransactionController extends EventEmitter { const fromAddress = txParams.from // add network/chain id txParams.chainId = this.getChainId() - const ethTx = this.txProviderUtil.buildEthTxFromParams(txParams) + const ethTx = new Transaction(txParams) await this.signEthTx(ethTx, fromAddress) this.txStateManager.setTxStatusSigned(txMeta.id) const rawTx = ethUtil.bufferToHex(ethTx.serialize()) @@ -208,7 +229,7 @@ module.exports = class TransactionController extends EventEmitter { const txMeta = this.txStateManager.getTx(txId) txMeta.rawTx = rawTx this.txStateManager.updateTx(txMeta) - const txHash = await this.txProviderUtil.publishTransaction(rawTx) + const txHash = await this.query.sendRawTransaction(rawTx) this.setTxHash(txId, txHash) this.txStateManager.setTxStatusSubmitted(txId) } @@ -217,17 +238,6 @@ module.exports = class TransactionController extends EventEmitter { this.txStateManager.setTxStatusRejected(txId) } - - getChainId () { - const networkState = this.networkStore.getState() - const getChainId = parseInt(networkState) - if (Number.isNaN(getChainId)) { - return 0 - } else { - return getChainId - } - } - // receives a txHash records the tx as signed setTxHash (txId, txHash) { // Add the tx hash to the persisted meta-tx object diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index d3314c286..64925c528 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -33,7 +33,6 @@ module.exports = class TransactionStateManger extends ObservableStore { }, {}) } - addTx (txMeta) { this.once(`${txMeta.id}:signed`, function (txId) { this.removeAllListeners(`${txMeta.id}:rejected`) diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index fdbddac4b..f969752ec 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -5,7 +5,7 @@ const ObservableStore = require('obs-store') const clone = require('clone') const sinon = require('sinon') const TransactionController = require('../../app/scripts/controllers/transactions') -const TxProvideUtils = require('../../app/scripts/lib/tx-utils') +const TxGasUtils = require('../../app/scripts/lib/tx-gas-utils') const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper') const noop = () => true @@ -34,7 +34,7 @@ describe('Transaction Controller', function () { }), }) txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop }) - txController.txProviderUtils = new TxProvideUtils(txController.provider) + txController.txProviderUtils = new TxGasUtils(txController.provider) }) describe('#newUnapprovedTransaction', function () { -- cgit v1.2.3 From a73aecc796c2f2416227508db8e96e22915cfa65 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Wed, 6 Sep 2017 14:01:07 -0700 Subject: fix merge and errors disaperaing on update --- app/scripts/controllers/transactions.js | 2 +- app/scripts/lib/tx-state-manager.js | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 3f2a7ce16..5aaee7be0 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -56,7 +56,7 @@ module.exports = class TransactionController extends EventEmitter { }) }, getConfirmedTransactions: (address) => { - return this.getFilteredTxList({ + return this.txStateManager.getFilteredTxList({ from: address, status: 'confirmed', err: undefined, diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index 64925c528..eb2a187db 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -180,9 +180,12 @@ module.exports = class TransactionStateManger extends ObservableStore { this._setTxStatus(txId, 'confirmed') } - setTxStatusFailed (txId, reason) { + setTxStatusFailed (txId, err) { const txMeta = this.getTx(txId) - txMeta.err = reason + txMeta.err = { + message: err.toString(), + stack: err.stack, + } this.updateTx(txMeta) this._setTxStatus(txId, 'failed') } -- cgit v1.2.3 From 00fca4f1f236c915eca8f0b068a7c5998e1092f3 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Wed, 6 Sep 2017 14:38:39 -0700 Subject: remove unused variable --- app/scripts/lib/tx-gas-utils.js | 1 - 1 file changed, 1 deletion(-) diff --git a/app/scripts/lib/tx-gas-utils.js b/app/scripts/lib/tx-gas-utils.js index 246c94ccd..41f67e230 100644 --- a/app/scripts/lib/tx-gas-utils.js +++ b/app/scripts/lib/tx-gas-utils.js @@ -1,5 +1,4 @@ const EthQuery = require('ethjs-query') -const normalize = require('eth-sig-util').normalize const { hexToBn, BnMultiplyByFraction, -- cgit v1.2.3 From 50075c6df5af4441db78b47f3bc2036a65228224 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Thu, 7 Sep 2017 00:55:21 -0700 Subject: fix messy merge --- app/scripts/controllers/transactions.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 5aaee7be0..d71be37d8 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -62,10 +62,6 @@ module.exports = class TransactionController extends EventEmitter { err: undefined, }) }, - giveUpOnTransaction: (txId) => { - const msg = `Gave up submitting after 3500 blocks un-mined.` - this.setTxStatusFailed(txId, msg) - }, }) this.pendingTxTracker = new PendingTransactionTracker({ @@ -80,6 +76,10 @@ module.exports = class TransactionController extends EventEmitter { getPendingTransactions: () => { return this.txStateManager.getFilteredTxList({ status: 'submitted' }) }, + giveUpOnTransaction: (txId) => { + const msg = `Gave up submitting after 3500 blocks un-mined.` + this.setTxStatusFailed(txId, msg) + }, }) this.txStateManager.subscribe(() => { -- cgit v1.2.3 From 9b9df417246dbf332f0a7d8afadb664544ceb484 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Fri, 8 Sep 2017 14:24:40 -0700 Subject: more tests and craete a getPendingTransactions function --- app/scripts/controllers/transactions.js | 15 ++++----------- app/scripts/lib/tx-state-manager.js | 6 ++++++ test/unit/components/pending-tx-test.js | 3 ++- test/unit/tx-controller-test.js | 22 ++++++++++++++++++++++ 4 files changed, 34 insertions(+), 12 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index d71be37d8..636424c64 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -49,12 +49,7 @@ module.exports = class TransactionController extends EventEmitter { this.nonceTracker = new NonceTracker({ provider: this.provider, - getPendingTransactions: (address) => { - return this.txStateManager.getFilteredTxList({ - from: address, - status: 'submitted', - }) - }, + getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager), getConfirmedTransactions: (address) => { return this.txStateManager.getFilteredTxList({ from: address, @@ -73,9 +68,7 @@ module.exports = class TransactionController extends EventEmitter { return account.balance }, publishTransaction: this.query.sendRawTransaction, - getPendingTransactions: () => { - return this.txStateManager.getFilteredTxList({ status: 'submitted' }) - }, + getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager), giveUpOnTransaction: (txId) => { const msg = `Gave up submitting after 3500 blocks un-mined.` this.setTxStatusFailed(txId, msg) @@ -122,8 +115,8 @@ module.exports = class TransactionController extends EventEmitter { return Object.keys(this.txStateManager.getUnapprovedTxList()).length } - getPendingTxCount () { - return this.txStateManager.getTxsByMetaData('status', 'signed').length + getPendingTxCount (account) { + return this.txStateManager.getPendingTransactions(account).length } getChainId () { diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index eb2a187db..05fbba612 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -33,6 +33,12 @@ module.exports = class TransactionStateManger extends ObservableStore { }, {}) } + getPendingTransactions (address) { + const opts = { status: 'submitted' } + if (address) opts.from = address + return this.txStateManager.getFilteredTxList(opts) + } + addTx (txMeta) { this.once(`${txMeta.id}:signed`, function (txId) { this.removeAllListeners(`${txMeta.id}:rejected`) diff --git a/test/unit/components/pending-tx-test.js b/test/unit/components/pending-tx-test.js index 22a98bc93..906564558 100644 --- a/test/unit/components/pending-tx-test.js +++ b/test/unit/components/pending-tx-test.js @@ -24,7 +24,8 @@ describe('PendingTx', function () { 'to': '0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb', 'value': '0xde0b6b3a7640000', gasPrice, - 'gas': '0x7b0c'}, + 'gas': '0x7b0c', + }, 'gasLimitSpecified': false, 'estimatedGas': '0x5208', } diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index f969752ec..937ac55de 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -37,6 +37,28 @@ describe('Transaction Controller', function () { txController.txProviderUtils = new TxGasUtils(txController.provider) }) + describe('#getState', function () { + it('should return a state object with the right keys and datat types', function (){ + const exposedState = txController.getState() + assert('unapprovedTxs' in exposedState, 'state should have the key unapprovedTxs') + assert('selectedAddressTxList' in exposedState, 'state should have the key selectedAddressTxList') + assert(typeof exposedState.unapprovedTxs === 'object', 'should be an object') + assert(Array.isArray(exposedState.selectedAddressTxList), 'should be an array') + }) + }) + + describe('#getUnapprovedTxCount', function () { + it('should return the number of unapproved txs', function () { + txController.txStateManager._saveTxList([ + { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 2, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 3, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, + ]) + const unapprovedTxCount = txController.getUnapprovedTxCount() + assert.equal(unapprovedTxCount, 3, 'should be 3') + }) + }) + describe('#newUnapprovedTransaction', function () { let stub, txMeta, txParams beforeEach(function () { -- cgit v1.2.3 From 62f26c5ba873280b536aa7ce31cf92733a3e707c Mon Sep 17 00:00:00 2001 From: frankiebee Date: Fri, 8 Sep 2017 15:02:36 -0700 Subject: fix miss type --- app/scripts/lib/tx-state-manager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index 05fbba612..661523f10 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -36,7 +36,7 @@ module.exports = class TransactionStateManger extends ObservableStore { getPendingTransactions (address) { const opts = { status: 'submitted' } if (address) opts.from = address - return this.txStateManager.getFilteredTxList(opts) + return this.getFilteredTxList(opts) } addTx (txMeta) { -- cgit v1.2.3 From 3ad67d1b14b5b56002cf34ab6dbb18d602705827 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 12 Sep 2017 09:59:59 -0700 Subject: match other controller patterns --- app/scripts/controllers/transactions.js | 22 ++++++++-------------- app/scripts/lib/tx-state-manager.js | 21 +++++++++++++-------- app/scripts/metamask-controller.js | 2 +- test/unit/tx-controller-test.js | 2 +- 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 636424c64..3cb6a609e 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -40,9 +40,7 @@ module.exports = class TransactionController extends EventEmitter { this.txGasUtil = new TxGasUtil(this.provider) this.txStateManager = new TransactionStateManger({ - initState: extend({ - transactions: [], - }, opts.initState), + initState: opts.initState, txHistoryLimit: opts.txHistoryLimit, getNetwork: this.getNetwork.bind(this), }) @@ -70,15 +68,12 @@ module.exports = class TransactionController extends EventEmitter { publishTransaction: this.query.sendRawTransaction, getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager), giveUpOnTransaction: (txId) => { - const msg = `Gave up submitting after 3500 blocks un-mined.` - this.setTxStatusFailed(txId, msg) + const err = new Error(`Gave up submitting after 3500 blocks un-mined.`) + this.setTxStatusFailed(txId, err) }, }) - this.txStateManager.subscribe(() => { - this.emit('update') - this.emit('updateBadge') - }) + this.txStateManager.store.subscribe(() => this.emit('updateBadge')) this.pendingTxTracker.on('txWarning', this.txStateManager.updateTx.bind(this.txStateManager)) this.pendingTxTracker.on('txFailed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) @@ -94,7 +89,7 @@ module.exports = class TransactionController extends EventEmitter { this.blockTracker.on('sync', this.pendingTxTracker.queryPendingTxs.bind(this.pendingTxTracker)) // memstore is computed from a few different stores this._updateMemstore() - this.txStateManager.subscribe(() => this._updateMemstore()) + this.txStateManager.store.subscribe(() => this._updateMemstore()) this.networkStore.subscribe(() => this._updateMemstore()) this.preferencesStore.subscribe(() => this._updateMemstore()) } @@ -250,10 +245,9 @@ module.exports = class TransactionController extends EventEmitter { this.txStateManager.updateTx(txMeta) } -/* _____________________________________ -| | -| PRIVATE METHODS | -|______________________________________*/ +// +// PRIVATE METHODS +// _updateMemstore () { const unapprovedTxs = this.txStateManager.getUnapprovedTxList() diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index 661523f10..843592504 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -1,10 +1,16 @@ const extend = require('xtend') +const EventEmitter = require('events') const ObservableStore = require('obs-store') const txStateHistoryHelper = require('./tx-state-history-helper') -module.exports = class TransactionStateManger extends ObservableStore { +module.exports = class TransactionStateManger extends EventEmitter { constructor ({initState, txHistoryLimit, getNetwork}) { - super(initState) + super() + + this.store = new ObservableStore( + extend({ + transactions: [], + }, initState)) this.txHistoryLimit = txHistoryLimit this.getNetwork = getNetwork } @@ -20,7 +26,7 @@ module.exports = class TransactionStateManger extends ObservableStore { } getFullTxList () { - return this.getState().transactions + return this.store.getState().transactions } // Returns the tx list @@ -196,10 +202,9 @@ module.exports = class TransactionStateManger extends ObservableStore { this._setTxStatus(txId, 'failed') } -/* _____________________________________ -| | -| PRIVATE METHODS | -|______________________________________*/ +// +// PRIVATE METHODS +// // Should find the tx in the tx list and // update it. @@ -225,6 +230,6 @@ module.exports = class TransactionStateManger extends ObservableStore { // Saves the new/updated txList. // Function is intended only for internal use _saveTxList (transactions) { - this.updateState({ transactions }) + this.store.updateState({ transactions }) } } \ No newline at end of file diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 7137190ac..23049c46d 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -133,7 +133,7 @@ module.exports = class MetamaskController extends EventEmitter { this.publicConfigStore = this.initPublicConfigStore() // manual disk state subscriptions - this.txController.txStateManager.subscribe((state) => { + this.txController.txStateManager.store.subscribe((state) => { this.store.updateState({ TransactionController: state }) }) this.keyringController.store.subscribe((state) => { diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index 937ac55de..479010b87 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -197,7 +197,7 @@ describe('Transaction Controller', function () { txParams: {} } - const eventNames = ['update', 'updateBadge', '1:unapproved'] + const eventNames = ['updateBadge', '1:unapproved'] const listeners = [] eventNames.forEach((eventName) => { listeners.push(new Promise((resolve) => { -- cgit v1.2.3 From 9e0c0745ab0f2aa207b0c062ad11efd8df1bb6c5 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 12 Sep 2017 12:19:26 -0700 Subject: linting && format fixing --- app/scripts/controllers/transactions.js | 10 +++------- app/scripts/lib/pending-tx-tracker.js | 9 ++++----- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 3cb6a609e..3ff53e72b 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -1,5 +1,4 @@ const EventEmitter = require('events') -const extend = require('xtend') const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') const Transaction = require('ethereumjs-tx') @@ -60,17 +59,14 @@ module.exports = class TransactionController extends EventEmitter { this.pendingTxTracker = new PendingTransactionTracker({ provider: this.provider, nonceTracker: this.nonceTracker, + retryLimit: 3500, // Retry 3500 blocks, or about 1 day. getBalance: (address) => { const account = this.ethStore.getState().accounts[address] if (!account) return return account.balance }, - publishTransaction: this.query.sendRawTransaction, + publishTransaction: (rawTx) => this.query.sendRawTransaction(rawTx), getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager), - giveUpOnTransaction: (txId) => { - const err = new Error(`Gave up submitting after 3500 blocks un-mined.`) - this.setTxStatusFailed(txId, err) - }, }) this.txStateManager.store.subscribe(() => this.emit('updateBadge')) @@ -193,7 +189,7 @@ module.exports = class TransactionController extends EventEmitter { // wait for a nonce nonceLock = await this.nonceTracker.getNonceLock(fromAddress) // add nonce to txParams - txMeta.txParams.nonce = nonceLock.nextNonce + txMeta.txParams.nonce = ethUtil.addHexPrefix(nonceLock.nextNonce.toString(16)) // add nonce debugging information to txMeta txMeta.nonceDetails = nonceLock.nonceDetails this.txStateManager.updateTx(txMeta) diff --git a/app/scripts/lib/pending-tx-tracker.js b/app/scripts/lib/pending-tx-tracker.js index b90851b58..cbc3f47e6 100644 --- a/app/scripts/lib/pending-tx-tracker.js +++ b/app/scripts/lib/pending-tx-tracker.js @@ -1,7 +1,6 @@ const EventEmitter = require('events') const EthQuery = require('ethjs-query') const sufficientBalance = require('./util').sufficientBalance -const RETRY_LIMIT = 3500 // Retry 3500 blocks, or about 1 day. /* Utility class for tracking the transactions as they @@ -25,11 +24,10 @@ module.exports = class PendingTransactionTracker extends EventEmitter { super() this.query = new EthQuery(config.provider) this.nonceTracker = config.nonceTracker - + this.retryLimit = config.retryLimit || Infinity this.getBalance = config.getBalance this.getPendingTransactions = config.getPendingTransactions this.publishTransaction = config.publishTransaction - this.giveUpOnTransaction = config.giveUpOnTransaction } // checks if a signed tx is in a block and @@ -102,8 +100,9 @@ module.exports = class PendingTransactionTracker extends EventEmitter { if (balance === undefined) return if (!('retryCount' in txMeta)) txMeta.retryCount = 0 - if (txMeta.retryCount > RETRY_LIMIT) { - return this.giveUpOnTransaction(txMeta.id) + if (txMeta.retryCount > this.retryLimit) { + const err = new Error(`Gave up submitting after ${this.retryLimit} blocks un-mined.`) + return this.emit('txFailed', txMeta.id, err) } // if the value of the transaction is greater then the balance, fail. -- cgit v1.2.3 From 59909601b887b2ed8473bea5a28b852668b2804e Mon Sep 17 00:00:00 2001 From: frankiebee Date: Wed, 13 Sep 2017 14:07:22 -0700 Subject: add test for pendingTxCount --- test/unit/tx-controller-test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index 479010b87..47bfe66f8 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -59,6 +59,19 @@ describe('Transaction Controller', function () { }) }) + describe('#getPendingTxCount', function () { + it('should return the number of pending txs', function () { + txController.txStateManager._saveTxList([ + { id: 1, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 2, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 3, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, + ]) + const pendingTxCount = txController.getPendingTxCount() + assert.equal(pendingTxCount, 3, 'should be 3') + }) + }) + + describe('#newUnapprovedTransaction', function () { let stub, txMeta, txParams beforeEach(function () { -- cgit v1.2.3 From 77a48fb0b16d7415377b02a3b7d383c9ef86fcb6 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Wed, 13 Sep 2017 14:27:27 -0700 Subject: ensure that values written to txParams are hex strings --- app/scripts/controllers/transactions.js | 2 +- app/scripts/lib/tx-state-manager.js | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 3ff53e72b..3ee1c22aa 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -212,7 +212,7 @@ module.exports = class TransactionController extends EventEmitter { const txParams = txMeta.txParams const fromAddress = txParams.from // add network/chain id - txParams.chainId = this.getChainId() + txParams.chainId = ethUtil.addHexPrefix(this.getChainId().toString(16)) const ethTx = new Transaction(txParams) await this.signEthTx(ethTx, fromAddress) this.txStateManager.setTxStatusSigned(txMeta.id) diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index 843592504..82c0b6131 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -1,6 +1,7 @@ const extend = require('xtend') const EventEmitter = require('events') const ObservableStore = require('obs-store') +const ethUtil = require('ethereumjs-util') const txStateHistoryHelper = require('./tx-state-history-helper') module.exports = class TransactionStateManger extends EventEmitter { @@ -82,6 +83,14 @@ module.exports = class TransactionStateManger extends EventEmitter { } updateTx (txMeta) { + if (txMeta.txParams) { + Object.keys(txMeta.txParams).forEach((key) => { + let value = txMeta.txParams[key] + if (typeof value !== 'string') console.error(`${key}: ${value} in txParams is not a string`) + if (!ethUtil.isHexPrefixed(value)) console.error('is not hex prefixed, anything on txParams must be hex prefixed') + }) + } + // create txMeta snapshot for history const currentState = txStateHistoryHelper.snapshotFromTxMeta(txMeta) // recover previous tx state obj -- cgit v1.2.3 From d4578836c99bfcdb66a6c989a7ecf79a896a2dc8 Mon Sep 17 00:00:00 2001 From: tmashuang Date: Fri, 22 Sep 2017 16:15:18 -0700 Subject: Most of transaction controller tests --- test/unit/tx-controller-test.js | 192 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 180 insertions(+), 12 deletions(-) diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index 47bfe66f8..e1e4ae8fe 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -7,12 +7,13 @@ const sinon = require('sinon') const TransactionController = require('../../app/scripts/controllers/transactions') const TxGasUtils = require('../../app/scripts/lib/tx-gas-utils') const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper') +const TxStateManager = require('../../app/scripts/lib/tx-state-manager') +const { createStubedProvider } = require('../stub/provider') const noop = () => true const currentNetworkId = 42 const otherNetworkId = 36 const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex') -const { createStubedProvider } = require('../stub/provider') describe('Transaction Controller', function () { @@ -34,11 +35,11 @@ describe('Transaction Controller', function () { }), }) txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop }) - txController.txProviderUtils = new TxGasUtils(txController.provider) + txController.txProviderUtils = new TxGasUtils(txController.provider) }) describe('#getState', function () { - it('should return a state object with the right keys and datat types', function (){ + it('should return a state object with the right keys and datat types', function () { const exposedState = txController.getState() assert('unapprovedTxs' in exposedState, 'state should have the key unapprovedTxs') assert('selectedAddressTxList' in exposedState, 'state should have the key selectedAddressTxList') @@ -71,13 +72,32 @@ describe('Transaction Controller', function () { }) }) + describe('#getConfirmedTransactions', function () { + let address + beforeEach(function () { + address = '0xc684832530fcbddae4b4230a47e991ddcec2831d' + const txParams = { + 'from': address, + 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', + } + txController.txStateManager._saveTxList([ + {id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, + {id: 2, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, + {id: 3, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, + ]) + }) + it('should return the number of confirmed txs', function () { + assert.equal(txController.nonceTracker.getConfirmedTransactions(address).length, 3) + }) + }) + describe('#newUnapprovedTransaction', function () { let stub, txMeta, txParams beforeEach(function () { txParams = { - 'from':'0xc684832530fcbddae4b4230a47e991ddcec2831d', - 'to':'0xc684832530fcbddae4b4230a47e991ddcec2831d', + 'from': '0xc684832530fcbddae4b4230a47e991ddcec2831d', + 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', }, txMeta = { status: 'unapproved', @@ -157,10 +177,10 @@ describe('Transaction Controller', function () { describe('#addTxDefaults', function () { it('should add the tx defaults if their are none', function (done) { - let txMeta = { + const txMeta = { 'txParams': { - 'from':'0xc684832530fcbddae4b4230a47e991ddcec2831d', - 'to':'0xc684832530fcbddae4b4230a47e991ddcec2831d', + 'from': '0xc684832530fcbddae4b4230a47e991ddcec2831d', + 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', }, } providerResultStub.eth_gasPrice = '4a817c800' @@ -168,7 +188,7 @@ describe('Transaction Controller', function () { providerResultStub.eth_estimateGas = '5209' txController.addTxDefaults(txMeta) .then((txMetaWithDefaults) => { - assert(txMetaWithDefaults.txParams.value, '0x0','should have added 0x0 as the value') + assert(txMetaWithDefaults.txParams.value, '0x0', 'should have added 0x0 as the value') assert(txMetaWithDefaults.txParams.gasPrice, 'should have added the gas price') assert(txMetaWithDefaults.txParams.gas, 'should have added the gas field') done() @@ -177,6 +197,16 @@ describe('Transaction Controller', function () { }) }) + xdescribe('#updateAndApprovedTransaction', function () { + it('should update txMeta and approve status for Tx', async function () { + txController.txStateManager.addTx({ id: 0, status: 'unapproved', txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', value: '0xfffff' }, metamaskNetworkId: currentNetworkId }) + const txMeta = txController.txStateManager.getTx(0) + txMeta.value = '0xffffe' + provider.eth_sendRawTransaction = 0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385 + await txController.updateAndApproveTransaction(txMeta) + }) + }) + describe('#validateTxParams', function () { it('does not throw for positive values', function (done) { var sample = { @@ -205,9 +235,8 @@ describe('Transaction Controller', function () { const txMeta = { id: '1', status: 'unapproved', - id: 1, metamaskNetworkId: currentNetworkId, - txParams: {} + txParams: {}, } const eventNames = ['updateBadge', '1:unapproved'] @@ -286,4 +315,143 @@ describe('Transaction Controller', function () { }).catch(done) }) }) -}) \ No newline at end of file + + describe('#getChainId', function () { + it('returns 0 when the chainId is NaN', async function () { + txController.networkStore = new ObservableStore('hello') + assert.equal(txController.getChainId(), 0) + }) + }) + + describe('#publishTransaction', async function () { + beforeEach(function () { + const txMeta = [ + { id: 0, status: 'unapproved', txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', value: '0xfffff' }, rawTx: 'f8498080808080801ca00255b75b550cf112e18fd699f27d043d85348c29d7e8fd234799db890f7c272da0238121aed40c3141e63aae5335aaa3c9711d4907f28071f81f8d055b9f8435e0', metamaskNetworkId: currentNetworkId }, + ] + txController.txStateManager.addTx(txMeta) + }) + + it('should update rawTx of a transaction', async function () { + txController.publishTransaction(0, 'f84c01808080830fffff801ca0e23554ce6f82186402dcdcfff377793fdfa8a872a5670c0ffc002c9cd2f6827aa02a83dfce20aef4064a55320bda47394043af3cbfa63c4e029c54ba6281dcc70e') + }) + }) + + describe('#cancelTransaction', function () { + beforeEach(function () { + const txMetas = [ + { id: 0, status: 'unapproved', txParams: { }, metamaskNetworkId: currentNetworkId }, + { id: 1, status: 'rejected', txParams: { }, metamaskNetworkId: currentNetworkId }, + { id: 2, status: 'approved', txParams: { }, metamaskNetworkId: currentNetworkId }, + { id: 3, status: 'signed', txParams: { }, metamaskNetworkId: currentNetworkId }, + { id: 4, status: 'submitted', txParams: { }, metamaskNetworkId: currentNetworkId }, + { id: 5, status: 'confirmed', txParams: { }, metamaskNetworkId: currentNetworkId }, + { id: 6, status: 'failed', txParams: { }, metamaskNetworkId: currentNetworkId }, + ] + txMetas.forEach((txMeta) => txController.txStateManager.addTx(txMeta)) + }) + + it('should set the transaction to rejected from unapproved', async function () { + await txController.cancelTransaction(0) + assert(txController.txStateManager.getTx(0).status, 'rejected') + }) + + it('should set the transaction to rejected from rejected', async function () { + await txController.cancelTransaction(1) + assert(txController.txStateManager.getTx(1).status, 'rejected') + }) + + it('should set the transaction to rejected from approved', async function () { + await txController.cancelTransaction(2) + assert(txController.txStateManager.getTx(2).status, 'rejected') + }) + + it('should set the transaction to rejected from signed', async function () { + await txController.cancelTransaction(3) + assert(txController.txStateManager.getTx(3).status, 'rejected') + }) + + it('should set the transaction to rejected from submitted', async function () { + await txController.cancelTransaction(4) + assert(txController.txStateManager.getTx(4).status, 'rejected') + }) + + it('should set the transaction to rejected from confirmed', async function () { + await txController.cancelTransaction(5) + assert(txController.txStateManager.getTx(5).status, 'rejected') + }) + + it('should set the transaction to rejected from failed', async function () { + await txController.cancelTransaction(6) + assert(txController.txStateManager.getTx(6).status, 'rejected') + }) + + }) + + describe('#publishTransaction', function () { + let replaceRawTx, rawTx, hash, txMeta + beforeEach(function () { + rawTx = 'f86c808504a817c800827b0d940c62bb85faa3311a998d3aba8098c1235c564966880de0b6b3a7640000802aa08ff665feb887a25d4099e40e11f0fef93ee9608f404bd3f853dd9e84ed3317a6a02ec9d3d1d6e176d4d2593dd760e74ccac753e6a0ea0d00cc9789d0d7ff1f471d' + replaceRawTx = 'f84c01808080830fffff801ca0e23554ce6f82186402dcdcfff377793fdfa8a872a5670c0ffc002c9cd2f6827aa02a83dfce20aef4064a55320bda47394043af3cbfa63c4e029c54ba6281dcc70e' + txMeta = { + id: 1, + status: 'approved', + txParams: {}, + rawTx, + hash, + metamaskNetworkId: currentNetworkId, + } + providerResultStub.eth_sendRawTransaction = '0x2a5523c6fa98b47b7d9b6c8320179785150b42a16bcff36b398c5062b65657e8' + }) + it('should publish a tx, updates the rawTx when provided a one', async function () { + txController.txStateManager.addTx(txMeta) + await txController.publishTransaction(txMeta.id, replaceRawTx) + txController.setTxHash(1, '0x2a5523c6fa98b47b7d9b6c8320179785150b42a16bcff36b398c5062b65657e8') + assert.equal(txController.txStateManager.getTx(1).rawTx, replaceRawTx) + assert.notEqual(txController.txStateManager.getTx(1).rawTx, rawTx) + }) + }) + + describe('#getBalance', function () { + it('gets balance', function () { + sinon.stub(txController.ethStore, 'getState').callsFake(() => { + return { + accounts: { + '0x1678a085c290ebd122dc42cba69373b5953b831d': { + address: '0x1678a085c290ebd122dc42cba69373b5953b831d', + balance: '0x00000000000000056bc75e2d63100000', + code: '0x', + nonce: '0x0', + }, + '0xc684832530fcbddae4b4230a47e991ddcec2831d': { + address: '0xc684832530fcbddae4b4230a47e991ddcec2831d', + balance: '0x0', + code: '0x', + nonce: '0x0', + }, + }, + } + }) + assert.equal(txController.pendingTxTracker.getBalance('0x1678a085c290ebd122dc42cba69373b5953b831d'), '0x00000000000000056bc75e2d63100000') + assert.equal(txController.pendingTxTracker.getBalance('0xc684832530fcbddae4b4230a47e991ddcec2831d'), '0x0') + }) + }) + + describe('#getPendingTransactions', function () { + beforeEach(function () { + txController.txStateManager._saveTxList([ + { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 2, status: 'rejected', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 3, status: 'approved', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 4, status: 'signed', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 5, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 6, status: 'confimed', metamaskNetworkId: currentNetworkId, txParams: {} }, + { id: 7, status: 'failed', metamaskNetworkId: currentNetworkId, txParams: {} }, + ]) + }) + it('should show only submitted transactions as pending transasction', function () { + assert(txController.pendingTxTracker.getPendingTransactions().length, 1) + assert(txController.pendingTxTracker.getPendingTransactions()[0].status, 'submitted') + }) + }) + +}) -- cgit v1.2.3 From 20fea3f1dee33455842d9c2ac7e620d3321b6011 Mon Sep 17 00:00:00 2001 From: tmashuang Date: Mon, 25 Sep 2017 10:47:36 -0700 Subject: Remove pending updateAndApprovedTransaction test --- test/unit/tx-controller-test.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index e1e4ae8fe..f6b41f2bb 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -197,16 +197,6 @@ describe('Transaction Controller', function () { }) }) - xdescribe('#updateAndApprovedTransaction', function () { - it('should update txMeta and approve status for Tx', async function () { - txController.txStateManager.addTx({ id: 0, status: 'unapproved', txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', value: '0xfffff' }, metamaskNetworkId: currentNetworkId }) - const txMeta = txController.txStateManager.getTx(0) - txMeta.value = '0xffffe' - provider.eth_sendRawTransaction = 0x7f9fade1c0d57a7af66ab4ead79fade1c0d57a7af66ab4ead7c2c2eb7b11a91385 - await txController.updateAndApproveTransaction(txMeta) - }) - }) - describe('#validateTxParams', function () { it('does not throw for positive values', function (done) { var sample = { -- cgit v1.2.3 From ff6f7b52e4b5397daef74695894e0cdad22fe273 Mon Sep 17 00:00:00 2001 From: tmashuang Date: Mon, 25 Sep 2017 19:47:03 -0700 Subject: Clean up transactionController tests --- test/unit/tx-controller-test.js | 124 +++++++++++++++++----------------------- 1 file changed, 53 insertions(+), 71 deletions(-) diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index f6b41f2bb..13056417c 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -2,12 +2,9 @@ const assert = require('assert') const ethUtil = require('ethereumjs-util') const EthTx = require('ethereumjs-tx') const ObservableStore = require('obs-store') -const clone = require('clone') const sinon = require('sinon') const TransactionController = require('../../app/scripts/controllers/transactions') const TxGasUtils = require('../../app/scripts/lib/tx-gas-utils') -const txStateHistoryHelper = require('../../app/scripts/lib/tx-state-history-helper') -const TxStateManager = require('../../app/scripts/lib/tx-state-manager') const { createStubedProvider } = require('../stub/provider') const noop = () => true @@ -17,7 +14,7 @@ const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f3 describe('Transaction Controller', function () { - let txController, engine, provider, providerResultStub + let txController, provider, providerResultStub beforeEach(function () { providerResultStub = {} @@ -81,11 +78,18 @@ describe('Transaction Controller', function () { 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', } txController.txStateManager._saveTxList([ + {id: 0, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, {id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, {id: 2, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, - {id: 3, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams}, + {id: 3, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams}, + {id: 4, status: 'rejected', metamaskNetworkId: currentNetworkId, txParams}, + {id: 5, status: 'approved', metamaskNetworkId: currentNetworkId, txParams}, + {id: 6, status: 'signed', metamaskNetworkId: currentNetworkId, txParams}, + {id: 7, status: 'submitted', metamaskNetworkId: currentNetworkId, txParams}, + {id: 8, status: 'failed', metamaskNetworkId: currentNetworkId, txParams}, ]) }) + it('should return the number of confirmed txs', function () { assert.equal(txController.nonceTracker.getConfirmedTransactions(address).length, 3) }) @@ -98,7 +102,7 @@ describe('Transaction Controller', function () { txParams = { 'from': '0xc684832530fcbddae4b4230a47e991ddcec2831d', 'to': '0xc684832530fcbddae4b4230a47e991ddcec2831d', - }, + } txMeta = { status: 'unapproved', id: 1, @@ -306,98 +310,76 @@ describe('Transaction Controller', function () { }) }) - describe('#getChainId', function () { - it('returns 0 when the chainId is NaN', async function () { - txController.networkStore = new ObservableStore('hello') - assert.equal(txController.getChainId(), 0) - }) - }) - - describe('#publishTransaction', async function () { + describe('#updateAndApproveTransaction', function () { + let txMeta beforeEach(function () { - const txMeta = [ - { id: 0, status: 'unapproved', txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', value: '0xfffff' }, rawTx: 'f8498080808080801ca00255b75b550cf112e18fd699f27d043d85348c29d7e8fd234799db890f7c272da0238121aed40c3141e63aae5335aaa3c9711d4907f28071f81f8d055b9f8435e0', metamaskNetworkId: currentNetworkId }, - ] + txMeta = { + id: 1, + status: 'unapproved', + txParams: { + from: '0xc684832530fcbddae4b4230a47e991ddcec2831d', + to: '0x1678a085c290ebd122dc42cba69373b5953b831d', + gasPrice: '0x77359400', + gas: '0x7b0d', + nonce: '0x4b', + }, + metamaskNetworkId: currentNetworkId, + } + }) + it('should update and approve transactions', function () { txController.txStateManager.addTx(txMeta) + txController.updateAndApproveTransaction(txMeta) + const tx = txController.txStateManager.getTx(1) + assert.equal(tx.status, 'approved') }) + }) - it('should update rawTx of a transaction', async function () { - txController.publishTransaction(0, 'f84c01808080830fffff801ca0e23554ce6f82186402dcdcfff377793fdfa8a872a5670c0ffc002c9cd2f6827aa02a83dfce20aef4064a55320bda47394043af3cbfa63c4e029c54ba6281dcc70e') + describe('#getChainId', function () { + it('returns 0 when the chainId is NaN', function () { + txController.networkStore = new ObservableStore(NaN) + assert.equal(txController.getChainId(), 0) }) }) describe('#cancelTransaction', function () { beforeEach(function () { - const txMetas = [ - { id: 0, status: 'unapproved', txParams: { }, metamaskNetworkId: currentNetworkId }, - { id: 1, status: 'rejected', txParams: { }, metamaskNetworkId: currentNetworkId }, - { id: 2, status: 'approved', txParams: { }, metamaskNetworkId: currentNetworkId }, - { id: 3, status: 'signed', txParams: { }, metamaskNetworkId: currentNetworkId }, - { id: 4, status: 'submitted', txParams: { }, metamaskNetworkId: currentNetworkId }, - { id: 5, status: 'confirmed', txParams: { }, metamaskNetworkId: currentNetworkId }, - { id: 6, status: 'failed', txParams: { }, metamaskNetworkId: currentNetworkId }, - ] - txMetas.forEach((txMeta) => txController.txStateManager.addTx(txMeta)) + txController.txStateManager._saveTxList([ + { id: 0, status: 'unapproved', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + { id: 1, status: 'rejected', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + { id: 2, status: 'approved', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + { id: 3, status: 'signed', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + { id: 4, status: 'submitted', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + { id: 5, status: 'confirmed', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + { id: 6, status: 'failed', txParams: {}, metamaskNetworkId: currentNetworkId, history: [{}] }, + ]) }) it('should set the transaction to rejected from unapproved', async function () { await txController.cancelTransaction(0) - assert(txController.txStateManager.getTx(0).status, 'rejected') - }) - - it('should set the transaction to rejected from rejected', async function () { - await txController.cancelTransaction(1) - assert(txController.txStateManager.getTx(1).status, 'rejected') - }) - - it('should set the transaction to rejected from approved', async function () { - await txController.cancelTransaction(2) - assert(txController.txStateManager.getTx(2).status, 'rejected') - }) - - it('should set the transaction to rejected from signed', async function () { - await txController.cancelTransaction(3) - assert(txController.txStateManager.getTx(3).status, 'rejected') - }) - - it('should set the transaction to rejected from submitted', async function () { - await txController.cancelTransaction(4) - assert(txController.txStateManager.getTx(4).status, 'rejected') - }) - - it('should set the transaction to rejected from confirmed', async function () { - await txController.cancelTransaction(5) - assert(txController.txStateManager.getTx(5).status, 'rejected') - }) - - it('should set the transaction to rejected from failed', async function () { - await txController.cancelTransaction(6) - assert(txController.txStateManager.getTx(6).status, 'rejected') + assert.equal(txController.txStateManager.getTx(0).status, 'rejected') }) }) describe('#publishTransaction', function () { - let replaceRawTx, rawTx, hash, txMeta + let hash, txMeta beforeEach(function () { - rawTx = 'f86c808504a817c800827b0d940c62bb85faa3311a998d3aba8098c1235c564966880de0b6b3a7640000802aa08ff665feb887a25d4099e40e11f0fef93ee9608f404bd3f853dd9e84ed3317a6a02ec9d3d1d6e176d4d2593dd760e74ccac753e6a0ea0d00cc9789d0d7ff1f471d' - replaceRawTx = 'f84c01808080830fffff801ca0e23554ce6f82186402dcdcfff377793fdfa8a872a5670c0ffc002c9cd2f6827aa02a83dfce20aef4064a55320bda47394043af3cbfa63c4e029c54ba6281dcc70e' + hash = '0x2a5523c6fa98b47b7d9b6c8320179785150b42a16bcff36b398c5062b65657e8' txMeta = { id: 1, - status: 'approved', + status: 'unapproved', txParams: {}, - rawTx, - hash, metamaskNetworkId: currentNetworkId, } - providerResultStub.eth_sendRawTransaction = '0x2a5523c6fa98b47b7d9b6c8320179785150b42a16bcff36b398c5062b65657e8' + providerResultStub.eth_sendRawTransaction = hash }) + it('should publish a tx, updates the rawTx when provided a one', async function () { txController.txStateManager.addTx(txMeta) - await txController.publishTransaction(txMeta.id, replaceRawTx) - txController.setTxHash(1, '0x2a5523c6fa98b47b7d9b6c8320179785150b42a16bcff36b398c5062b65657e8') - assert.equal(txController.txStateManager.getTx(1).rawTx, replaceRawTx) - assert.notEqual(txController.txStateManager.getTx(1).rawTx, rawTx) + await txController.publishTransaction(txMeta.id) + const publishedTx = txController.txStateManager.getTx(1) + assert.equal(publishedTx.hash, hash) + assert.equal(publishedTx.status, 'submitted') }) }) -- cgit v1.2.3 From 9fd545811226c16e11e4f2dc100a348e07f094bf Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 26 Sep 2017 16:52:08 -0700 Subject: transactions: lint fixes and reveal status-update event for balance controller --- app/scripts/background.js | 2 +- app/scripts/controllers/balance.js | 15 ++++++++++++--- app/scripts/controllers/transactions.js | 5 +++-- app/scripts/lib/tx-state-manager.js | 12 ++++++------ app/scripts/metamask-controller.js | 2 +- test/unit/tx-controller-test.js | 2 +- 6 files changed, 24 insertions(+), 14 deletions(-) diff --git a/app/scripts/background.js b/app/scripts/background.js index 1b96d68b5..195881e15 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -114,7 +114,7 @@ function setupController (initState) { // updateBadge() - controller.txController.on('updateBadge', updateBadge) + controller.txController.on('update:badge', updateBadge) controller.messageManager.on('updateBadge', updateBadge) controller.personalMessageManager.on('updateBadge', updateBadge) diff --git a/app/scripts/controllers/balance.js b/app/scripts/controllers/balance.js index 964dff0df..4fa4c78fe 100644 --- a/app/scripts/controllers/balance.js +++ b/app/scripts/controllers/balance.js @@ -33,9 +33,18 @@ class BalanceController { _registerUpdates () { const update = this.updateBalance.bind(this) - this.txController.on('submitted', update) - this.txController.on('confirmed', update) - this.txController.on('failed', update) + + this.txController.on('tx:status-update', (txId, status) => { + switch (status) { + case 'submitted': + case 'confirmed': + case 'failed': + update() + return + default: + return + } + }) this.accountTracker.store.subscribe(update) this.blockTracker.on('block', update) } diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index de5fa5b20..1b647a4ed 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -43,7 +43,8 @@ module.exports = class TransactionController extends EventEmitter { txHistoryLimit: opts.txHistoryLimit, getNetwork: this.getNetwork.bind(this), }) - + 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), @@ -69,7 +70,7 @@ module.exports = class TransactionController extends EventEmitter { getPendingTransactions: this.txStateManager.getPendingTransactions.bind(this.txStateManager), }) - this.txStateManager.store.subscribe(() => this.emit('updateBadge')) + this.txStateManager.store.subscribe(() => this.emit('update:badge')) this.pendingTxTracker.on('txWarning', this.txStateManager.updateTx.bind(this.txStateManager)) this.pendingTxTracker.on('txFailed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index d7b76fe22..abb9d7910 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -5,7 +5,7 @@ const ethUtil = require('ethereumjs-util') const txStateHistoryHelper = require('./tx-state-history-helper') module.exports = class TransactionStateManger extends EventEmitter { - constructor ({initState, txHistoryLimit, getNetwork}) { + constructor ({ initState, txHistoryLimit, getNetwork }) { super() this.store = new ObservableStore( @@ -15,7 +15,8 @@ module.exports = class TransactionStateManger extends EventEmitter { this.txHistoryLimit = txHistoryLimit this.getNetwork = getNetwork } - // Returns the number of txs for the current network. + + // Returns the number of txs for the current network. getTxCount () { return this.getTxList().length } @@ -31,7 +32,6 @@ module.exports = class TransactionStateManger extends EventEmitter { } // Returns the tx list - getUnapprovedTxList () { const txList = this.getTxsByMetaData('status', 'unapproved') return txList.reduce((result, tx) => { @@ -69,7 +69,7 @@ module.exports = class TransactionStateManger extends EventEmitter { // or rejected tx's. // not tx's that are pending or unapproved if (txCount > txHistoryLimit - 1) { - const index = transactions.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected'))) + const index = transactions.findIndex((metaTx) => metaTx.status === 'confirmed' || metaTx.status === 'rejected') transactions.splice(index, 1) } transactions.push(txMeta) @@ -229,12 +229,12 @@ module.exports = class TransactionStateManger extends EventEmitter { const txMeta = this.getTx(txId) txMeta.status = status this.emit(`${txMeta.id}:${status}`, txId) - this.emit(`${status}`, txId) + this.emit(`tx:status-update`, txId, status) if (status === 'submitted' || status === 'rejected') { this.emit(`${txMeta.id}:finished`, txMeta) } this.updateTx(txMeta) - this.emit('updateBadge') + this.emit('update:badge') } // Saves the new/updated txList. diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 96b34507f..0f850b7f5 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -157,7 +157,7 @@ module.exports = class MetamaskController extends EventEmitter { this.publicConfigStore = this.initPublicConfigStore() // manual disk state subscriptions - this.txController.txStateManager.store.subscribe((state) => { + this.txController.store.subscribe((state) => { this.store.updateState({ TransactionController: state }) }) this.keyringController.store.subscribe((state) => { diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index 8d45fb9b5..c1612a30c 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -210,7 +210,7 @@ describe('Transaction Controller', function () { txParams: {} } - const eventNames = ['updateBadge', '1:unapproved'] + const eventNames = ['update:badge', '1:unapproved'] const listeners = [] eventNames.forEach((eventName) => { listeners.push(new Promise((resolve) => { -- cgit v1.2.3 From 80c98b16531db4c6a13a52df800967af2bc4a676 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 26 Sep 2017 16:55:11 -0700 Subject: transactions: make evnt names pretty and eaiser to read --- app/scripts/controllers/transactions.js | 6 +++--- app/scripts/lib/pending-tx-tracker.js | 16 ++++++++-------- test/unit/pending-tx-test.js | 18 +++++++++--------- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 1b647a4ed..ec1524968 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -72,9 +72,9 @@ module.exports = class TransactionController extends EventEmitter { this.txStateManager.store.subscribe(() => this.emit('update:badge')) - this.pendingTxTracker.on('txWarning', this.txStateManager.updateTx.bind(this.txStateManager)) - this.pendingTxTracker.on('txFailed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) - this.pendingTxTracker.on('txConfirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager)) + this.pendingTxTracker.on('tx:warning', this.txStateManager.updateTx.bind(this.txStateManager)) + this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) + this.pendingTxTracker.on('tx:confirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager)) this.blockTracker.on('rawBlock', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker)) // this is a little messy but until ethstore has been either diff --git a/app/scripts/lib/pending-tx-tracker.js b/app/scripts/lib/pending-tx-tracker.js index 4541221d5..31cf9babb 100644 --- a/app/scripts/lib/pending-tx-tracker.js +++ b/app/scripts/lib/pending-tx-tracker.js @@ -42,13 +42,13 @@ module.exports = class PendingTransactionTracker extends EventEmitter { if (!txHash) { const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.') noTxHashErr.name = 'NoTxHashError' - this.emit('txFailed', txId, noTxHashErr) + this.emit('tx:failed', txId, noTxHashErr) return } block.transactions.forEach((tx) => { - if (tx.hash === txHash) this.emit('txConfirmed', txId) + if (tx.hash === txHash) this.emit('tx:confirmed', txId) }) }) } @@ -94,7 +94,7 @@ module.exports = class PendingTransactionTracker extends EventEmitter { // ignore resubmit warnings, return early if (isKnownTx) return // encountered real error - transition to error state - this.emit('txFailed', txMeta.id, err) + this.emit('tx:failed', txMeta.id, err) })) } @@ -106,13 +106,13 @@ module.exports = class PendingTransactionTracker extends EventEmitter { if (txMeta.retryCount > this.retryLimit) { const err = new Error(`Gave up submitting after ${this.retryLimit} blocks un-mined.`) - return this.emit('txFailed', txMeta.id, err) + return this.emit('tx:failed', txMeta.id, err) } // if the value of the transaction is greater then the balance, fail. if (!sufficientBalance(txMeta.txParams, balance)) { const insufficientFundsError = new Error('Insufficient balance during rebroadcast.') - this.emit('txFailed', txMeta.id, insufficientFundsError) + this.emit('tx:failed', txMeta.id, insufficientFundsError) log.error(insufficientFundsError) return } @@ -136,7 +136,7 @@ module.exports = class PendingTransactionTracker extends EventEmitter { if (!txHash) { const noTxHashErr = new Error('We had an error while submitting this transaction, please try again.') noTxHashErr.name = 'NoTxHashError' - this.emit('txFailed', txId, noTxHashErr) + this.emit('tx:failed', txId, noTxHashErr) return } // get latest transaction status @@ -145,14 +145,14 @@ module.exports = class PendingTransactionTracker extends EventEmitter { txParams = await this.query.getTransactionByHash(txHash) if (!txParams) return if (txParams.blockNumber) { - this.emit('txConfirmed', txId) + this.emit('tx:confirmed', txId) } } catch (err) { txMeta.warning = { error: err, message: 'There was a problem loading this transaction.', } - this.emit('txWarning', txMeta) + this.emit('tx:warning', txMeta) throw err } } diff --git a/test/unit/pending-tx-test.js b/test/unit/pending-tx-test.js index 8c6d287f8..2865a30e6 100644 --- a/test/unit/pending-tx-test.js +++ b/test/unit/pending-tx-test.js @@ -62,7 +62,7 @@ describe('PendingTransactionTracker', function () { it('should emit \'txFailed\' if the txMeta does not have a hash', function (done) { const block = Proxy.revocable({}, {}).revoke() pendingTxTracker.getPendingTransactions = () => [txMetaNoHash] - pendingTxTracker.once('txFailed', (txId, err) => { + pendingTxTracker.once('tx:failed', (txId, err) => { assert(txId, txMetaNoHash.id, 'should pass txId') done() }) @@ -71,11 +71,11 @@ describe('PendingTransactionTracker', function () { it('should emit \'txConfirmed\' if the tx is in the block', function (done) { const block = { transactions: [txMeta]} pendingTxTracker.getPendingTransactions = () => [txMeta] - pendingTxTracker.once('txConfirmed', (txId) => { + pendingTxTracker.once('tx:confirmed', (txId) => { assert(txId, txMeta.id, 'should pass txId') done() }) - pendingTxTracker.once('txFailed', (_, err) => { done(err) }) + pendingTxTracker.once('tx:failed', (_, err) => { done(err) }) pendingTxTracker.checkForTxInBlock(block) }) }) @@ -108,7 +108,7 @@ describe('PendingTransactionTracker', function () { describe('#_checkPendingTx', function () { it('should emit \'txFailed\' if the txMeta does not have a hash', function (done) { - pendingTxTracker.once('txFailed', (txId, err) => { + pendingTxTracker.once('tx:failed', (txId, err) => { assert(txId, txMetaNoHash.id, 'should pass txId') done() }) @@ -122,11 +122,11 @@ describe('PendingTransactionTracker', function () { it('should emit \'txConfirmed\'', function (done) { providerResultStub.eth_getTransactionByHash = {blockNumber: '0x01'} - pendingTxTracker.once('txConfirmed', (txId) => { + pendingTxTracker.once('tx:confirmed', (txId) => { assert(txId, txMeta.id, 'should pass txId') done() }) - pendingTxTracker.once('txFailed', (_, err) => { done(err) }) + pendingTxTracker.once('tx:failed', (_, err) => { done(err) }) pendingTxTracker._checkPendingTx(txMeta) }) }) @@ -188,7 +188,7 @@ describe('PendingTransactionTracker', function () { ] const enoughForAllErrors = txList.concat(txList) - pendingTxTracker.on('txFailed', (_, err) => done(err)) + pendingTxTracker.on('tx:failed', (_, err) => done(err)) pendingTxTracker.getPendingTransactions = () => enoughForAllErrors pendingTxTracker._resubmitTx = async (tx) => { @@ -202,7 +202,7 @@ describe('PendingTransactionTracker', function () { pendingTxTracker.resubmitPendingTxs() }) it('should emit \'txFailed\' if it encountered a real error', function (done) { - pendingTxTracker.once('txFailed', (id, err) => err.message === 'im some real error' ? txList[id - 1].resolve() : done(err)) + pendingTxTracker.once('tx:failed', (id, err) => err.message === 'im some real error' ? txList[id - 1].resolve() : done(err)) pendingTxTracker.getPendingTransactions = () => txList pendingTxTracker._resubmitTx = async (tx) => { throw new TypeError('im some real error') } @@ -226,7 +226,7 @@ describe('PendingTransactionTracker', function () { // Stubbing out current account state: // Adding the fake tx: - pendingTxTracker.once('txFailed', (txId, err) => { + pendingTxTracker.once('tx:failed', (txId, err) => { assert(err, 'Should have a error') done() }) -- cgit v1.2.3 From 508696f71d6b5b14c708a3229039f9f915ce48ce Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 26 Sep 2017 18:11:51 -0700 Subject: transactions: reveal #getFilteredTxList from txStateManage and fix accountTracker.store reference --- app/scripts/controllers/transactions.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index ec1524968..6ea2933dc 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -62,7 +62,7 @@ module.exports = class TransactionController extends EventEmitter { nonceTracker: this.nonceTracker, retryLimit: 3500, // Retry 3500 blocks, or about 1 day. getBalance: (address) => { - const account = this.accountTracker.getState().accounts[address] + const account = this.accountTracker.store.getState().accounts[address] if (!account) return return account.balance }, @@ -111,6 +111,10 @@ module.exports = class TransactionController extends EventEmitter { return this.txStateManager.getPendingTransactions(account).length } + getFilteredTxList (opts) { + return this.txStateManager.getFilteredTxList(opts) + } + getChainId () { const networkState = this.networkStore.getState() const getChainId = parseInt(networkState) -- cgit v1.2.3 From b05a6f89cb2c4de1e53d96f8cac01653a8165555 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 26 Sep 2017 18:19:44 -0700 Subject: fix tests --- test/unit/tx-controller-test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index dd8b48684..9ffba31ee 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -25,7 +25,7 @@ describe('Transaction Controller', function () { networkStore: new ObservableStore(currentNetworkId), txHistoryLimit: 10, blockTracker: { getCurrentBlock: noop, on: noop, once: noop }, - accountTracker: { getState: noop }, + accountTracker: { store: {getState: noop} }, signTransaction: (ethTx) => new Promise((resolve) => { ethTx.sign(privKey) resolve() @@ -385,7 +385,7 @@ describe('Transaction Controller', function () { describe('#getBalance', function () { it('gets balance', function () { - sinon.stub(txController.ethStore, 'getState').callsFake(() => { + sinon.stub(txController.accountTracker.store, 'getState').callsFake(() => { return { accounts: { '0x1678a085c290ebd122dc42cba69373b5953b831d': { -- cgit v1.2.3 From 0a94ec41d3a2877ed7cfd3c8f9e9f9d725659183 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 26 Sep 2017 22:42:59 -0700 Subject: pending-tx - move incrementing of the retryCount on the txMeta outside pending-tx-tracker --- app/scripts/controllers/transactions.js | 5 +++++ app/scripts/lib/pending-tx-tracker.js | 3 +-- test/unit/tx-controller-test.js | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 6ea2933dc..3cd107031 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -75,6 +75,11 @@ module.exports = class TransactionController extends EventEmitter { this.pendingTxTracker.on('tx:warning', this.txStateManager.updateTx.bind(this.txStateManager)) this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) this.pendingTxTracker.on('tx:confirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager)) + this.pendingTxTracker.on('tx:retry', (txMeta) => { + if (!('retryCount' in txMeta)) txMeta.retryCount = 0 + txMeta.retryCount++ + this.txStateManager.updateTx(txMeta) + }) this.blockTracker.on('rawBlock', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker)) // this is a little messy but until ethstore has been either diff --git a/app/scripts/lib/pending-tx-tracker.js b/app/scripts/lib/pending-tx-tracker.js index 31cf9babb..b07a6bd39 100644 --- a/app/scripts/lib/pending-tx-tracker.js +++ b/app/scripts/lib/pending-tx-tracker.js @@ -102,7 +102,6 @@ module.exports = class PendingTransactionTracker extends EventEmitter { const address = txMeta.txParams.from const balance = this.getBalance(address) if (balance === undefined) return - if (!('retryCount' in txMeta)) txMeta.retryCount = 0 if (txMeta.retryCount > this.retryLimit) { const err = new Error(`Gave up submitting after ${this.retryLimit} blocks un-mined.`) @@ -124,7 +123,7 @@ module.exports = class PendingTransactionTracker extends EventEmitter { const txHash = await this.publishTransaction(rawTx) // Increment successful tries: - txMeta.retryCount++ + this.emit('tx:retry', txMeta) return txHash } diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js index 9ffba31ee..66772ff88 100644 --- a/test/unit/tx-controller-test.js +++ b/test/unit/tx-controller-test.js @@ -25,7 +25,7 @@ describe('Transaction Controller', function () { networkStore: new ObservableStore(currentNetworkId), txHistoryLimit: 10, blockTracker: { getCurrentBlock: noop, on: noop, once: noop }, - accountTracker: { store: {getState: noop} }, + accountTracker: { store: { getState: noop } }, signTransaction: (ethTx) => new Promise((resolve) => { ethTx.sign(privKey) resolve() -- cgit v1.2.3 From 8d3fec42d0a49c2e0fe7ef3dc504533deb223d95 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 27 Sep 2017 12:09:32 -0700 Subject: Fix bug where block gas limit was incorrectly parsed. --- CHANGELOG.md | 2 ++ app/scripts/lib/account-tracker.js | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eedfa89c5..4898d27fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Current Master +- Fix block gas limit estimation. + ## 3.10.4 2017-9-27 - Fix bug that could mis-render token balances when very small. (Not actually included in 3.9.9) diff --git a/app/scripts/lib/account-tracker.js b/app/scripts/lib/account-tracker.js index e2892b1ce..07fc32b10 100644 --- a/app/scripts/lib/account-tracker.js +++ b/app/scripts/lib/account-tracker.js @@ -11,6 +11,7 @@ const async = require('async') const EthQuery = require('eth-query') const ObservableStore = require('obs-store') const EventEmitter = require('events').EventEmitter +const ethUtil = require('ethereumjs-util') function noop () {} @@ -59,8 +60,9 @@ class AccountTracker extends EventEmitter { _updateForBlock (block) { const blockNumber = '0x' + block.number.toString('hex') this._currentBlockNumber = blockNumber + const currentBlockGasLimit = ethUtil.addHexPrefix(block.gasLimit.toString()) - this.store.updateState({ currentBlockGasLimit: `0x${block.gasLimit.toString('hex')}` }) + this.store.updateState({ currentBlockGasLimit }) async.parallel([ this._updateAccounts.bind(this), -- cgit v1.2.3 From a453eb132d1aa97923df8900f8290a1b3ca1dee3 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 27 Sep 2017 12:10:25 -0700 Subject: Version 3.10.5 --- CHANGELOG.md | 2 ++ app/manifest.json | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4898d27fc..3ad9888fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Current Master +## 3.10.5 2017-9-27 + - Fix block gas limit estimation. ## 3.10.4 2017-9-27 diff --git a/app/manifest.json b/app/manifest.json index 8812f4eea..4d02cd334 100644 --- a/app/manifest.json +++ b/app/manifest.json @@ -1,7 +1,7 @@ { "name": "MetaMask", "short_name": "Metamask", - "version": "3.10.4", + "version": "3.10.5", "manifest_version": 2, "author": "https://metamask.io", "description": "Ethereum Browser Extension", -- cgit v1.2.3 From 1983e161c658979872bad66f8dd5e9b2c7a616b5 Mon Sep 17 00:00:00 2001 From: Dan Finlay Date: Wed, 27 Sep 2017 12:29:09 -0700 Subject: Fix accountTracker store references --- app/scripts/controllers/transactions.js | 2 +- app/scripts/keyring-controller.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 4cd307b07..87521c76b 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -52,7 +52,7 @@ module.exports = class TransactionController extends EventEmitter { provider: this.provider, nonceTracker: this.nonceTracker, getBalance: (address) => { - const account = this.accountTracker.getState().accounts[address] + const account = this.accountTracker.store.getState().accounts[address] if (!account) return return account.balance }, diff --git a/app/scripts/keyring-controller.js b/app/scripts/keyring-controller.js index 34e008ec4..1a1904621 100644 --- a/app/scripts/keyring-controller.js +++ b/app/scripts/keyring-controller.js @@ -568,7 +568,7 @@ class KeyringController extends EventEmitter { clearKeyrings () { let accounts try { - accounts = Object.keys(this.accountTracker.getState()) + accounts = Object.keys(this.accountTracker.store.getState()) } catch (e) { accounts = [] } -- cgit v1.2.3