autobounty/bot/prices.js

63 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-03-19 22:02:24 +00:00
'use strict'
2018-03-19 22:02:24 +00:00
function getGasPrice () {
const url = 'https://ethgasstation.info/json/ethgasAPI.json'
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http')
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`Failed to load page, status code: ${response.statusCode}`))
}
// temporary data holder
const body = []
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk))
// we are done, resolve promise with those joined chunks
response.on('end', () => {
// safeLowWait returns GWei (10^10 Wei).
const jsonBody = JSON.parse(body.join(''))
const gasPriceWei = parseInt(jsonBody['safeLowWait']) * Math.pow(10, 10)
resolve(gasPriceWei)
})
})
2018-03-19 22:02:24 +00:00
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
2018-03-19 21:37:38 +00:00
}
2018-03-19 22:02:24 +00:00
function getTokenPrice (token) {
const currency = 'USD'
const url = `https://min-api.cryptocompare.com/data/price?fsym=${token}&tsyms=${currency}`
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http')
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`Failed to load page, status code: ${response.statusCode}`))
}
// temporary data holder
const body = []
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk))
// we are done, resolve promise with those joined chunks
response.on('end', () => {
const jsonBody = JSON.parse(body.join(''))
const tokenPrice = parseFloat(jsonBody[currency])
resolve(tokenPrice)
})
})
2018-03-19 22:02:24 +00:00
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
}
module.exports = {
2018-03-19 22:02:24 +00:00
getGasPrice: getGasPrice,
getTokenPrice: getTokenPrice
}