1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-27 04:46:10 +01:00
metamask-extension/app/scripts/controllers/transactions/tx-state-manager.js

487 lines
15 KiB
JavaScript
Raw Normal View History

import EventEmitter from 'safe-event-emitter'
import ObservableStore from 'obs-store'
import log from 'loglevel'
import txStateHistoryHelper from './lib/tx-state-history-helper'
import createId from '../../lib/random-id'
import { getFinalStates, normalizeTxParams } from './lib/util'
2018-04-19 20:29:26 +02:00
/**
TransactionStateManager is responsible for the state of a transaction and
storing the transaction
it also has some convenience methods for finding subsets of transactions
*
*STATUS METHODS
<br>statuses:
<br> - `'unapproved'` the user has not responded
<br> - `'rejected'` the user has responded no!
<br> - `'approved'` the user has approved the tx
<br> - `'signed'` the tx is signed
<br> - `'submitted'` the tx is sent to a server
<br> - `'confirmed'` the tx has been included in a block.
<br> - `'failed'` the tx failed for some reason, included on tx data.
<br> - `'dropped'` the tx nonce was already used
@param {Object} opts
@param {Object} [opts.initState={ transactions: [] }] initial transactions list with the key transaction {array}
2018-04-25 20:13:51 +02:00
@param {number} [opts.txHistoryLimit] limit for how many finished
2018-04-19 20:29:26 +02:00
transactions can hang around in state
2018-04-25 20:13:51 +02:00
@param {function} opts.getNetwork return network number
2018-04-19 20:29:26 +02:00
@class
*/
class TransactionStateManager extends EventEmitter {
constructor ({ initState, txHistoryLimit, getNetwork }) {
2017-09-12 18:59:59 +02:00
super()
this.store = new ObservableStore(
Object.assign({
2017-09-12 18:59:59 +02:00
transactions: [],
}, initState))
2017-08-11 23:19:35 +02:00
this.txHistoryLimit = txHistoryLimit
this.getNetwork = getNetwork
}
2018-04-19 20:29:26 +02:00
/**
@param {Object} opts - the object to use when overwriting defaults
@returns {txMeta} - the default txMeta object
2018-04-19 20:29:26 +02:00
*/
generateTxMeta (opts) {
const netId = this.getNetwork()
if (netId === 'loading') {
throw new Error('MetaMask is having trouble connecting to the network')
}
return Object.assign({
id: createId(),
time: (new Date()).getTime(),
status: 'unapproved',
metamaskNetworkId: netId,
loadingDefaults: true,
}, opts)
}
2018-04-19 20:29:26 +02:00
/**
@returns {array} - of txMetas that have been filtered for only the current network
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
getTxList () {
const network = this.getNetwork()
const fullTxList = this.getFullTxList()
return fullTxList.filter((txMeta) => txMeta.metamaskNetworkId === network)
}
2018-04-19 20:29:26 +02:00
/**
@returns {array} - of all the txMetas in store
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
getFullTxList () {
2017-09-12 18:59:59 +02:00
return this.store.getState().transactions
2017-08-11 23:19:35 +02:00
}
2018-04-19 20:29:26 +02:00
/**
@returns {array} - the tx list whos status is unapproved
2018-04-19 20:29:26 +02:00
*/
2017-08-18 21:23:35 +02:00
getUnapprovedTxList () {
const txList = this.getTxsByMetaData('status', 'unapproved')
return txList.reduce((result, tx) => {
result[tx.id] = tx
return result
}, {})
}
/**
@param [address] {string} - hex prefixed address to sort the txMetas for [optional]
@returns {array} - the tx list whos status is approved if no address is provide
returns all txMetas who's status is approved for the current network
*/
getApprovedTransactions (address) {
const opts = { status: 'approved' }
if (address) {
opts.from = address
}
return this.getFilteredTxList(opts)
}
2018-04-19 20:29:26 +02:00
/**
2018-04-25 20:13:51 +02:00
@param [address] {string} - hex prefixed address to sort the txMetas for [optional]
@returns {array} - the tx list whos status is submitted if no address is provide
2018-04-25 20:13:51 +02:00
returns all txMetas who's status is submitted for the current network
2018-04-19 20:29:26 +02:00
*/
getPendingTransactions (address) {
const opts = { status: 'submitted' }
if (address) {
opts.from = address
}
2017-09-09 00:02:36 +02:00
return this.getFilteredTxList(opts)
}
2018-04-19 20:29:26 +02:00
/**
2018-04-25 20:13:51 +02:00
@param [address] {string} - hex prefixed address to sort the txMetas for [optional]
@returns {array} - the tx list whos status is confirmed if no address is provide
2018-04-25 20:13:51 +02:00
returns all txMetas who's status is confirmed for the current network
2018-04-19 20:29:26 +02:00
*/
getConfirmedTransactions (address) {
const opts = { status: 'confirmed' }
if (address) {
opts.from = address
}
return this.getFilteredTxList(opts)
}
2018-04-19 20:29:26 +02:00
/**
Adds the txMeta to the list of transactions in the store.
if the list is over txHistoryLimit it will remove a transaction that
is in its final state
it will allso add the key `history` to the txMeta with the snap shot of the original
object
@param {Object} txMeta
@returns {Object} - the txMeta
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
addTx (txMeta) {
// normalize and validate txParams if present
if (txMeta.txParams) {
txMeta.txParams = this.normalizeAndValidateTxParams(txMeta.txParams)
}
this.once(`${txMeta.id}:signed`, function () {
2017-08-18 21:23:35 +02:00
this.removeAllListeners(`${txMeta.id}:rejected`)
})
this.once(`${txMeta.id}:rejected`, function () {
2017-08-18 21:23:35 +02:00
this.removeAllListeners(`${txMeta.id}:signed`)
})
// initialize history
txMeta.history = []
// capture initial snapshot of txMeta for history
const snapshot = txStateHistoryHelper.snapshotFromTxMeta(txMeta)
txMeta.history.push(snapshot)
2017-08-18 21:23:35 +02:00
2017-08-11 23:19:35 +02:00
const transactions = this.getFullTxList()
const txCount = transactions.length
2017-08-11 23:19:35 +02:00
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) {
2018-04-10 23:53:40 +02:00
const index = transactions.findIndex((metaTx) => {
2018-04-19 20:29:26 +02:00
return getFinalStates().includes(metaTx.status)
})
if (index !== -1) {
transactions.splice(index, 1)
}
2017-08-11 23:19:35 +02:00
}
const newTxIndex = transactions
.findIndex((currentTxMeta) => currentTxMeta.time > txMeta.time)
newTxIndex === -1
? transactions.push(txMeta)
: transactions.splice(newTxIndex, 0, txMeta)
2017-08-11 23:19:35 +02:00
this._saveTxList(transactions)
return txMeta
2017-08-11 23:19:35 +02:00
}
2018-04-19 20:29:26 +02:00
/**
@param {number} txId
@returns {Object} - the txMeta who matches the given id if none found
2018-04-19 20:29:26 +02:00
for the network returns undefined
*/
2017-08-11 23:19:35 +02:00
getTx (txId) {
const txMeta = this.getTxsByMetaData('id', txId)[0]
return txMeta
}
2018-04-19 20:29:26 +02:00
/**
updates the txMeta in the list and adds a history entry
@param {Object} txMeta - the txMeta to update
@param {string} [note] - a note about the update for history
2018-04-19 20:29:26 +02:00
*/
updateTx (txMeta, note) {
// normalize and validate txParams if present
if (txMeta.txParams) {
txMeta.txParams = this.normalizeAndValidateTxParams(txMeta.txParams)
}
2017-08-11 23:19:35 +02:00
// create txMeta snapshot for history
const currentState = txStateHistoryHelper.snapshotFromTxMeta(txMeta)
// recover previous tx state obj
const previousState = txStateHistoryHelper.replayHistory(txMeta.history)
// generate history entry and add to history
const entry = txStateHistoryHelper.generateHistoryEntry(previousState, currentState, note)
txMeta.history.push(entry)
// commit txMeta to state
2017-08-11 23:19:35 +02:00
const txId = txMeta.id
const txList = this.getFullTxList()
const index = txList.findIndex(txData => txData.id === txId)
txList[index] = txMeta
this._saveTxList(txList)
}
2018-04-19 20:29:26 +02:00
/**
merges txParams obj onto txMeta.txParams
use extend to ensure that all fields are filled
@param {number} txId - the id of the txMeta
@param {Object} txParams - the updated txParams
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
updateTxParams (txId, txParams) {
const txMeta = this.getTx(txId)
txMeta.txParams = { ...txMeta.txParams, ...txParams }
this.updateTx(txMeta, `txStateManager#updateTxParams`)
2017-08-11 23:19:35 +02:00
}
/**
* normalize and validate txParams members
* @param {Object} txParams - txParams
*/
normalizeAndValidateTxParams (txParams) {
if (typeof txParams.data === 'undefined') {
delete txParams.data
}
txParams = normalizeTxParams(txParams, false)
this.validateTxParams(txParams)
return txParams
}
2018-04-19 20:29:26 +02:00
/**
validates txParams members by type
@param {Object} txParams - txParams to validate
2018-04-19 20:29:26 +02:00
*/
2018-04-10 23:53:40 +02:00
validateTxParams (txParams) {
Object.keys(txParams).forEach((key) => {
const value = txParams[key]
// validate types
switch (key) {
case 'chainId':
if (typeof value !== 'number' && typeof value !== 'string') {
throw new Error(`${key} in txParams is not a Number or hex string. got: (${value})`)
}
break
default:
if (typeof value !== 'string') {
throw new Error(`${key} in txParams is not a string. got: (${value})`)
}
break
}
})
}
/**
@param {Object} opts - an object of fields to search for eg:<br>
2018-04-19 20:29:26 +02:00
let <code>thingsToLookFor = {<br>
to: '0x0..',<br>
from: '0x0..',<br>
status: 'signed', \\ (status) => status !== 'rejected' give me all txs who's status is not rejected<br>
2018-04-19 20:29:26 +02:00
err: undefined,<br>
}<br></code>
optionally the values of the keys can be functions for situations like where
you want all but one status.
2018-04-25 20:13:51 +02:00
@param [initialList=this.getTxList()]
@returns {array} - array of txMeta with all
2017-08-11 23:19:35 +02:00
options matching
2018-04-19 20:29:26 +02:00
*/
/*
2017-08-11 23:19:35 +02:00
****************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 filtering for all txs from one account
2017-08-11 23:19:35 +02:00
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
}
2018-04-19 20:29:26 +02:00
/**
2017-08-11 23:19:35 +02:00
@param {string} key - the key to check
@param value - the value your looking for can also be a function that returns a bool
2018-04-25 20:13:51 +02:00
@param [txList=this.getTxList()] {array} - the list to search. default is the txList
2018-04-19 20:29:26 +02:00
from txStateManager#getTxList
@returns {array} - a list of txMetas who matches the search params
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
getTxsByMetaData (key, value, txList = this.getTxList()) {
const filter = typeof value === 'function' ? value : (v) => v === value
2017-08-11 23:19:35 +02:00
return txList.filter((txMeta) => {
if (key in txMeta.txParams) {
return filter(txMeta.txParams[key])
2017-08-11 23:19:35 +02:00
} else {
return filter(txMeta[key])
2017-08-11 23:19:35 +02:00
}
})
}
// get::set status
2018-04-19 20:29:26 +02:00
/**
@param {number} txId - the txMeta Id
@returns {string} - the status of the tx.
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
getTxStatus (txId) {
const txMeta = this.getTx(txId)
return txMeta.status
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'rejected'.
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
setTxStatusRejected (txId) {
this._setTxStatus(txId, 'rejected')
this._removeTx(txId)
2017-08-11 23:19:35 +02:00
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'unapproved'.
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
2017-12-07 04:20:11 +01:00
setTxStatusUnapproved (txId) {
this._setTxStatus(txId, 'unapproved')
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'approved'.
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
setTxStatusApproved (txId) {
this._setTxStatus(txId, 'approved')
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'signed'.
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
setTxStatusSigned (txId) {
this._setTxStatus(txId, 'signed')
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'submitted'.
and add a time stamp for when it was called
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
setTxStatusSubmitted (txId) {
const txMeta = this.getTx(txId)
txMeta.submittedTime = (new Date()).getTime()
this.updateTx(txMeta, 'txStateManager - add submitted time stamp')
2017-08-11 23:19:35 +02:00
this._setTxStatus(txId, 'submitted')
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'confirmed'.
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
setTxStatusConfirmed (txId) {
this._setTxStatus(txId, 'confirmed')
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'dropped'.
@param {number} txId - the txMeta Id
2018-04-19 20:29:26 +02:00
*/
setTxStatusDropped (txId) {
this._setTxStatus(txId, 'dropped')
}
2018-04-19 20:29:26 +02:00
/**
should update the status of the tx to 'failed'.
and put the error on the txMeta
@param {number} txId - the txMeta Id
@param {erroObject} err - error object
2018-04-19 20:29:26 +02:00
*/
setTxStatusFailed (txId, err) {
const error = !err ? new Error('Internal metamask failure') : err
2017-08-11 23:19:35 +02:00
const txMeta = this.getTx(txId)
txMeta.err = {
message: error.toString(),
rpc: error.value,
stack: error.stack,
}
this.updateTx(txMeta, 'transactions:tx-state-manager#fail - add error')
2017-08-11 23:19:35 +02:00
this._setTxStatus(txId, 'failed')
}
2018-04-19 20:29:26 +02:00
/**
Removes transaction from the given address for the current network
from the txList
@param {string} address - hex string of the from address on the txParams to remove
2018-04-19 20:29:26 +02:00
*/
wipeTransactions (address) {
// network only tx
2018-01-31 19:29:02 +01:00
const txs = this.getFullTxList()
const network = this.getNetwork()
2018-01-31 19:29:02 +01:00
// Filter out the ones from the current account and network
const otherAccountTxs = txs.filter((txMeta) => !(txMeta.txParams.from === address && txMeta.metamaskNetworkId === network))
// Update state
this._saveTxList(otherAccountTxs)
2018-01-31 09:33:15 +01:00
}
//
// PRIVATE METHODS
//
2017-08-11 23:19:35 +02:00
// STATUS METHODS
// statuses:
2017-08-11 23:19:35 +02:00
// - `'unapproved'` the user has not responded
// - `'rejected'` the user has responded no!
// - `'approved'` the user has approved the tx
// - `'signed'` the tx is signed
// - `'submitted'` the tx is sent to a server
// - `'confirmed'` the tx has been included in a block.
// - `'failed'` the tx failed for some reason, included on tx data.
// - `'dropped'` the tx nonce was already used
2018-04-19 20:29:26 +02:00
/**
@param {number} txId - the txMeta Id
@param {string} status - the status to set on the txMeta
2018-04-19 20:29:26 +02:00
@emits tx:status-update - passes txId and status
@emits ${txMeta.id}:finished - if it is a finished state. Passes the txMeta
@emits update:badge
*/
2017-08-11 23:19:35 +02:00
_setTxStatus (txId, status) {
const txMeta = this.getTx(txId)
if (!txMeta) {
return
}
2017-08-11 23:19:35 +02:00
txMeta.status = status
setTimeout(() => {
2018-04-30 01:33:46 +02:00
try {
this.updateTx(txMeta, `txStateManager: setting status to ${status}`)
this.emit(`${txMeta.id}:${status}`, txId)
this.emit(`tx:status-update`, txId, status)
if (['submitted', 'rejected', 'failed'].includes(status)) {
this.emit(`${txMeta.id}:finished`, txMeta)
}
this.emit('update:badge')
} catch (error) {
log.error(error)
}
})
2017-08-11 23:19:35 +02:00
}
2018-04-19 20:29:26 +02:00
/**
Saves the new/updated txList.
@param {array} transactions - the list of transactions to save
2018-04-19 20:29:26 +02:00
*/
2017-08-11 23:19:35 +02:00
// Function is intended only for internal use
_saveTxList (transactions) {
2017-09-12 18:59:59 +02:00
this.store.updateState({ transactions })
2017-08-11 23:19:35 +02:00
}
_removeTx (txId) {
const transactionList = this.getFullTxList()
this._saveTxList(transactionList.filter((txMeta) => txMeta.id !== txId))
}
}
2018-04-19 20:29:26 +02:00
export default TransactionStateManager