Skip to content

Commit

Permalink
rework firstOpen logic in WebSocketProvider and ignore old events (#87)
Browse files Browse the repository at this point in the history
* rework firstOpen logic in WebSocketProvider

* ignore old events in ContractEventsEmitter
  • Loading branch information
defi-dev authored Feb 21, 2024
1 parent 2469e5e commit a0abfe3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
7 changes: 6 additions & 1 deletion app/services/ContractEventsEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export default class ContractEventsEmitter {
contractEmitterCount = {};
emitByBlockCount = {};

lastBlockNumber = null;

constructor(_blockLogsMode) {
this.setBlockLogsMode(_blockLogsMode);
}
Expand All @@ -22,7 +24,10 @@ export default class ContractEventsEmitter {
}

emitByContractAddress(address, eventName, value) {
this.contractEmitterByAddress[address].emit(eventName, value);
if (!this.lastBlockNumber || value.blockNumber >= this.lastBlockNumber) {
this.contractEmitterByAddress[address].emit(eventName, value);
this.lastBlockNumber = value.blockNumber;
}
}

emitByBlockLogs(logs, forceEmit = false) {
Expand Down
9 changes: 5 additions & 4 deletions app/services/WebSocketProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export default class WebSocketProvider extends WebSocketProviderClass() {
private events: ethers.providers.WebSocketProvider['_events'] = [];
private requests: ethers.providers.WebSocketProvider['_requests'] = {};

firstOpen = true;

private handler = {
get(target: WebSocketProvider, prop: string, receiver: unknown) {
const value = target.provider && Reflect.get(target.provider, prop, receiver);
Expand All @@ -35,7 +37,6 @@ export default class WebSocketProvider extends WebSocketProviderClass() {
const provider = new ethers.providers.WebSocketProvider(this.providerUrl, this.provider?.network?.chainId);
let pingInterval: NodeJS.Timer | undefined;
let pongTimeout: NodeJS.Timeout | undefined;
let firstOpen = true;

provider._websocket.on('open', () => {
pingInterval = setInterval(() => {
Expand All @@ -57,9 +58,9 @@ export default class WebSocketProvider extends WebSocketProviderClass() {
provider._websocket.send(this.requests[key].payload);
delete this.requests[key];
}
console.log('connection established.');
if (firstOpen) {
firstOpen = false;
console.log('connection established (firstOpen=' + this.firstOpen + ')');
if (this.firstOpen) {
this.firstOpen = false;
} else {
provider.emit('reconnect');
}
Expand Down

0 comments on commit a0abfe3

Please sign in to comment.