Skip to content
This repository has been archived by the owner on May 19, 2023. It is now read-only.

Commit

Permalink
feat: fix pr comments
Browse files Browse the repository at this point in the history
  • Loading branch information
nduchak committed Sep 9, 2020
1 parent ba16314 commit 5c6a63f
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 57 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"scripts": {
"prepack": "tasegir run --watch node_modules/.bin/oclif-dev -- manifest && sed -i '' 's#\"./src/cli\"#\"./lib/cli\"#g' package.json",
"postpack": "sed -i '' 's#\"./lib/cli\"#\"./src/cli\"#g' package.json",
"bin": "tasegir run --watch ./bin/run -- ",
"bin": "tasegir run ./bin/run -- ",
"compile": "tasegir compile",
"docs": "typedoc --mode modules --excludeNotExported --readme none --excludePrivate --tsconfig ./node_modules/tasegir/src/config/tsconfig.json --exclude 'src/providers/*,test/**/*' --out docs src",
"types-check": "tasegir types-check",
Expand Down
6 changes: 3 additions & 3 deletions src/cli/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,13 @@ ${formattedServices}`
const resetPromise = new Promise(resolve => {
appFactory({
appResetCallBack: () => resolve()
}).then((application: { app: Application, stop: () => void }) => {
}).then(({ app, stop }) => {
// Lets save the function that stops the app
stopCallback = application.stop
stopCallback = stop

// Start server
const port = config.get('port')
const server = application.app.listen(port)
const server = app.listen(port)

server.on('listening', () =>
logger.info(`Server started on port ${port}`)
Expand Down
29 changes: 9 additions & 20 deletions src/services/storage/handlers/stake.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EventData } from 'web3-eth-contract'
import BigNumber from 'bignumber.js'

import { loggingFactory } from '../../../logger'
import { Handler } from '../../../definitions'
Expand All @@ -11,13 +12,13 @@ const handlers = {
async Staked (event: EventData, { stakeService }: StorageServices): Promise<void> {
const { user: account, total, token, amount } = event.returnValues

const stake = await StakeModel.findOne({ where: { token, account } })
let stake = await StakeModel.findOne({ where: { token, account } })

if (!stake) {
throw new Error(`Stake for acoount ${account}, token ${token} not created`)
stake = new StakeModel({ account, token, total: 0 })
}

stake.total = total
stake.total = new BigNumber(stake.total).plus(amount)
await stake.save()
logger.info(`Account ${account} stake amount ${amount}, final balance ${total}`)

Expand All @@ -29,18 +30,18 @@ const handlers = {
async Unstaked (event: EventData, { stakeService }: StorageServices): Promise<void> {
const { user: account, total, token, amount } = event.returnValues

const stake = await StakeModel.findOne({ where: { token, account } })
let stake = await StakeModel.findOne({ where: { token, account } })

if (!stake) {
throw new Error(`Stake for acoount ${account}, token ${token} not created`)
stake = new StakeModel({ account, token, total: 0 })
}

stake.total = total
stake.total = new BigNumber(stake.total).minus(amount)
await stake.save()
logger.info(`Account ${account} stake amount ${amount}, final balance ${total}`)

if (stakeService.emit) {
stakeService.emit('updated', stake!.toJSON())
stakeService.emit('updated', stake.toJSON())
}
}
}
Expand All @@ -51,22 +52,10 @@ function isValidEvent (value: string): value is keyof typeof handlers {

const handler: Handler<StorageServices> = {
events: ['Staked', 'Unstaked'],
async process (event: EventData, services: StorageServices): Promise<void> {
process (event: EventData, services: StorageServices): Promise<void> {
if (!isValidEvent(event.event)) {
return Promise.reject(new Error(`Unknown event ${event.event}`))
}
const { user: account, token } = event.returnValues
const stake = await StakeModel.findOne({ where: { account, token } })

// Create stake row if not exist
if (!stake) {
const stakeFromDb = await StakeModel.create({ account, token, total: '0' })
logger.debug('Stake created: ', stakeFromDb.toJSON())

if (services.stakeService.emit) {
services.stakeService.emit('created', stakeFromDb.toJSON())
}
}

return handlers[event.event](event, services)
}
Expand Down
43 changes: 22 additions & 21 deletions src/services/storage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { EventEmitter } from 'events'
import { ethFactory } from '../../blockchain'
import { getEventsEmitterForService, isServiceInitialized } from '../../blockchain/utils'
import { REORG_OUT_OF_RANGE_EVENT_NAME } from '../../blockchain/events'
import { Application, CachedService, ServiceAddresses } from '../../definitions'
import { Application, CachedService, Logger, ServiceAddresses } from '../../definitions'
import { loggingFactory } from '../../logger'
import { errorHandler, waitForReadyApp } from '../../utils'
import Agreement from './models/agreement.model'
Expand Down Expand Up @@ -43,13 +43,14 @@ export interface StorageServices {
stakeService: StakeService
}

const SERVICE_NAME = 'storage'
const STORAGE_MANAGER = 'storageManager'
const STAKING = 'staking'
const STORAGE_MANAGER = 'storage.storageManager'
const STAKING = 'storage.staking'

const logger = loggingFactory(SERVICE_NAME)
const storageLogger = loggingFactory('storage')
const storageManagerLogger = loggingFactory(STORAGE_MANAGER)
const stakingLogger = loggingFactory(STAKING)

function precacheContract (eventEmitter: EventEmitter, services: StorageServices, eth: Eth): Promise<void> {
function precacheContract (eventEmitter: EventEmitter, services: StorageServices, eth: Eth, logger: Logger): Promise<void> {
return new Promise<void>((resolve, reject) => {
const dataQueue: EventData[] = []
const dataQueuePusher = (event: EventData): void => { dataQueue.push(event) }
Expand Down Expand Up @@ -77,8 +78,8 @@ function precacheContract (eventEmitter: EventEmitter, services: StorageServices

async function precache (possibleEth?: Eth): Promise<void> {
const eth = possibleEth || ethFactory()
const storageEventsEmitter = getEventsEmitterForService(`${SERVICE_NAME}.${STORAGE_MANAGER}`, eth, storageManagerContract.abi as AbiItem[])
const stakingEventsEmitter = getEventsEmitterForService(`${SERVICE_NAME}.${STAKING}`, eth, stakingContract.abi as AbiItem[])
const storageEventsEmitter = getEventsEmitterForService(`${STORAGE_MANAGER}`, eth, storageManagerContract.abi as AbiItem[])
const stakingEventsEmitter = getEventsEmitterForService(`${STAKING}`, eth, stakingContract.abi as AbiItem[])

const services: StorageServices = {
stakeService: new StakeService({ Model: StakeModel }),
Expand All @@ -87,19 +88,19 @@ async function precache (possibleEth?: Eth): Promise<void> {
}

// Precache Storage Manager
await precacheContract(storageEventsEmitter, services, eth)
await precacheContract(storageEventsEmitter, services, eth, storageManagerLogger)

// Precache Staking
await precacheContract(stakingEventsEmitter, services, eth)
await precacheContract(stakingEventsEmitter, services, eth, stakingLogger)
}

const storage: CachedService = {
async initialize (app: Application): Promise<{ stop: () => void }> {
if (!config.get<boolean>('storage.enabled')) {
logger.info('Storage service: disabled')
storageLogger.info('Storage service: disabled')
return { stop: () => undefined }
}
logger.info('Storage service: enabled')
storageLogger.info('Storage service: enabled')

await waitForReadyApp(app)

Expand All @@ -125,28 +126,28 @@ const storage: CachedService = {
const reorgEmitterService = app.service(ServiceAddresses.REORG_EMITTER)

// We require services to be precached before running server
if (!isServiceInitialized(`${SERVICE_NAME}.${STORAGE_MANAGER}`)) {
return logger.critical('Storage service is not initialized! Run precache command.')
if (!isServiceInitialized(`${STORAGE_MANAGER}`) || !isServiceInitialized(STAKING)) {
return storageLogger.critical('Storage service is not initialized! Run precache command.')
}

const eth = app.get('eth') as Eth
const confirmationService = app.service(ServiceAddresses.CONFIRMATIONS)

// Storage Manager watcher
const storageManagerEventsEmitter = getEventsEmitterForService(`${SERVICE_NAME}.${STORAGE_MANAGER}`, eth, storageManagerContract.abi as AbiItem[])
storageManagerEventsEmitter.on('newEvent', errorHandler(eventProcessor(services, eth), logger))
const storageManagerEventsEmitter = getEventsEmitterForService(`${STORAGE_MANAGER}`, eth, storageManagerContract.abi as AbiItem[])
storageManagerEventsEmitter.on('newEvent', errorHandler(eventProcessor(services, eth), storageManagerLogger))
storageManagerEventsEmitter.on('error', (e: Error) => {
logger.error(`There was unknown error in Events Emitter! ${e}`)
storageManagerLogger.error(`There was unknown error in Events Emitter! ${e}`)
})
storageManagerEventsEmitter.on('newConfirmation', (data) => confirmationService.emit('newConfirmation', data))
storageManagerEventsEmitter.on('invalidConfirmation', (data) => confirmationService.emit('invalidConfirmation', data))
storageManagerEventsEmitter.on(REORG_OUT_OF_RANGE_EVENT_NAME, (blockNumber: number) => reorgEmitterService.emitReorg(blockNumber, 'storage'))

// Staking watcher
const stakingEventsEmitter = getEventsEmitterForService(`${SERVICE_NAME}.${STAKING}`, eth, stakingContract.abi as AbiItem[])
stakingEventsEmitter.on('newEvent', errorHandler(eventProcessor(services, eth), logger))
const stakingEventsEmitter = getEventsEmitterForService(`${STAKING}`, eth, stakingContract.abi as AbiItem[])
stakingEventsEmitter.on('newEvent', errorHandler(eventProcessor(services, eth), stakingLogger))
stakingEventsEmitter.on('error', (e: Error) => {
logger.error(`There was unknown error in Events Emitter! ${e}`)
stakingLogger.error(`There was unknown error in Events Emitter! ${e}`)
})
stakingEventsEmitter.on('newConfirmation', (data) => confirmationService.emit('newConfirmation', data))
stakingEventsEmitter.on('invalidConfirmation', (data) => confirmationService.emit('invalidConfirmation', data))
Expand All @@ -166,7 +167,7 @@ const storage: CachedService = {
const agreementsCount = await Agreement.destroy({ where: {}, truncate: true, cascade: true })
const offersCount = await Offer.destroy({ where: {}, truncate: true, cascade: true })
const stakeCount = await StakeModel.destroy({ where: {}, truncate: true, cascade: true })
logger.info(`Removed ${priceCount} billing plans entries, ${stakeCount} stakes, ${offersCount} offers and ${agreementsCount} agreements`)
storageLogger.info(`Removed ${priceCount} billing plans entries, ${stakeCount} stakes, ${offersCount} offers and ${agreementsCount} agreements`)

const store = getObject()
delete store['storage.storageManager.lastFetchedBlockNumber']
Expand Down
13 changes: 1 addition & 12 deletions test/services/storage/processor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,18 +429,7 @@ describe('Storage services: Events Processor', () => {
expect(createdStake).to.be.instanceOf(StakeModel)
expect(createdStake?.account).to.be.eql(account)
expect(createdStake?.token).to.be.eql(token)
expect(stakeServiceEmitSpy).to.have.been.calledWith('created')
})
it('should not create if existed', async () => {
const total = 1000
const event = eventMock({
event: 'Staked',
returnValues: { user: account, total, token, amount: 1000 }
})
await StakeModel.create({ account, token, total: '0' })
await processor(event)

expect(stakeServiceEmitSpy).to.have.not.been.calledWith('created')
expect(stakeServiceEmitSpy).to.have.been.calledWith('updated')
})
describe('Staked', () => {
it('should update total', async () => {
Expand Down

0 comments on commit 5c6a63f

Please sign in to comment.