11 Commits

Author SHA1 Message Date
Danil Kovtonyuk
b13a4252ab feat: add fetch gas price from rpc 2021-10-05 11:47:34 +03:00
Danil Kovtonyuk
5036c65643 add xDAI 2021-08-25 22:31:20 +10:00
Danil Kovtonyuk
89a69519b2 fix: test 2021-08-17 17:14:50 +10:00
Danil Kovtonyuk
3fce50efbb fix: constructor 2021-08-17 17:04:01 +10:00
Danil Kovtonyuk
9b0c229ace add polygon 2021-06-15 13:26:02 +03:00
Danil Kovtonyuk
a508e41652 fix: bscgas property 2021-06-10 23:33:59 +03:00
Danil Kovtonyuk
bb58318b6f add defaultFallbackGasPrices option 2021-06-03 15:16:49 +03:00
Danil Kovtonyuk
32c256bc4e update readme 2021-06-03 13:01:25 +03:00
Danil Kovtonyuk
efd3cb3c7c fix test 2021-06-03 12:51:14 +03:00
Danil Kovtonyuk
88a757bb45 bump version 2021-06-03 12:46:36 +03:00
Danil Kovtonyuk
c30c7aed63 add binance 2021-06-03 12:46:36 +03:00
10 changed files with 242 additions and 31 deletions

View File

@@ -2,10 +2,13 @@
A library that has a collection of onchain and offchain gas price oracle URLs A library that has a collection of onchain and offchain gas price oracle URLs
## Supported networks
### Ethereum Mainnet
Current offchain list: Current offchain list:
- https://ethgasstation.info/json/ethgasAPI.json - https://ethgasstation.info/json/ethgasAPI.json
- https://gas-oracle.zoltu.io/
- https://www.etherchain.org/api/gasPriceOracle - https://www.etherchain.org/api/gasPriceOracle
- https://gasprice.poa.network/ - https://gasprice.poa.network/
- https://www.gasnow.org/api/v3/gas/price - https://www.gasnow.org/api/v3/gas/price
@@ -14,6 +17,24 @@ Current onchain list:
- [chainlink](https://etherscan.io/address/0x169e633a2d1e6c10dd91238ba11c4a708dfef37c#readContract) - [chainlink](https://etherscan.io/address/0x169e633a2d1e6c10dd91238ba11c4a708dfef37c#readContract)
### Binance Smart Chain
Current offchain list:
- https://bscgas.info/
### xDAI Chain
Current offchain list:
- https://www.xdaichain.com/for-developers/developer-resources/gas-price-oracle
### Polygon (Matic) Network
Current offchain list:
- https://gasstation-mainnet.matic.network/
## Installation ## Installation
`npm i gas-price-oracle` `npm i gas-price-oracle`
@@ -30,8 +51,15 @@ const { GasPriceOracle } = require('gas-price-oracle');
```js ```js
const options = { const options = {
chainId: 1,
defaultRpc: 'https://api.mycryptoapi.com/eth', defaultRpc: 'https://api.mycryptoapi.com/eth',
timeout: 10000, timeout: 10000,
defaultFallbackGasPrices: {
instant: 28,
fast: 22,
standard: 17,
low: 11,
},
}; };
const oracle = new GasPriceOracle(options); const oracle = new GasPriceOracle(options);
// optional fallbackGasPrices // optional fallbackGasPrices

View File

@@ -1,6 +1,6 @@
{ {
"name": "gas-price-oracle", "name": "gas-price-oracle",
"version": "0.2.2", "version": "0.4.0",
"description": "Gas Price Oracle library for Ethereum dApps.", "description": "Gas Price Oracle library for Ethereum dApps.",
"main": "lib/index.js", "main": "lib/index.js",
"homepage": "https://github.com/peppersec/gas-price-oracle", "homepage": "https://github.com/peppersec/gas-price-oracle",

23
src/config/binance.ts Normal file
View File

@@ -0,0 +1,23 @@
import { OffChainOracle, OffChainOracles, OnChainOracles } from '../types';
const bscgas: OffChainOracle = {
name: 'bscgas',
url: 'https://bscgas.info/gas',
instantPropertyName: 'instant',
fastPropertyName: 'fast',
standardPropertyName: 'standard',
lowPropertyName: 'slow',
denominator: 1,
additionalDataProperty: null,
};
export const offChainOracles: OffChainOracles = {
bscgas,
};
export const onChainOracles: OnChainOracles = {};
export default {
offChainOracles,
onChainOracles,
};

20
src/config/index.ts Normal file
View File

@@ -0,0 +1,20 @@
import { NetworkConfig } from '../types';
import mainnetOracles from './mainnet';
import binanceOracles from './binance';
import xdaiOracles from './xdai';
import polygonOracles from './polygon';
export enum ChainId {
MAINNET = 1,
BINANCE = 56,
XDAI = 100,
POLYGON = 137,
}
export const networks: NetworkConfig = {
[ChainId.MAINNET]: mainnetOracles,
[ChainId.BINANCE]: binanceOracles,
[ChainId.XDAI]: xdaiOracles,
[ChainId.POLYGON]: polygonOracles,
};

View File

@@ -1,4 +1,4 @@
import { OffChainOracle, OnChainOracle } from './types'; import { OffChainOracle, OnChainOracle, OffChainOracles, OnChainOracles } from '../types';
const ethgasstation: OffChainOracle = { const ethgasstation: OffChainOracle = {
name: 'ethgasstation', name: 'ethgasstation',
@@ -11,17 +11,6 @@ const ethgasstation: OffChainOracle = {
additionalDataProperty: null, additionalDataProperty: null,
}; };
const zoltu: OffChainOracle = {
name: 'zoltu',
url: 'https://gas-oracle.zoltu.io/',
instantPropertyName: 'percentile_99',
fastPropertyName: 'percentile_90',
standardPropertyName: 'percentile_60',
lowPropertyName: 'percentile_30',
denominator: 1,
additionalDataProperty: null,
};
const etherchain: OffChainOracle = { const etherchain: OffChainOracle = {
name: 'etherchain', name: 'etherchain',
url: 'https://www.etherchain.org/api/gasPriceOracle', url: 'https://www.etherchain.org/api/gasPriceOracle',
@@ -73,16 +62,15 @@ const chainlink: OnChainOracle = {
denominator: '1000000000', denominator: '1000000000',
}; };
export const offChainOracles: { [key: string]: OffChainOracle } = { export const offChainOracles: OffChainOracles = {
ethgasstation, ethgasstation,
anyblock, anyblock,
gasNow, gasNow,
poa, poa,
etherchain, etherchain,
zoltu,
}; };
export const onChainOracles: { [key: string]: OnChainOracle } = { export const onChainOracles: OnChainOracles = {
chainlink, chainlink,
}; };

23
src/config/polygon.ts Normal file
View File

@@ -0,0 +1,23 @@
import { OffChainOracle, OffChainOracles, OnChainOracles } from '../types';
const maticGasStation: OffChainOracle = {
name: 'maticGasStation',
url: 'https://gasstation-mainnet.matic.network',
instantPropertyName: 'fastest',
fastPropertyName: 'fast',
standardPropertyName: 'standard',
lowPropertyName: 'safeLow',
denominator: 1,
additionalDataProperty: null,
};
export const offChainOracles: OffChainOracles = {
maticGasStation,
};
export const onChainOracles: OnChainOracles = {};
export default {
offChainOracles,
onChainOracles,
};

23
src/config/xdai.ts Normal file
View File

@@ -0,0 +1,23 @@
import { OffChainOracle, OffChainOracles, OnChainOracles } from '../types';
const blockscout: OffChainOracle = {
name: 'blockscout',
url: 'https://blockscout.com/xdai/mainnet/api/v1/gas-price-oracle',
instantPropertyName: 'fast',
fastPropertyName: 'average',
standardPropertyName: 'slow',
lowPropertyName: 'slow',
denominator: 1,
additionalDataProperty: null,
};
export const offChainOracles: OffChainOracles = {
blockscout,
};
export const onChainOracles: OnChainOracles = {};
export default {
offChainOracles,
onChainOracles,
};

View File

@@ -1,21 +1,46 @@
import axios from 'axios'; import axios from 'axios';
import config from './config'; import { ChainId, networks } from './config';
import { GasPrice, OffChainOracle, OnChainOracle, Config, GasPriceKey, Options } from './types'; import {
Config,
Options,
GasPrice,
GasPriceKey,
OffChainOracle,
OnChainOracle,
OnChainOracles,
OffChainOracles,
} from './types';
import BigNumber from 'bignumber.js'; import BigNumber from 'bignumber.js';
const defaultFastGas = 22;
export class GasPriceOracle { export class GasPriceOracle {
lastGasPrice: GasPrice; lastGasPrice: GasPrice;
offChainOracles = { ...config.offChainOracles }; offChainOracles: OffChainOracles;
onChainOracles = { ...config.onChainOracles }; onChainOracles: OnChainOracles;
configuration: Config = { configuration: Config = {
chainId: ChainId.MAINNET,
defaultRpc: 'https://api.mycryptoapi.com/eth', defaultRpc: 'https://api.mycryptoapi.com/eth',
timeout: 10000, timeout: 10000,
defaultFallbackGasPrices: {
instant: defaultFastGas * 1.3,
fast: defaultFastGas,
standard: defaultFastGas * 0.85,
low: defaultFastGas * 0.5,
},
}; };
constructor(options?: Options) { constructor(options?: Options) {
if (options) { if (options) {
Object.assign(this.configuration, options); Object.assign(this.configuration, options);
} }
const network = networks[this.configuration.chainId];
if (network) {
const { offChainOracles, onChainOracles } = network;
this.offChainOracles = { ...offChainOracles };
this.onChainOracles = { ...onChainOracles };
}
} }
async askOracle(oracle: OffChainOracle): Promise<GasPrice> { async askOracle(oracle: OffChainOracle): Promise<GasPrice> {
@@ -160,15 +185,36 @@ export class GasPriceOracle {
throw new Error('All oracles are down. Probably a network error.'); throw new Error('All oracles are down. Probably a network error.');
} }
async gasPrices(fallbackGasPrices?: GasPrice, median = true): Promise<GasPrice> { async fetchGasPriceFromRpc(): Promise<number> {
const defaultFastGas = 22; const rpcUrl = this.configuration.defaultRpc;
const defaultFallbackGasPrices = { const body = {
instant: defaultFastGas * 1.3, jsonrpc: '2.0',
fast: defaultFastGas, id: 1337,
standard: defaultFastGas * 0.85, method: 'eth_gasPrice',
low: defaultFastGas * 0.5, params: [],
}; };
this.lastGasPrice = this.lastGasPrice || fallbackGasPrices || defaultFallbackGasPrices; try {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const response = await axios.post(rpcUrl!, body, { timeout: this.configuration.timeout });
if (response.status === 200) {
const { result } = response.data;
let fastGasPrice = new BigNumber(result);
if (fastGasPrice.isZero()) {
throw new Error(`Default RPC provides corrupted values`);
}
fastGasPrice = fastGasPrice.div(1e9);
return fastGasPrice.toNumber();
}
throw new Error(`Fetch gasPrice from default RPC failed..`);
} catch (e) {
console.error(e.message);
throw new Error('Default RPC is down. Probably a network error.');
}
}
async gasPrices(fallbackGasPrices?: GasPrice, median = true): Promise<GasPrice> {
this.lastGasPrice = this.lastGasPrice || fallbackGasPrices || this.configuration.defaultFallbackGasPrices;
try { try {
this.lastGasPrice = median this.lastGasPrice = median
? await this.fetchMedianGasPriceOffChain() ? await this.fetchMedianGasPriceOffChain()
@@ -188,7 +234,20 @@ export class GasPriceOracle {
}; };
return this.lastGasPrice; return this.lastGasPrice;
} catch (e) { } catch (e) {
console.log('Failed to fetch gas prices from onchain oracles. Last known gas will be returned'); console.log('Failed to fetch gas prices from onchain oracles. Trying from default RPC...');
}
try {
const fastGas = await this.fetchGasPriceFromRpc();
this.lastGasPrice = {
instant: fastGas * 1.3,
fast: fastGas,
standard: fastGas * 0.85,
low: fastGas * 0.5,
};
return this.lastGasPrice;
} catch (e) {
console.log('Failed to fetch gas prices from default RPC. Last known gas will be returned');
} }
return this.lastGasPrice; return this.lastGasPrice;
} }

View File

@@ -9,6 +9,8 @@ export type OffChainOracle = {
additionalDataProperty: string | null; additionalDataProperty: string | null;
}; };
export type OffChainOracles = { [key: string]: OffChainOracle };
export type OnChainOracle = { export type OnChainOracle = {
name: string; name: string;
rpc?: string; rpc?: string;
@@ -17,6 +19,13 @@ export type OnChainOracle = {
denominator: string; denominator: string;
}; };
export type OnChainOracles = { [key: string]: OnChainOracle };
export type AllOracles = {
offChainOracles: OffChainOracles;
onChainOracles: OnChainOracles;
};
export type GasPrice = { export type GasPrice = {
[key in GasPriceKey]: number; [key in GasPriceKey]: number;
}; };
@@ -24,8 +33,14 @@ export type GasPrice = {
export type GasPriceKey = 'instant' | 'fast' | 'standard' | 'low'; export type GasPriceKey = 'instant' | 'fast' | 'standard' | 'low';
export type Options = { export type Options = {
chainId?: number;
defaultRpc?: string; defaultRpc?: string;
timeout?: number; timeout?: number;
defaultFallbackGasPrices?: GasPrice;
}; };
export type Config = Required<Options>; export type Config = Required<Options>;
export type NetworkConfig = {
[key in number]: AllOracles;
};

View File

@@ -3,12 +3,12 @@
import { GasPrice, OffChainOracle } from '../src/types'; import { GasPrice, OffChainOracle } from '../src/types';
import mockery from 'mockery'; import mockery from 'mockery';
import chai from 'chai'; import chai from 'chai';
import { onChainOracles, offChainOracles } from '../src/config';
import { GasPriceOracle } from '../src/index'; import { GasPriceOracle } from '../src/index';
chai.use(require('chai-as-promised')); chai.use(require('chai-as-promised'));
chai.should(); chai.should();
let oracle = new GasPriceOracle(); let oracle = new GasPriceOracle();
let { onChainOracles, offChainOracles } = oracle;
before('before', function () { before('before', function () {
const axiosMock = { const axiosMock = {
@@ -24,6 +24,7 @@ before('before', function () {
beforeEach('beforeEach', function () { beforeEach('beforeEach', function () {
oracle = new GasPriceOracle(); oracle = new GasPriceOracle();
({ onChainOracles, offChainOracles } = oracle);
}); });
describe('constructor', function () { describe('constructor', function () {
@@ -118,6 +119,37 @@ describe('fetchGasPricesOnChain', function () {
}); });
}); });
describe('fetchGasPriceFromRpc', function () {
it('should work', async function () {
const gas: number = await oracle.fetchGasPriceFromRpc();
gas.should.be.a('number');
gas.should.be.above(1);
gas.should.not.be.equal(0);
});
it('should work with custom rpc', async function () {
const rpc = 'https://ethereum-rpc.trustwalletapp.com';
const oracle = new GasPriceOracle({ defaultRpc: rpc });
oracle.configuration.defaultRpc.should.be.equal(rpc);
const gas: number = await oracle.fetchGasPriceFromRpc();
gas.should.be.a('number');
gas.should.be.above(1);
gas.should.not.be.equal(0);
});
it('should throw if default rpc is down', async function () {
mockery.enable({ useCleanCache: true, warnOnUnregistered: false });
const { GasPriceOracle } = require('../src/index');
oracle = new GasPriceOracle();
await oracle
.fetchGasPriceFromRpc()
.should.be.rejectedWith('Default RPC is down. Probably a network error.');
mockery.disable();
});
});
describe('gasPrice', function () { describe('gasPrice', function () {
it('should work', async function () { it('should work', async function () {
const gas: GasPrice = await oracle.gasPrices(); const gas: GasPrice = await oracle.gasPrices();