This repository was archived by the owner on Oct 16, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathSubscribeBlockTracker.ts
More file actions
332 lines (278 loc) · 8.68 KB
/
SubscribeBlockTracker.ts
File metadata and controls
332 lines (278 loc) · 8.68 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
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import SafeEventEmitter from '@metamask/safe-event-emitter';
import {
createDeferredPromise,
type DeferredPromise,
type Json,
type JsonRpcNotification,
} from '@metamask/utils';
import getCreateRandomId from 'json-rpc-random-id';
import type { BlockTracker } from './BlockTracker';
const createRandomId = getCreateRandomId();
const sec = 1000;
const blockTrackerEvents: (string | symbol)[] = ['sync', 'latest'];
export interface SubscribeBlockTrackerOptions {
provider?: SafeEventEmitterProvider;
blockResetDuration?: number;
usePastBlocks?: boolean;
}
interface SubscriptionNotificationParams {
[key: string]: Json;
subscription: string;
result: { number: string };
}
type InternalListener = (value: string) => void;
export class SubscribeBlockTracker
extends SafeEventEmitter
implements BlockTracker
{
private _isRunning: boolean;
private readonly _blockResetDuration: number;
private readonly _usePastBlocks: boolean;
private _currentBlock: string | null;
private _blockResetTimeout?: ReturnType<typeof setTimeout>;
private readonly _provider: SafeEventEmitterProvider;
private _subscriptionId: string | null;
readonly #internalEventListeners: InternalListener[] = [];
#pendingLatestBlock?: Omit<DeferredPromise<string>, 'resolve'>;
constructor(opts: SubscribeBlockTrackerOptions = {}) {
// parse + validate args
if (!opts.provider) {
throw new Error('SubscribeBlockTracker - no provider specified.');
}
super();
// config
this._blockResetDuration = opts.blockResetDuration || 20 * sec;
this._usePastBlocks = opts.usePastBlocks || false;
// 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();
// config
this._provider = opts.provider;
this._subscriptionId = null;
}
async destroy() {
this._cancelBlockResetTimeout();
await this._maybeEnd();
super.removeAllListeners();
this.#rejectPendingLatestBlock(new Error('Block tracker destroyed'));
}
isRunning(): boolean {
return this._isRunning;
}
getCurrentBlock(): string | null {
return this._currentBlock;
}
async getLatestBlock(): Promise<string> {
// return if available
if (this._currentBlock) {
return this._currentBlock;
} else if (this.#pendingLatestBlock) {
return await this.#pendingLatestBlock.promise;
}
const { resolve, reject, promise } = createDeferredPromise<string>({
suppressUnhandledRejection: true,
});
this.#pendingLatestBlock = { reject, promise };
// wait for a new latest block
const onLatestBlock = (value: string) => {
this.#removeInternalListener(onLatestBlock);
resolve(value);
this.#pendingLatestBlock = undefined;
};
this.#addInternalListener(onLatestBlock);
this.once('latest', onLatestBlock);
return await promise;
}
// dont allow module consumer to remove our internal event listeners
removeAllListeners(eventName?: string | symbol) {
// 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;
}
private _setupInternalEvents(): void {
// 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);
}
private _onNewListener(eventName: string | symbol): void {
// `newListener` is called *before* the listener is added
if (blockTrackerEvents.includes(eventName)) {
// TODO: Handle dangling promise
this._maybeStart();
}
}
private _onRemoveListener(): void {
// `removeListener` is called *after* the listener is removed
if (this._getBlockTrackerEventCount() > 0) {
return;
}
this._maybeEnd();
}
private async _maybeStart(): Promise<void> {
if (this._isRunning) {
return;
}
this._isRunning = true;
// cancel setting latest block to stale
this._cancelBlockResetTimeout();
await this._start();
this.emit('_started');
}
private async _maybeEnd(): Promise<void> {
if (!this._isRunning) {
return;
}
this._isRunning = false;
this._setupBlockResetTimeout();
await this._end();
this.emit('_ended');
}
private _getBlockTrackerEventCount(): number {
return (
blockTrackerEvents
.map((eventName) => this.listeners(eventName))
.flat()
// internal listeners are not included in the count
.filter((listener) =>
this.#internalEventListeners.every(
(internalListener) => !Object.is(internalListener, listener),
),
).length
);
}
private _shouldUseNewBlock(newBlock: string) {
const currentBlock = this._currentBlock;
if (!currentBlock) {
return true;
}
const newBlockInt = hexToInt(newBlock);
const currentBlockInt = hexToInt(currentBlock);
return (
(this._usePastBlocks && newBlockInt < currentBlockInt) ||
newBlockInt > currentBlockInt
);
}
private _newPotentialLatest(newBlock: string): void {
if (!this._shouldUseNewBlock(newBlock)) {
return;
}
this._setCurrentBlock(newBlock);
}
private _setCurrentBlock(newBlock: string): void {
const oldBlock = this._currentBlock;
this._currentBlock = newBlock;
this.emit('latest', newBlock);
this.emit('sync', { oldBlock, newBlock });
}
private _setupBlockResetTimeout(): void {
// 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();
}
}
private _cancelBlockResetTimeout(): void {
if (this._blockResetTimeout) {
clearTimeout(this._blockResetTimeout);
}
}
private _resetCurrentBlock(): void {
this._currentBlock = null;
}
async checkForLatestBlock(): Promise<string> {
return await this.getLatestBlock();
}
private async _start(): Promise<void> {
if (this._subscriptionId === undefined || this._subscriptionId === null) {
try {
const blockNumber = (await this._call('eth_blockNumber')) as string;
this._subscriptionId = (await this._call(
'eth_subscribe',
'newHeads',
)) as string;
this._provider.on('data', this._handleSubData.bind(this));
this._newPotentialLatest(blockNumber);
} catch (e) {
this.emit('error', e);
this.#rejectPendingLatestBlock(e);
}
}
}
private async _end() {
if (this._subscriptionId !== null && this._subscriptionId !== undefined) {
try {
await this._call('eth_unsubscribe', this._subscriptionId);
this._subscriptionId = null;
} catch (e) {
this.emit('error', e);
this.#rejectPendingLatestBlock(e);
}
}
}
private async _call(method: string, ...params: Json[]): Promise<unknown> {
return this._provider.request({
id: createRandomId(),
method,
params,
jsonrpc: '2.0',
});
}
private _handleSubData(
_: unknown,
response: JsonRpcNotification<SubscriptionNotificationParams>,
): void {
if (
response.method === 'eth_subscription' &&
response.params?.subscription === this._subscriptionId
) {
this._newPotentialLatest(response.params.result.number);
}
}
#addInternalListener(listener: InternalListener) {
this.#internalEventListeners.push(listener);
}
#removeInternalListener(listener: InternalListener) {
this.#internalEventListeners.splice(
this.#internalEventListeners.indexOf(listener),
1,
);
}
#rejectPendingLatestBlock(error: unknown) {
this.#pendingLatestBlock?.reject(error);
this.#pendingLatestBlock = undefined;
}
}
/**
* 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: string): number {
return Number.parseInt(hexInt, 16);
}