1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-30 08:09:15 +01:00
metamask-extension/app/scripts/transaction-manager.js

380 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-01-14 03:01:50 +01:00
const BN = require('ethereumjs-util').BN
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
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()
2017-02-03 05:59:47 +01:00
let fullTxList = this.store.getState().transactions
return fullTxList.filter(txMeta => txMeta.metamaskNetworkId === network)
}
2016-12-14 21:55:41 +01:00
// Adds a tx to the txlist
addTx (txMeta) {
2016-12-14 21:55:41 +01:00
var txList = this.getTxList()
2016-12-16 19:33:36 +01:00
var txHistoryLimit = this.txHistoryLimit
// checks if the length of th 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
2016-12-16 19:33:36 +01:00
if (txList.length > txHistoryLimit - 1) {
var index = txList.findIndex((metaTx) => metaTx.status === 'confirmed' || metaTx.status === 'rejected')
txList.splice(index, 1)
2016-12-14 21:55:41 +01:00
}
2016-12-16 19:33:36 +01:00
txList.push(txMeta)
2016-12-14 21:55:41 +01:00
this._saveTxList(txList)
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
2016-12-14 21:55:41 +01:00
var txList = this.getTxList()
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),
// prepare txMeta
(cb) => {
// create txMeta obj with parameters and meta data
let time = (new Date()).getTime()
let txId = createId()
txParams.metamaskId = txId
txParams.metamaskNetworkId = this.getNetwork()
txMeta = {
id: txId,
time: time,
status: 'unapproved',
metamaskNetworkId: this.getNetwork(),
txParams: txParams,
}
// calculate metadata for tx
this.txProviderUtils.analyzeGasUsage(txMeta, cb)
},
// save txMeta
(cb) => {
this.addTx(txMeta)
this.setMaxTxCostAndFee(txMeta)
cb(null, txMeta)
},
], done)
2016-12-16 19:33:36 +01:00
}
setMaxTxCostAndFee (txMeta) {
var txParams = txMeta.txParams
var gasCost = new BN(ethUtil.stripHexPrefix(txParams.gas || txMeta.estimatedGas), 16)
var gasPrice = new BN(ethUtil.stripHexPrefix(txParams.gasPrice || '0x4a817c800'), 16)
var txFee = gasCost.mul(gasPrice)
var txValue = new BN(ethUtil.stripHexPrefix(txParams.value || '0x0'), 16)
var maxCost = txValue.add(txFee)
txMeta.txFee = txFee
txMeta.txValue = txValue
txMeta.maxCost = maxCost
2017-02-25 00:06:55 +01:00
txMeta.gasPrice = gasPrice
this.updateTx(txMeta)
}
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) {
this.setTxStatusFailed(txId)
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
}
setTxStatusFailed (txId) {
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-01-12 00:44:21 +01:00
txMeta.err = {
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-01-12 00:44:21 +01:00
this.updateTx(txMeta)
return this.setTxStatusFailed(txId)
}
2017-01-12 00:44:21 +01:00
this.txProviderUtils.query.getTransactionByHash(txHash, (err, txParams) => {
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')