1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 11:46:13 +02:00
metamask-extension/app/scripts/lib/nonce-tracker.js

66 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-06-22 02:28:19 +02:00
const EthQuery = require('eth-query')
const assert = require('assert')
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 pendingCount = pendingTransactions.length
assert(Number.isInteger(pendingCount), 'nonce-tracker - pendingCount is an integer')
const baseCountHex = await this._getTxCount(address, currentBlock)
const baseCount = parseInt(baseCountHex, 16)
assert(Number.isInteger(baseCount), 'nonce-tracker - baseCount is an integer')
const nextNonce = baseCount + pendingCount
assert(Number.isInteger(nextNonce), 'nonce-tracker - nextNonce is an integer')
2017-06-15 07:16:14 +02:00
// return next nonce and release cb
return { nextNonce: '0x' + 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) {
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