1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00
metamask-extension/app/scripts/transaction-manager.js

393 lines
11 KiB
JavaScript
Raw Normal View History

2016-12-14 21:55:41 +01:00
const EventEmitter = require('events')
const async = require('async')
2016-12-14 21:55:41 +01:00
const extend = require('xtend')
const Semaphore = require('semaphore')
const ObservableStore = require('obs-store')
2016-12-16 19:33:36 +01:00
const ethUtil = require('ethereumjs-util')
2017-03-28 22:56:35 +02:00
const EthQuery = require('eth-query')
2016-12-16 19:33:36 +01:00
const TxProviderUtil = require('./lib/tx-utils')
const createId = require('./lib/random-id')
2016-12-14 21:55:41 +01:00
module.exports = class TransactionManager extends EventEmitter {
constructor (opts) {
super()
this.store = new ObservableStore(extend({
2017-02-03 05:59:47 +01:00
transactions: [],
}, opts.initState))
this.memStore = new ObservableStore({})
2017-02-03 05:59:47 +01:00
this.networkStore = opts.networkStore || new ObservableStore({})
2017-02-03 06:09:17 +01:00
this.preferencesStore = opts.preferencesStore || new ObservableStore({})
2016-12-16 19:33:36 +01:00
this.txHistoryLimit = opts.txHistoryLimit
2016-12-14 21:55:41 +01:00
this.provider = opts.provider
2016-12-16 19:33:36 +01:00
this.blockTracker = opts.blockTracker
2017-03-28 22:56:35 +02:00
this.query = new EthQuery(this.provider)
2016-12-16 19:33:36 +01:00
this.txProviderUtils = new TxProviderUtil(this.provider)
2017-01-04 22:13:34 +01:00
this.blockTracker.on('block', this.checkForTxInBlock.bind(this))
this.signEthTx = opts.signTransaction
this.nonceLock = Semaphore(1)
2017-02-03 06:09:17 +01:00
// memstore is computed from a few different stores
this._updateMemstore()
this.store.subscribe(() => this._updateMemstore() )
2017-02-03 05:59:47 +01:00
this.networkStore.subscribe(() => this._updateMemstore() )
2017-02-03 06:09:17 +01:00
this.preferencesStore.subscribe(() => this._updateMemstore() )
2016-12-16 19:33:36 +01:00
}
getState () {
return this.memStore.getState()
2016-12-14 21:55:41 +01:00
}
2017-02-03 05:59:47 +01:00
getNetwork () {
return this.networkStore.getState().network
}
2017-02-03 06:09:17 +01:00
getSelectedAddress () {
return this.preferencesStore.getState().selectedAddress
}
// Returns the tx list
2016-12-14 21:55:41 +01:00
getTxList () {
let network = this.getNetwork()
let fullTxList = this.getFullTxList()
return fullTxList.filter(txMeta => txMeta.metamaskNetworkId === network)
}
// 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
}
2016-12-14 21:55:41 +01:00
// Adds a tx to the txlist
addTx (txMeta) {
let txCount = this.getTxCount()
let network = this.getNetwork()
let fullTxList = this.getFullTxList()
let 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) {
var index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId))
fullTxList.splice(index, 1)
2016-12-14 21:55:41 +01:00
}
fullTxList.push(txMeta)
this._saveTxList(fullTxList)
this.emit('update')
2016-12-16 19:33:36 +01:00
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')
2016-12-16 19:33:36 +01:00
this.emit(`${txMeta.id}:unapproved`, txMeta)
2016-12-14 21:55:41 +01:00
}
2016-12-15 00:04:33 +01:00
// gets tx by Id and returns it
2016-12-14 21:55:41 +01:00
getTx (txId, cb) {
var txList = this.getTxList()
var txMeta = txList.find(txData => txData.id === txId)
2016-12-16 19:33:36 +01:00
return cb ? cb(txMeta) : txMeta
2016-12-14 21:55:41 +01:00
}
2016-12-15 00:04:33 +01:00
//
2016-12-16 19:33:36 +01:00
updateTx (txMeta) {
var txId = txMeta.id
var txList = this.getFullTxList()
var index = txList.findIndex(txData => txData.id === txId)
2016-12-16 19:33:36 +01:00
txList[index] = txMeta
this._saveTxList(txList)
2017-01-12 00:44:21 +01:00
this.emit('update')
2016-12-14 21:55:41 +01:00
}
get unapprovedTxCount () {
2016-12-14 21:55:41 +01:00
return Object.keys(this.getUnapprovedTxList()).length
}
get pendingTxCount () {
return this.getTxsByMetaData('status', 'signed').length
}
addUnapprovedTransaction (txParams, done) {
let txMeta
async.waterfall([
// validate
(cb) => this.txProviderUtils.validateTxParams(txParams, cb),
// construct txMeta
(cb) => {
txMeta = {
id: createId(),
time: (new Date()).getTime(),
status: 'unapproved',
metamaskNetworkId: this.getNetwork(),
txParams: txParams,
}
cb()
},
// add default tx params
(cb) => this.addTxDefaults(txMeta, cb),
// save txMeta
(cb) => {
this.addTx(txMeta)
cb(null, txMeta)
},
], done)
2016-12-16 19:33:36 +01:00
}
addTxDefaults (txMeta, cb) {
const txParams = txMeta.txParams
// ensure value
txParams.value = txParams.value || '0x0'
this.query.gasPrice((err, gasPrice) => {
if (err) return cb(err)
// set gasPrice
txParams.gasPrice = gasPrice
// set gasLimit
this.txProviderUtils.analyzeGasUsage(txMeta, cb)
})
}
2016-12-14 21:55:41 +01:00
getUnapprovedTxList () {
var txList = this.getTxList()
2016-12-16 19:33:36 +01:00
return txList.filter((txMeta) => txMeta.status === 'unapproved')
.reduce((result, tx) => {
2016-12-14 21:55:41 +01:00
result[tx.id] = tx
return result
}, {})
}
approveTransaction (txId, cb = warn) {
const self = this
// approve
self.setTxStatusApproved(txId)
// only allow one tx at a time for atomic nonce usage
self.nonceLock.take(() => {
// begin signature process
async.waterfall([
(cb) => self.fillInTxParams(txId, cb),
(cb) => self.signTransaction(txId, cb),
(rawTx, cb) => self.publishTransaction(txId, rawTx, cb),
], (err) => {
self.nonceLock.leave()
if (err) {
2017-03-22 17:48:41 +01:00
this.setTxStatusFailed(txId, {
errCode: err.errCode || err,
message: err.message || 'Transaction failed during approval',
})
return cb(err)
}
cb()
})
})
2016-12-16 19:33:36 +01:00
}
cancelTransaction (txId, cb = warn) {
2016-12-16 19:33:36 +01:00
this.setTxStatusRejected(txId)
cb()
2016-12-16 19:33:36 +01:00
}
fillInTxParams (txId, cb) {
let txMeta = this.getTx(txId)
this.txProviderUtils.fillInTxParams(txMeta.txParams, (err) => {
if (err) return cb(err)
this.updateTx(txMeta)
cb()
})
}
signTransaction (txId, cb) {
let txMeta = this.getTx(txId)
let txParams = txMeta.txParams
let fromAddress = txParams.from
let ethTx = this.txProviderUtils.buildEthTxFromParams(txParams)
this.signEthTx(ethTx, fromAddress).then(() => {
2017-01-18 20:33:37 +01:00
this.setTxStatusSigned(txMeta.id)
cb(null, ethUtil.bufferToHex(ethTx.serialize()))
}).catch((err) => {
cb(err)
})
}
publishTransaction (txId, rawTx, cb) {
2017-01-18 20:33:37 +01:00
this.txProviderUtils.publishTransaction(rawTx, (err, txHash) => {
if (err) return cb(err)
2017-01-18 20:33:37 +01:00
this.setTxHash(txId, txHash)
this.setTxStatusSubmitted(txId)
cb()
})
}
2017-01-18 20:33:37 +01:00
// receives a txHash records the tx as signed
setTxHash (txId, txHash) {
// Add the tx hash to the persisted meta-tx object
let txMeta = this.getTx(txId)
txMeta.hash = txHash
this.updateTx(txMeta)
2016-12-16 19:33:36 +01:00
}
2016-12-15 00:04:33 +01:00
/*
Takes an object of fields to search for eg:
var thingsToLookFor = {
to: '0x0..',
from: '0x0..',
status: 'signed',
}
and returns a list of tx with all
options matching
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'
*/
2016-12-16 19:33:36 +01:00
getFilteredTxList (opts) {
2016-12-14 21:55:41 +01:00
var filteredTxList
Object.keys(opts).forEach((key) => {
filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList)
})
return filteredTxList
}
getTxsByMetaData (key, value, txList = this.getTxList()) {
2016-12-16 19:33:36 +01:00
return txList.filter((txMeta) => {
if (txMeta.txParams[key]) {
2016-12-16 19:33:36 +01:00
return txMeta.txParams[key] === value
2016-12-14 21:55:41 +01:00
} else {
2016-12-16 19:33:36 +01:00
return txMeta[key] === value
2016-12-14 21:55:41 +01:00
}
})
}
// STATUS METHODS
// get::set status
// should return the status of the tx.
getTxStatus (txId) {
2016-12-16 19:33:36 +01:00
const txMeta = this.getTx(txId)
return txMeta.status
2016-12-14 21:55:41 +01:00
}
// 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')
}
2016-12-14 21:55:41 +01:00
// should update the status of the tx to 'signed'.
2016-12-14 21:55:41 +01:00
setTxStatusSigned (txId) {
2016-12-16 19:33:36 +01:00
this._setTxStatus(txId, 'signed')
2016-12-14 21:55:41 +01:00
}
// should update the status of the tx to 'submitted'.
setTxStatusSubmitted (txId) {
this._setTxStatus(txId, 'submitted')
2016-12-14 21:55:41 +01:00
}
// should update the status of the tx to 'confirmed'.
2016-12-14 21:55:41 +01:00
setTxStatusConfirmed (txId) {
2016-12-16 19:33:36 +01:00
this._setTxStatus(txId, 'confirmed')
2016-12-14 21:55:41 +01:00
}
2017-03-22 17:48:41 +01:00
setTxStatusFailed (txId, reason) {
let txMeta = this.getTx(txId)
txMeta.err = reason
this.updateTx(txMeta)
this._setTxStatus(txId, 'failed')
}
2016-12-14 21:55:41 +01:00
// merges txParams obj onto txData.txParams
// use extend to ensure that all fields are filled
updateTxParams (txId, txParams) {
2016-12-16 19:33:36 +01:00
var txMeta = this.getTx(txId)
txMeta.txParams = extend(txMeta.txParams, txParams)
2016-12-16 19:33:36 +01:00
this.updateTx(txMeta)
2016-12-14 21:55:41 +01:00
}
2016-12-15 00:04:33 +01:00
// checks if a signed tx is in a block and
// if included sets the tx status as 'confirmed'
2016-12-14 21:55:41 +01:00
checkForTxInBlock () {
var signedTxList = this.getFilteredTxList({status: 'submitted'})
2016-12-14 21:55:41 +01:00
if (!signedTxList.length) return
2017-01-12 00:44:21 +01:00
signedTxList.forEach((txMeta) => {
var txHash = txMeta.hash
var txId = txMeta.id
if (!txHash) {
2017-03-22 17:48:41 +01:00
let errReason = {
2017-01-11 21:23:00 +01:00
errCode: 'No hash was provided',
2017-01-12 00:44:21 +01:00
message: 'We had an error while submitting this transaction, please try again.',
2017-01-11 21:23:00 +01:00
}
2017-03-22 17:48:41 +01:00
return this.setTxStatusFailed(txId, errReason)
}
2017-03-28 22:56:35 +02:00
this.query.getTransactionByHash(txHash, (err, txParams) => {
2017-01-12 00:44:21 +01:00
if (err || !txParams) {
if (!txParams) return
txMeta.err = {
isWarning: true,
2017-01-11 21:23:00 +01:00
errorCode: err,
2017-01-12 00:44:21 +01:00
message: 'There was a problem loading this transaction.',
2017-01-11 21:23:00 +01:00
}
2017-01-12 00:44:21 +01:00
this.updateTx(txMeta)
return console.error(err)
2016-12-14 21:55:41 +01:00
}
2017-01-12 00:44:21 +01:00
if (txParams.blockNumber) {
2016-12-16 19:33:36 +01:00
this.setTxStatusConfirmed(txId)
2016-12-14 21:55:41 +01:00
}
})
})
}
2016-12-16 19:33:36 +01:00
// PRIVATE METHODS
2016-12-16 19:33:36 +01:00
// 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
2016-12-16 19:33:36 +01:00
// - `'signed'` the tx is signed
// - `'submitted'` the tx is sent to a server
// - `'confirmed'` the tx has been included in a block.
_setTxStatus (txId, status) {
2016-12-16 19:33:36 +01:00
var txMeta = this.getTx(txId)
txMeta.status = status
this.emit(`${txMeta.id}:${status}`, txId)
if (status === 'submitted' || status === 'rejected') {
this.emit(`${txMeta.id}:finished`, txMeta)
}
2016-12-16 19:33:36 +01:00
this.updateTx(txMeta)
this.emit('updateBadge')
2016-12-16 19:33:36 +01:00
}
// Saves the new/updated txList.
// Function is intended only for internal use
2017-02-03 05:59:47 +01:00
_saveTxList (transactions) {
this.store.updateState({ transactions })
}
_updateMemstore () {
const unapprovedTxs = this.getUnapprovedTxList()
const selectedAddressTxList = this.getFilteredTxList({
from: this.getSelectedAddress(),
metamaskNetworkId: this.getNetwork(),
})
this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
}
2016-12-14 21:55:41 +01:00
}
2016-12-16 19:33:36 +01:00
const warn = () => console.warn('warn was used no cb provided')