Skip to content
This repository has been archived by the owner on Mar 17, 2024. It is now read-only.

Commit

Permalink
Fetch BNB, MATIC, AVAX, HR or MOVR gas price (#251)
Browse files Browse the repository at this point in the history
* feat(gas): allow to fetch BNB and MATIC price

* feat(GasPriceAPI): add Avalanche, Heco and Moonriver

* fix(gasPriceApi): default to etherscan.io API

* docs(README): add gasPriceApi networks details
  • Loading branch information
lucaperret committed Nov 25, 2021
1 parent 23fc576 commit 27ba98a
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 27 deletions.
59 changes: 40 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- National currency costs of deploying and using your contract system.
- CI integration with [codechecks](http://codechecks.io)
- Simple installation for Truffle and Buidler
- Use ETH, BNB, MATIC, AVAX, HT or MOVR price to calculate the gas price.

### Example output

Expand Down Expand Up @@ -76,28 +77,47 @@ Beginning March 2020, CoinMarketCap requires an API key to access currency marke
price data. The reporter uses an unprotected free tier key by default (10k reqs/mo). You can get
your own API key [here][55] and set it with the `coinmarketcap` option.

| Option | Type | Default | Description |
| ----------------- | ---------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| currency | _String_ | 'EUR' | National currency to represent gas costs in. Exchange rates loaded at runtime from the `coinmarketcap` api. Available currency codes can be found [here](https://coinmarketcap.com/api/documentation/v1/#section/Standards-and-Conventions). |
| coinmarketcap | _String_ | (unprotected API key) | [API key][55] to use when fetching current market price data. (Use this if you stop seeing price data) |
| gasPrice | _Number_ | (varies) | Denominated in `gwei`. Default is loaded at runtime from the `eth gas station` api |
| outputFile | _String_ | stdout | File path to write report output to |
| noColors | _Boolean_ | false | Suppress report color. Useful if you are printing to file b/c terminal colorization corrupts the text. |
| onlyCalledMethods | _Boolean_ | true | Omit methods that are never called from report. |
| rst | _Boolean_ | false | Output with a reStructured text code-block directive. Useful if you want to include report in RTD |
| rstTitle | _String_ | "" | Title for reStructured text header (See Travis for example output) |
| showTimeSpent | _Boolean_ | false | Show the amount of time spent as well as the gas consumed |
| excludeContracts | _String[]_ | [] | Contract names to exclude from report. Ex: `['Migrations']` |
| src | _String_ | "contracts" | Folder in root directory to begin search for `.sol` files. This can also be a path to a subfolder relative to the root, e.g. "planets/annares/contracts" |
| url | _String_ | `web3.currentProvider.host` | RPC client url (ex: "http://localhost:8545") |
| proxyResolver | _Function_ | none | Custom method to resolve identity of methods managed by a proxy contract. |
| artifactType | _Function_ or _String_ | "truffle-v5" | Compilation artifact format to consume. (See [advanced use](https://github.com/cgewecke/eth-gas-reporter/blob/master/docs/advanced.md).) |
| showMethodSig | _Boolean_ | false | Display complete method signatures. Useful when you have overloaded methods you can't tell apart. |
| maxMethodDiff | _Number_ | undefined | Codechecks failure threshold, triggered when the % diff for any method is greater than `number` (integer) |
| maxDeploymentDiff | _Number_ | undefined | Codechecks failure threshold, triggered when the % diff for any deployment is greater than `number` (integer) |
In order to retrieve the gas price of a particular blockchain, you can configure the `token` and `gasPriceApi` (API key rate limit may apply).

| Option | Type | Default | Description |
| ----------------- | ---------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| currency | _String_ | 'EUR' | National currency to represent gas costs in. Exchange rates loaded at runtime from the `coinmarketcap` api. Available currency codes can be found [here](https://coinmarketcap.com/api/documentation/v1/#section/Standards-and-Conventions). |
| coinmarketcap | _String_ | (unprotected API key) | [API key][55] to use when fetching current market price data. (Use this if you stop seeing price data) |
| gasPrice | _Number_ | (varies) | Denominated in `gwei`. Default is loaded at runtime from the `eth gas station` api |
| token | _String_ | 'ETH' | The reference token for gas price |
| gasPriceApi | _String_ | [Etherscan](https://api.etherscan.io/api?module=proxy&action=eth_gasPrice) | The API endpoint to retrieve the gas price. Find below other networks. |
| outputFile | _String_ | stdout | File path to write report output to |
| noColors | _Boolean_ | false | Suppress report color. Useful if you are printing to file b/c terminal colorization corrupts the text. |
| onlyCalledMethods | _Boolean_ | true | Omit methods that are never called from report. |
| rst | _Boolean_ | false | Output with a reStructured text code-block directive. Useful if you want to include report in RTD |
| rstTitle | _String_ | "" | Title for reStructured text header (See Travis for example output) |
| showTimeSpent | _Boolean_ | false | Show the amount of time spent as well as the gas consumed |
| excludeContracts | _String[]_ | [] | Contract names to exclude from report. Ex: `['Migrations']` |
| src | _String_ | "contracts" | Folder in root directory to begin search for `.sol` files. This can also be a path to a subfolder relative to the root, e.g. "planets/annares/contracts" |
| url | _String_ | `web3.currentProvider.host` | RPC client url (ex: "http://localhost:8545") |
| proxyResolver | _Function_ | none | Custom method to resolve identity of methods managed by a proxy contract. |
| artifactType | _Function_ or _String_ | "truffle-v5" | Compilation artifact format to consume. (See [advanced use](https://github.com/cgewecke/eth-gas-reporter/blob/master/docs/advanced.md).) |
| showMethodSig | _Boolean_ | false | Display complete method signatures. Useful when you have overloaded methods you can't tell apart. |
| maxMethodDiff | _Number_ | undefined | Codechecks failure threshold, triggered when the % diff for any method is greater than `number` (integer) |
| maxDeploymentDiff | _Number_ | undefined | Codechecks failure threshold, triggered when the % diff for any deployment is greater than `number` (integer) |

[55]: https://coinmarketcap.com/api/pricing/

#### `token` and `gasPriceApi` options example

| Network | token | gasPriceApi |
| ------------------ | ----- | ---------------------------------------------------------------------- |
| Ethereum (default) | ETH | https://api.etherscan.io/api?module=proxy&action=eth_gasPrice |
| Binance | BNB | https://api.bscscan.com/api?module=proxy&action=eth_gasPrice |
| Polygon | MATIC | https://api.polygonscan.com/api?module=proxy&action=eth_gasPrice |
| Avalanche | AVAX | https://api.snowtrace.io/api?module=proxy&action=eth_gasPrice |
| Heco | HT | https://api.hecoinfo.com/api?module=proxy&action=eth_gasPrice |
| Moonriver | MOVR | https://api-moonriver.moonscan.io/api?module=proxy&action=eth_gasPrice |

These APIs have [rate limits](https://docs.etherscan.io/support/rate-limits). Depending on the usage, it might require an [API Key](https://docs.etherscan.io/getting-started/viewing-api-usage-statistics).

> NB: Any gas price API call which returns a JSON-RPC response formatted like this is supported: `{"jsonrpc":"2.0","id":73,"result":"0x6fc23ac00"}`.
### Advanced Use

An advanced use guide is available [here](https://github.com/cgewecke/eth-gas-reporter/blob/master/docs/advanced.md). Topics include:
Expand Down Expand Up @@ -144,3 +164,4 @@ All the ideas in this utility have been borrowed from elsewhere. Many thanks to:
- [@gnidan](https://github.com/gnidan)
- [@fodisi](https://github.com/fodisi)
- [@vicnaum](https://github.com/vicnaum)
- [@lucaperret](https://github.com/lucaperret)
7 changes: 5 additions & 2 deletions lib/codechecksReport.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ class CodeChecksReport {

const solc = utils.getSolcInfo(this.config.metadata);

const token = this.config.token.toLowerCase();
if (this.config.ethPrice && this.config.gasPrice) {
gwei = `${parseInt(this.config.gasPrice)} gwei/gas`;
currency = `${this.config.currency.toLowerCase()}`;
rate = `${parseFloat(this.config.ethPrice).toFixed(2)} ${currency}/eth`;
rate = `${parseFloat(this.config.ethPrice).toFixed(
2
)} ${currency}/${token}`;
}

const configRows = [
Expand All @@ -49,7 +52,7 @@ class CodeChecksReport {
["solc: runs", solc.runs],
["gas: block limit", ethers.utils.commify(info.blockLimit)],
["gas: price", gwei],
["gas: currency/eth rate", rate]
[`gas: currency/${token} rate`, rate]
];

const configTable = table(configRows);
Expand Down
4 changes: 4 additions & 0 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@

class Config {
constructor(options = {}) {
this.token = options.token || "ETH";
this.blockLimit = options.blockLimit || 6718946;
this.defaultGasPrice = 5;

this.currency = options.currency || "eur";
this.gasPriceApi =
options.gasPriceApi ||
"https://api.etherscan.io/api?module=proxy&action=eth_gasPrice";
this.coinmarketcap =
options.coinmarketcap || "d25b5576-a4ee-41be-bb2b-aca2ba3ae5d8";
this.ethPrice = options.ethPrice || null;
Expand Down
3 changes: 2 additions & 1 deletion lib/gasTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ class GasTable {
const gwei = parseInt(this.config.gasPrice);
const rate = parseFloat(this.config.ethPrice).toFixed(2);
const currency = `${this.config.currency.toLowerCase()}`;
const token = `${this.config.token.toLowerCase()}`;

methodSubtitle = [
{ hAlign: "left", colSpan: 2, content: colors.green.bold("Methods") },
Expand All @@ -193,7 +194,7 @@ class GasTable {
{
hAlign: "center",
colSpan: 2,
content: colors.red(`${rate} ${currency}/eth`)
content: colors.red(`${rate} ${currency}/${token}`)
}
];
} else {
Expand Down
15 changes: 10 additions & 5 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,11 @@ const utils = {
* @param {Object} config
*/
setGasAndPriceRates: async function(config) {
const ethgasstation = `https://ethgasstation.info/json/ethgasAPI.json`;
const token = config.token.toUpperCase();
const gasPriceApi = config.gasPriceApi;
const coinmarketcap =
`https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/` +
`latest?symbol=ETH&CMC_PRO_API_KEY=${config.coinmarketcap}&convert=`;
`latest?symbol=${token}&CMC_PRO_API_KEY=${config.coinmarketcap}&convert=`;

const currencyKey = config.currency.toUpperCase();
const currencyPath = `${coinmarketcap}${currencyKey}`;
Expand All @@ -188,7 +189,9 @@ const utils = {
try {
let response = await request.get(currencyPath);
response = JSON.parse(response);
config.ethPrice = response.data.ETH.quote[currencyKey].price.toFixed(2);
config.ethPrice = response.data[token].quote[currencyKey].price.toFixed(
2
);
} catch (error) {
config.ethPrice = null;
}
Expand All @@ -197,9 +200,11 @@ const utils = {
// Gas price data: ethgasstation
if (!config.gasPrice) {
try {
let response = await request.get(ethgasstation);
let response = await request.get(gasPriceApi);
response = JSON.parse(response);
config.gasPrice = Math.round(response.safeLow / 10);
config.gasPrice = Math.round(
parseInt(response.result, 16) / Math.pow(10, 9)
);
} catch (error) {
config.gasPrice = config.defaultGasPrice;
}
Expand Down
3 changes: 3 additions & 0 deletions mock/config-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ module.exports = {
reporterOptions: {
currency: "chf",
gasPrice: 21,
token: "ETH",
gasPriceApi:
"https://api.etherscan.io/api?module=proxy&action=eth_gasPrice&apikey=YourApiKeyToken",
onlyCalledMethods: false,
noColors: true,
rst: true,
Expand Down

0 comments on commit 27ba98a

Please sign in to comment.