tornado-pool-relayer/src/services/gas-price.service.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
2021-10-11 18:06:41 +02:00
import { BigNumber } from 'ethers';
import { GasPriceOracle } from 'gas-price-oracle';
2021-10-11 18:06:41 +02:00
import { toWei } from '@/utilities';
2021-12-15 11:24:09 +01:00
import { SERVICE_ERRORS } from '@/constants';
2021-10-19 16:31:19 +02:00
const bump = (gas: BigNumber, percent: number) => gas.mul(percent).div(100).toHexString();
const gweiToWei = (value: number) => toWei(String(value), 'gwei');
const percentBump = {
INSTANT: 150,
FAST: 130,
STANDARD: 85,
LOW: 50,
};
@Injectable()
export class GasPriceService {
private readonly chainId: number;
2021-12-09 15:58:05 +01:00
private readonly rpcUrl: string;
constructor(private configService: ConfigService) {
this.chainId = this.configService.get<number>('base.chainId');
2021-12-09 15:58:05 +01:00
this.rpcUrl = this.configService.get('base.rpcUrl');
}
2021-10-11 18:06:41 +02:00
async getGasPrice() {
2021-12-15 11:24:09 +01:00
try {
const instance = new GasPriceOracle({
chainId: this.chainId,
defaultRpc: this.rpcUrl,
});
const result = await instance.gasPrices();
return {
instant: bump(gweiToWei(result.instant), percentBump.INSTANT),
fast: bump(gweiToWei(result.instant), percentBump.FAST),
standard: bump(gweiToWei(result.standard), percentBump.STANDARD),
low: bump(gweiToWei(result.low), percentBump.LOW),
};
} catch (err) {
console.log('getGasPrice has error:', err.message);
throw new Error(SERVICE_ERRORS.GAS_PRICE);
}
}
}