forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBaseBlockTracker.js
More file actions
151 lines (151 loc) · 4.92 KB
/
Copy pathBaseBlockTracker.js
File metadata and controls
151 lines (151 loc) · 4.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
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseBlockTracker = void 0;
const safe_event_emitter_1 = __importDefault(require("@metamask/safe-event-emitter"));
const sec = 1000;
const calculateSum = (accumulator, currentValue) => accumulator + currentValue;
const blockTrackerEvents = ['sync', 'latest'];
class BaseBlockTracker extends safe_event_emitter_1.default {
constructor(opts) {
super();
// config
this._blockResetDuration = opts.blockResetDuration || 20 * sec;
// state
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();
}
async destroy() {
await this._maybeEnd();
this._cancelBlockResetTimeout();
super.removeAllListeners();
}
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();
return this;
}
_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) {
// `newListener` is called *before* the listener is added
if (blockTrackerEvents.includes(eventName)) {
this._maybeStart();
}
}
_onRemoveListener() {
// `removeListener` is called *after* the listener is removed
if (this._getBlockTrackerEventCount() > 0) {
return;
}
this._maybeEnd();
}
async _maybeStart() {
if (this._isRunning) {
return;
}
this._isRunning = true;
// cancel setting latest block to stale
this._cancelBlockResetTimeout();
await this._start();
this.emit('_started');
}
async _maybeEnd() {
if (!this._isRunning) {
return;
}
this._isRunning = false;
this._setupBlockResetTimeout();
await this._end();
this.emit('_ended');
}
_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() {
if (this._blockResetTimeout) {
clearTimeout(this._blockResetTimeout);
}
}
_resetCurrentBlock() {
this._currentBlock = null;
}
}
exports.BaseBlockTracker = BaseBlockTracker;
/**
* Converts a number represented as a string in hexadecimal format into a native
* number.
*
* @param hexInt - The hex string.
* @returns The number.
*/
function hexToInt(hexInt) {
return Number.parseInt(hexInt, 16);
}
//# sourceMappingURL=BaseBlockTracker.js.map