@atomiqlabs/chain-evm 1.0.0-dev.50 → 1.0.0-dev.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chains/botanix/BotanixChainType.d.ts +1 -2
- package/dist/chains/botanix/BotanixInitializer.js +1 -4
- package/dist/chains/citrea/CitreaChainType.d.ts +1 -2
- package/dist/chains/citrea/CitreaInitializer.js +1 -4
- package/dist/evm/ReconnectingWebSocketProvider.d.ts +18 -0
- package/dist/evm/ReconnectingWebSocketProvider.js +65 -0
- package/dist/evm/SocketProvider.d.ts +110 -0
- package/dist/evm/SocketProvider.js +322 -0
- package/dist/evm/WebSocketProviderWithRetries.d.ts +15 -0
- package/dist/evm/WebSocketProviderWithRetries.js +19 -0
- package/dist/evm/events/EVMChainEvents.js +2 -0
- package/dist/evm/events/EVMChainEventsBrowser.d.ts +18 -2
- package/dist/evm/events/EVMChainEventsBrowser.js +118 -12
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/package.json +1 -1
- package/src/chains/botanix/BotanixChainType.ts +1 -2
- package/src/chains/botanix/BotanixInitializer.ts +1 -4
- package/src/chains/citrea/CitreaChainType.ts +1 -2
- package/src/chains/citrea/CitreaInitializer.ts +1 -4
- package/src/evm/ReconnectingWebSocketProvider.ts +82 -0
- package/src/evm/SocketProvider.ts +353 -0
- package/src/evm/WebSocketProviderWithRetries.ts +27 -0
- package/src/evm/events/EVMChainEvents.ts +1 -0
- package/src/evm/events/EVMChainEventsBrowser.ts +148 -15
- package/src/index.ts +2 -1
- package/dist/evm/events/EVMChainEventsBrowserWS.d.ts +0 -66
- package/dist/evm/events/EVMChainEventsBrowserWS.js +0 -264
- package/src/evm/events/EVMChainEventsBrowserWS.ts +0 -354
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic long-lived socket provider.
|
|
3
|
+
*
|
|
4
|
+
* Sub-classing notes
|
|
5
|
+
* - a sub-class MUST call the `_start()` method once connected
|
|
6
|
+
* - a sub-class MUST override the `_write(string)` method
|
|
7
|
+
* - a sub-class MUST call `_processMessage(string)` for each message
|
|
8
|
+
*
|
|
9
|
+
* @_subsection: api/providers/abstract-provider:Socket Providers [about-socketProvider]
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
assert,
|
|
13
|
+
assertArgument, EventFilter,
|
|
14
|
+
JsonRpcApiProvider,
|
|
15
|
+
JsonRpcApiProviderOptions, JsonRpcError,
|
|
16
|
+
JsonRpcPayload, JsonRpcResult, makeError,
|
|
17
|
+
Networkish,
|
|
18
|
+
Subscriber, Subscription, UnmanagedSubscriber
|
|
19
|
+
} from "ethers";
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
type JsonRpcSubscription = {
|
|
23
|
+
method: string,
|
|
24
|
+
params: {
|
|
25
|
+
result: any,
|
|
26
|
+
subscription: string
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A **SocketSubscriber** uses a socket transport to handle events and
|
|
32
|
+
* should use [[_emit]] to manage the events.
|
|
33
|
+
*/
|
|
34
|
+
export class SocketSubscriber implements Subscriber {
|
|
35
|
+
#provider: SocketProvider;
|
|
36
|
+
|
|
37
|
+
#filter: string;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The filter.
|
|
41
|
+
*/
|
|
42
|
+
get filter(): Array<any> { return JSON.parse(this.#filter); }
|
|
43
|
+
|
|
44
|
+
#filterId: null | Promise<string |number>;
|
|
45
|
+
#paused: null | boolean;
|
|
46
|
+
|
|
47
|
+
#emitPromise: null | Promise<void>;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Creates a new **SocketSubscriber** attached to %%provider%% listening
|
|
51
|
+
* to %%filter%%.
|
|
52
|
+
*/
|
|
53
|
+
constructor(provider: SocketProvider, filter: Array<any>) {
|
|
54
|
+
this.#provider = provider;
|
|
55
|
+
this.#filter = JSON.stringify(filter);
|
|
56
|
+
this.#filterId = null;
|
|
57
|
+
this.#paused = null;
|
|
58
|
+
this.#emitPromise = null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
start(): void {
|
|
62
|
+
this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId) => {;
|
|
63
|
+
this.#provider._register(filterId, this);
|
|
64
|
+
return filterId;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
stop(): void {
|
|
69
|
+
(<Promise<number>>(this.#filterId)).then((filterId) => {
|
|
70
|
+
if (this.#provider.destroyed) { return; }
|
|
71
|
+
this.#provider.send("eth_unsubscribe", [ filterId ]);
|
|
72
|
+
});
|
|
73
|
+
this.#filterId = null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs
|
|
77
|
+
// and resume
|
|
78
|
+
pause(dropWhilePaused?: boolean): void {
|
|
79
|
+
assert(dropWhilePaused, "preserve logs while paused not supported by SocketSubscriber yet",
|
|
80
|
+
"UNSUPPORTED_OPERATION", { operation: "pause(false)" });
|
|
81
|
+
this.#paused = !!dropWhilePaused;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
resume(): void {
|
|
85
|
+
this.#paused = null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* @_ignore:
|
|
90
|
+
*/
|
|
91
|
+
_handleMessage(message: any): void {
|
|
92
|
+
if (this.#filterId == null) { return; }
|
|
93
|
+
if (this.#paused === null) {
|
|
94
|
+
let emitPromise: null | Promise<void> = this.#emitPromise;
|
|
95
|
+
if (emitPromise == null) {
|
|
96
|
+
emitPromise = this._emit(this.#provider, message);
|
|
97
|
+
} else {
|
|
98
|
+
emitPromise = emitPromise.then(async () => {
|
|
99
|
+
await this._emit(this.#provider, message);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
this.#emitPromise = emitPromise.then(() => {
|
|
103
|
+
if (this.#emitPromise === emitPromise) {
|
|
104
|
+
this.#emitPromise = null;
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Sub-classes **must** override this to emit the events on the
|
|
112
|
+
* provider.
|
|
113
|
+
*/
|
|
114
|
+
async _emit(provider: SocketProvider, message: any): Promise<void> {
|
|
115
|
+
throw new Error("sub-classes must implemente this; _emit");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A **SocketBlockSubscriber** listens for ``newHeads`` events and emits
|
|
121
|
+
* ``"block"`` events.
|
|
122
|
+
*/
|
|
123
|
+
export class SocketBlockSubscriber extends SocketSubscriber {
|
|
124
|
+
/**
|
|
125
|
+
* @_ignore:
|
|
126
|
+
*/
|
|
127
|
+
constructor(provider: SocketProvider) {
|
|
128
|
+
super(provider, [ "newHeads" ]);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async _emit(provider: SocketProvider, message: any): Promise<void> {
|
|
132
|
+
provider.emit("block", parseInt(message.number));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* A **SocketPendingSubscriber** listens for pending transacitons and emits
|
|
138
|
+
* ``"pending"`` events.
|
|
139
|
+
*/
|
|
140
|
+
export class SocketPendingSubscriber extends SocketSubscriber {
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* @_ignore:
|
|
144
|
+
*/
|
|
145
|
+
constructor(provider: SocketProvider) {
|
|
146
|
+
super(provider, [ "newPendingTransactions" ]);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async _emit(provider: SocketProvider, message: any): Promise<void> {
|
|
150
|
+
provider.emit("pending", message);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A **SocketEventSubscriber** listens for event logs.
|
|
156
|
+
*/
|
|
157
|
+
export class SocketEventSubscriber extends SocketSubscriber {
|
|
158
|
+
#logFilter: string;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The filter.
|
|
162
|
+
*/
|
|
163
|
+
get logFilter(): EventFilter { return JSON.parse(this.#logFilter); }
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* @_ignore:
|
|
167
|
+
*/
|
|
168
|
+
constructor(provider: SocketProvider, filter: EventFilter) {
|
|
169
|
+
super(provider, [ "logs", filter ]);
|
|
170
|
+
this.#logFilter = JSON.stringify(filter);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async _emit(provider: SocketProvider, message: any): Promise<void> {
|
|
174
|
+
provider.emit(this.logFilter, provider._wrapLog(message, provider._network));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* A **SocketProvider** is backed by a long-lived connection over a
|
|
180
|
+
* socket, which can subscribe and receive real-time messages over
|
|
181
|
+
* its communication channel.
|
|
182
|
+
*/
|
|
183
|
+
export class SocketProvider extends JsonRpcApiProvider {
|
|
184
|
+
#callbacks: Map<number, { payload: JsonRpcPayload, resolve: (r: any) => void, reject: (e: Error) => void }>;
|
|
185
|
+
|
|
186
|
+
// Maps each filterId to its subscriber
|
|
187
|
+
#subs: Map<number | string, SocketSubscriber>;
|
|
188
|
+
|
|
189
|
+
// If any events come in before a subscriber has finished
|
|
190
|
+
// registering, queue them
|
|
191
|
+
#pending: Map<number | string, Array<any>>;
|
|
192
|
+
|
|
193
|
+
#connected: boolean;
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Creates a new **SocketProvider** connected to %%network%%.
|
|
197
|
+
*
|
|
198
|
+
* If unspecified, the network will be discovered.
|
|
199
|
+
*/
|
|
200
|
+
constructor(network?: Networkish, _options?: JsonRpcApiProviderOptions) {
|
|
201
|
+
// Copy the options
|
|
202
|
+
const options = Object.assign({ }, (_options != null) ? _options: { });
|
|
203
|
+
|
|
204
|
+
// Support for batches is generally not supported for
|
|
205
|
+
// connection-base providers; if this changes in the future
|
|
206
|
+
// the _send should be updated to reflect this
|
|
207
|
+
assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1,
|
|
208
|
+
"sockets-based providers do not support batches", "options.batchMaxCount", _options);
|
|
209
|
+
options.batchMaxCount = 1;
|
|
210
|
+
|
|
211
|
+
// Socket-based Providers (generally) cannot change their network,
|
|
212
|
+
// since they have a long-lived connection; but let people override
|
|
213
|
+
// this if they have just cause.
|
|
214
|
+
if (options.staticNetwork == null) { options.staticNetwork = true; }
|
|
215
|
+
|
|
216
|
+
super(network, options);
|
|
217
|
+
this.#callbacks = new Map();
|
|
218
|
+
this.#subs = new Map();
|
|
219
|
+
this.#pending = new Map();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// This value is only valid after _start has been called
|
|
223
|
+
/*
|
|
224
|
+
get _network(): Network {
|
|
225
|
+
if (this.#network == null) {
|
|
226
|
+
throw new Error("this shouldn't happen");
|
|
227
|
+
}
|
|
228
|
+
return this.#network.clone();
|
|
229
|
+
}
|
|
230
|
+
*/
|
|
231
|
+
|
|
232
|
+
_getSubscriber(sub: Subscription): Subscriber {
|
|
233
|
+
switch (sub.type) {
|
|
234
|
+
case "close":
|
|
235
|
+
return new UnmanagedSubscriber("close");
|
|
236
|
+
case "block":
|
|
237
|
+
return new SocketBlockSubscriber(this);
|
|
238
|
+
case "pending":
|
|
239
|
+
return new SocketPendingSubscriber(this);
|
|
240
|
+
case "event":
|
|
241
|
+
return new SocketEventSubscriber(this, sub.filter);
|
|
242
|
+
case "orphan":
|
|
243
|
+
// Handled auto-matically within AbstractProvider
|
|
244
|
+
// when the log.removed = true
|
|
245
|
+
if (sub.filter.orphan === "drop-log") {
|
|
246
|
+
return new UnmanagedSubscriber("drop-log");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return super._getSubscriber(sub);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Register a new subscriber. This is used internalled by Subscribers
|
|
254
|
+
* and generally is unecessary unless extending capabilities.
|
|
255
|
+
*/
|
|
256
|
+
_register(filterId: number | string, subscriber: SocketSubscriber): void {
|
|
257
|
+
this.#subs.set(filterId, subscriber);
|
|
258
|
+
const pending = this.#pending.get(filterId);
|
|
259
|
+
if (pending) {
|
|
260
|
+
for (const message of pending) {
|
|
261
|
+
subscriber._handleMessage(message);
|
|
262
|
+
}
|
|
263
|
+
this.#pending.delete(filterId);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async _send(payload: JsonRpcPayload | Array<JsonRpcPayload>): Promise<Array<JsonRpcResult | JsonRpcError>> {
|
|
268
|
+
// WebSocket provider doesn't accept batches
|
|
269
|
+
assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload);
|
|
270
|
+
|
|
271
|
+
if(!this.#connected) return Promise.reject(makeError("WebSocket not connected!", "NETWORK_ERROR"));
|
|
272
|
+
|
|
273
|
+
// Prepare a promise to respond to
|
|
274
|
+
const promise = new Promise((resolve, reject) => {
|
|
275
|
+
this.#callbacks.set(payload.id, { payload, resolve, reject });
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
// Wait until the socket is connected before writing to it
|
|
279
|
+
await this._waitUntilReady();
|
|
280
|
+
|
|
281
|
+
// Write the request to the socket
|
|
282
|
+
await this._write(JSON.stringify(payload));
|
|
283
|
+
|
|
284
|
+
return <Array<JsonRpcResult | JsonRpcError>>[ await promise ];
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
_connected() {
|
|
288
|
+
this.#connected = true;
|
|
289
|
+
this.resume();
|
|
290
|
+
this._forEachSubscriber(subscriber => subscriber.start());
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
_disconnected() {
|
|
294
|
+
this.#connected = false;
|
|
295
|
+
this.pause(true);
|
|
296
|
+
|
|
297
|
+
this.#callbacks.forEach(val => {
|
|
298
|
+
val.reject(makeError("WebSocket disconnected!", "NETWORK_ERROR"))
|
|
299
|
+
});
|
|
300
|
+
this.#callbacks.clear();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Sub-classes **must** call this with messages received over their
|
|
305
|
+
* transport to be processed and dispatched.
|
|
306
|
+
*/
|
|
307
|
+
async _processMessage(message: string): Promise<void> {
|
|
308
|
+
const result = <JsonRpcResult | JsonRpcError | JsonRpcSubscription>(JSON.parse(message));
|
|
309
|
+
|
|
310
|
+
if (result && typeof(result) === "object" && "id" in result) {
|
|
311
|
+
const callback = this.#callbacks.get(result.id);
|
|
312
|
+
if (callback == null) {
|
|
313
|
+
this.emit("error", makeError("received result for unknown id", "UNKNOWN_ERROR", {
|
|
314
|
+
reasonCode: "UNKNOWN_ID",
|
|
315
|
+
result
|
|
316
|
+
}));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
this.#callbacks.delete(result.id);
|
|
320
|
+
|
|
321
|
+
callback.resolve(result);
|
|
322
|
+
|
|
323
|
+
} else if (result && (result as any).method === "eth_subscription") {
|
|
324
|
+
const filterId = (result as any).params.subscription;
|
|
325
|
+
const subscriber = this.#subs.get(filterId);
|
|
326
|
+
if (subscriber) {
|
|
327
|
+
subscriber._handleMessage((result as any).params.result);
|
|
328
|
+
} else {
|
|
329
|
+
let pending = this.#pending.get(filterId);
|
|
330
|
+
if (pending == null) {
|
|
331
|
+
pending = [ ];
|
|
332
|
+
this.#pending.set(filterId, pending);
|
|
333
|
+
}
|
|
334
|
+
pending.push((result as any).params.result);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
} else {
|
|
338
|
+
this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", {
|
|
339
|
+
reasonCode: "UNEXPECTED_MESSAGE",
|
|
340
|
+
result
|
|
341
|
+
}));
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Sub-classes **must** override this to send %%message%% over their
|
|
348
|
+
* transport.
|
|
349
|
+
*/
|
|
350
|
+
async _write(message: string): Promise<void> {
|
|
351
|
+
throw new Error("sub-classes must override this");
|
|
352
|
+
}
|
|
353
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {JsonRpcApiProviderOptions, WebSocketProvider} from "ethers";
|
|
2
|
+
import type {Networkish, WebSocketCreator, WebSocketLike} from "ethers";
|
|
3
|
+
import {tryWithRetries} from "../utils/Utils";
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
export class WebSocketProviderWithRetries extends WebSocketProvider {
|
|
7
|
+
|
|
8
|
+
readonly retryPolicy?: {
|
|
9
|
+
maxRetries?: number, delay?: number, exponential?: boolean
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
constructor(url: string | WebSocketLike | WebSocketCreator, network?: Networkish, options?: JsonRpcApiProviderOptions & {
|
|
13
|
+
maxRetries?: number, delay?: number, exponential?: boolean
|
|
14
|
+
}) {
|
|
15
|
+
super(url, network, options);
|
|
16
|
+
this.retryPolicy = options;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
send(method: string, params: Array<any> | Record<string, any>): Promise<any> {
|
|
20
|
+
return tryWithRetries(() => super.send(method, params), this.retryPolicy, e => {
|
|
21
|
+
return false;
|
|
22
|
+
// if(e?.error?.code!=null) return false; //Error returned by the RPC
|
|
23
|
+
// return true;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
}
|
|
@@ -72,6 +72,7 @@ export class EVMChainEvents extends EVMChainEventsBrowser {
|
|
|
72
72
|
|
|
73
73
|
async init(): Promise<void> {
|
|
74
74
|
const lastState = await this.getLastEventData();
|
|
75
|
+
if((this.provider as any).websocket!=null) await this.setupWebsocket();
|
|
75
76
|
await this.setupPoll(
|
|
76
77
|
lastState,
|
|
77
78
|
(newState: EVMEventListenerState[]) => this.saveLastEventData(newState)
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
} from "@atomiqlabs/base";
|
|
10
10
|
import {IClaimHandler} from "../swaps/handlers/claim/ClaimHandlers";
|
|
11
11
|
import {EVMSwapData} from "../swaps/EVMSwapData";
|
|
12
|
-
import {Block, hexlify, JsonRpcApiProvider} from "ethers";
|
|
12
|
+
import {Block, hexlify, JsonRpcApiProvider, EventFilter, Log} from "ethers";
|
|
13
13
|
import { EVMSwapContract } from "../swaps/EVMSwapContract";
|
|
14
14
|
import {getLogger, onceAsync} from "../../utils/Utils";
|
|
15
15
|
import {EVMSpvVaultContract, unpackOwnerAndVaultId} from "../spv_swap/EVMSpvVaultContract";
|
|
@@ -21,8 +21,15 @@ import {EVMTxTrace} from "../chain/modules/EVMTransactions";
|
|
|
21
21
|
|
|
22
22
|
const LOGS_SLIDING_WINDOW_LENGTH = 60;
|
|
23
23
|
|
|
24
|
+
const PROCESSED_EVENTS_BACKLOG = 1000;
|
|
25
|
+
|
|
24
26
|
export type EVMEventListenerState = {lastBlockNumber: number, lastEvent?: {blockHash: string, logIndex: number}};
|
|
25
27
|
|
|
28
|
+
type AtomiqTypedEvent = (
|
|
29
|
+
TypedEventLog<EscrowManager["filters"]["Initialize" | "Refund" | "Claim"]> |
|
|
30
|
+
TypedEventLog<SpvVaultManager["filters"]["Opened" | "Deposited" | "Fronted" | "Claimed" | "Closed"]>
|
|
31
|
+
);
|
|
32
|
+
|
|
26
33
|
/**
|
|
27
34
|
* EVM on-chain event handler for front-end systems without access to fs, uses WS or long-polling to subscribe, might lose
|
|
28
35
|
* out on some events if the network is unreliable, front-end systems should take this into consideration and not
|
|
@@ -30,6 +37,12 @@ export type EVMEventListenerState = {lastBlockNumber: number, lastEvent?: {block
|
|
|
30
37
|
*/
|
|
31
38
|
export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
32
39
|
|
|
40
|
+
private eventsProcessing: {
|
|
41
|
+
[signature: string]: Promise<void>
|
|
42
|
+
} = {};
|
|
43
|
+
private processedEvents: string[] = [];
|
|
44
|
+
private processedEventsIndex: number = 0;
|
|
45
|
+
|
|
33
46
|
protected readonly listeners: EventListener<EVMSwapData>[] = [];
|
|
34
47
|
protected readonly provider: JsonRpcApiProvider;
|
|
35
48
|
protected readonly chainInterface: EVMChainInterface;
|
|
@@ -42,6 +55,12 @@ export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
|
42
55
|
|
|
43
56
|
private timeout: number;
|
|
44
57
|
|
|
58
|
+
//Websocket
|
|
59
|
+
protected readonly spvVaultContractLogFilter: EventFilter;
|
|
60
|
+
protected readonly swapContractLogFilter: EventFilter;
|
|
61
|
+
|
|
62
|
+
protected unconfirmedEventQueue: AtomiqTypedEvent[] = [];
|
|
63
|
+
|
|
45
64
|
constructor(
|
|
46
65
|
chainInterface: EVMChainInterface,
|
|
47
66
|
evmSwapContract: EVMSwapContract,
|
|
@@ -53,6 +72,23 @@ export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
|
53
72
|
this.evmSwapContract = evmSwapContract;
|
|
54
73
|
this.evmSpvVaultContract = evmSpvVaultContract;
|
|
55
74
|
this.pollIntervalSeconds = pollIntervalSeconds;
|
|
75
|
+
|
|
76
|
+
this.spvVaultContractLogFilter = {
|
|
77
|
+
address: this.evmSpvVaultContract.contractAddress
|
|
78
|
+
};
|
|
79
|
+
this.swapContractLogFilter = {
|
|
80
|
+
address: this.evmSwapContract.contractAddress
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private addProcessedEvent(event: AtomiqTypedEvent) {
|
|
85
|
+
this.processedEvents[this.processedEventsIndex] = event.transactionHash+":"+event.transactionIndex;
|
|
86
|
+
this.processedEventsIndex += 1;
|
|
87
|
+
if(this.processedEventsIndex >= PROCESSED_EVENTS_BACKLOG) this.processedEventsIndex = 0;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private isEventProcessed(event: AtomiqTypedEvent): boolean {
|
|
91
|
+
return this.processedEvents.includes(event.transactionHash+":"+event.transactionIndex);
|
|
56
92
|
}
|
|
57
93
|
|
|
58
94
|
findInitSwapData(call: EVMTxTrace, escrowHash: string, claimHandler: IClaimHandler<any, any>): EVMSwapData {
|
|
@@ -216,11 +252,16 @@ export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
|
216
252
|
TypedEventLog<EscrowManager["filters"]["Initialize" | "Refund" | "Claim"]> |
|
|
217
253
|
TypedEventLog<SpvVaultManager["filters"]["Opened" | "Deposited" | "Fronted" | "Claimed" | "Closed"]>
|
|
218
254
|
)[],
|
|
219
|
-
currentBlock
|
|
255
|
+
currentBlock?: Block
|
|
220
256
|
) {
|
|
221
|
-
const parsedEvents: ChainEvent<EVMSwapData>[] = [];
|
|
222
|
-
|
|
223
257
|
for(let event of events) {
|
|
258
|
+
const eventIdentifier = event.transactionHash+":"+event.transactionIndex;
|
|
259
|
+
|
|
260
|
+
if(this.isEventProcessed(event)) {
|
|
261
|
+
this.logger.debug("processEvents(): skipping already processed event: "+eventIdentifier);
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
|
|
224
265
|
let parsedEvent: ChainEvent<EVMSwapData>;
|
|
225
266
|
switch(event.eventName) {
|
|
226
267
|
case "Claim":
|
|
@@ -248,17 +289,33 @@ export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
|
248
289
|
parsedEvent = this.parseSpvCloseEvent(event as any);
|
|
249
290
|
break;
|
|
250
291
|
}
|
|
251
|
-
const timestamp = event.blockNumber===currentBlock.number ? currentBlock.timestamp : await this.chainInterface.Blocks.getBlockTime(event.blockNumber);
|
|
252
|
-
parsedEvent.meta = {
|
|
253
|
-
blockTime: timestamp,
|
|
254
|
-
txId: event.transactionHash,
|
|
255
|
-
timestamp //Maybe deprecated
|
|
256
|
-
} as any;
|
|
257
|
-
parsedEvents.push(parsedEvent);
|
|
258
|
-
}
|
|
259
292
|
|
|
260
|
-
|
|
261
|
-
|
|
293
|
+
if(this.eventsProcessing[eventIdentifier]!=null) {
|
|
294
|
+
this.logger.debug("processEvents(): awaiting event that is currently processing: "+eventIdentifier);
|
|
295
|
+
await this.eventsProcessing[eventIdentifier];
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const promise = (async() => {
|
|
300
|
+
const timestamp = event.blockNumber===currentBlock?.number ? currentBlock.timestamp : await this.chainInterface.Blocks.getBlockTime(event.blockNumber);
|
|
301
|
+
parsedEvent.meta = {
|
|
302
|
+
blockTime: timestamp,
|
|
303
|
+
txId: event.transactionHash,
|
|
304
|
+
timestamp //Maybe deprecated
|
|
305
|
+
} as any;
|
|
306
|
+
for(let listener of this.listeners) {
|
|
307
|
+
await listener([parsedEvent]);
|
|
308
|
+
}
|
|
309
|
+
this.addProcessedEvent(event);
|
|
310
|
+
})();
|
|
311
|
+
this.eventsProcessing[eventIdentifier] = promise;
|
|
312
|
+
try {
|
|
313
|
+
await promise;
|
|
314
|
+
delete this.eventsProcessing[eventIdentifier];
|
|
315
|
+
} catch (e) {
|
|
316
|
+
delete this.eventsProcessing[eventIdentifier];
|
|
317
|
+
throw e;
|
|
318
|
+
}
|
|
262
319
|
}
|
|
263
320
|
}
|
|
264
321
|
|
|
@@ -364,8 +421,78 @@ export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
|
364
421
|
await func();
|
|
365
422
|
}
|
|
366
423
|
|
|
424
|
+
//Websocket
|
|
425
|
+
|
|
426
|
+
protected handleWsEvents(
|
|
427
|
+
events : AtomiqTypedEvent[]
|
|
428
|
+
): Promise<void> {
|
|
429
|
+
if(this.chainInterface.config.safeBlockTag==="latest" || this.chainInterface.config.safeBlockTag==="pending") {
|
|
430
|
+
return this.processEvents(events);
|
|
431
|
+
}
|
|
432
|
+
this.unconfirmedEventQueue.push(...events);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
protected spvVaultContractListener: (log: Log) => void;
|
|
436
|
+
protected swapContractListener: (log: Log) => void;
|
|
437
|
+
protected blockListener: (blockNumber: number) => Promise<void>;
|
|
438
|
+
|
|
439
|
+
protected wsStarted: boolean = false;
|
|
440
|
+
|
|
441
|
+
protected async setupWebsocket() {
|
|
442
|
+
this.wsStarted = true;
|
|
443
|
+
|
|
444
|
+
await this.provider.on(this.spvVaultContractLogFilter, this.spvVaultContractListener = (log) => {
|
|
445
|
+
let events = this.evmSpvVaultContract.Events.toTypedEvents([log]);
|
|
446
|
+
events = events.filter(val => !val.removed);
|
|
447
|
+
this.handleWsEvents(events);
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
await this.provider.on(this.swapContractLogFilter, this.swapContractListener = (log) => {
|
|
451
|
+
let events = this.evmSwapContract.Events.toTypedEvents([log]);
|
|
452
|
+
events = events.filter(val => !val.removed && (val.eventName==="Initialize" || val.eventName==="Refund" || val.eventName==="Claim"));
|
|
453
|
+
this.handleWsEvents(events);
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
const safeBlockTag = this.chainInterface.config.safeBlockTag;
|
|
457
|
+
let processing = false;
|
|
458
|
+
if(safeBlockTag!=="latest" && safeBlockTag!=="pending") await this.provider.on("block", this.blockListener = async (blockNumber: number) => {
|
|
459
|
+
if(processing) return;
|
|
460
|
+
processing = true;
|
|
461
|
+
try {
|
|
462
|
+
const latestSafeBlock = await this.provider.getBlock(this.chainInterface.config.safeBlockTag);
|
|
463
|
+
|
|
464
|
+
const events = [];
|
|
465
|
+
this.unconfirmedEventQueue = this.unconfirmedEventQueue.filter(event => {
|
|
466
|
+
if(event.blockNumber <= latestSafeBlock.number) {
|
|
467
|
+
events.push(event);
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
return true;
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
const blocks: {[blockNumber: number]: Block} = {};
|
|
474
|
+
for(let event of events) {
|
|
475
|
+
const block = blocks[event.blockNumber] ?? (blocks[event.blockNumber] = await this.provider.getBlock(event.blockNumber));
|
|
476
|
+
if(block.hash===event.blockHash) {
|
|
477
|
+
//Valid event
|
|
478
|
+
await this.processEvents([event], block);
|
|
479
|
+
} else {
|
|
480
|
+
//Block hash doesn't match
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
} catch (e) {
|
|
484
|
+
this.logger.error(`on('block'): Error when processing new block ${blockNumber}:`, e);
|
|
485
|
+
}
|
|
486
|
+
processing = false;
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
367
490
|
async init(): Promise<void> {
|
|
368
|
-
this.
|
|
491
|
+
if((this.provider as any).websocket!=null) {
|
|
492
|
+
await this.setupWebsocket();
|
|
493
|
+
} else {
|
|
494
|
+
await this.setupPoll();
|
|
495
|
+
}
|
|
369
496
|
this.stopped = false;
|
|
370
497
|
return Promise.resolve();
|
|
371
498
|
}
|
|
@@ -373,6 +500,12 @@ export class EVMChainEventsBrowser implements ChainEvents<EVMSwapData> {
|
|
|
373
500
|
async stop(): Promise<void> {
|
|
374
501
|
this.stopped = true;
|
|
375
502
|
if(this.timeout!=null) clearTimeout(this.timeout);
|
|
503
|
+
if(this.wsStarted) {
|
|
504
|
+
await this.provider.off(this.spvVaultContractLogFilter, this.spvVaultContractListener);
|
|
505
|
+
await this.provider.off(this.swapContractLogFilter, this.swapContractListener);
|
|
506
|
+
await this.provider.off("block", this.blockListener);
|
|
507
|
+
this.wsStarted = false;
|
|
508
|
+
}
|
|
376
509
|
}
|
|
377
510
|
|
|
378
511
|
registerListener(cbk: EventListener<EVMSwapData>): void {
|
package/src/index.ts
CHANGED
|
@@ -17,7 +17,6 @@ export * from "./evm/contract/EVMContractBase";
|
|
|
17
17
|
export * from "./evm/contract/EVMContractModule";
|
|
18
18
|
|
|
19
19
|
export * from "./evm/events/EVMChainEventsBrowser";
|
|
20
|
-
export * from "./evm/events/EVMChainEventsBrowserWS";
|
|
21
20
|
|
|
22
21
|
export * from "./evm/spv_swap/EVMSpvVaultContract";
|
|
23
22
|
export * from "./evm/spv_swap/EVMSpvWithdrawalData";
|
|
@@ -49,3 +48,5 @@ export * from "./chains/botanix/BotanixInitializer";
|
|
|
49
48
|
export * from "./chains/botanix/BotanixChainType";
|
|
50
49
|
|
|
51
50
|
export * from "./evm/JsonRpcProviderWithRetries";
|
|
51
|
+
export * from "./evm/WebSocketProviderWithRetries";
|
|
52
|
+
export * from "./evm/ReconnectingWebSocketProvider";
|