forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscribeBlockTracker.ts
More file actions
83 lines (70 loc) · 2.4 KB
/
SubscribeBlockTracker.ts
File metadata and controls
83 lines (70 loc) · 2.4 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
import getCreateRandomId from 'json-rpc-random-id';
import { JsonRpcNotification, JsonRpcSuccess } from 'json-rpc-engine';
import { BaseBlockTracker, Provider } from './BaseBlockTracker';
const createRandomId = getCreateRandomId();
interface SubscribeBlockTrackerArgs {
provider: Provider;
blockResetDuration?: number;
}
interface SubscriptionNotificationParams {
subscription: string;
result: { number: string };
}
export class SubscribeBlockTracker extends BaseBlockTracker {
private _provider: Provider;
private _subscriptionId: string | null;
constructor(opts: Partial<SubscribeBlockTrackerArgs> = {}) {
// parse + validate args
if (!opts.provider) {
throw new Error('SubscribeBlockTracker - no provider specified.');
}
// BaseBlockTracker constructor
super(opts);
// config
this._provider = opts.provider;
this._subscriptionId = null;
}
async checkForLatestBlock(): Promise<string> {
return await this.getLatestBlock();
}
protected 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);
}
}
}
protected 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);
}
}
}
private _call(method: string, ...params: unknown[]): Promise<unknown> {
return new Promise((resolve, reject) => {
this._provider.sendAsync({
id: createRandomId(), method, params, jsonrpc: '2.0',
}, (err, res) => {
if (err) {
reject(err);
} else {
resolve((res as JsonRpcSuccess<unknown>).result);
}
});
});
}
private _handleSubData(_: unknown, response: JsonRpcNotification<SubscriptionNotificationParams>): void {
if (response.method === 'eth_subscription' && response.params?.subscription === this._subscriptionId) {
this._newPotentialLatest(response.params.result.number);
}
}
}