forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolling.js
More file actions
87 lines (74 loc) · 2.28 KB
/
polling.js
File metadata and controls
87 lines (74 loc) · 2.28 KB
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
const EthQuery = require('eth-query')
const EventEmitter = require('events')
const pify = require('pify')
const BaseBlockTracker = require('./base')
const sec = 1000
const min = 60 * sec
class PollingBlockTracker extends BaseBlockTracker {
constructor(opts = {}) {
// parse + validate args
if (!opts.provider) throw new Error('PollingBlockTracker - no provider specified.')
const pollingInterval = opts.pollingInterval || 20 * sec
const retryTimeout = opts.retryTimeout || pollingInterval / 10
const keepEventLoopActive = opts.keepEventLoopActive !== undefined ? opts.keepEventLoopActive : true
// BaseBlockTracker constructor
super(Object.assign({
blockResetDuration: pollingInterval,
}, opts))
// config
this._provider = opts.provider
this._pollingInterval = pollingInterval
this._retryTimeout = retryTimeout
this._keepEventLoopActive = keepEventLoopActive
// util
this._query = new EthQuery(this._provider)
}
//
// public
//
// trigger block polling
async checkForLatestBlock() {
await this._updateLatestBlock()
return await this.getLatestBlock()
}
//
// private
//
_start() {
this._performSync().catch(err => this.emit('error', err))
}
async _performSync () {
while (this._isRunning) {
try {
await this._updateLatestBlock()
await timeout(this._pollingInterval, !this._keepEventLoopActive)
} catch (err) {
const newErr = new Error(`PollingBlockTracker - encountered an error while attempting to update latest block:\n${err.stack}`)
try {
this.emit('error', newErr)
} catch (emitErr) {
console.error(newErr)
}
await timeout(this._retryTimeout, !this._keepEventLoopActive)
}
}
}
async _updateLatestBlock () {
// fetch + set latest block
const latestBlock = await this._fetchLatestBlock()
this._newPotentialLatest(latestBlock)
}
async _fetchLatestBlock () {
return await pify(this._query.blockNumber).call(this._query)
}
}
module.exports = PollingBlockTracker
function timeout (duration, unref) {
return new Promise(resolve => {
const timoutRef = setTimeout(resolve, duration)
// don't keep process open
if (timoutRef.unref && unref) {
timoutRef.unref()
}
})
}