2017-06-22 02:28:19 +02:00
|
|
|
const EthQuery = require('eth-query')
|
2017-06-15 07:16:14 +02:00
|
|
|
|
|
|
|
class NonceTracker {
|
|
|
|
|
2017-06-22 04:51:00 +02:00
|
|
|
constructor ({ blockTracker, provider, getPendingTransactions }) {
|
2017-06-15 07:16:14 +02:00
|
|
|
this.blockTracker = blockTracker
|
|
|
|
this.ethQuery = new EthQuery(provider)
|
|
|
|
this.getPendingTransactions = getPendingTransactions
|
|
|
|
this.lockMap = {}
|
|
|
|
}
|
|
|
|
|
|
|
|
// releaseLock must be called
|
|
|
|
// releaseLock must be called after adding signed tx to pending transactions (or discarding)
|
2017-06-22 04:51:00 +02:00
|
|
|
async getNonceLock (address) {
|
2017-06-15 07:16:14 +02:00
|
|
|
// await lock free
|
2017-07-05 21:00:42 +02:00
|
|
|
await this.lockMap[address]
|
2017-06-15 07:16:14 +02:00
|
|
|
// take lock
|
|
|
|
const releaseLock = this._takeLock(address)
|
|
|
|
// calculate next nonce
|
2017-07-05 21:00:42 +02:00
|
|
|
// we need to make sure our base count
|
|
|
|
// and pending count are from the same block
|
|
|
|
const currentBlock = await this._getCurrentBlock()
|
|
|
|
const pendingTransactions = this.getPendingTransactions(address)
|
|
|
|
const baseCount = await this._getTxCount(address, currentBlock)
|
2017-06-22 04:51:00 +02:00
|
|
|
const nextNonce = parseInt(baseCount) + pendingTransactions.length
|
2017-06-15 07:16:14 +02:00
|
|
|
// return next nonce and release cb
|
2017-06-22 02:28:19 +02:00
|
|
|
return { nextNonce: nextNonce.toString(16), releaseLock }
|
2017-06-15 07:16:14 +02:00
|
|
|
}
|
|
|
|
|
2017-06-22 04:51:00 +02:00
|
|
|
async _getCurrentBlock () {
|
2017-06-15 07:16:14 +02:00
|
|
|
const currentBlock = this.blockTracker.getCurrentBlock()
|
|
|
|
if (currentBlock) return currentBlock
|
|
|
|
return await Promise((reject, resolve) => {
|
|
|
|
this.blockTracker.once('latest', resolve)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-06-22 04:51:00 +02:00
|
|
|
_takeLock (lockId) {
|
2017-06-15 07:16:14 +02:00
|
|
|
let releaseLock = null
|
|
|
|
// create and store lock
|
2017-06-22 02:28:19 +02:00
|
|
|
const lock = new Promise((resolve, reject) => { releaseLock = resolve })
|
2017-06-15 07:16:14 +02:00
|
|
|
this.lockMap[lockId] = lock
|
|
|
|
// setup lock teardown
|
2017-06-22 04:51:00 +02:00
|
|
|
lock.then(() => delete this.lockMap[lockId])
|
2017-06-15 07:16:14 +02:00
|
|
|
return releaseLock
|
|
|
|
}
|
|
|
|
|
2017-07-05 21:00:42 +02:00
|
|
|
async _getTxCount (address, currentBlock) {
|
2017-06-28 01:46:14 +02:00
|
|
|
const blockNumber = currentBlock.number
|
2017-06-22 02:28:19 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this.ethQuery.getTransactionCount(address, blockNumber, (err, result) => {
|
|
|
|
err ? reject(err) : resolve(result)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-06-15 07:16:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = NonceTracker
|