mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-23 09:52:26 +01:00
make addUnapprovedTransaction async function and use promise based ethQuery
This commit is contained in:
parent
5af753a597
commit
432f516ab0
@ -1,10 +1,11 @@
|
|||||||
const EventEmitter = require('events')
|
const EventEmitter = require('events')
|
||||||
const async = require('async')
|
const async = require('async')
|
||||||
const extend = require('xtend')
|
const extend = require('xtend')
|
||||||
|
const pify = require('pify')
|
||||||
const clone = require('clone')
|
const clone = require('clone')
|
||||||
const ObservableStore = require('obs-store')
|
const ObservableStore = require('obs-store')
|
||||||
const ethUtil = require('ethereumjs-util')
|
const ethUtil = require('ethereumjs-util')
|
||||||
const pify = require('pify')
|
const EthQuery = require('ethjs-query');
|
||||||
const TxProviderUtil = require('../lib/tx-utils')
|
const TxProviderUtil = require('../lib/tx-utils')
|
||||||
const getStack = require('../lib/util').getStack
|
const getStack = require('../lib/util').getStack
|
||||||
const createId = require('../lib/random-id')
|
const createId = require('../lib/random-id')
|
||||||
@ -33,7 +34,7 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
this.query = opts.ethQuery
|
this.query = new EthQuery(this.provider)
|
||||||
this.txProviderUtils = new TxProviderUtil(this.query)
|
this.txProviderUtils = new TxProviderUtil(this.query)
|
||||||
this.blockTracker.on('rawBlock', this.checkForTxInBlock.bind(this))
|
this.blockTracker.on('rawBlock', this.checkForTxInBlock.bind(this))
|
||||||
// this is a little messy but until ethstore has been either
|
// this is a little messy but until ethstore has been either
|
||||||
@ -62,13 +63,6 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
return this.preferencesStore.getState().selectedAddress
|
return this.preferencesStore.getState().selectedAddress
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the tx list
|
|
||||||
getTxList () {
|
|
||||||
const network = this.getNetwork()
|
|
||||||
const fullTxList = this.getFullTxList()
|
|
||||||
return fullTxList.filter(txMeta => txMeta.metamaskNetworkId === network)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the number of txs for the current network.
|
// Returns the number of txs for the current network.
|
||||||
getTxCount () {
|
getTxCount () {
|
||||||
return this.getTxList().length
|
return this.getTxList().length
|
||||||
@ -79,6 +73,50 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
return this.store.getState().transactions
|
return this.store.getState().transactions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get unapprovedTxCount () {
|
||||||
|
return Object.keys(this.getUnapprovedTxList()).length
|
||||||
|
}
|
||||||
|
|
||||||
|
get pendingTxCount () {
|
||||||
|
return this.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 () {
|
||||||
|
let txList = this.getTxList()
|
||||||
|
return txList.filter((txMeta) => txMeta.status === 'unapproved')
|
||||||
|
.reduce((result, tx) => {
|
||||||
|
result[tx.id] = tx
|
||||||
|
return result
|
||||||
|
}, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
updateTx (txMeta) {
|
||||||
|
const txMetaForHistory = clone(txMeta)
|
||||||
|
txMetaForHistory.stack = getStack()
|
||||||
|
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
|
// Adds a tx to the txlist
|
||||||
addTx (txMeta) {
|
addTx (txMeta) {
|
||||||
const txCount = this.getTxCount()
|
const txCount = this.getTxCount()
|
||||||
@ -92,7 +130,7 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
// or rejected tx's.
|
// or rejected tx's.
|
||||||
// not tx's that are pending or unapproved
|
// not tx's that are pending or unapproved
|
||||||
if (txCount > txHistoryLimit - 1) {
|
if (txCount > txHistoryLimit - 1) {
|
||||||
var index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId))
|
let index = fullTxList.findIndex((metaTx) => ((metaTx.status === 'confirmed' || metaTx.status === 'rejected') && network === txMeta.metamaskNetworkId))
|
||||||
fullTxList.splice(index, 1)
|
fullTxList.splice(index, 1)
|
||||||
}
|
}
|
||||||
fullTxList.push(txMeta)
|
fullTxList.push(txMeta)
|
||||||
@ -110,86 +148,40 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
this.emit(`${txMeta.id}:unapproved`, txMeta)
|
this.emit(`${txMeta.id}:unapproved`, txMeta)
|
||||||
}
|
}
|
||||||
|
|
||||||
// gets tx by Id and returns it
|
async addUnapprovedTransaction (txParams) {
|
||||||
getTx (txId, cb) {
|
// validate
|
||||||
var txList = this.getTxList()
|
await this.txProviderUtils.validateTxParams(txParams)
|
||||||
var txMeta = txList.find(txData => txData.id === txId)
|
// construct txMeta
|
||||||
return cb ? cb(txMeta) : txMeta
|
const txMeta = {
|
||||||
|
id: createId(),
|
||||||
|
time: (new Date()).getTime(),
|
||||||
|
status: 'unapproved',
|
||||||
|
metamaskNetworkId: this.getNetwork(),
|
||||||
|
txParams: txParams,
|
||||||
|
history: [],
|
||||||
|
}
|
||||||
|
// add default tx params
|
||||||
|
await this.addTxDefaults(txMeta),
|
||||||
|
// save txMeta
|
||||||
|
this.addTx(txMeta)
|
||||||
|
return txMeta
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
async addTxDefaults (txMeta) {
|
||||||
updateTx (txMeta) {
|
|
||||||
const txMetaForHistory = clone(txMeta)
|
|
||||||
txMetaForHistory.stack = getStack()
|
|
||||||
var txId = txMeta.id
|
|
||||||
var txList = this.getFullTxList()
|
|
||||||
var 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')
|
|
||||||
}
|
|
||||||
|
|
||||||
get unapprovedTxCount () {
|
|
||||||
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,
|
|
||||||
history: [],
|
|
||||||
}
|
|
||||||
cb()
|
|
||||||
},
|
|
||||||
// add default tx params
|
|
||||||
(cb) => this.addTxDefaults(txMeta, cb),
|
|
||||||
// save txMeta
|
|
||||||
(cb) => {
|
|
||||||
this.addTx(txMeta)
|
|
||||||
cb(null, txMeta)
|
|
||||||
},
|
|
||||||
], done)
|
|
||||||
}
|
|
||||||
|
|
||||||
addTxDefaults (txMeta, cb) {
|
|
||||||
const txParams = txMeta.txParams
|
const txParams = txMeta.txParams
|
||||||
// ensure value
|
// ensure value
|
||||||
txParams.value = txParams.value || '0x0'
|
txParams.value = txParams.value || '0x0'
|
||||||
if (!txParams.gasPrice) {
|
if (!txParams.gasPrice) {
|
||||||
this.query.gasPrice((err, gasPrice) => {
|
gassPrice = await this.query.gasPrice()
|
||||||
|
txParams.gasPrice = gasPrice
|
||||||
if (err) return cb(err)
|
|
||||||
// set gasPrice
|
|
||||||
txParams.gasPrice = gasPrice
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
// set gasLimit
|
// set gasLimit
|
||||||
this.txProviderUtils.analyzeGasUsage(txMeta, cb)
|
return await this.txProviderUtils.analyzeGasUsage(txMeta)
|
||||||
}
|
}
|
||||||
|
|
||||||
getUnapprovedTxList () {
|
async updateAndApproveTransaction (txMeta) {
|
||||||
var txList = this.getTxList()
|
this.updateTx(txMeta)
|
||||||
return txList.filter((txMeta) => txMeta.status === 'unapproved')
|
await this.approveTransaction(txMeta.id)
|
||||||
.reduce((result, tx) => {
|
|
||||||
result[tx.id] = tx
|
|
||||||
return result
|
|
||||||
}, {})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async approveTransaction (txId) {
|
async approveTransaction (txId) {
|
||||||
@ -221,26 +213,6 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cancelTransaction (txId, cb = warn) {
|
|
||||||
this.setTxStatusRejected(txId)
|
|
||||||
cb()
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateAndApproveTransaction (txMeta) {
|
|
||||||
this.updateTx(txMeta)
|
|
||||||
await this.approveTransaction(txMeta.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
getChainId () {
|
|
||||||
const networkState = this.networkStore.getState()
|
|
||||||
const getChainId = parseInt(networkState)
|
|
||||||
if (Number.isNaN(getChainId)) {
|
|
||||||
return 0
|
|
||||||
} else {
|
|
||||||
return getChainId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async signTransaction (txId) {
|
async signTransaction (txId) {
|
||||||
const txMeta = this.getTx(txId)
|
const txMeta = this.getTx(txId)
|
||||||
const txParams = txMeta.txParams
|
const txParams = txMeta.txParams
|
||||||
@ -265,6 +237,22 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cancelTransaction (txId) {
|
||||||
|
this.setTxStatusRejected(txId)
|
||||||
|
return Promise.resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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
|
// receives a txHash records the tx as signed
|
||||||
setTxHash (txId, txHash) {
|
setTxHash (txId, txHash) {
|
||||||
// Add the tx hash to the persisted meta-tx object
|
// Add the tx hash to the persisted meta-tx object
|
||||||
@ -275,7 +263,7 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
Takes an object of fields to search for eg:
|
Takes an object of fields to search for eg:
|
||||||
var thingsToLookFor = {
|
let thingsToLookFor = {
|
||||||
to: '0x0..',
|
to: '0x0..',
|
||||||
from: '0x0..',
|
from: '0x0..',
|
||||||
status: 'signed',
|
status: 'signed',
|
||||||
@ -298,7 +286,7 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
and that have been 'confirmed'
|
and that have been 'confirmed'
|
||||||
*/
|
*/
|
||||||
getFilteredTxList (opts) {
|
getFilteredTxList (opts) {
|
||||||
var filteredTxList
|
let filteredTxList
|
||||||
Object.keys(opts).forEach((key) => {
|
Object.keys(opts).forEach((key) => {
|
||||||
filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList)
|
filteredTxList = this.getTxsByMetaData(key, opts[key], filteredTxList)
|
||||||
})
|
})
|
||||||
@ -359,7 +347,7 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
// merges txParams obj onto txData.txParams
|
// merges txParams obj onto txData.txParams
|
||||||
// use extend to ensure that all fields are filled
|
// use extend to ensure that all fields are filled
|
||||||
updateTxParams (txId, txParams) {
|
updateTxParams (txId, txParams) {
|
||||||
var txMeta = this.getTx(txId)
|
const txMeta = this.getTx(txId)
|
||||||
txMeta.txParams = extend(txMeta.txParams, txParams)
|
txMeta.txParams = extend(txMeta.txParams, txParams)
|
||||||
this.updateTx(txMeta)
|
this.updateTx(txMeta)
|
||||||
}
|
}
|
||||||
@ -367,20 +355,19 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
// checks if a signed tx is in a block and
|
// checks if a signed tx is in a block and
|
||||||
// if included sets the tx status as 'confirmed'
|
// if included sets the tx status as 'confirmed'
|
||||||
checkForTxInBlock (block) {
|
checkForTxInBlock (block) {
|
||||||
var signedTxList = this.getFilteredTxList({status: 'submitted'})
|
const signedTxList = this.getFilteredTxList({status: 'submitted'})
|
||||||
if (!signedTxList.length) return
|
if (!signedTxList.length) return
|
||||||
signedTxList.forEach((txMeta) => {
|
signedTxList.forEach((txMeta) => {
|
||||||
var txHash = txMeta.hash
|
const txHash = txMeta.hash
|
||||||
var txId = txMeta.id
|
const txId = txMeta.id
|
||||||
|
|
||||||
if (!txHash) {
|
if (!txHash) {
|
||||||
return this.setTxStatusFailed(txId, {
|
const noTxHash = new Error('We had an error while submitting this transaction, please try again.')
|
||||||
stack: 'checkForTxInBlock: custom tx-controller error message',
|
noTxHash.name = 'NoTxHashError'
|
||||||
errCode: 'No hash was provided',
|
this.setTxStatusFailed(noTxHash)
|
||||||
message: 'We had an error while submitting this transaction, please try again.',
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
block.transactions.forEach((tx) => {
|
block.transactions.forEach((tx) => {
|
||||||
if (tx.hash === txHash) this.setTxStatusConfirmed(txId)
|
if (tx.hash === txHash) this.setTxStatusConfirmed(txId)
|
||||||
})
|
})
|
||||||
@ -398,44 +385,6 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
if (diff > 1) this._checkPendingTxs()
|
if (diff > 1) this._checkPendingTxs()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
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({
|
|
||||||
from: this.getSelectedAddress(),
|
|
||||||
metamaskNetworkId: this.getNetwork(),
|
|
||||||
})
|
|
||||||
this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
|
|
||||||
}
|
|
||||||
|
|
||||||
resubmitPendingTxs () {
|
resubmitPendingTxs () {
|
||||||
const pending = this.getTxsByMetaData('status', 'submitted')
|
const pending = this.getTxsByMetaData('status', 'submitted')
|
||||||
// only try resubmitting if their are transactions to resubmit
|
// only try resubmitting if their are transactions to resubmit
|
||||||
@ -469,6 +418,44 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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({
|
||||||
|
from: this.getSelectedAddress(),
|
||||||
|
metamaskNetworkId: this.getNetwork(),
|
||||||
|
})
|
||||||
|
this.memStore.updateState({ unapprovedTxs, selectedAddressTxList })
|
||||||
|
}
|
||||||
|
|
||||||
async _resubmitTx (txMeta) {
|
async _resubmitTx (txMeta) {
|
||||||
const address = txMeta.txParams.from
|
const address = txMeta.txParams.from
|
||||||
const balance = this.ethStore.getState().accounts[address].balance
|
const balance = this.ethStore.getState().accounts[address].balance
|
||||||
@ -515,17 +502,14 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
// extra check in case there was an uncaught error during the
|
// extra check in case there was an uncaught error during the
|
||||||
// signature and submission process
|
// signature and submission process
|
||||||
if (!txHash) {
|
if (!txHash) {
|
||||||
this.setTxStatusFailed(txId, {
|
const noTxHash = new Error('We had an error while submitting this transaction, please try again.')
|
||||||
stack: '_checkPendingTxs: custom tx-controller error message',
|
noTxHash.name = 'NoTxHashError'
|
||||||
errCode: 'No hash was provided',
|
this.setTxStatusFailed(noTxHash)
|
||||||
message: 'We had an error while submitting this transaction, please try again.',
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
// get latest transaction status
|
// get latest transaction status
|
||||||
let txParams
|
let txParams
|
||||||
try {
|
try {
|
||||||
txParams = await pify((cb) => this.query.getTransactionByHash(txHash, cb))()
|
txParams = await this.query.getTransactionByHash(txHash)
|
||||||
if (!txParams) return
|
if (!txParams) return
|
||||||
if (txParams.blockNumber) {
|
if (txParams.blockNumber) {
|
||||||
this.setTxStatusConfirmed(txId)
|
this.setTxStatusConfirmed(txId)
|
||||||
@ -538,12 +522,8 @@ module.exports = class TransactionController extends EventEmitter {
|
|||||||
message: 'There was a problem loading this transaction.',
|
message: 'There was a problem loading this transaction.',
|
||||||
}
|
}
|
||||||
this.updateTx(txMeta)
|
this.updateTx(txMeta)
|
||||||
log.error(err)
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const warn = () => log.warn('warn was used no cb provided')
|
|
@ -10,24 +10,18 @@ its passed ethquery
|
|||||||
and used to do things like calculate gas of a tx.
|
and used to do things like calculate gas of a tx.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
module.exports = class txProviderUtils {
|
module.exports = class txProvideUtils {
|
||||||
|
|
||||||
constructor (ethQuery) {
|
constructor (ethQuery) {
|
||||||
this.query = ethQuery
|
this.query = ethQuery
|
||||||
}
|
}
|
||||||
|
|
||||||
analyzeGasUsage (txMeta, cb) {
|
async analyzeGasUsage (txMeta) {
|
||||||
var self = this
|
const block = await this.query.getBlockByNumber('latest', true)
|
||||||
this.query.getBlockByNumber('latest', true, (err, block) => {
|
const estimatedGasHex = await this.estimateTxGas(txMeta, block.gasLimit)
|
||||||
if (err) return cb(err)
|
this.setTxGas(txMeta, block.gasLimit, estimatedGasHex)
|
||||||
async.waterfall([
|
|
||||||
self.estimateTxGas.bind(self, txMeta, block.gasLimit),
|
|
||||||
self.setTxGas.bind(self, txMeta, block.gasLimit),
|
|
||||||
], cb)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
estimateTxGas (txMeta, blockGasLimitHex, cb) {
|
async estimateTxGas (txMeta, blockGasLimitHex) {
|
||||||
const txParams = txMeta.txParams
|
const txParams = txMeta.txParams
|
||||||
// check if gasLimit is already specified
|
// check if gasLimit is already specified
|
||||||
txMeta.gasLimitSpecified = Boolean(txParams.gas)
|
txMeta.gasLimitSpecified = Boolean(txParams.gas)
|
||||||
@ -38,10 +32,10 @@ module.exports = class txProviderUtils {
|
|||||||
txParams.gas = bnToHex(saferGasLimitBN)
|
txParams.gas = bnToHex(saferGasLimitBN)
|
||||||
}
|
}
|
||||||
// run tx, see if it will OOG
|
// run tx, see if it will OOG
|
||||||
this.query.estimateGas(txParams, cb)
|
return await this.query.estimateGas(txParams)
|
||||||
}
|
}
|
||||||
|
|
||||||
setTxGas (txMeta, blockGasLimitHex, estimatedGasHex, cb) {
|
setTxGas (txMeta, blockGasLimitHex, estimatedGasHex) {
|
||||||
txMeta.estimatedGas = estimatedGasHex
|
txMeta.estimatedGas = estimatedGasHex
|
||||||
const txParams = txMeta.txParams
|
const txParams = txMeta.txParams
|
||||||
|
|
||||||
@ -49,14 +43,12 @@ module.exports = class txProviderUtils {
|
|||||||
// use original specified amount
|
// use original specified amount
|
||||||
if (txMeta.gasLimitSpecified) {
|
if (txMeta.gasLimitSpecified) {
|
||||||
txMeta.estimatedGas = txParams.gas
|
txMeta.estimatedGas = txParams.gas
|
||||||
cb()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// if gasLimit not originally specified,
|
// if gasLimit not originally specified,
|
||||||
// try adding an additional gas buffer to our estimation for safety
|
// try adding an additional gas buffer to our estimation for safety
|
||||||
const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex)
|
const recommendedGasHex = this.addGasBuffer(txMeta.estimatedGas, blockGasLimitHex)
|
||||||
txParams.gas = recommendedGasHex
|
txParams.gas = recommendedGasHex
|
||||||
cb()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,22 +66,6 @@ module.exports = class txProviderUtils {
|
|||||||
return bnToHex(upperGasLimitBn)
|
return bnToHex(upperGasLimitBn)
|
||||||
}
|
}
|
||||||
|
|
||||||
fillInTxParams (txParams, cb) {
|
|
||||||
const fromAddress = txParams.from
|
|
||||||
const reqs = {}
|
|
||||||
|
|
||||||
if (isUndef(txParams.gas)) reqs.gas = (cb) => this.query.estimateGas(txParams, cb)
|
|
||||||
if (isUndef(txParams.gasPrice)) reqs.gasPrice = (cb) => this.query.gasPrice(cb)
|
|
||||||
if (isUndef(txParams.nonce)) reqs.nonce = (cb) => this.query.getTransactionCount(fromAddress, 'pending', cb)
|
|
||||||
|
|
||||||
async.parallel(reqs, function (err, result) {
|
|
||||||
if (err) return cb(err)
|
|
||||||
// write results to txParams obj
|
|
||||||
Object.assign(txParams, result)
|
|
||||||
cb()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// builds ethTx from txParams object
|
// builds ethTx from txParams object
|
||||||
buildEthTxFromParams (txParams) {
|
buildEthTxFromParams (txParams) {
|
||||||
// normalize values
|
// normalize values
|
||||||
@ -107,20 +83,17 @@ module.exports = class txProviderUtils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
publishTransaction (rawTx) {
|
publishTransaction (rawTx) {
|
||||||
return new Promise((resolve, reject) => {
|
return this.query.sendRawTransaction(rawTx)
|
||||||
this.query.sendRawTransaction(rawTx, (err, ress) => {
|
|
||||||
if (err) reject(err)
|
|
||||||
else resolve(ress)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
validateTxParams (txParams, cb) {
|
validateTxParams (txParams) {
|
||||||
if (('value' in txParams) && txParams.value.indexOf('-') === 0) {
|
return new Promise ((resolve, reject) => {
|
||||||
cb(new Error(`Invalid transaction value of ${txParams.value} not a positive number.`))
|
if (('value' in txParams) && txParams.value.indexOf('-') === 0) {
|
||||||
} else {
|
reject(new Error(`Invalid transaction value of ${txParams.value} not a positive number.`))
|
||||||
cb()
|
} else {
|
||||||
}
|
resolve()
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
sufficientBalance (txParams, hexBalance) {
|
sufficientBalance (txParams, hexBalance) {
|
||||||
|
@ -195,7 +195,7 @@ module.exports = class MetamaskController extends EventEmitter {
|
|||||||
cb(null, result)
|
cb(null, result)
|
||||||
},
|
},
|
||||||
// tx signing
|
// tx signing
|
||||||
processTransaction: (txParams, cb) => this.newUnapprovedTransaction(txParams, cb),
|
processTransaction: nodeify(this.newUnapprovedTransaction, this),
|
||||||
// old style msg signing
|
// old style msg signing
|
||||||
processMessage: this.newUnsignedMessage.bind(this),
|
processMessage: this.newUnsignedMessage.bind(this),
|
||||||
|
|
||||||
@ -308,7 +308,7 @@ module.exports = class MetamaskController extends EventEmitter {
|
|||||||
exportAccount: nodeify(keyringController.exportAccount, keyringController),
|
exportAccount: nodeify(keyringController.exportAccount, keyringController),
|
||||||
|
|
||||||
// txController
|
// txController
|
||||||
cancelTransaction: txController.cancelTransaction.bind(txController),
|
cancelTransaction: nodeify(txController.cancelTransaction, txController),
|
||||||
updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController),
|
updateAndApproveTransaction: nodeify(txController.updateAndApproveTransaction, txController),
|
||||||
|
|
||||||
// messageManager
|
// messageManager
|
||||||
@ -440,22 +440,21 @@ module.exports = class MetamaskController extends EventEmitter {
|
|||||||
// Identity Management
|
// Identity Management
|
||||||
//
|
//
|
||||||
|
|
||||||
newUnapprovedTransaction (txParams, cb) {
|
async newUnapprovedTransaction (txParams) {
|
||||||
log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
|
log.debug(`MetaMaskController newUnapprovedTransaction ${JSON.stringify(txParams)}`)
|
||||||
const self = this
|
const txMeta = await this.txController.addUnapprovedTransaction(txParams)
|
||||||
self.txController.addUnapprovedTransaction(txParams, (err, txMeta) => {
|
this.sendUpdate()
|
||||||
if (err) return cb(err)
|
this.opts.showUnapprovedTx(txMeta)
|
||||||
self.sendUpdate()
|
// listen for tx completion (success, fail)
|
||||||
self.opts.showUnapprovedTx(txMeta)
|
return new Promise ((resolve, reject) => {
|
||||||
// listen for tx completion (success, fail)
|
this.txController.once(`${txMeta.id}:finished`, (completedTx) => {
|
||||||
self.txController.once(`${txMeta.id}:finished`, (completedTx) => {
|
|
||||||
switch (completedTx.status) {
|
switch (completedTx.status) {
|
||||||
case 'submitted':
|
case 'submitted':
|
||||||
return cb(null, completedTx.hash)
|
return reoslve(completedTx.hash)
|
||||||
case 'rejected':
|
case 'rejected':
|
||||||
return cb(new Error('MetaMask Tx Signature: User denied transaction signature.'))
|
return reject(new Error('MetaMask Tx Signature: User denied transaction signature.'))
|
||||||
default:
|
default:
|
||||||
return cb(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(completedTx.txParams)}`))
|
return reject(new Error(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(completedTx.txParams)}`))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@ -646,6 +645,4 @@ module.exports = class MetamaskController extends EventEmitter {
|
|||||||
return Promise.resolve(rpcTarget)
|
return Promise.resolve(rpcTarget)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
|
@ -77,6 +77,7 @@
|
|||||||
"ethereumjs-util": "ethereumjs/ethereumjs-util#ac5d0908536b447083ea422b435da27f26615de9",
|
"ethereumjs-util": "ethereumjs/ethereumjs-util#ac5d0908536b447083ea422b435da27f26615de9",
|
||||||
"ethereumjs-wallet": "^0.6.0",
|
"ethereumjs-wallet": "^0.6.0",
|
||||||
"ethjs-ens": "^2.0.0",
|
"ethjs-ens": "^2.0.0",
|
||||||
|
"ethjs-query": "^0.2.6",
|
||||||
"express": "^4.14.0",
|
"express": "^4.14.0",
|
||||||
"extension-link-enabler": "^1.0.0",
|
"extension-link-enabler": "^1.0.0",
|
||||||
"extensionizer": "^1.0.0",
|
"extensionizer": "^1.0.0",
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
const assert = require('assert')
|
const assert = require('assert')
|
||||||
const ethUtil = require('ethereumjs-util')
|
const ethUtil = require('ethereumjs-util')
|
||||||
const EthTx = require('ethereumjs-tx')
|
const EthTx = require('ethereumjs-tx')
|
||||||
const EthQuery = require('eth-query')
|
|
||||||
const ObservableStore = require('obs-store')
|
const ObservableStore = require('obs-store')
|
||||||
const clone = require('clone')
|
const clone = require('clone')
|
||||||
const sinon = require('sinon')
|
const sinon = require('sinon')
|
||||||
@ -11,7 +10,7 @@ const currentNetworkId = 42
|
|||||||
const otherNetworkId = 36
|
const otherNetworkId = 36
|
||||||
const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex')
|
const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex')
|
||||||
|
|
||||||
describe('Transaction Controller', function () {
|
describe.only('Transaction Controller', function () {
|
||||||
let txController
|
let txController
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
@ -20,7 +19,6 @@ describe('Transaction Controller', function () {
|
|||||||
txHistoryLimit: 10,
|
txHistoryLimit: 10,
|
||||||
blockTracker: { getCurrentBlock: noop, on: noop, once: noop },
|
blockTracker: { getCurrentBlock: noop, on: noop, once: noop },
|
||||||
provider: { sendAsync: noop },
|
provider: { sendAsync: noop },
|
||||||
ethQuery: new EthQuery({ sendAsync: noop }),
|
|
||||||
ethStore: { getState: noop },
|
ethStore: { getState: noop },
|
||||||
signTransaction: (ethTx) => new Promise((resolve) => {
|
signTransaction: (ethTx) => new Promise((resolve) => {
|
||||||
ethTx.sign(privKey)
|
ethTx.sign(privKey)
|
||||||
@ -28,24 +26,59 @@ describe('Transaction Controller', function () {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop })
|
txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop })
|
||||||
|
const queryStubResult = {}
|
||||||
|
txController.query = new Proxy({}, {
|
||||||
|
get: (_, key) => {
|
||||||
|
if (key === 'stubResult') {
|
||||||
|
return function (method, ...args) {
|
||||||
|
queryStubResult[method] = args
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
returnValue = queryStubResult[key]
|
||||||
|
return () => Promise.resolve(...returnValue)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('#addUnapprovedTransaction', function () {
|
||||||
|
it('should add an unapproved transaction and return a valid txMeta', function (done) {
|
||||||
|
const addTxDefaultsStub = sinon.stub(txController, 'addTxDefaults').callsFake(() => Promise.resolve)
|
||||||
|
txController.addUnapprovedTransaction({})
|
||||||
|
.then((txMeta) => {
|
||||||
|
assert(('id' in txMeta), 'should have a id')
|
||||||
|
assert(('time' in txMeta), 'should have a time stamp')
|
||||||
|
assert(('metamaskNetworkId' in txMeta), 'should have a metamaskNetworkId')
|
||||||
|
assert(('txParams' in txMeta), 'should have a txParams')
|
||||||
|
assert(('history' in txMeta), 'should have a history')
|
||||||
|
|
||||||
|
const memTxMeta = txController.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()
|
||||||
|
}).catch(done)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('#validateTxParams', function () {
|
describe('#validateTxParams', function () {
|
||||||
it('returns null for positive values', function () {
|
it('does not throw for positive values', function (done) {
|
||||||
var sample = {
|
var sample = {
|
||||||
value: '0x01',
|
value: '0x01',
|
||||||
}
|
}
|
||||||
txController.txProviderUtils.validateTxParams(sample, (err) => {
|
txController.txProviderUtils.validateTxParams(sample).then(() => {
|
||||||
assert.equal(err, null, 'no error')
|
done()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('returns error for negative values', function () {
|
it('returns error for negative values', function (done) {
|
||||||
var sample = {
|
var sample = {
|
||||||
value: '-0x01',
|
value: '-0x01',
|
||||||
}
|
}
|
||||||
txController.txProviderUtils.validateTxParams(sample, (err) => {
|
txController.txProviderUtils.validateTxParams(sample)
|
||||||
|
.then(() => done('expected to thrown on negativity values but didn\'t'))
|
||||||
|
.catch((err) => {
|
||||||
assert.ok(err, 'error')
|
assert.ok(err, 'error')
|
||||||
|
done()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@ -56,9 +89,6 @@ describe('Transaction Controller', function () {
|
|||||||
assert.ok(Array.isArray(result))
|
assert.ok(Array.isArray(result))
|
||||||
assert.equal(result.length, 0)
|
assert.equal(result.length, 0)
|
||||||
})
|
})
|
||||||
it('should also return transactions from local storage if any', function () {
|
|
||||||
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('#addTx', function () {
|
describe('#addTx', function () {
|
||||||
@ -276,16 +306,15 @@ describe('Transaction Controller', function () {
|
|||||||
|
|
||||||
txController.addTx(txMeta)
|
txController.addTx(txMeta)
|
||||||
|
|
||||||
const estimateStub = sinon.stub(txController.txProviderUtils.query, 'estimateGas')
|
txController.query.stubResult('estimateGas', wrongValue)
|
||||||
.callsArgWithAsync(1, null, wrongValue)
|
txController.query.stubResult('gasPrice', wrongValue)
|
||||||
|
|
||||||
const priceStub = sinon.stub(txController.txProviderUtils.query, 'gasPrice')
|
const signStub = sinon.stub(txController, 'signTransaction').callsFake(() => Promise.resolve())
|
||||||
.callsArgWithAsync(0, null, wrongValue)
|
|
||||||
|
|
||||||
|
const pubStub = sinon.stub(txController, 'publishTransaction').callsFake(() => {
|
||||||
const signStub = sinon.stub(txController, 'signTransaction', () => Promise.resolve())
|
txController.setTxHash('1', originalValue)
|
||||||
|
txController.setTxStatusSubmitted('1')
|
||||||
const pubStub = sinon.stub(txController.txProviderUtils, 'publishTransaction', () => Promise.resolve(originalValue))
|
})
|
||||||
|
|
||||||
txController.approveTransaction(txMeta.id).then(() => {
|
txController.approveTransaction(txMeta.id).then(() => {
|
||||||
const result = txController.getTx(txMeta.id)
|
const result = txController.getTx(txMeta.id)
|
||||||
@ -294,9 +323,6 @@ describe('Transaction Controller', function () {
|
|||||||
assert.equal(params.gas, originalValue, 'gas unmodified')
|
assert.equal(params.gas, originalValue, 'gas unmodified')
|
||||||
assert.equal(params.gasPrice, originalValue, 'gas price unmodified')
|
assert.equal(params.gasPrice, originalValue, 'gas price unmodified')
|
||||||
assert.equal(result.hash, originalValue, `hash was set \n got: ${result.hash} \n expected: ${originalValue}`)
|
assert.equal(result.hash, originalValue, `hash was set \n got: ${result.hash} \n expected: ${originalValue}`)
|
||||||
|
|
||||||
estimateStub.restore()
|
|
||||||
priceStub.restore()
|
|
||||||
signStub.restore()
|
signStub.restore()
|
||||||
pubStub.restore()
|
pubStub.restore()
|
||||||
done()
|
done()
|
||||||
@ -352,7 +378,7 @@ describe('Transaction Controller', function () {
|
|||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
assert.ifError(err, 'should not throw an error')
|
assert.ifError(err, 'should not throw an error')
|
||||||
done()
|
done(err)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
const assert = require('assert')
|
const assert = require('assert')
|
||||||
|
const sinon = require('sinon')
|
||||||
const ethUtil = require('ethereumjs-util')
|
const ethUtil = require('ethereumjs-util')
|
||||||
const BN = ethUtil.BN
|
const BN = ethUtil.BN
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user