Skip to content

Commit

Permalink
Beta Final Review Fixes (#208)
Browse files Browse the repository at this point in the history
  • Loading branch information
cgewecke authored Mar 14, 2024
1 parent c60640f commit 0b6ef22
Show file tree
Hide file tree
Showing 26 changed files with 106 additions and 49 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ env:
CMC_API_KEY: ${{ secrets.CMC_API_KEY }}
POLYGONSCAN_API_KEY: ${{ secrets.POLYGONSCAN_API_KEY }}
ALCHEMY_TOKEN: ${{ secrets.ALCHEMY_TOKEN }}
ETHERSCAN_API_KEY: ${{ secrets.ETHERSCAN_API_KEY }}
OPTIMISTIC_API_KEY: ${{ secrets.OPTIMISTIC_API_KEY }}

jobs:
lint:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"typescript": "~5.0.4"
},
"peerDependencies": {
"hardhat": "^2.0.2"
"hardhat": "^2.16.0"
},
"dependencies": {
"@ethersproject/abi": "^5.7.0",
Expand Down
2 changes: 1 addition & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const TABLE_NAME_MARKDOWN = "markdown";
export const DEFAULT_CURRENCY = "USD";
export const DEFAULT_CURRENCY_DISPLAY_PRECISION = 2;
export const DEFAULT_JSON_OUTPUT_FILE = "./gasReporterOutput.json";
export const DEFAULT_GAS_PRICE_PRECISION = 5;
export const DEFAULT_GAS_PRICE_PRECISION = 7;

export const DEFAULT_GET_BLOCK_API_ARGS = "action=eth_getBlockByNumber&tag=latest&boolean=false"
export const DEFAULT_GAS_PRICE_API_ARGS = "action=eth_gasPrice"
Expand Down
12 changes: 11 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ subtask(TASK_GAS_REPORTER_START).setAction(
return result;
}

// solidity-coverage disables gas reporter via mocha but that
// no longer works for this version. (No warning necessary)
if ((hre as any).__SOLIDITY_COVERAGE_RUNNING === true) {
return runSuper();
}

// Need to compile so we have access to the artifact data.
// This will rerun in TASK_TEST & TASK_RUN but should be a noop there.
if (!args.noCompile) {
Expand Down Expand Up @@ -146,7 +152,11 @@ subtask(TASK_GAS_REPORTER_STOP).setAction(
async (args: any, hre) => {
const options = hre.config.gasReporter;

if (options.enabled === true && args.parallel !== true) {
if (
options.enabled === true &&
args.parallel !== true &&
(hre as any).__SOLIDITY_COVERAGE_RUNNING !== true
) {
const { setGasAndPriceRates } = await import("./utils/prices");
const { render } = await import("./lib/render");

Expand Down
14 changes: 7 additions & 7 deletions src/lib/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export async function getResolvedRemoteContracts(
contract.bytecodeHash = sha1(contract.bytecode!);
} catch (error: any) {
console.log(
`Warning: failed to fetch bytecode for remote contract: ${contract.name}`
`hardhat-gas-reporter:warning: failed to fetch bytecode for remote contract: ${contract.name}`
);
console.log(`Error was: ${error}\n`);
}
Expand All @@ -55,11 +55,9 @@ export async function getResolvedRemoteContracts(

/**
* Loads and processes artifacts
* @param {HardhatRuntimeEnvironment} hre.artifacts
* @param {String[]} skippable contract *not* to track
* @param {RemoteContract[]} resolvedRemoteContracts
* @param {String} resolvedQualifiedNames
* @return {object[]} objects w/ abi and bytecode
* @param {HardhatRuntimeEnvironment} hre
* @param {GasReporterOptions[]} options
* @return {ContractInfo[]}
*/
export async function getContracts(
hre: HardhatRuntimeEnvironment,
Expand Down Expand Up @@ -136,9 +134,11 @@ export async function getContracts(
*
* @param {HardhatRuntimeEnvironment} hre
* @param {GasReporterOptions} options
* @param {any[]} abi
* @param {string} name
* @param {string} qualifiedName
* @returns
* @param {[key: string]: string[]} visited (cache)
* @returns {Promise<string[]>}
*/
async function getExcludedMethodKeys(
hre: HardhatRuntimeEnvironment,
Expand Down
7 changes: 3 additions & 4 deletions src/lib/collector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,18 @@ import type { RpcReceiptOutput } from "hardhat/internal/hardhat-network/provider
import { hexlify } from "@ethersproject/bytes";

import { HardhatRuntimeEnvironment } from "hardhat/types";

import { getMethodID } from "../utils/sources";
import {
getCalldataGasForNetwork,
hexToDecimal,
getIntrinsicGas,
getGasSubIntrinsic
} from "../utils/gas";

import { GasReporterOptions, JsonRpcTx, FakeTx, ValidatedRequestArguments } from "../types"
import { GasData } from "./gasData";
import { Resolver } from "./resolvers";


/**
* Collects gas usage data, associating it with the relevant contracts, methods.
*/
Expand Down Expand Up @@ -43,7 +42,7 @@ export class Collector {
}

/**
* Method called by the request monitor on the provider to gas data for `eth_call`
* Method called by the request monitor on the provider to get gas data for `eth_call`
* @param {ValidatedRequestArguments} params.args of the call
* @param {number} estimate_gas result
*/
Expand Down Expand Up @@ -92,6 +91,7 @@ export class Collector {
* Extracts and stores methods gas usage data for a tx
* @param {JsonRpcTx} transaction return value of `getTransactionByHash`
* @param {TransactionReceipt} receipt
* @param {boolean} isCall
*/
private async _collectMethodsData(
tx: JsonRpcTx | FakeTx,
Expand Down Expand Up @@ -119,7 +119,6 @@ export class Collector {
const id = getMethodID(contractName!, tx.input!);

if (this.data.methods[id] !== undefined) {

const executionGas = (this.options.includeIntrinsicGas)
? hexToDecimal(receipt.gasUsed)
: getGasSubIntrinsic(tx.input, hexToDecimal(receipt.gasUsed));
Expand Down
8 changes: 2 additions & 6 deletions src/lib/gasData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,8 @@ export class GasData {

/**
* Sets up data structures to store deployments and methods gas usage
* @param config {Config}
* @param provider {EthereumProvider}
* @param artifacts {Artifacts}
* @param skippable {string[]}
* @param remoteContracts {RemoteContracts[]}
* @param qualifiedNames {string[]}
* @param {EthereumProvider} provider
* @param {ContractInfo[]} contracts
* @returns
*/
public initialize(
Expand Down
9 changes: 5 additions & 4 deletions src/lib/render/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import type { GasData } from "../gasData";
import { writeFileSync } from "fs";

import { HardhatRuntimeEnvironment as HRE } from "hardhat/types";
import { warnReportFormat } from "../../utils/ui";
import {
TABLE_NAME_LEGACY,
TABLE_NAME_MARKDOWN,
TABLE_NAME_TERMINAL
} from "../../constants";

import { GasReporterOptions } from "../../types";
import { getSolcInfo } from "../../utils/sources";
import { warnReportFormat } from "../../utils/ui";
import { GasReporterOptions } from "../../types";
import { generateTerminalTextTable } from "./terminal";
import { generateLegacyTextTable } from "./legacy";
import { generateMarkdownTable} from "./markdown";
Expand All @@ -22,6 +21,7 @@ import { generateJSONData } from "./json";
* @param {HardhatRuntimeEnvironment} hre
* @param {GasData} data
* @param {GasReporterOptions} options
* @param {string} toolchain
* @returns {string} table
*/
export function getTableForFormat(
Expand All @@ -41,8 +41,9 @@ export function getTableForFormat(
/**
* Manages table rendering and file saving
* @param {HardhatRuntimeEnvironment} hre
* @param {GasData} data
* @param {GasReporterOptions} options
* @param {string[]} warnings
* @param {string} toolchain
*/
export function render(
hre: HRE,
Expand Down
4 changes: 3 additions & 1 deletion src/lib/render/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { GasReporterOptions, GasReporterOutput } from "../../types";
/**
* Writes acccumulated data and the current options to gasReporterOutput.json so it
* can be consumed by other tools (CI etc...)
* @param {Object} data GasData instance
* @param {GasData} data
* @param {GasReporterOptions} options
* @param {string} toolchain
*/
export function generateJSONData(
data: GasData,
Expand Down
2 changes: 1 addition & 1 deletion src/lib/render/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
} from "../../utils/ui";

import { GasReporterOptions, MethodDataItem } from "../../types";

interface Section {row: string[], contractName: string, methodName: string}

/**
Expand All @@ -25,6 +24,7 @@ interface Section {row: string[], contractName: string, methodName: string}
* @param {HardhatRuntimeEnvironment} hre
* @param {GasData} data
* @param {GasReporterOptions} options
* @param {string} toolchain
*/
export function generateMarkdownTable(
hre: HardhatRuntimeEnvironment,
Expand Down
3 changes: 1 addition & 2 deletions src/lib/render/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
} from "../../utils/ui";

import { GasReporterOptions, MethodDataItem } from "../../types";

interface Section {row: HorizontalTableRow, contractName: string, methodName: string}

/**
Expand All @@ -23,6 +22,7 @@ interface Section {row: HorizontalTableRow, contractName: string, methodName: st
* @param {HardhatRuntimeEnvironment} hre
* @param {GasData} data
* @param {GasReporterOptions} options
* @param {string} string
*/
export function generateTerminalTextTable(
hre: HardhatRuntimeEnvironment,
Expand Down Expand Up @@ -292,7 +292,6 @@ export function generateTerminalTextTable(
content: chalk.cyan(`Network: ${network}`)
});

// TODO: Clarify that this is baseFee not gasPrice when L2
networkConfig.push({
hAlign: "left",
colSpan: 2,
Expand Down
3 changes: 1 addition & 2 deletions src/lib/resolvers/etherrouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ export class EtherRouterResolver implements CustomGasReporterResolver {
}

// With the correct address, we can use the reporter's Resolver class methods
// `data.getNameByAddress` and/or `resolveByDeployedBytecode` methods
// (both are available in this scope, bound to `this`) to derive
// `data.getNameByAddress` and/or `resolveByDeployedBytecode` to derive
// the target contract's name.
if (contractAddress && contractAddress !== "0x") {
contractName = await this.data.getNameByAddress(contractAddress);
Expand Down
1 change: 1 addition & 0 deletions src/lib/resolvers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {GasData} from "../gasData";
import { HardhatRuntimeEnvironment } from "hardhat/types";
import { CustomGasReporterResolver, GasReporterOptions, JsonRpcTx } from "../../types";

import { OZResolver } from "./oz";

export class Resolver {
Expand Down
8 changes: 3 additions & 5 deletions src/tasks/mergeReports.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { HardhatPluginError } from "hardhat/plugins";
import { HardhatRuntimeEnvironment, TaskArguments } from "hardhat/types";
import { generateJSONData } from "../lib/render/json";
import {
TASK_GAS_REPORTER_MERGE_REPORTS,
} from "../task-names";

import { TASK_GAS_REPORTER_MERGE_REPORTS } from "../task-names";
import { GasReporterOutput } from "../types";

/**
Expand Down Expand Up @@ -104,6 +100,8 @@ export async function taskMergeImplementation(
const { reportMerge } = await import("../utils/ui");
const { GasData } = await import("../lib/gasData");
const { setGasAndPriceRates } = await import("../utils/prices");
const { generateJSONData } = await import("../lib/render/json");


const output = path.resolve(process.cwd(), taskArguments.output);

Expand Down
8 changes: 4 additions & 4 deletions src/utils/gas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,10 @@ export function getCalldataCostForNetwork(

/**
* Expresses gas usage as a nation-state currency price
* @param {Number} gas gas used
* @param {Number} tokenPrice e.g chf/eth
* @param {Number} gasPrice in gwei
* @return {Number} cost of gas used (0.00)
* @param {Number} executionGas execution gas used
* @param {Number} calldataGas data gas used
* @param {GasReporterOptions} options
* @return {string} cost of gas used "0.00"
*/
export function gasToCost(
executionGas: number,
Expand Down
5 changes: 5 additions & 0 deletions src/utils/sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { utf8ToBytes, bytesToHex } from "ethereum-cryptography/utils";
import { SolcInfo } from "../types";


/**
* Generates hashed function selector from the human readable function signature
* @param {string} fnSig
* @returns
*/
export function getHashedFunctionSignature(fnSig: string ): string {
return bytesToHex(keccak256(Buffer.from(utf8ToBytes(fnSig)))).slice(0, 8);
}
Expand Down
8 changes: 4 additions & 4 deletions src/utils/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export function warnEthers(name: string, err: any) {
) }${EOL
}Please report the error below with the source that caused it to ` +
`github.com/cgewecke/hardhat-gas-reporter${ EOL
}${chalk.red(`>>>>>>>>>>>>>>>>>>>>`)}${EOL}${
}${chalk.yellow(`>>>>>>>>>>>>>>>>>>>>`)}${EOL}${
chalk.red(`${err}`)}`;

log(msg);
Expand All @@ -141,7 +141,7 @@ export function warnReportFormat(name: string | undefined) {
}${chalk.green(`> "${TABLE_NAME_TERMINAL}"`) }${EOL
}${chalk.green(`> "${TABLE_NAME_MARKDOWN}"`) }${EOL
}${chalk.green(`> "${TABLE_NAME_LEGACY}"`) }${EOL
}${chalk.red(`>>>>>>>>>>>>>>>>>>>>`) }${EOL}`;
}${chalk.yellow(`>>>>>>>>>>>>>>>>>>>>`) }${EOL}`;

log(msg);
}
Expand All @@ -157,7 +157,7 @@ export function warnParallel() {
"Gas reporting has been skipped because plugin `hardhat-gas-reporter` " +
"does not support the --parallel flag."
) }${EOL
}${chalk.red(`>>>>>>>>>>>>>>>>>>>>`) }${EOL}`;
}${chalk.yellow(`>>>>>>>>>>>>>>>>>>>>`) }${EOL}`;

log(msg);
}
Expand All @@ -172,7 +172,7 @@ export function warnDeprecatedTask(newName: string) {
}${chalk.bold(
`This gas reporter task has been renamed to "${chalk.green(newName)}"`
) }${EOL
}${chalk.red(`>>>>>>>>>>>>>>>>>>>>`) }${EOL}`;
}${chalk.yellow(`>>>>>>>>>>>>>>>>>>>>`) }${EOL}`;

log(msg);
}
Expand Down
10 changes: 10 additions & 0 deletions test/integration/options.a.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ import { Deployment, GasReporterOptions, GasReporterOutput, MethodData } from ".

import { useEnvironment, findMethod, findDeployment } from "../helpers";

/**
* OPTIONS ARE SET UP TO TEST:
* + Complex compiler details
* + Non-ethereum L1 (polygon) with live market price
* + Custom gasPrice API call
* + Exclude contracts from reporting
* + Display full method signature
* + Dark mode
* + RST titles
*/
describe("Options A", function () {
let output: GasReporterOutput;
let options: GasReporterOptions;
Expand Down
7 changes: 7 additions & 0 deletions test/integration/options.b.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import { GasReporterOptions, GasReporterOutput } from "../types";

import { useEnvironment } from "../helpers";

/**
* OPTIONS ARE SET UP TO TEST:
* + user-configured token and gasPrice
* + write-to-custom-file-name (JSON & txt)
* + force terminal output w/ custom output
* + show uncalled methods
*/
describe("Options B", function () {
let output: GasReporterOutput;
let options: GasReporterOptions;
Expand Down
7 changes: 7 additions & 0 deletions test/integration/options.c.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ import { Deployment, GasReporterOptions, GasReporterOutput, MethodData } from ".

import { useEnvironment, findMethod, findDeployment } from "../helpers";

/**
* OPTIONS ARE SET UP TO TEST:
* + Markdown format
* + L2: Optimism
* + Live market prices in CHF
* + User configured gasPrice and baseGas
*/
describe("Options C", function () {
let output: GasReporterOutput;
let options: GasReporterOptions;
Expand Down
7 changes: 7 additions & 0 deletions test/integration/options.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,11 @@ describe("Default Options", function () {
assert(deployment!.executionGasAverage! < deployment!.max!)
assert(deployment!.percent! > 0);
});

it ("should delete the bytecode & deployedBytecode", function() {
const deployment = findDeployment(deployments, "VariableConstructor");

assert.isUndefined(deployment?.bytecode);
assert.isUndefined(deployment?.deployedBytecode);
})
});
Loading

0 comments on commit 0b6ef22

Please sign in to comment.