forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.js
More file actions
160 lines (133 loc) · 3.92 KB
/
base.js
File metadata and controls
160 lines (133 loc) · 3.92 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
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
const EthQuery = require('eth-query')
const EventEmitter = require('events')
const pify = require('pify')
const sec = 1000
const calculateSum = (accumulator, currentValue) => accumulator + currentValue
const blockTrackerEvents = ['sync', 'latest']
class BaseBlockTracker extends EventEmitter {
//
// public
//
constructor(opts = {}) {
super()
// config
this._blockResetDuration = opts.blockResetDuration || 20 * sec
// state
this._blockResetTimeout
this._currentBlock = null
this._isRunning = false
// bind functions for internal use
this._onNewListener = this._onNewListener.bind(this)
this._onRemoveListener = this._onRemoveListener.bind(this)
this._resetCurrentBlock = this._resetCurrentBlock.bind(this)
// listen for handler changes
this._setupInternalEvents()
}
isRunning() {
return this._isRunning
}
getCurrentBlock () {
return this._currentBlock
}
async getLatestBlock () {
// return if available
if (this._currentBlock) return this._currentBlock
// wait for a new latest block
const latestBlock = await new Promise(resolve => this.once('latest', resolve))
// return newly set current block
return latestBlock
}
// dont allow module consumer to remove our internal event listeners
removeAllListeners(eventName) {
// perform default behavior, preserve fn arity
if (eventName) {
super.removeAllListeners(eventName)
} else {
super.removeAllListeners()
}
// re-add internal events
this._setupInternalEvents()
// trigger stop check just in case
this._onRemoveListener()
}
//
// to be implemented in subclass
//
_start () {
// default behavior is noop
}
_end () {
// default behavior is noop
}
//
// private
//
_setupInternalEvents () {
// first remove listeners for idempotence
this.removeListener('newListener', this._onNewListener)
this.removeListener('removeListener', this._onRemoveListener)
// then add them
this.on('newListener', this._onNewListener)
this.on('removeListener', this._onRemoveListener)
}
_onNewListener (eventName, handler) {
// `newListener` is called *before* the listener is added
if (!blockTrackerEvents.includes(eventName)) return
this._maybeStart()
}
_onRemoveListener (eventName, handler) {
// `removeListener` is called *after* the listener is removed
if (this._getBlockTrackerEventCount() > 0) return
this._maybeEnd()
}
_maybeStart () {
if (this._isRunning) return
this._isRunning = true
// cancel setting latest block to stale
this._cancelBlockResetTimeout()
this._start()
}
_maybeEnd () {
if (!this._isRunning) return
this._isRunning = false
this._setupBlockResetTimeout()
this._end()
}
_getBlockTrackerEventCount () {
return blockTrackerEvents
.map(eventName => this.listenerCount(eventName))
.reduce(calculateSum)
}
_newPotentialLatest (newBlock) {
const currentBlock = this._currentBlock
// only update if blok number is higher
if (currentBlock && (hexToInt(newBlock) <= hexToInt(currentBlock))) return
this._setCurrentBlock(newBlock)
}
_setCurrentBlock (newBlock) {
const oldBlock = this._currentBlock
this._currentBlock = newBlock
this.emit('latest', newBlock)
this.emit('sync', { oldBlock, newBlock })
}
_setupBlockResetTimeout() {
// clear any existing timeout
this._cancelBlockResetTimeout()
// clear latest block when stale
this._blockResetTimeout = setTimeout(this._resetCurrentBlock, this._blockResetDuration)
// nodejs - dont hold process open
if (this._blockResetTimeout.unref) {
this._blockResetTimeout.unref()
}
}
_cancelBlockResetTimeout() {
clearTimeout(this._blockResetTimeout)
}
_resetCurrentBlock () {
this._currentBlock = null
}
}
module.exports = BaseBlockTracker
function hexToInt(hexInt) {
return Number.parseInt(hexInt, 16)
}