-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathpending-tx-tracker.js
263 lines (234 loc) · 7.97 KB
/
pending-tx-tracker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import EventEmitter from 'safe-event-emitter'
import log from 'loglevel'
import EthQuery from 'ethjs-query'
/**
Event emitter utility class for tracking the transactions as they<br>
go from a pending state to a confirmed (mined in a block) state<br>
<br>
As well as continues broadcast while in the pending state
<br>
@param {Object} config - non optional configuration object consists of:
@param {Object} config.provider - A network provider.
@param {Object} config.nonceTracker see nonce tracker
@param {function} config.getPendingTransactions a function for getting an array of transactions,
@param {function} config.publishTransaction a async function for publishing raw transactions,
@class
*/
export default class PendingTransactionTracker extends EventEmitter {
/**
* We wait this many blocks before emitting a 'tx:dropped' event
*
* This is because we could be talking to a node that is out of sync.
*
* @type {number}
*/
DROPPED_BUFFER_COUNT = 3
/**
* A map of transaction hashes to the number of blocks we've seen
* since first considering it dropped
*
* @type {Map<String, number>}
*/
droppedBlocksBufferByHash = new Map()
constructor(config) {
super()
this.query = config.query || new EthQuery(config.provider)
this.nonceTracker = config.nonceTracker
this.getPendingTransactions = config.getPendingTransactions
this.getCompletedTransactions = config.getCompletedTransactions
this.publishTransaction = config.publishTransaction
this.approveTransaction = config.approveTransaction
this.confirmTransaction = config.confirmTransaction
}
/**
checks the network for signed txs and releases the nonce global lock if it is
*/
async updatePendingTxs() {
// in order to keep the nonceTracker accurate we block it while updating pending transactions
const nonceGlobalLock = await this.nonceTracker.getGlobalLock()
try {
const pendingTxs = this.getPendingTransactions()
await Promise.all(
pendingTxs.map((txMeta) => this._checkPendingTx(txMeta)),
)
} catch (err) {
log.error(
'PendingTransactionTracker - Error updating pending transactions',
)
log.error(err)
}
nonceGlobalLock.releaseLock()
}
/**
* Resubmits each pending transaction
* @param {string} blockNumber - the latest block number in hex
* @emits tx:warning
* @returns {Promise<void>}
*/
async resubmitPendingTxs(blockNumber) {
const pending = this.getPendingTransactions()
if (!pending.length) {
return
}
for (const txMeta of pending) {
try {
await this._resubmitTx(txMeta, blockNumber)
} catch (err) {
const errorMessage =
err.value?.message?.toLowerCase() || err.message.toLowerCase()
const isKnownTx =
// geth
errorMessage.includes('replacement transaction underpriced') ||
errorMessage.includes('known transaction') ||
// parity
errorMessage.includes('gas price too low to replace') ||
errorMessage.includes(
'transaction with the same hash was already imported',
) ||
// other
errorMessage.includes('gateway timeout') ||
errorMessage.includes('nonce too low')
// ignore resubmit warnings, return early
if (isKnownTx) {
return
}
// encountered real error - transition to error state
txMeta.warning = {
error: errorMessage,
message: 'There was an error when resubmitting this transaction.',
}
this.emit('tx:warning', txMeta, err)
}
}
}
/**
* Attempts to resubmit the given transaction with exponential backoff
*
* Will only attempt to retry the given tx every {@code 2**(txMeta.retryCount)} blocks.
*
* @param {Object} txMeta - the transaction metadata
* @param {string} latestBlockNumber - the latest block number in hex
* @returns {Promise<string|undefined>} the tx hash if retried
* @emits tx:block-update
* @emits tx:retry
* @private
*/
async _resubmitTx(txMeta, latestBlockNumber) {
if (!txMeta.firstRetryBlockNumber) {
this.emit('tx:block-update', txMeta, latestBlockNumber)
}
const firstRetryBlockNumber =
txMeta.firstRetryBlockNumber || latestBlockNumber
const txBlockDistance =
Number.parseInt(latestBlockNumber, 16) -
Number.parseInt(firstRetryBlockNumber, 16)
const retryCount = txMeta.retryCount || 0
// Exponential backoff to limit retries at publishing
if (txBlockDistance <= Math.pow(2, retryCount) - 1) {
return undefined
}
// Only auto-submit already-signed txs:
if (!('rawTx' in txMeta)) {
return this.approveTransaction(txMeta.id)
}
const { rawTx } = txMeta
const txHash = await this.publishTransaction(rawTx)
// Increment successful tries:
this.emit('tx:retry', txMeta)
return txHash
}
/**
* Query the network to see if the given {@code txMeta} has been included in a block
* @param {Object} txMeta - the transaction metadata
* @returns {Promise<void>}
* @emits tx:confirmed
* @emits tx:dropped
* @emits tx:failed
* @emits tx:warning
* @private
*/
async _checkPendingTx(txMeta) {
const txHash = txMeta.hash
const txId = txMeta.id
// Only check submitted txs
if (txMeta.status !== 'submitted') {
return
}
// extra check in case there was an uncaught error during the
// signature and submission process
if (!txHash) {
const noTxHashErr = new Error(
'We had an error while submitting this transaction, please try again.',
)
noTxHashErr.name = 'NoTxHashError'
this.emit('tx:failed', txId, noTxHashErr)
return
}
if (await this._checkIfNonceIsTaken(txMeta)) {
this.emit('tx:dropped', txId)
return
}
try {
const transactionReceipt = await this.query.getTransactionReceipt(txHash)
if (transactionReceipt?.blockNumber) {
this.emit('tx:confirmed', txId, transactionReceipt)
return
}
} catch (err) {
txMeta.warning = {
error: err.message,
message: 'There was a problem loading this transaction.',
}
this.emit('tx:warning', txMeta, err)
return
}
if (await this._checkIfTxWasDropped(txMeta)) {
this.emit('tx:dropped', txId)
}
}
/**
* Checks whether the nonce in the given {@code txMeta} is behind the network nonce
*
* @param {Object} txMeta - the transaction metadata
* @returns {Promise<boolean>}
* @private
*/
async _checkIfTxWasDropped(txMeta) {
const {
hash: txHash,
txParams: { nonce, from },
} = txMeta
const networkNextNonce = await this.query.getTransactionCount(from)
if (parseInt(nonce, 16) >= networkNextNonce.toNumber()) {
return false
}
if (!this.droppedBlocksBufferByHash.has(txHash)) {
this.droppedBlocksBufferByHash.set(txHash, 0)
}
const currentBlockBuffer = this.droppedBlocksBufferByHash.get(txHash)
if (currentBlockBuffer < this.DROPPED_BUFFER_COUNT) {
this.droppedBlocksBufferByHash.set(txHash, currentBlockBuffer + 1)
return false
}
this.droppedBlocksBufferByHash.delete(txHash)
return true
}
/**
* Checks whether the nonce in the given {@code txMeta} is correct against the local set of transactions
* @param {Object} txMeta - the transaction metadata
* @returns {Promise<boolean>}
* @private
*/
async _checkIfNonceIsTaken(txMeta) {
const address = txMeta.txParams.from
const completed = this.getCompletedTransactions(address)
return completed.some(
// This is called while the transaction is in-flight, so it is possible that the
// list of completed transactions now includes the transaction we were looking at
// and if that is the case, don't consider the transaction to have taken its own nonce
(other) =>
!(other.id === txMeta.id) &&
other.txParams.nonce === txMeta.txParams.nonce,
)
}
}