Pipepline working until dummy tx

This commit is contained in:
Pol.Alvarez@BSC 2018-01-22 21:21:31 +01:00
parent bcb7b939c8
commit 5188fa7923
4 changed files with 50 additions and 36 deletions

View File

@ -6,32 +6,45 @@ const config = require('../config');
// Returns the url for getting the labels of a request (Github v3) // Returns the url for getting the labels of a request (Github v3)
// req has req.issue.labels_url // req has req.issue.labels_url
const getLabelsURL = function(req) { const getLabelsURL = function(req) {
let url = req.issue.labels_url; let url = req.body.issue.labels_url;
// Make the URL generic removing the name of the label // Make the URL generic removing the name of the label
return url.replace('{/name}', ''); return url.replace('{/name}', '');
} }
const getLabels = function(req) { const getLabel = function(req) {
let url = getLabelsURL(req); let url = getLabelsURL(req);
const options = {
hostname: 'api.github.com',
path: '/repos/jomsdev/my-github-bot/issues/6/labels',
headers: { 'User-Agent': 'kafkasl' }
};
console.log('Url in getLabels(): [' + url + ']');
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const request = https.get(url, (response) => { const request = https.get(options, (response) => {
// handle http errors // handle http errors
if (response.statusCode < 200 || response.statusCode > 299) { if (response.statusCode < 200 || response.statusCode > 299) {
bot.error(response, 'Failed to load page, status code: ' + response.statusCode);
reject(new Error('Failed to load page, status code: ' + response.statusCode)); reject(new Error('Failed to load page, status code: ' + response.statusCode));
} }
console.log('Processing Promise');
// temporary data holder // temporary data holder
const body = []; const body = [];
// on every content chunk, push it to the data array // on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk)); response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks // we are done, resolve promise with those joined chunks
response.on('end', () => { response.on('end', () => {
let labels = JSON.parse(body.join('')).map(lableObj => lableObj.name);
let bountyLabels = labels.filter(name => config.BOUNTY_LABELS.hasOwnProperty(name));
resolve(bountyLabels); let labels = JSON.parse(body.join('')).map(labelObj => labelObj.name);
let bountyLabel = labels.filter(name => config.bountyLabels.hasOwnProperty(name));
console.log('Label: ' + bountyLabel);
resolve(bountyLabel);
}); });
}); });
// handle connection errors of the request // handle connection errors of the request
request.on('error', (err) => reject(err)) request.on('error', (err) => reject(err))
}); });
} }
module.exports = {
getLabel: getLabel
}

View File

@ -1,15 +1,8 @@
const winston = require('winston'); const winston = require('winston');
const signerProvider = require('ethjs-provider-signer');
const sign = require('ethjs-signer').sign;
const eth = require('ethjs-query');
const prices = require('./prices'); const prices = require('./prices');
const config = require('../config'); const config = require('../config');
const github = require('./github');
const provider = new signerProvider(config.signerPath, {
signTransaction: (rawTx, cb) => cb(null, sign(rawTx, process.env.KEY)),
accounts: (cb) => cb(null, [address]),
});
const eth = new eth(provider);
const logger = winston.createLogger({ const logger = winston.createLogger({
level: 'info', level: 'info',
@ -37,14 +30,16 @@ const getAddress = function(req) {
} }
const getLabel = function(req) { const getLabel = function(req) {
return github.getLabels(req).then(labels => { return github.getLabel(req).then(labels => {
if (labels.length === 1) { if (labels.length === 1) {
resolve(labels[0]); return labels[0];
} else { } else {
// TODO: Handle error error(req.body, 'More than 1 label found: ['+ labels.length + ']');
// reject(new Error('More than 1 label found: ['+ labels.length + ']'));
} }
}).catch(err => { }).catch(err => {
// TODO: Handle error error(req.body, 'Could not get label' + err);
// reject(new Error('Could not get label' + err));
}); });
} }
@ -52,14 +47,18 @@ const getAmount = function(req) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let labelPromise = getLabel(req); let labelPromise = getLabel(req);
let tokenPricePromise = prices.getTokenPrice(config.token); let tokenPricePromise = prices.getTokenPrice(config.token);
Promise.all([labelPromise, tokenPricePromise]).then(function(values) {
let label = values[0];
let tockenPrice = values[1];
let amountToPayDollar = config.priceHour * config.workHours[label];
reslove(config.amountToPayDollar/tockenPrice); Promise.all([labelPromise, tokenPricePromise])
}).catch(error => { .then(function(values) {
// TODO: Handle error let label = values[0];
let tokenPrice = values[1];
let amountToPayDollar = config.priceHour * config.bountyLabels[label];
console.log('Amount: ' + amountToPayDollar +', ' + tokenPrice);
resolve(config.amountToPayDollar/tokenPrice);
})
.catch(err => {
error(req.body, 'Failed to resolve label or token price: ' + err);
reject(new Error('Failed to resolve label or token price: ' + err));
}); });
}); });
} }
@ -72,11 +71,11 @@ const getGasPrice = function(req) {
// Logging functions // Logging functions
const logTransaction = function(txId, from, to, amount, gasPrice){ const logTransaction = function(txId, from, to, amount, gasPrice){
logger.info("\n[OK] Succesfully funded bounty with transaction ", txId); logger.info("[OK] Succesfully funded bounty with transaction " + txId);
logger.info(" * From: ", from); logger.info(" * From: " + from);
logger.info(" * To: ", to); logger.info(" * To: " + to);
logger.info(" * Amount: ", amount); logger.info(" * Amount: " + amount);
logger.info(" * Gas Price: ", gasPrice); logger.info(" * Gas Price: " + gasPrice);
logger.info("===================================================="); logger.info("====================================================");
} }
@ -85,13 +84,12 @@ const log = function(msg) {
} }
const error = function(requestInfo, errorMessage) { const error = function(requestInfo, errorMessage) {
logger.error("[ERROR] Request processing failed: ", errorMessage); logger.error("[ERROR] Request processing failed: " + errorMessage);
logger.error("[ERROR] Request body: ", requestInfo); logger.error("[ERROR] Request: " + requestInfo);
} }
module.exports = { module.exports = {
eth: new eth(provider),
needsFunding: needsFunding, needsFunding: needsFunding,
getAddress: getAddress, getAddress: getAddress,
getAmount: getAmount, getAmount: getAmount,

View File

@ -13,10 +13,11 @@ const BOUNTY_LABELS = {
module.exports = { module.exports = {
debug: true, debug: true,
urlEndpoint: '/autobounty/fund', urlEndpoint: '/autobounty/fund',
logPath: '../log/', logPath: './log/',
signerPath: 'https://ropsten.infura.io', signerPath: 'https://ropsten.infura.io',
sourceAddress: 'XXXXX', sourceAddress: 'XXXXX',
token: 'SNT', token: 'SNT',
gasLimit: 92000, gasLimit: 92000,
priceHour: 35, priceHour: 35,
bountyLabels: BOUNTY_LABELS
} }

View File

@ -24,8 +24,10 @@ app.use(helmet());
// Receive a POST request at the address specified by an env. var. // Receive a POST request at the address specified by an env. var.
app.post(`${config.urlEndpoint}`, jsonParser, function(req, res, next) { app.post(`${config.urlEndpoint}`, jsonParser, function(req, res, next) {
// TODO decide how long the delay to start everything should be // TODO decide how long the delay to start everything should be
console.log('Request: ', req)
if (!req.body || !req.body.action) { if (!req.body || !req.body.action) {
bot.error(req, 'Wrong format');
bot.error('', 'Wrong format');
return res.sendStatus(400); return res.sendStatus(400);
} }
@ -77,7 +79,7 @@ const sendTransaction = function(eth, from, to, amount, gasPrice){
return res.sendStatus(200); return res.sendStatus(200);
} else { } else {
let txId = -1; let txID = -1;
bot.logTransaction(txID, from, to, amount, gasPrice); bot.logTransaction(txID, from, to, amount, gasPrice);
} }
} }