2019-06-20 00:20:09 +02:00
|
|
|
import ContractBase from './contracts/ContractBase'
|
2019-03-21 02:56:58 +01:00
|
|
|
|
|
|
|
interface EventEmitter {
|
|
|
|
subscribe: Function
|
|
|
|
unsubscribe: Function
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface ContractEventSubscription {
|
2019-03-21 03:17:36 +01:00
|
|
|
unsubscribe: () => void
|
2019-03-21 02:56:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export class ContractEvent {
|
|
|
|
constructor(
|
|
|
|
private eventEmitter: EventEmitter,
|
|
|
|
private contract: ContractBase,
|
|
|
|
private eventName: string,
|
2019-06-20 00:20:09 +02:00
|
|
|
private filter: { [key: string]: any }
|
|
|
|
) {}
|
2019-03-21 02:56:58 +01:00
|
|
|
|
2019-09-09 12:18:54 +02:00
|
|
|
public subscribe(callback: (events: any[]) => void): ContractEventSubscription {
|
2019-10-31 11:23:41 +01:00
|
|
|
const onEvent = async (blockNumber: number) => {
|
2019-03-21 02:56:58 +01:00
|
|
|
const events = await this.contract.getEventData(this.eventName, {
|
|
|
|
filter: this.filter,
|
|
|
|
fromBlock: blockNumber,
|
2019-06-20 00:20:09 +02:00
|
|
|
toBlock: 'latest'
|
2019-03-21 02:56:58 +01:00
|
|
|
})
|
|
|
|
if (events.length) {
|
|
|
|
callback(events)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
this.eventEmitter.subscribe(onEvent)
|
|
|
|
return {
|
2019-06-20 00:20:09 +02:00
|
|
|
unsubscribe: () => this.eventEmitter.unsubscribe(onEvent)
|
2019-03-21 02:56:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-21 03:17:36 +01:00
|
|
|
public once(callback?: (events: any[]) => void) {
|
2020-05-19 16:15:56 +02:00
|
|
|
return new Promise((resolve) => {
|
|
|
|
const subscription = this.subscribe((events) => {
|
2019-03-21 02:56:58 +01:00
|
|
|
subscription.unsubscribe()
|
|
|
|
if (callback) {
|
|
|
|
callback(events)
|
|
|
|
}
|
|
|
|
resolve(events)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|