-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventHandler.js
152 lines (127 loc) · 5.03 KB
/
eventHandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
'use strict'
const path = require('path')
const fs = require('fs-extra')
const Web3 = require('web3')
const Web3Utils = require('web3-utils')
const EEAClient = require('web3-eea')
const config = require('./config')
const mail = require('./mail-sender')
const { logger } = require("./utils/logger")
const { toUUID } = require("to-uuid");
const mailTemplate = fs
.readFileSync(path.join(__dirname, "templates", "mail.template"))
.toString();
const chainId = 1337
const web3 = new EEAClient(new Web3(config.besu.node.url), chainId)
// Add ABI contract
const insuranceContractPath = path.resolve(__dirname, 'contract', 'Insurance.json')
const InsuranceContractJSON = JSON.parse(fs.readFileSync(insuranceContractPath))
/**
* Obtiene el abi (datos de una función en solidity) de la función elegida
* @param {Object} abi
* @param {String} functionName
* @param {Web3} web3
* @returns {Object} Abi de la función elegida
*/
function getFunctionAbi(abi, functionName) {
const contract = new web3.eth.Contract(abi)
const functionAbi = contract._jsonInterface.find((e) => {
return e.name === functionName;
})
return functionAbi
}
/**
* Actualiza la PCR del contrato de póliza
*/
function updatePCR(insuranceContractAddress, idPCR, resultPCR) {
return new Promise(async function (resolve, reject) {
try {
let funcAbi = await getFunctionAbi(InsuranceContractJSON.abi, 'updatePCR')
logger.debug(funcAbi)
// Encode arguments
let funcArguments = web3.eth.abi
.encodeParameters(funcAbi.inputs, [
Web3Utils.fromAscii(idPCR),
Web3Utils.fromAscii(resultPCR)
])
.slice(2)
let functionParams = {
to: insuranceContractAddress,
data: funcAbi.signature + funcArguments,
privateFrom: config.orion.taker.publicKey,
privateFor: [config.orion.insurer.publicKey],
privateKey: config.besu.node.privateKey,
}
logger.info(`Launching updatePCR transaction to insurance contract...`)
let transactionHash = await web3.eea.sendRawTransaction(functionParams)
logger.debug(`Transaction hash: ${transactionHash}`)
let result = await web3.priv.getTransactionReceipt(
transactionHash,
config.orion.taker.publicKey
)
logger.info(`updatePCR transaction executed`)
logger.debug(result)
if (result.revertReason) {
logger.error(
Web3Utils.toAscii(result.revertReason),
'//////////////////////////////////////////'
)
reject(Web3Utils.toAscii(result.revertReason))
}
resolve(result)
} catch(error) {
reject(error)
}
})
}
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 2; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
/**
* Envio de correos a la aseguradora con los datos del pago a realizar
*/
function sendEmailToInsurer(takerId, insuranceId) {
const parsedInsuranceId = toUUID(insuranceId);
const parsedTakerId = toUUID(takerId);
const htmlEmail = mailTemplate
.replace(/\<INSURANCEID\>/g, parsedInsuranceId)
.replace(/\<TAKERID\>/g, parsedTakerId);
// send email
mail.sendEmail(
config.EMAIL.insurerEmail,
"SPC19: Indemnización calculada por la blockchain",
`Hola,\nSe ha recibido un evento de la blockchain indicando que procede un pago con los siguientes datos.\n - Identificador de la póliza: ${parsedInsuranceId}\n - Identitifador del hotel: ${parsedTakerId}`,
htmlEmail
);
}
async function manage(log) {
logger.info(`Event detected: ${log.name}`)
switch (log.name) {
case 'pcrUpdate':
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)
logger.info(`Event insuranceContractAddress: ${insuranceContractAddress}`)
logger.info(`Event idPCR: ${idPCR}`)
logger.info(`Event idResult: ${idResult}`)
await updatePCR(insuranceContractAddress, idPCR, idResult)
break;
case 'checkPayment':
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)
logger.info('Email sended to insurer')
break;
default:
logger.warn("WARNING: Event log not recognized!")
}
}
module.exports = {
manage
}