-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathsubscriber-polling.ts
More file actions
321 lines (260 loc) · 8.99 KB
/
Copy pathsubscriber-polling.ts
File metadata and controls
321 lines (260 loc) · 8.99 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
import { assert, isHexString } from "../utils/index.js";
import type { AbstractProvider, Subscriber } from "./abstract-provider.js";
import type { EventFilter, OrphanFilter, ProviderEvent } from "./provider.js";
function copy(obj: any): any {
return JSON.parse(JSON.stringify(obj));
}
/**
* Return the polling subscriber for common events.
*
* @_docloc: api/providers/abstract-provider
*/
export function getPollingSubscriber(provider: AbstractProvider, event: ProviderEvent): Subscriber {
if (event === "block") { return new PollingBlockSubscriber(provider); }
if (isHexString(event, 32)) { return new PollingTransactionSubscriber(provider, event); }
assert(false, "unsupported polling event", "UNSUPPORTED_OPERATION", {
operation: "getPollingSubscriber", info: { event }
});
}
// @TODO: refactor this
/**
* A **PollingBlockSubscriber** polls at a regular interval for a change
* in the block number.
*
* @_docloc: api/providers/abstract-provider
*/
export class PollingBlockSubscriber implements Subscriber {
#provider: AbstractProvider;
#poller: null | number;
#interval: number;
// The most recent block we have scanned for events. The value -2
// indicates we still need to fetch an initial block number
#blockNumber: number;
/**
* Create a new **PollingBlockSubscriber** attached to %%provider%%.
*/
constructor(provider: AbstractProvider) {
this.#provider = provider;
this.#poller = null;
this.#interval = 4000;
this.#blockNumber = -2;
}
/**
* The polling interval.
*/
get pollingInterval(): number { return this.#interval; }
set pollingInterval(value: number) { this.#interval = value; }
async #poll(): Promise<void> {
try {
const blockNumber = await this.#provider.getBlockNumber();
// Bootstrap poll to setup our initial block number
if (this.#blockNumber === -2) {
this.#blockNumber = blockNumber;
return;
}
// @TODO: Put a cap on the maximum number of events per loop?
if (blockNumber !== this.#blockNumber) {
for (let b = this.#blockNumber + 1; b <= blockNumber; b++) {
// We have been stopped
if (this.#poller == null) { return; }
await this.#provider.emit("block", b);
}
this.#blockNumber = blockNumber;
}
} catch (error) {
// @TODO: Minor bump, add an "error" event to let subscribers
// know things went awry.
//console.log(error);
}
// We have been stopped
if (this.#poller == null) { return; }
this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
}
start(): void {
if (this.#poller) { return; }
this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
this.#poll();
}
stop(): void {
if (!this.#poller) { return; }
this.#provider._clearTimeout(this.#poller);
this.#poller = null;
}
pause(dropWhilePaused?: boolean): void {
this.stop();
if (dropWhilePaused) { this.#blockNumber = -2; }
}
resume(): void {
this.start();
}
}
/**
* An **OnBlockSubscriber** can be sub-classed, with a [[_poll]]
* implmentation which will be called on every new block.
*
* @_docloc: api/providers/abstract-provider
*/
export class OnBlockSubscriber implements Subscriber {
#provider: AbstractProvider;
#poll: (b: number) => void;
#running: boolean;
/**
* Create a new **OnBlockSubscriber** attached to %%provider%%.
*/
constructor(provider: AbstractProvider) {
this.#provider = provider;
this.#running = false;
this.#poll = (blockNumber: number) => {
this._poll(blockNumber, this.#provider);
}
}
/**
* Called on every new block.
*/
async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
throw new Error("sub-classes must override this");
}
start(): void {
if (this.#running) { return; }
this.#running = true;
this.#poll(-2);
this.#provider.on("block", this.#poll);
}
stop(): void {
if (!this.#running) { return; }
this.#running = false;
this.#provider.off("block", this.#poll);
}
pause(dropWhilePaused?: boolean): void { this.stop(); }
resume(): void { this.start(); }
}
export class PollingBlockTagSubscriber extends OnBlockSubscriber {
readonly #tag: string;
#lastBlock: number;
constructor(provider: AbstractProvider, tag: string) {
super(provider);
this.#tag = tag;
this.#lastBlock = -2;
}
pause(dropWhilePaused?: boolean): void {
if (dropWhilePaused) { this.#lastBlock = -2; }
super.pause(dropWhilePaused);
}
async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
const block = await provider.getBlock(this.#tag);
if (block == null) { return; }
if (this.#lastBlock === -2) {
this.#lastBlock = block.number;
} else if (block.number > this.#lastBlock) {
provider.emit(this.#tag, block.number);
this.#lastBlock = block.number;
}
}
}
/**
* @_ignore:
*
* @_docloc: api/providers/abstract-provider
*/
export class PollingOrphanSubscriber extends OnBlockSubscriber {
#filter: OrphanFilter;
constructor(provider: AbstractProvider, filter: OrphanFilter) {
super(provider);
this.#filter = copy(filter);
}
async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
throw new Error("@TODO");
console.log(this.#filter);
}
}
/**
* A **PollingTransactionSubscriber** will poll for a given transaction
* hash for its receipt.
*
* @_docloc: api/providers/abstract-provider
*/
export class PollingTransactionSubscriber extends OnBlockSubscriber {
#hash: string;
/**
* Create a new **PollingTransactionSubscriber** attached to
* %%provider%%, listening for %%hash%%.
*/
constructor(provider: AbstractProvider, hash: string) {
super(provider);
this.#hash = hash;
}
async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
const tx = await provider.getTransactionReceipt(this.#hash);
if (tx) { provider.emit(this.#hash, tx); }
}
}
/**
* A **PollingEventSubscriber** will poll for a given filter for its logs.
*
* @_docloc: api/providers/abstract-provider
*/
export class PollingEventSubscriber implements Subscriber {
#provider: AbstractProvider;
#filter: EventFilter;
#poller: (b: number) => void;
#running: boolean;
// The most recent block we have scanned for events. The value -2
// indicates we still need to fetch an initial block number
#blockNumber: number;
/**
* Create a new **PollingTransactionSubscriber** attached to
* %%provider%%, listening for %%filter%%.
*/
constructor(provider: AbstractProvider, filter: EventFilter) {
this.#provider = provider;
this.#filter = copy(filter);
this.#poller = this.#poll.bind(this);
this.#running = false;
this.#blockNumber = -2;
}
async #poll(blockNumber: number): Promise<void> {
// The initial block hasn't been determined yet
if (this.#blockNumber === -2) { return; }
const filter = copy(this.#filter);
filter.fromBlock = this.#blockNumber + 1;
filter.toBlock = blockNumber;
const logs = await this.#provider.getLogs(filter);
// No logs could just mean the node has not indexed them yet,
// so we keep a sliding window of 60 blocks to keep scanning
if (logs.length === 0) {
if (this.#blockNumber < blockNumber - 60) {
this.#blockNumber = blockNumber - 60;
}
return;
}
for (const log of logs) {
this.#provider.emit(this.#filter, log);
// Only advance the block number when logs were found to
// account for networks (like BNB and Polygon) which may
// sacrifice event consistency for block event speed
this.#blockNumber = log.blockNumber;
}
}
start(): void {
if (this.#running) { return; }
this.#running = true;
if (this.#blockNumber === -2) {
this.#provider.getBlockNumber().then((blockNumber) => {
this.#blockNumber = blockNumber;
});
}
this.#provider.on("block", this.#poller);
}
stop(): void {
if (!this.#running) { return; }
this.#running = false;
this.#provider.off("block", this.#poller);
}
pause(dropWhilePaused?: boolean): void {
this.stop();
if (dropWhilePaused) { this.#blockNumber = -2; }
}
resume(): void {
this.start();
}
}