Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor event and tasks #843

Merged
merged 4 commits into from
Apr 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions systemservices/marketplace/src/contracts/parseEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { hexToAscii, fromUnit, parseTimestamp } from "./utils";

const serviceCreated = (data: any) => ({
sid: hexToAscii(data.sid),
owner: data.owner,
})
const serviceOfferCreated = (data: any) => ({
sid: hexToAscii(data.sid),
offerIndex: data.offerIndex,
price: fromUnit(data.price),
duration: data.duration,
})
const serviceOfferDisabled = (data: any) => ({
sid: hexToAscii(data.sid),
offerIndex: data.offerIndex,
})
const serviceOwnershipTransferred = (data: any) => ({
sid: hexToAscii(data.sid),
previousOwner: data.previousOwner,
newOwner: data.newOwner,
})
const servicePurchased = (data: any) => ({
sid: hexToAscii(data.sid),
offerIndex: data.offerIndex,
purchaser: data.purchaser,
price: fromUnit(data.price),
duration: data.duration,
expire: parseTimestamp(data.expire),
})
const serviceVersionCreated = (data: any) => ({
sid: hexToAscii(data.sid),
versionHash: data.versionHash,
manifest: hexToAscii(data.manifest),
manifestProtocol: hexToAscii(data.manifestProtocol),
})

export {
serviceCreated,
serviceOfferCreated,
serviceOfferDisabled,
serviceOwnershipTransferred,
servicePurchased,
serviceVersionCreated,
}
3 changes: 2 additions & 1 deletion systemservices/marketplace/src/contracts/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Web3 from 'web3'
import BigNumber from 'bignumber.js';
import Contract from 'web3/eth/contract';
import { TaskInputs } from 'mesg-js/lib/service';
import { Tx } from 'web3/eth/types';
const base58 = require('base-x')('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')

BigNumber.config({ EXPONENTIAL_AT: 100 })
Expand Down Expand Up @@ -37,7 +38,7 @@ interface CreateTransaction {
inputs: TaskInputs,
data: string,
shiftNonce?: number
): Promise<any>;
): Promise<Tx>;
};

const createTransactionTemplate = (
Expand Down
54 changes: 54 additions & 0 deletions systemservices/marketplace/src/events/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Web3 from "web3"
import { EventLog } from "web3/types"
import { Service, EmitEventReply } from "mesg-js/lib/service"

import { newBlockEventEmitter } from "../newBlock"
import { Marketplace } from "../contracts/Marketplace";

import serviceCreated from "./serviceCreated"
import serviceOfferCreated from "./serviceOfferCreated"
import serviceOfferDisabled from "./serviceOfferDisabled"
import serviceOwnershipTransferred from "./serviceOwnershipTransferred"
import serviceVersionCreated from "./serviceVersionCreated"
import servicePurchased from "./servicePurchased"

const eventHandlers: {[eventName: string]: (mesg: Service, event: EventLog) => Promise<EmitEventReply | Error>} = {
'ServiceCreated': serviceCreated,
'ServiceOfferCreated': serviceOfferCreated,
'ServiceOfferDisabled': serviceOfferDisabled,
'ServiceOwnershipTransferred': serviceOwnershipTransferred,
'ServicePurchased': servicePurchased,
'ServiceVersionCreated': serviceVersionCreated,
}

export default async (
mesg: Service,
web3: Web3,
marketplace: Marketplace,
blockConfirmations: number,
pollingTime: number
) => {
const newBlock = await newBlockEventEmitter(web3, blockConfirmations, null, pollingTime)
newBlock.on('newBlock', async blockNumber => {
try {
console.log('new block', blockNumber)
const events = await marketplace.getPastEvents("allEvents", {
fromBlock: blockNumber,
toBlock: blockNumber,
})
events.forEach(async event => {
try {
if (!eventHandlers[event.event]) {
throw new Error(`Event '${event.event}' not implemented`)
}
eventHandlers[event.event](mesg, event)
} catch(error) {
console.error('An error occurred during processing of an event', event)
}
})
}
catch (error) {
console.error('catch newBlock on', error)
}
})
}
7 changes: 2 additions & 5 deletions systemservices/marketplace/src/events/serviceCreated.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import Service, { EmitEventReply } from "mesg-js/lib/service/service"
import { EventLog } from "web3/types";
import { hexToAscii } from "../contracts/utils";
import { serviceCreated } from "../contracts/parseEvents";

export = (mesg: Service, event: EventLog): Promise<EmitEventReply | Error> => {
return mesg.emitEvent('serviceCreated', {
sid: hexToAscii(event.returnValues.sid),
owner: event.returnValues.owner,
})
return mesg.emitEvent('serviceCreated', serviceCreated(event.returnValues))
}
9 changes: 2 additions & 7 deletions systemservices/marketplace/src/events/serviceOfferCreated.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import Service, { EmitEventReply } from "mesg-js/lib/service/service"
import { EventLog } from "web3/types";
import { fromUnit, hexToAscii } from "../contracts/utils";
import { serviceOfferCreated } from "../contracts/parseEvents";

export = (mesg: Service, event: EventLog): Promise<EmitEventReply | Error> => {
return mesg.emitEvent('serviceOfferCreated', {
sid: hexToAscii(event.returnValues.sid),
offerIndex: event.returnValues.offerIndex,
price: fromUnit(event.returnValues.price),
duration: event.returnValues.duration,
})
return mesg.emitEvent('serviceOfferCreated', serviceOfferCreated(event.returnValues))
}
7 changes: 2 additions & 5 deletions systemservices/marketplace/src/events/serviceOfferDisabled.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import Service, { EmitEventReply } from "mesg-js/lib/service/service"
import { EventLog } from "web3/types";
import { hexToAscii } from "../contracts/utils";
import { serviceOfferDisabled } from "../contracts/parseEvents";

export = (mesg: Service, event: EventLog): Promise<EmitEventReply | Error> => {
return mesg.emitEvent('serviceOfferDisabled', {
sid: hexToAscii(event.returnValues.sid),
offerIndex: event.returnValues.offerIndex,
})
return mesg.emitEvent('serviceOfferDisabled', serviceOfferDisabled(event.returnValues))
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import Service, { EmitEventReply } from "mesg-js/lib/service/service"
import { EventLog } from "web3/types";
import { hexToAscii } from "../contracts/utils";
import { serviceOwnershipTransferred } from "../contracts/parseEvents";

export = (mesg: Service, event: EventLog): Promise<EmitEventReply | Error> => {
return mesg.emitEvent('serviceOwnershipTransferred', {
sid: hexToAscii(event.returnValues.sid),
previousOwner: event.returnValues.previousOwner,
newOwner: event.returnValues.newOwner,
})
return mesg.emitEvent('serviceOwnershipTransferred', serviceOwnershipTransferred(event.returnValues))
}
11 changes: 2 additions & 9 deletions systemservices/marketplace/src/events/servicePurchased.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import Service, { EmitEventReply } from "mesg-js/lib/service/service"
import { EventLog } from "web3/types";
import { fromUnit, hexToAscii } from "../contracts/utils";
import { servicePurchased } from "../contracts/parseEvents";

export = (mesg: Service, event: EventLog): Promise<EmitEventReply | Error> => {
return mesg.emitEvent('servicePurchased', {
sid: hexToAscii(event.returnValues.sid),
offerIndex: event.returnValues.offerIndex,
purchaser: event.returnValues.purchaser,
price: fromUnit(event.returnValues.price),
duration: event.returnValues.duration,
expire: event.returnValues.expire,
})
return mesg.emitEvent('servicePurchased', servicePurchased(event.returnValues))
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import Service, { EmitEventReply } from "mesg-js/lib/service/service"
import { EventLog } from "web3/types";
import { hexToAscii } from "../contracts/utils";
import { serviceVersionCreated } from "../contracts/parseEvents";

export = (mesg: Service, event: EventLog): Promise<EmitEventReply | Error> => {
return mesg.emitEvent('serviceVersionCreated', {
sid: hexToAscii(event.returnValues.sid),
versionHash: event.returnValues.versionHash,
manifest: hexToAscii(event.returnValues.manifest),
manifestProtocol: hexToAscii(event.returnValues.manifestProtocol),
})
return mesg.emitEvent('serviceVersionCreated', serviceVersionCreated(event.returnValues))
}
72 changes: 4 additions & 68 deletions systemservices/marketplace/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,13 @@
import { service as MESG } from "mesg-js"
import { TaskInputs, Service, EmitEventReply } from "mesg-js/lib/service"

import Web3 from "web3"
import { EventLog } from "web3/types"

import { newBlockEventEmitter } from "./newBlock"

import marketplaceABI from "./contracts/Marketplace.abi.json"
import { Marketplace } from "./contracts/Marketplace"

import ERC20ABI from "./contracts/ERC20.abi.json"
import { ERC20 } from "./contracts/ERC20"

import serviceCreated from "./events/serviceCreated"
import serviceOfferCreated from "./events/serviceOfferCreated"
import serviceOfferDisabled from "./events/serviceOfferDisabled"
import serviceOwnershipTransferred from "./events/serviceOwnershipTransferred"
import serviceVersionCreated from "./events/serviceVersionCreated"
import servicePurchased from "./events/servicePurchased"

import publishServiceVersion from "./tasks/publishServiceVersion"
import getService from "./tasks/getService"
import createServiceOffer from "./tasks/createServiceOffer"
import listServices from "./tasks/listServices"
import purchase from "./tasks/purchase"
import sendSignedTransaction from "./tasks/sendSignedTransaction"
import isAuthorized from "./tasks/isAuthorized"
import { createTransactionTemplate } from "./contracts/utils";
import listenTasks from "./tasks"
import listenEvents from "./events"

const providerEndpoint = process.env.PROVIDER_ENDPOINT as string
const marketplaceAddress = process.env.MARKETPLACE_ADDRESS
Expand All @@ -35,15 +16,6 @@ const blockConfirmations = parseInt(<string>process.env.BLOCK_CONFIRMATIONS, 10)
const defaultGas = parseInt(<string>process.env.DEFAULT_GAS, 10)
const pollingTime = parseInt(<string>process.env.POLLING_TIME, 10)

const eventHandlers: {[key: string]: (mesg: Service, event: EventLog) => Promise<EmitEventReply | Error>} = {
'ServiceCreated': serviceCreated,
'ServiceOfferCreated': serviceOfferCreated,
'ServiceOfferDisabled': serviceOfferDisabled,
'ServiceOwnershipTransferred': serviceOwnershipTransferred,
'ServicePurchased': servicePurchased,
'ServiceVersionCreated': serviceVersionCreated,
}

const main = async () => {
const mesg = MESG()
const web3 = new Web3(providerEndpoint)
Expand All @@ -55,44 +27,8 @@ const main = async () => {
const defaultGasPrice = await web3.eth.getGasPrice()
console.log('defaultGasPrice', defaultGasPrice)

const createTransaction = createTransactionTemplate(chainID, web3, defaultGas, defaultGasPrice)

mesg.listenTask({
listServices: listServices(marketplace),
getService: getService(marketplace),
publishServiceVersion: publishServiceVersion(marketplace, createTransaction),
createServiceOffer: createServiceOffer(marketplace, createTransaction),
purchase: purchase(marketplace, token, createTransaction),
sendSignedTransaction: sendSignedTransaction(web3),
isAuthorized: isAuthorized(marketplace),
})
.on('error', error => console.error('catch listenTask', error))

const newBlock = await newBlockEventEmitter(web3, blockConfirmations, null, pollingTime)
newBlock.on('newBlock', async blockNumber => {
try {
console.error('new block', blockNumber)

const events = await marketplace.getPastEvents("allEvents", {
fromBlock: blockNumber,
toBlock: blockNumber,
})
events.forEach(async event => {
// TODO: check if really async
try {
if (!eventHandlers[event.event]) {
return console.error('Event not implemented', event.event)
}
eventHandlers[event.event](mesg, event)
} catch(error) {
return console.error('An error occurred during processing of an event', event)
}
})
}
catch (error) {
console.error('catch newBlock on', error)
}
})
listenTasks(mesg, web3, marketplace, token, chainID, defaultGas, defaultGasPrice)
await listenEvents(mesg, web3, marketplace, blockConfirmations, pollingTime)

console.log('service is ready and running')
}
Expand Down
36 changes: 36 additions & 0 deletions systemservices/marketplace/src/tasks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import Web3 from "web3"
import { Service } from "mesg-js/lib/service"

import { Marketplace } from "../contracts/Marketplace";
import { createTransactionTemplate } from "../contracts/utils";
import { ERC20 } from "../contracts/ERC20";

import publishServiceVersion from "./publishServiceVersion"
import getService from "./getService"
import createServiceOffer from "./createServiceOffer"
import listServices from "./listServices"
import purchase from "./purchase"
import sendSignedTransaction from "./sendSignedTransaction"
import isAuthorized from "./isAuthorized"

export default async (
mesg: Service,
web3: Web3,
marketplace: Marketplace,
token: ERC20,
chainID: number,
defaultGas: number,
defaultGasPrice: number
) => {
const createTransaction = createTransactionTemplate(chainID, web3, defaultGas, defaultGasPrice)
mesg.listenTask({
listServices: listServices(marketplace),
getService: getService(marketplace),
publishServiceVersion: publishServiceVersion(marketplace, createTransaction),
createServiceOffer: createServiceOffer(marketplace, createTransaction),
purchase: purchase(marketplace, token, createTransaction),
sendSignedTransaction: sendSignedTransaction(web3),
isAuthorized: isAuthorized(marketplace),
})
.on('error', error => console.error('catch listenTask', error))
}