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

reword event handling

This commit is contained in:
Sebastian Gerske 2018-10-04 13:14:03 +02:00
parent db19f6b070
commit f4f32ab402
5 changed files with 77 additions and 75 deletions

View File

@ -1,4 +1,4 @@
import Contract from "web3" import {Contract} from "web3-utils"
import Logger from "../utils/Logger" import Logger from "../utils/Logger"
import Web3Helper from "./Web3Helper" import Web3Helper from "./Web3Helper"

View File

@ -1,4 +1,5 @@
import Config from "../models/Config" import Config from "../models/Config"
import Logger from "../utils/Logger"
import ContractHandler from "./ContractHandler" import ContractHandler from "./ContractHandler"
import Web3Helper from "./Web3Helper" import Web3Helper from "./Web3Helper"
@ -16,6 +17,37 @@ export default class ContractWrapperBase {
this.web3Helper = web3Helper this.web3Helper = web3Helper
} }
public async listenToEventOnce(eventName: string, options: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!this.contract.events[eventName]) {
throw new Error(`Event ${eventName} not found on contract ${this.contractName}`)
}
this.contract.once(eventName, options, (error: any, eventData: any) => {
if (error) {
Logger.log(`Error in keeper ${eventName} event: `, error)
return reject(error)
}
resolve(eventData)
})
})
}
public async getEventData(eventName: any, options: any): Promise<any[]> {
return new Promise<any>((resolve, reject) => {
if (!this.contract.events[eventName]) {
throw new Error(`Event ${eventName} not found on contract ${this.contractName}`)
}
this.contract.events[eventName](options)
.on("data", (eventData: any[]) => {
Logger.log(eventData)
resolve(eventData)
})
.on("error", (error) => {
return reject(error)
})
})
}
public async init() { public async init() {
this.contract = await ContractHandler.get(this.contractName, this.web3Helper) this.contract = await ContractHandler.get(this.contractName, this.web3Helper)
} }
@ -24,10 +56,4 @@ export default class ContractWrapperBase {
return this.contract.address return this.contract.address
} }
public getEvent(name: string) {
if (!this.contract.events[name]) {
throw new Error(`Event ${name} not found on contract ${this.contractName}`)
}
return this.contract.events[name]
}
} }

View File

@ -1,30 +0,0 @@
import Logger from "../utils/Logger"
export default class EventListener {
public static async listenOnce(event: any, eventName: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
event.watch((error: any, result: any) => {
event.stopWatching()
if (error) {
Logger.log(`Error in keeper ${eventName} event: `, error)
return reject(error)
}
resolve(result)
})
})
}
public static getEvents(event: any): Promise<any[]> {
return new Promise<any>((resolve, reject) => {
event.get((error: any, logs: any[]) => {
if (error) {
reject(error)
throw new Error(error)
} else {
resolve(logs)
}
})
})
}
}

View File

@ -1,5 +1,9 @@
import Web3 = require("web3") import * as Web3 from "web3"
import * as web3pkg from "../../node_modules/web3/package.json"
import Config from "../models/Config" import Config from "../models/Config"
import Logger from "../utils/Logger"
Logger.log(web3pkg.version)
export default class Web3Helper { export default class Web3Helper {
@ -7,7 +11,7 @@ export default class Web3Helper {
public constructor(config: Config) { public constructor(config: Config) {
const web3Provider = config.web3Provider || new Web3.providers.HttpProvider(config.nodeUri) const web3Provider = config.web3Provider || new Web3.providers.HttpProvider(config.nodeUri)
this.web3 = new Web3(web3Provider) this.web3 = new Web3(Web3.givenProvider || web3Provider)
} }
public getWeb3() { public getWeb3() {

View File

@ -2,7 +2,6 @@ import * as EthCrypto from "eth-crypto"
import EthEcies from "eth-ecies" import EthEcies from "eth-ecies"
import * as EthjsUtil from "ethereumjs-util" import * as EthjsUtil from "ethereumjs-util"
import JWT from "jsonwebtoken" import JWT from "jsonwebtoken"
import EventListener from "../keeper/EventListener"
import Keeper from "../keeper/Keeper" import Keeper from "../keeper/Keeper"
import Asset from "../models/Asset" import Asset from "../models/Asset"
import OrderModel from "../models/Order" import OrderModel from "../models/Order"
@ -34,24 +33,30 @@ export default class Order {
public async getOrdersByConsumer(consumerAddress: string) { public async getOrdersByConsumer(consumerAddress: string) {
const {auth, market} = this.keeper const {auth, market} = this.keeper
const accessConsentEvent = auth.getEvent("AccessConsentRequested")({
_consumer: consumerAddress, const accessConsentRequestedData = await auth.getEventData("AccessConsentRequested", {
}, { filter: {
_consumer: consumerAddress,
},
fromBlock: 0, fromBlock: 0,
toBlock: "latest",
}) })
const events = await EventListener.getEvents(accessConsentEvent) Logger.log("wai", accessConsentRequestedData)
const orders = await Promise.all(
accessConsentRequestedData
.filter((event: any) => (event.args._consumer === consumerAddress))
.map(async (event: any) => ({
...event.args,
timeout: event.args._timeout.toNumber(),
status: await auth.getOrderStatus(event.args._id),
paid: await market.verifyOrderPayment(event.args._id),
key: null,
} as Order
),
),
)
const orders = await Promise.all(events
.filter((event: any) => (event.args._consumer === consumerAddress))
.map(async (event: any) => ({
...event.args,
timeout: event.args._timeout.toNumber(),
status: await auth.getOrderStatus(event.args._id),
paid: await market.verifyOrderPayment(event.args._id),
key: null,
} as Order)))
Logger.log("Got orders: ", orders) Logger.log("Got orders: ", orders)
return orders return orders
} }
@ -81,36 +86,33 @@ export default class Order {
} catch (err) { } catch (err) {
Logger.log("initiateAccessRequest", err) Logger.log("initiateAccessRequest", err)
} }
const resourceFilter = {
_resourceId: asset.assetId,
_consumer: buyerAddress,
}
// todo: Event - implement proper eventing
const accessConsentRequestedEvent = auth.getEvent("AccessConsentRequested")(resourceFilter)
let order: OrderModel let order: OrderModel
const finalOrder: OrderModel = await EventListener.listenOnce( const finalOrder: OrderModel = await auth.listenToEventOnce(
accessConsentRequestedEvent, "AccessConsentRequested", {
"AccessConsentRequested") filter: {
_resourceId: asset.assetId,
_consumer: buyerAddress,
},
})
.then((accessConsentRequestedResult) => { .then((accessConsentRequestedResult) => {
order = Order.create(asset, accessConsentRequestedResult.args, key) order = Order.create(asset, accessConsentRequestedResult.args, key)
const requestIdFilter = {
_id: order.id,
}
// todo: Event - implement proper eventing
const accessCommittedEvent = auth.getEvent("AccessRequestCommitted")(requestIdFilter)
return EventListener.listenOnce(accessCommittedEvent, "AccessRequestCommitted") return auth.listenToEventOnce("AccessRequestCommitted", {
filter: {
_id: order.id,
},
})
}) })
.then((accessRequestCommittedResult) => { .then((accessRequestCommittedResult) => {
return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress) return this.payAsset(asset, accessRequestCommittedResult.args, order, buyerAddress)
}) })
.then(() => { .then(() => {
const requestIdFilter = { return auth.listenToEventOnce("EncryptedTokenPublished", {
_id: order.id, filter: {
} _id: order.id,
// todo: Event - implement proper eventing },
const tokenPublishedEvent = auth.getEvent("EncryptedTokenPublished")(requestIdFilter) })
return EventListener.listenOnce(tokenPublishedEvent, "EncryptedTokenPublished")
}) })
.then((result) => { .then((result) => {
return this.finalizePurchaseAsset( return this.finalizePurchaseAsset(