This repository has been archived by the owner on Feb 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
79 lines (62 loc) · 1.94 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
73
74
75
76
77
78
const BN = require('bn.js')
const Eth = require('ethjs');
class Suggestor {
constructor (opts = {}) {
this.blockTracker = opts.blockTracker
if (!this.blockTracker) {
throw new Error('gas suggestor requires a block tracker.')
}
this.historyLength = opts.historyLength || 20
this.defaultPrice = opts.defaultPrice || 20000000000
this.query = this.blockTracker._query
this.recentPriceAverages = []
this.firstPriceQuery = this.fetchFirstGasPrice()
this.trackBlocks()
}
trackBlocks() {
this.blockTracker.on('block', block => this.processBlock(block))
}
processBlock (newBlock) {
if (newBlock.transactions.length === 0) {
return
}
const gasPriceSum = newBlock.transactions
.map(tx => Eth.toBN(tx.gasPrice))
.reduce((result, gasPrice) => {
return result.add(gasPrice)
}, new BN(0))
const average = gasPriceSum.divn(newBlock.transactions.length)
this.recentPriceAverages.push(Math.round(average.toNumber()))
if (this.recentPriceAverages.length > this.historyLength) {
this.recentPriceAverages.shift()
}
}
fetchFirstGasPrice() {
return new Promise((resolve, reject) => {
this.query.gasPrice((err, gasPriceBn) => {
if (err) {
console.warn('Failed to retrieve gas price, defaulting.', err)
this.fillHistoryWith(this.defaultPrice)
} else {
const gasPrice = parseInt(gasPriceBn.toString(10))
this.fillHistoryWith(gasPrice)
}
return resolve(this.currentAverage())
})
})
}
fillHistoryWith (value) {
this.recentPriceAverages.push(value)
}
async currentAverage() {
if (this.recentPriceAverages.length === 0) {
return this.firstPriceQuery
}
const sum = this.recentPriceAverages.reduce((result, value) => {
return result + value
}, 0)
const result = sum / this.recentPriceAverages.length
return result
}
}
module.exports = Suggestor