diff --git a/src/blockchain/reorg-emitter.ts b/src/blockchain/reorg-emitter.ts index 53fe30d4..f5301e6f 100644 --- a/src/blockchain/reorg-emitter.ts +++ b/src/blockchain/reorg-emitter.ts @@ -7,7 +7,10 @@ const DEFAULT_DEBOUNCE_TIME = 5000 const REORG_EVENT = 'reorg-event' export class ReorgEmitterService implements Partial> { - private readonly debounceTime: number = DEFAULT_DEBOUNCE_TIME + private readonly debounceTime: number = DEFAULT_DEBOUNCE_TIME // ms + private reorgContract: string[] = [] + private lastProcessedBlockNumber = 0 + private timeoutStarted = false emit?: Function events: string[] @@ -22,7 +25,21 @@ export class ReorgEmitterService implements Partial> { if (!this.emit) { throw new Error('ReorgEmitterService invalid setup. Missing \'emit\' function') } + + if (!this.timeoutStarted) { + setTimeout(() => { + if (this.emit) { + this.emit({ contracts: this.reorgContract, lastProcessedBlockNumber: this.lastProcessedBlockNumber }) + } + this.reorgContract = [] + this.lastProcessedBlockNumber = 0 + }) + this.timeoutStarted = true + } + + this.reorgContract = [...this.reorgContract, contractName] + this.lastProcessedBlockNumber = lastProcessedBlockNumber + logger.info(`Reorg happens on block number ${lastProcessedBlockNumber} for ${contractName} contract`) - this.emit(REORG_EVENT, { lastProcessedBlockNumber, contractName }) } }