-
Notifications
You must be signed in to change notification settings - Fork 2
/
gasPriceFetcher.ts
56 lines (49 loc) · 1.59 KB
/
gasPriceFetcher.ts
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
import fetch from "node-fetch";
export default class Fetcher {
gasPrices: {
fast: number,
standard: number,
low: number
test: number
}
gasOracleUrls: string[]
constructor() {
this.gasPrices = {
fast: 20,
standard: 10,
low: 1,
test: 2.1
}
this.gasOracleUrls = ['https://ethgasstation.info/json/ethgasAPI.json', 'https://gas-oracle.zoltu.io/']
this.fetchGasPrice()
}
async fetchGasPrice({ oracleIndex = 0 } = {}) {
oracleIndex = (oracleIndex + 1) % this.gasOracleUrls.length
const url = this.gasOracleUrls[oracleIndex]
try {
const response = await fetch(url)
if (response.status === 200) {
const json = await response.json()
if (Number(json.fast) === 0) {
throw new Error('Fetch gasPrice failed')
}
if (url === 'https://ethgasstation.info/json/ethgasAPI.json') {
this.gasPrices.fast = Number(json.fast) / 10
this.gasPrices.standard = Number(json.average) / 10
this.gasPrices.low = Number(json.safeLow) / 10
}
if (url === 'https://gas-oracle.zoltu.io/') {
this.gasPrices.fast = parseInt(json.percentile_90)
this.gasPrices.standard = parseInt(json.percentile_60)
this.gasPrices.low = parseInt(json.percentile_30)
}
// console.log('gas price fetch', this.gasPrices)
} else {
throw Error('Fetch gasPrice failed')
}
setTimeout(() => this.fetchGasPrice({ oracleIndex }), 15000)
} catch (e) {
setTimeout(() => this.fetchGasPrice({ oracleIndex }), 15000)
}
}
}