-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.ts
92 lines (81 loc) · 2.57 KB
/
utils.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import axios from "axios";
import { utils } from "ethers";
function notUndefined(para) {
if (typeof para === "undefined") {
return false;
}
return true;
}
const sleepMs = (ms) => new Promise((res) => setTimeout(res, ms));
const axiosConfig = {
headers: {
"Content-Type": "application/json",
},
};
async function getUrlRequest(queryURL, defaultResponse) {
let response;
try {
response = await axios.get(queryURL);
if (response.statusCode < 200 || response.statusCode > 299) {
return defaultResponse;
}
} catch (err) {
console.log("axios.get() EXCEPTION:");
return defaultResponse;
}
if (notUndefined(response.data)) {
return response.data;
} else {
console.log("getPassword() ERROR: " + JSON.stringify(response.data));
return defaultResponse;
}
}
async function postUrlRequest(queryURL, payload, defaultResponse) {
let response;
try {
response = await axios.post(queryURL, payload, axiosConfig);
if (response.statusCode < 200 || response.statusCode > 299) {
return defaultResponse;
}
} catch (err) {
console.log("axios.post() EXCEPTION:");
return defaultResponse;
}
if (notUndefined(response.data)) {
return response.data;
} else {
console.log("getPassword() ERROR: " + JSON.stringify(response.data));
return defaultResponse;
}
}
// Do NOT access it frequently, otherwise request might be blocked
async function getGasPrice(debug) {
const defaultGasPrice = {
code: 200,
data: {
rapid: utils.parseUnits("122", "gwei"),
fast: utils.parseUnits("116", "gwei"),
standard: utils.parseUnits("100", "gwei"),
slow: utils.parseUnits("93", "gwei"),
timestamp: new Date("2021-04-15T00:59:04.593Z").getTime(),
},
};
// Alternative: https://docs.ethgasstation.info/gas-price
// https://ethgasstation.info/api/ethgasAPI.json?api-key=XXAPI_Key_HereXXX
// ***Note: To convert the provided values to gwei, divide by 10.***
// https://taichi.network/#gasnow
const queryURL = "https://www.gasnow.org/api/v3/gas/price?utm_source=:AutomaticTraders";
const resonse = await getUrlRequest(queryURL, defaultGasPrice);
const priceList = resonse.data;
// console.log(priceList);
if (debug) {
console.log("gas price", {
rapid: utils.formatUnits(priceList.rapid, "gwei"),
fast: utils.formatUnits(priceList.fast, "gwei"),
standard: utils.formatUnits(priceList.standard, "gwei"),
slow: utils.formatUnits(priceList.slow, "gwei"),
});
}
return priceList;
}
export { notUndefined, sleepMs, getUrlRequest, postUrlRequest, getGasPrice };