1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00

added event listener

This commit is contained in:
Sebastian Gerske 2018-11-23 11:39:16 +01:00
parent dccd58802a
commit df475b6958
3 changed files with 131 additions and 0 deletions

35
src/keeper/Event.ts Normal file
View File

@ -0,0 +1,35 @@
import GenericContract from "./contracts/GenericContract"
export default class Event {
private poller
private lastBlock: number = 0
constructor(private contractName: string,
private eventName: string,
private filter: any) {
}
public stopListen() {
clearTimeout(this.poller)
}
public listen(callback: any) {
this.poller = setTimeout(() => this.handler(callback), 200)
}
private async handler(callback: any) {
const contract = await
GenericContract.getInstance(this.contractName)
const events = await
contract.getEventData(this.eventName, {
filter: this.filter,
fromBlock: this.lastBlock,
toBlock: "latest",
})
this.lastBlock = events[events.length - 1].blockNumber
callback(events)
}
}

View File

@ -0,0 +1,25 @@
import Event from "./Event"
export default class EventListener {
private static events: Event[] = []
public subscribe(contractName: string,
eventName: string,
filter: any): Event {
const event = new Event(contractName, eventName, filter)
EventListener.events.push(event)
return event
}
public unsubscribe(event): boolean {
EventListener.events = EventListener.events.splice(
EventListener.events.findIndex((e) => e === event),
1)
return true
}
}

View File

@ -0,0 +1,71 @@
import {assert} from "chai"
import ConfigProvider from "../../src/ConfigProvider"
import EventListener from "../../src/keeper/EventListener"
import Keeper from "../../src/keeper/Keeper"
import Account from "../../src/ocean/Account"
import Ocean from "../../src/ocean/Ocean"
import config from "../config"
import TestContractHandler from "./TestContractHandler"
let keeper: Keeper
let ocean: Ocean
let accounts: Account[]
describe("EventListener", () => {
before(async () => {
ConfigProvider.setConfig(config)
await TestContractHandler.prepareContracts()
keeper = await Keeper.getInstance()
assert(keeper)
ocean = await Ocean.getInstance(config)
assert(ocean)
accounts = await ocean.getAccounts()
assert(accounts)
})
describe("#subscribe()", () => {
it("should subscribe to an event", (done) => {
const eventListener = new EventListener()
const acc = accounts[1]
const event = eventListener.subscribe("OceanToken",
"Transfer",
{
to: acc.getId(),
})
event.listen((events) => {
assert(events)
assert(events.length === 2)
done()
})
const {market} = keeper
market.requestTokens(400, acc.getId())
market.requestTokens(400, acc.getId())
})
})
describe("#unsubscribe()", () => {
it("should subscribe to an event", (done) => {
const eventListener = new EventListener()
const event = eventListener.subscribe("OceanToken",
"Transfer",
{})
const unsubscribed = eventListener.unsubscribe(event)
assert(unsubscribed)
done()
})
})
})