Skip to content

Commit

Permalink
Fix event emitter (#673)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben-Rey authored Aug 26, 2024
1 parent 867fab1 commit 5216708
Showing 1 changed file with 26 additions and 15 deletions.
41 changes: 26 additions & 15 deletions src/events/eventsPoller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { EventEmitter } from 'events'
import { Provider } from '../provider'
import { EventFilter, NB_THREADS, SCEvent, Slot } from '../client'

Expand All @@ -23,7 +22,7 @@ function nextSlot(prevSlot: Slot): Slot {
/**
* The EventPoller class provides a convenient way to poll events from the Massa network.
*/
export class EventPoller extends EventEmitter {
export class EventPoller extends EventTarget {
private intervalId: NodeJS.Timeout
private lastSlot: Slot

Expand All @@ -44,30 +43,36 @@ export class EventPoller extends EventEmitter {

private poll = async (): Promise<void> => {
try {
// get all events using the filter.
if (this.lastSlot) {
this.eventsFilter.start = nextSlot(this.lastSlot)
} else {
this.lastSlot = this.eventsFilter.start || nextSlot(this.lastSlot)
}

const events = await this.provider.getEvents(this.eventsFilter)

if (events.length) {
this.emit(ON_MASSA_EVENT_DATA, events)
this.dispatchEvent(
new CustomEvent(ON_MASSA_EVENT_DATA, {
detail: events,
})
)
this.lastSlot = events[events.length - 1].context.slot
}
} catch (ex) {
this.emit(ON_MASSA_EVENT_ERROR, ex)
this.dispatchEvent(
new CustomEvent(ON_MASSA_EVENT_ERROR, {
detail: ex,
})
)
}

// reset the interval.
this.intervalId = setTimeout(this.poll, this.pollIntervalMs)
}

/**
* Stops polling for events.
*/
private stop = (): void => {
if (this.intervalId?.hasRef()) {
if (this.intervalId) {
clearInterval(this.intervalId)
}
}
Expand Down Expand Up @@ -101,14 +106,20 @@ export class EventPoller extends EventEmitter {
): { stopPolling: () => void } {
const eventPoller = new EventPoller(provider, eventsFilter, pollIntervalMs)
if (onData) {
eventPoller.on(ON_MASSA_EVENT_DATA, (data: SCEvent[]) => {
onData(data)
})
eventPoller.addEventListener(
ON_MASSA_EVENT_DATA,
(e: CustomEvent<SCEvent[]>) => {
onData(e.detail)
}
)
}
if (onError) {
eventPoller.on(ON_MASSA_EVENT_ERROR, (e) => {
onError(e)
})
eventPoller.addEventListener(
ON_MASSA_EVENT_ERROR,
(e: CustomEvent<Error>) => {
onError(e.detail)
}
)
}

eventPoller.start()
Expand Down

1 comment on commit 5216708

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage report for experimental massa-web3

St.
Category Percentage Covered / Total
🟡 Statements 63.03% 1108/1758
🔴 Branches 43.49% 187/430
🔴 Functions 46.19% 206/446
🟡 Lines 63.33% 1102/1740

Test suite run success

129 tests passing in 13 suites.

Report generated by 🧪jest coverage report action from 5216708

Please sign in to comment.