-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (65 loc) · 1.88 KB
/
index.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
require('dotenv').config()
const fetch = require('node-fetch')
const { Client } = require('pg');
const { toWei } = require('web3-utils');
const connectionString = process.env.DATABASE_URL_GASPRICE
const INTERVAL = process.env.INTERVAL
let gasPrices = {
standard: 0,
fast: 0
}
const smartContractPollTime = 5 // in seconds
const gasOracleUrls = [
'https://gasprice.poa.network/',
'https://www.etherchain.org/api/gasPriceOracle'
]
function fetchGasPrice() {
let oracleIndex = 0
const getPrices = async (resolve, reject) => {
try {
const response = await fetch(gasOracleUrls[oracleIndex % gasOracleUrls.length])
if (response.status === 200) {
const json = await response.json()
if (json.standard) {
gasPrices.standard = Number(json.standard)
}
if (json.fast) {
gasPrices.fast = Number(json.fast)
}
} else {
throw Error('Fetch gasPrice failed')
}
if (gasPrices.standard === 0 || gasPrices.fast === 0) {
throw Error('Invalid data returned')
}
resolve(gasPrices)
} catch (e) {
console.error(e)
oracleIndex++
setTimeout(() => getPrices(resolve, reject), 1000 * smartContractPollTime)
}
}
return new Promise(getPrices)
}
async function main() {
let client
try {
client = new Client({
connectionString: connectionString,
})
client.connect()
const prices = await fetchGasPrice();
const add = prices.fast
const fast = toWei(add.toString(), 'gwei')
console.log(`${Date.now()}, fast gas price: ${fast} wei == ${prices.fast} gwei`)
const querytext = 'UPDATE configurations SET value = $1 WHERE name = $2'
await client.query(querytext, [fast, 'ETH_GAS_PRICE_DEFAULT'])
} catch (e) {
console.error(e)
process.exit(e.message)
} finally {
client.end()
}
setTimeout(main, INTERVAL || 15000)
}
main()