Skip to content

Commit

Permalink
Merge pull request #8 from bosonprotocol/revert-7-error-handling
Browse files Browse the repository at this point in the history
Revert "Error handling"
  • Loading branch information
HristiyanG authored Dec 7, 2020
2 parents db2e562 + 02f8fde commit af3db39
Show file tree
Hide file tree
Showing 13 changed files with 113 additions and 198 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
package-lock.json
.DS_Store
yarn.lock
/local
/tests

.idea
115 changes: 34 additions & 81 deletions functions/index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
const functions = require('firebase-functions');
const axios = require('axios').default;

const VOUCHER_KERNEL_ADDRESS = functions.config().poc1.voucherkerneladdress;
const CASHIER_ADDRESS = functions.config().poc1.cashieraddress;
const VOUCHER_KERNEL_ADDRESS = functions.config().scheduledkeepers.voucherkerneladdress;
const CASHIER_ADDRESS = functions.config().scheduledkeepers.cashieraddress;

const VoucherKernel = require("./abis/VoucherKernel.json");
const Cashier = require("./abis/Cashier.json");

const ethers = require('ethers');

const EXECUTOR_PRIVATE_KEY = functions.config().poc1.executorsecret;
const NETWORK_NAME = functions.config().poc1.networkname;
const ETHERSCAN_API_KEY = functions.config().poc1.etherscanapikey;
const INFURA_API_KEY = functions.config().poc1.infuraapikey;
const EXECUTOR_PRIVATE_KEY = functions.config().scheduledkeepers.executorsecret;
const NETWORK_NAME = functions.config().scheduledkeepers.networkname;
const ETHERSCAN_API_KEY = functions.config().scheduledkeepers.etherscanapikey;
const INFURA_API_KEY = functions.config().scheduledkeepers.infuraapikey;

const provider = ethers.getDefaultProvider(NETWORK_NAME, {
etherscan: ETHERSCAN_API_KEY,
infura: INFURA_API_KEY
});
const executor = new ethers.Wallet(EXECUTOR_PRIVATE_KEY, provider);

const API_URL = functions.config().poc1.apiurl;
const ALL_VOUCHERS_URL = `${API_URL}/user-vouchers/all`;
const CHECK_PAYMENTS_BY_VOUCHER_URL = `${API_URL}/payments/check-payment`;
const FINALIZE_VOUCHER_URL = `${API_URL}/user-vouchers/finalize`;
const WITHDRAW_VOUCHER_URL = `${API_URL}/payments/create-payment`;
const API_URL = functions.config().scheduledkeepers.apiurl;
const ALL_VOUCHERS_URL = `${ API_URL }/user-vouchers/all`;
const CHECK_PAYMENTS_BY_VOUCHER_URL = `${ API_URL }/payments/check-payment`;
const FINALIZE_VOUCHER_URL = `${ API_URL }/user-vouchers/finalize`;
const WITHDRAW_VOUCHER_URL = `${ API_URL }/payments/create-payment`;

const COMMIT_IDX = 7; // usingHelpers contract
const GAS_LIMIT = '300000';
Expand Down Expand Up @@ -62,33 +62,16 @@ exports.scheduledKeepers = functions.https.onRequest(async (request, response) =
response.send("Аll keepers were executed successfully!");
});

exports.scheduledKeepersDev = functions.https.onRequest(async (request, response) => {
// Expiration process
await triggerExirations();

// Finalization process
await triggerFinalizations();

// Withdrawal process
await triggerWithdrawals();

response.send("Аll keepers were executed successfully!");
});

async function triggerExirations() {
let hasErrors = false;
let voucherKernelContractExecutor = new ethers.Contract(VOUCHER_KERNEL_ADDRESS, VoucherKernel.abi, executor);
let vouchers;

try {
vouchers = await axios.get(ALL_VOUCHERS_URL);
} catch (e) {
hasErrors = true;
console.error(`Error while getting all vouchers from the DB. Error: ${e}`);
console.error(`Error while getting all vouchers from the DB. Error: ${ e }`);
}

if (typeof vouchers === 'undefined' || !vouchers.hasOwnProperty('data')) return;

for (let i = 0; i < vouchers.data.vouchersDocuments.length; i++) {
let voucher = vouchers.data.vouchersDocuments[i];
let voucherID = voucher._tokenIdVoucher;
Expand All @@ -98,54 +81,46 @@ async function triggerExirations() {
let voucherStatus = await voucherKernelContractExecutor.getVoucherStatus(voucherID);
isStatusCommit = voucherStatus[0] == (0 | 1 << COMMIT_IDX); // condition is borrowed from helper contract
} catch (e) {
hasErrors = true;
console.error(`Error while checking voucher status toward the contract. Error: ${e}`);
console.error(`Error while checking voucher status toward the contract. Error: ${ e }`);
}

if (!isStatusCommit || EXPIRATION_BLACKLISTED_VOUCHER_IDS.includes(voucherID)) {
continue;
}

console.log(`Voucher: ${voucherID} is with commit status. The expiration is triggered.`);
console.log(`Voucher: ${ voucherID } is with commit status. The expiration is triggered.`);

try {
let txOrder = await voucherKernelContractExecutor.triggerExpiration(voucherID);
await txOrder.wait();
} catch (e) {
hasErrors = true;
console.error(`Error while triggering expiration of the voucher. Error: ${e}`);
console.error(`Error while triggering expiration of the voucher. Error: ${ e }`);
}
}

let infoMsg = hasErrors ? 'triggerExirations function finished with errors' : 'triggerExirations function finished successfully'

console.info(infoMsg);
console.info(`triggerExirations function finished successfully`);
}

async function triggerFinalizations() {
let hasErrors = false;
let voucherKernelContractExecutor = new ethers.Contract(VOUCHER_KERNEL_ADDRESS, VoucherKernel.abi, executor);
let vouchers;

try {
vouchers = await axios.get(ALL_VOUCHERS_URL);
} catch (e) {
console.error(`Error while getting all vouchers from the DB. Error: ${e}`);
return;
console.error(`Error while getting all vouchers from the DB. Error: ${ e }`);
}

if (typeof vouchers === 'undefined' || !vouchers.hasOwnProperty('data')) return;

for (let i = 0; i < vouchers.data.vouchersDocuments.length; i++) {
let voucher = vouchers.data.vouchersDocuments[i];
let voucherID = voucher._tokenIdVoucher;

if (voucher.FINALIZED || FINALIZATION_BLACKLISTED_VOUCHER_IDS.includes(voucherID)) {
console.log(`Voucher: ${voucherID} is already finalized`);
console.log(`Voucher: ${ voucherID } is already finalized`);
continue;
}

console.log(`Voucher: ${voucherID}. The finalization has started.`);
console.log(`Voucher: ${ voucherID }. The finalization has started.`);

let txOrder;
let receipt;
Expand All @@ -155,9 +130,7 @@ async function triggerFinalizations() {

receipt = await txOrder.wait();
} catch (e) {
hasErrors = true;
console.error(`Error while triggering finalization of the voucher. Error: ${e}`);
continue;
console.error(`Error while triggering finalization of the voucher. Error: ${ e }`);
}
let parsedEvent = await findEventByName(receipt, 'LogFinalizeVoucher', '_tokenIdVoucher', '_triggeredBy');

Expand All @@ -168,40 +141,33 @@ async function triggerFinalizations() {
status: "FINALIZED"
}];

console.log(`Voucher: ${voucherID}. The finalization finished.`);
console.log(`Voucher: ${ voucherID }. The finalization finished.`);

try {
await axios.patch(FINALIZE_VOUCHER_URL, payload);

console.log(`Voucher: ${voucherID}. Database updated.`);
console.log(`Voucher: ${ voucherID }. Database updated.`);
} catch (e) {
hasErrors = true;
console.log(e);
console.error(`Error while updating the DB related to finalization of the voucher. Error: ${e}`);
continue;
console.error(`Error while updating the DB related to finalization of the voucher. Error: ${ e }`);
}
}
}

let infoMsg = hasErrors ? 'triggerFinalizations function finished with errors' : 'triggerFinalizations function finished successfully'

console.info(infoMsg);
console.info(`triggerFinalizations function finished successfully`);
}

async function triggerWithdrawals() {
let hasErrors = false;
let cashierContractExecutor = new ethers.Contract(CASHIER_ADDRESS, Cashier.abi, executor);
let voucherKernelContractExecutor = new ethers.Contract(VOUCHER_KERNEL_ADDRESS, VoucherKernel.abi, executor);
let vouchers;

try {
vouchers = await axios.get(ALL_VOUCHERS_URL);
} catch (e) {
console.error(`Error while getting all vouchers from the DB. Error: ${e}`);
console.error(`Error while getting all vouchers from the DB. Error: ${ e }`);
}

if (typeof vouchers === 'undefined' || !vouchers.hasOwnProperty('data')) return;

for (let i = 0; i < vouchers.data.vouchersDocuments.length; i++) {
let voucher = vouchers.data.vouchersDocuments[i];
let voucherID = voucher._tokenIdVoucher;
Expand All @@ -212,17 +178,15 @@ async function triggerWithdrawals() {
isPaymentAndDepositsReleased = voucherStatus[1] && voucherStatus[2];

} catch (e) {
hasErrors = true;
console.error(`Error while checking existing payments for a voucher from the DB. Error: ${e}`);
continue;
console.error(`Error while checking existing payments for a voucher from the DB. Error: ${ e }`);
}

if (isPaymentAndDepositsReleased || WITHDRAWAL_BLACKLISTED_VOUCHER_IDS.includes(voucherID)) {
console.log(`Voucher: ${voucherID} - a payment and deposits withdrawal completed `);
console.log(`Voucher: ${ voucherID } - a payment and deposits withdrawal completed `);
continue;
}

console.log(`Voucher: ${voucherID}. The withdraw process has started`);
console.log(`Voucher: ${ voucherID }. The withdraw process has started`);

let txOrder;
let receipt;
Expand All @@ -231,37 +195,26 @@ async function triggerWithdrawals() {
txOrder = await cashierContractExecutor.withdraw([voucherID], { gasLimit: GAS_LIMIT });
receipt = await txOrder.wait();
} catch (e) {
hasErrors = true;
console.error(`Error while executing withdraw process. Error: ${e}`);
continue;
console.error(`Error while executing withdraw process. Error: ${ e }`);
}

console.log(`Voucher: ${voucherID}. The withdraw process finished`);
console.log(`Voucher: ${ voucherID }. The withdraw process finished`);

let events = await findEventByName(receipt, 'LogWithdrawal', '_caller', '_payee', '_payment')

try {
if (Array.isArray(events)
&& typeof events[0] === 'object'
&& events[0].hasOwnProperty('_tokenIdVoucher')) {
await sendPayments(events);
}
await sendPayments(events);
} catch (e) {
hasErrors = true;
console.error(`Error while executing a create payment call to the backend . Error: ${e}`);
console.error(`Error while executing a create payment call to the backend . Error: ${ e }`);
}

console.log(`Voucher: ${voucherID}. Database updated`);
console.log(`Voucher: ${ voucherID }. Database updated`);
}

let infoMsg = hasErrors ? 'triggerWithdrawals function finished with errors' : 'triggerWithdrawals function finished successfully'

console.info(infoMsg);
console.info(`triggerWithdrawals function finished successfully`);
}

async function findEventByName(txReceipt, eventName, ...eventFields) {
if (typeof txReceipt !== 'object' && txReceipt !== null) return

let eventsArr = [];

for (const key in txReceipt.events) {
Expand Down
15 changes: 5 additions & 10 deletions src/api/controllers/admin-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,14 @@ class AdminController {
return next(new ApiError(400, `Provided address: ${address} is not a valid ETH address!`))
}

try {
const user = await mongooseService.getUser(address)

if (!user) {
return next(new ApiError(400, `Provided user does not exist in the DB!`))
}

await mongooseService.makeAdmin(address);
const user = await mongooseService.getUser(address)

} catch (error) {
return next(new ApiError(400, `Provided address: ${address} was not set as admin!`))
if (!user) {
return next(new ApiError(400, `Provided user does not exist in the DB!`))
}

await mongooseService.makeAdmin(address);

res.status(200).send({updated: true})
}
}
Expand Down
9 changes: 1 addition & 8 deletions src/api/controllers/payment-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,7 @@ class PaymentController {
static async getPaymentsByVoucherID(req, res, next) {
const tokenIdVoucher = req.params.tokenIdVoucher;

let payments;

try {
payments = await mongooseService.getPaymentsByVoucherID(tokenIdVoucher);
} catch (error) {
console.error(error)
return next(new APIError(400, `Get payment for voucher id: ${ tokenIdVoucher } could not be completed.`))
}
const payments = await mongooseService.getPaymentsByVoucherID(tokenIdVoucher);

res.status(200).send({ payments })
}
Expand Down
Loading

0 comments on commit af3db39

Please sign in to comment.