forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSubscribeBlockTracker.js
More file actions
75 lines (75 loc) · 2.64 KB
/
Copy pathSubscribeBlockTracker.js
File metadata and controls
75 lines (75 loc) · 2.64 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
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubscribeBlockTracker = void 0;
const json_rpc_random_id_1 = __importDefault(require("json-rpc-random-id"));
const BaseBlockTracker_1 = require("./BaseBlockTracker");
const createRandomId = (0, json_rpc_random_id_1.default)();
class SubscribeBlockTracker extends BaseBlockTracker_1.BaseBlockTracker {
constructor(opts = {}) {
// 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() {
return await this.getLatestBlock();
}
async _start() {
if (this._subscriptionId === undefined || this._subscriptionId === null) {
try {
const blockNumber = (await this._call('eth_blockNumber'));
this._subscriptionId = (await this._call('eth_subscribe', 'newHeads', {}));
this._provider.on('data', this._handleSubData.bind(this));
this._newPotentialLatest(blockNumber);
}
catch (e) {
this.emit('error', e);
}
}
}
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);
}
}
}
_call(method, ...params) {
return new Promise((resolve, reject) => {
this._provider.sendAsync({
id: createRandomId(),
method,
params,
jsonrpc: '2.0',
}, (err, res) => {
if (err) {
reject(err);
}
else {
resolve(res.result);
}
});
});
}
_handleSubData(_, response) {
var _a;
if (response.method === 'eth_subscription' &&
((_a = response.params) === null || _a === void 0 ? void 0 : _a.subscription) === this._subscriptionId) {
this._newPotentialLatest(response.params.result.number);
}
}
}
exports.SubscribeBlockTracker = SubscribeBlockTracker;
//# sourceMappingURL=SubscribeBlockTracker.js.map