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
68 lines (56 loc) · 1.57 KB
/
polling.js
File metadata and controls
68 lines (56 loc) · 1.57 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
const EthQuery = require('eth-query')
const EventEmitter = require('events')
const pify = require('pify')
const BaseBlockTracker = require('./base')
const timeout = (duration) => new Promise(resolve => setTimeout(resolve, duration))
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
// BaseBlockTracker constructor
super(Object.assign({
blockResetDuration: pollingInterval,
}, opts))
// config
this._provider = opts.provider
this._pollingInterval = pollingInterval
// 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()
} catch (err) {
this.emit('error', err)
}
await timeout(this._pollingInterval)
}
}
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