/
gas-price-api.ts
80 lines (71 loc) · 2.67 KB
/
gas-price-api.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
import pTimeout from '@rsdk-common/utils/p-timeout';
import { BLOCKCHAIN_NAME, BlockchainName } from '@rsdk-core/blockchain/models/blockchain-name';
import { Injector } from '@rsdk-core/sdk/injector';
import { Cache } from 'src/common';
import BigNumber from 'bignumber.js';
import { HttpClient } from '@rsdk-common/models/http-client';
import { Web3Pure } from '@rsdk-core/blockchain/web3-pure/web3-pure';
/**
* Uses different api or web3 to retrieve current gas price.
*/
export class GasPriceApi {
/**
* Gas price request interval in seconds.
*/
private static readonly requestInterval = 15_000;
constructor(private readonly httpClient: HttpClient) {}
/**
* Gets gas price in Wei for selected blockchain.
* @param blockchain Blockchain to get gas price from.
*/
public getGasPrice(blockchain: BlockchainName): Promise<string> {
if (blockchain === BLOCKCHAIN_NAME.ETHEREUM) {
return this.fetchEthGas();
}
return this.fetchGas(blockchain);
}
/**
* Gets gas price in Eth units for selected blockchain.
* @param blockchain Blockchain to get gas price from.
*/
public async getGasPriceInEthUnits(blockchain: BlockchainName): Promise<BigNumber> {
return Web3Pure.fromWei(await this.getGasPrice(blockchain));
}
/**
* Gets Ethereum gas price from different APIs, sorted by priority.
* @returns Average gas price in Wei.
*/
@Cache({
maxAge: GasPriceApi.requestInterval
})
private async fetchEthGas(): Promise<string> {
const requestTimeout = 3000;
try {
const response: { high: { maxFeePerGas: string } } = await pTimeout(
this.httpClient.get('https://gas-price-api.1inch.io/v1.2/1'),
requestTimeout
);
return response.high.maxFeePerGas;
} catch (_err) {}
try {
const response: { average: number } = await pTimeout(
this.httpClient.get('https://ethgasstation.info/api/ethgasAPI.json'),
requestTimeout
);
return new BigNumber(response.average / 10).multipliedBy(10 ** 9).toFixed(0);
} catch (_err) {}
const web3Public = Injector.web3PublicService.getWeb3Public(BLOCKCHAIN_NAME.ETHEREUM);
return web3Public.getGasPrice();
}
/**
* Gets gas price from web3.
* @returns Average gas price in Wei.
*/
@Cache({
maxAge: GasPriceApi.requestInterval
})
private fetchGas(blockchain: BlockchainName): Promise<string> {
const web3Public = Injector.web3PublicService.getWeb3Public(blockchain);
return web3Public.getGasPrice();
}
}