Skip to content

Commit

Permalink
feat: Usar logger utilizado en el componente api
Browse files Browse the repository at this point in the history
  • Loading branch information
bcuestav committed Apr 22, 2021
1 parent 45f66f4 commit 450217d
Show file tree
Hide file tree
Showing 8 changed files with 105 additions and 40 deletions.
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ RUN npm install
# Bundle app source
COPY . /usr/src/app

# Install node global dependencies
RUN npm install -g pino-pretty

# VOLUME ["/usr/src/app/contract/contractABI.json"]

CMD [ "npm", "start" ]
35 changes: 17 additions & 18 deletions event-listener.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@ const EEAClient = require("web3-eea")

const config = require('./config')
const eventHandler = require('./eventHandler')
const { logger } = require('./utils/logger')

const chainId = 1337

// Add ABI contract
const contractPath = path.resolve(__dirname, 'contract', config.besu.contractABIFile)
const contractJSON = JSON.parse(fs.readFileSync(contractPath))
console.log(`Contract ABI file used: ${config.besu.contractABIFile}`)
logger.info(`Contract ABI file used: ${config.besu.contractABIFile}`)
abiDecoder.addABI(contractJSON.abi)

// Connect with node
console.log(`Connecting to node ${config.besu.node.wsUrl}`)
console.log(`ChainId = ${chainId}`)
logger.info(`Connecting to node ${config.besu.node.wsUrl}`)
logger.info(`ChainId = ${chainId}`)
const node = new EEAClient(new Web3(config.besu.node.wsUrl), chainId)

function initializeEventMonitor() {
Expand All @@ -26,15 +27,15 @@ function initializeEventMonitor() {
fromBlock: '0x01'
}

console.log(`Installing filter ${JSON.stringify(filter)} with privacyGroupId ${config.besu.privacyGroupId}`)
logger.info(`Installing filter ${JSON.stringify(filter)} with privacyGroupId ${config.besu.privacyGroupId}`)

// Create subscription
return node.priv.subscribe(config.besu.privacyGroupId, filter, (error, result) => {
if (! error) {
console.log("Installed filter", result)
console.log(`Watching privacyGroupId ${config.besu.privacyGroupId}`)
logger.info("Installed filter", result)
logger.info(`Watching privacyGroupId ${config.besu.privacyGroupId}`)
} else {
console.error("Problem installing filter:", error)
logger.error("Problem installing filter:", error)
throw error
}
})
Expand All @@ -44,36 +45,34 @@ function initializeEventMonitor() {
.on("data", async log => {
if (log.result != null) {
// Logs from subscription are nested in `result` key
console.log("LOG =>", log.result)
logger.debug("LOG =>", log.result)

// Decode event
console.log("Decoding received log...")
logger.info("Decoding received log...")
const decodedLogs = abiDecoder.decodeLogs([ log.result ])
console.log(JSON.stringify(decodedLogs))
logger.info(JSON.stringify(decodedLogs))

// Execute actions
try {
await eventHandler.manage(decodedLogs[0])

//TODO: enviar correo
} catch(error) {
console.log(error)
logger.error(error)
}
} else {
console.log("LOG =>", log)
logger.debug("LOG =>", log)
}
})
.on("error", console.error)
.on("error", logger.error)

// Unsubscribe and disconnect on interrupt
process
.on("SIGINT", async () => {
console.log("unsubscribing")
logger.info("unsubscribing")
await subscription.unsubscribe((error, success) => {
if (!error) {
console.log("Unsubscribed:", success)
logger.info("Unsubscribed:", success)
} else {
console.error("Failed to unsubscribe:", error)
logger.error("Failed to unsubscribe:", error)
}

node.currentProvider.disconnect()
Expand Down
33 changes: 18 additions & 15 deletions eventHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const EEAClient = require('web3-eea')

const config = require('./config')
const mail = require('./mail-sender')
const { logger } = require("./utils/logger")

const chainId = 1337
const web3 = new EEAClient(new Web3(config.besu.node.url), chainId)
Expand Down Expand Up @@ -38,7 +39,7 @@ function updatePCR(insuranceContractAddress, idPCR, resultPCR) {
return new Promise(async function (resolve, reject) {
try {
let funcAbi = await getFunctionAbi(InsuranceContractJSON.abi, 'updatePCR')
console.log(funcAbi)
logger.debug(funcAbi)

// Encode arguments
let funcArguments = web3.eth.abi
Expand All @@ -57,19 +58,21 @@ function updatePCR(insuranceContractAddress, idPCR, resultPCR) {
privateKey: config.besu.node.privateKey,
}

logger.info(`Launching updatePCR transaction to insurance contract...`)
let transactionHash = await web3.eea.sendRawTransaction(functionParams)
console.log(`Transaction hash: ${transactionHash}`)
logger.debug(`Transaction hash: ${transactionHash}`)
let result = await web3.priv.getTransactionReceipt(
transactionHash,
config.orion.taker.publicKey
)
logger.info(`updatePCR transaction executed`)

console.log(result)
logger.debug(result)

if (result.revertReason) {
console.log(
Web3Utils.toAscii(result.revertReason),
'//////////////////////////////////////////'
logger.error(
Web3Utils.toAscii(result.revertReason),
'//////////////////////////////////////////'
)
reject(Web3Utils.toAscii(result.revertReason))
}
Expand Down Expand Up @@ -104,36 +107,36 @@ function sendEmailToInsurer(takerId, insuranceId) {
}

async function manage(log) {
console.log(`Event detected: ${log.name}`)
logger.info(`Event detected: ${log.name}`)
switch (log.name) {
case 'pcrUpdate':
console.log('Updating PCR in Insurance...')
logger.info('Updating PCR in Insurance...')

let insuranceContractAddress = log.events.find(e => e.name === 'insuranceAddress').value
let idPCR = hex2a(log.events.find(e => e.name === 'pcrId').value)
let idResult = hex2a(log.events.find(e => e.name === 'result').value)

console.log(`Event insuranceContractAddress: ${insuranceContractAddress}`)
console.log(`Event idPCR: ${idPCR}`)
console.log(`Event idResult: ${idResult}`)
logger.info(`Event insuranceContractAddress: ${insuranceContractAddress}`)
logger.info(`Event idPCR: ${idPCR}`)
logger.info(`Event idResult: ${idResult}`)

await updatePCR(insuranceContractAddress, idPCR, idResult)

break;
case 'checkPayment':
console.log('Sending email to insurer...')
logger.info('Sending email to insurer...')

let takerId = hex2a(log.events.find(e => e.name === 'takerId').value)
let insuranceId = hex2a(log.events.find(e => e.name === 'insuranceId').value)

sendEmailToInsurer(takerId, insuranceId)
console.log('Email sended to insurer')
logger.info('Email sended to insurer')
break;
default:
console.log("WARNING: Event log not recognized!")
logger.warn("WARNING: Event log not recognized!")
}
}

module.exports = {
manage,
manage
}
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
'use strict'

const config = require('./config')
const eventListener = require('./event-listener')
const { logger } = require("./utils/logger");

console.log('Initializing event monitor...')
logger.info('Initializing event monitor...')

try {
eventListener.initializeEventMonitor()
} catch(error) {
console.log('ERROR: Error al inicializar el monitor de eventos...')
console.log(error)
logger.error('ERROR: Error al inicializar el monitor de eventos...')
logger.error(error)
}
5 changes: 3 additions & 2 deletions mail-sender.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const nodemailer = require('nodemailer')
const config = require('./config')
const { logger } = require("./utils/logger")

function sendEmail(email, subject, text, html) {
console.log(`Sending validation email to ${email} with subject '${subject}'`)
logger.info(`Sending validation email to ${email} with subject '${subject}'`)

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
Expand All @@ -27,7 +28,7 @@ function sendEmail(email, subject, text, html) {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId)
logger.info('Message sent: %s', info.messageId)
})
}

Expand Down
52 changes: 52 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
"description": "Servicio de notificación de eventos de blockchain del proyecto SPC19",
"main": "index.js",
"scripts": {
"start": "node index.js",
"start": "node index.js | pino-pretty -c -t",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Benito Cuesta <[email protected]>",
"license": "UNLICENSED",
"dependencies": {
"abi-decoder": "^2.4.0",
"nodemailer": "^4.6.8",
"pino": "^6.11.3",
"web3": "^1.2.6",
"web3-eea": "^0.10.0"
}
Expand Down
6 changes: 6 additions & 0 deletions utils/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const pino = require("pino");
const logger = pino({
enabled: process.env.NODE_ENV !== "test",
});

module.exports = { logger };

0 comments on commit 450217d

Please sign in to comment.