diff --git a/.changeset/console-log-stack-traces.md b/.changeset/console-log-stack-traces.md new file mode 100644 index 00000000000..f778e306f14 --- /dev/null +++ b/.changeset/console-log-stack-traces.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed Solidity stack traces not recognising `console.log` calls made through the Hardhat console address. diff --git a/.changeset/debug-trace-tracers-and-options.md b/.changeset/debug-trace-tracers-and-options.md new file mode 100644 index 00000000000..8436dbf4f0e --- /dev/null +++ b/.changeset/debug-trace-tracers-and-options.md @@ -0,0 +1,16 @@ +--- +"hardhat": minor +--- + +Updated `debug_traceTransaction` and `debug_traceCall`: + +- Added support for geth's built-in tracers, such as `callTracer` and `prestateTracer`, which return geth's output unchanged. +- Fixed an empty `tracer` to select the default tracer, as the Ethereum execution API spec requires. +- Added the `enableMemory` and `enableReturnData` options to the default tracer. `enableMemory` takes precedence over `disableMemory`, and `enableReturnData` adds `returnData` to each step. +- Changed the default tracer output in a few places: + - A step that halts now has an `error` message that comes from EDR, so do not match on its exact text. + - An unknown opcode is now named `Unknown`. + - A `STOP` at the first step is no longer dropped, so traces can have one more step. + - Storage no longer shows slots of another contract after a warm `SLOAD`. + - When `disableStack` is set, storage values can be stale until the next `SLOAD` or `SSTORE`. + - With the default tracer and storage enabled, `debug_traceTransaction` now reads the traced transaction to find its recipient. That costs one remote request when the transaction is on a forked chain. diff --git a/.changeset/default-gas-limit-osaka-cap.md b/.changeset/default-gas-limit-osaka-cap.md new file mode 100644 index 00000000000..2b770ebc11f --- /dev/null +++ b/.changeset/default-gas-limit-osaka-cap.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed `eth_call` and `eth_estimateGas` requests without a `gas` field failing under the Osaka transaction gas cap. Hardhat no longer passes a default transaction gas limit to EDR. EDR derives it from the hardfork and gas limit of the block that runs the request. diff --git a/.changeset/edr-call-trace-memory.md b/.changeset/edr-call-trace-memory.md new file mode 100644 index 00000000000..c0ec5960793 --- /dev/null +++ b/.changeset/edr-call-trace-memory.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Improved the performance of the Hardhat Network provider by reducing the memory used to record the call traces of transactions and calls. diff --git a/.changeset/edr-glibc-2-34.md b/.changeset/edr-glibc-2-34.md new file mode 100644 index 00000000000..a0e3317aba7 --- /dev/null +++ b/.changeset/edr-glibc-2-34.md @@ -0,0 +1,5 @@ +--- +"hardhat": minor +--- + +Raised the minimum glibc version of the prebuilt Linux gnu binaries of EDR from 2.29 to 2.34. diff --git a/.changeset/edr-install-size.md b/.changeset/edr-install-size.md new file mode 100644 index 00000000000..94a5338944a --- /dev/null +++ b/.changeset/edr-install-size.md @@ -0,0 +1,5 @@ +--- +"hardhat": minor +--- + +Reduced Hardhat's install size because EDR now installs only the native build for the current platform through `optionalDependencies`. diff --git a/.changeset/estimate-gas-osaka-cap.md b/.changeset/estimate-gas-osaka-cap.md new file mode 100644 index 00000000000..e1752d469c1 --- /dev/null +++ b/.changeset/estimate-gas-osaka-cap.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed `eth_estimateGas` failing from the Osaka hardfork when its search probed gas values above the EIP-7825 transaction gas cap. diff --git a/.changeset/fork-loopback-proxy-bypass.md b/.changeset/fork-loopback-proxy-bypass.md new file mode 100644 index 00000000000..ab18fae9c70 --- /dev/null +++ b/.changeset/fork-loopback-proxy-bypass.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed forking requests to loopback URLs being sent through `HTTP_PROXY` or `HTTPS_PROXY`. Requests to `localhost`, `*.localhost`, `127.0.0.0/8`, `0.0.0.0` and `::1` now bypass the proxy. diff --git a/.changeset/fork-oldest-hardfork-error.md b/.changeset/fork-oldest-hardfork-error.md new file mode 100644 index 00000000000..1db5a83831f --- /dev/null +++ b/.changeset/fork-oldest-hardfork-error.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed forking from a block that precedes the oldest supported hardfork being silently accepted. It now fails with an error that names the oldest supported hardfork. diff --git a/.changeset/fork-retry-error-message.md b/.changeset/fork-retry-error-message.md new file mode 100644 index 00000000000..d1d1e6c7522 --- /dev/null +++ b/.changeset/fork-retry-error-message.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Changed the error of a forking request that fails on every retry. It now reads `Request failed after 9 retries` and no longer names the host or the cause, such as a DNS error. diff --git a/.changeset/fork-rpc-cache-v2.md b/.changeset/fork-rpc-cache-v2.md new file mode 100644 index 00000000000..b7e9b9ce9f5 --- /dev/null +++ b/.changeset/fork-rpc-cache-v2.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Changed the location of the forking RPC cache to an `rpc_cache/v2` subdirectory. Data cached by previous Hardhat versions is not reused. Everything else in the `rpc_cache` directory is ignored and can be deleted. diff --git a/.changeset/genesis-system-account-nonce.md b/.changeset/genesis-system-account-nonce.md new file mode 100644 index 00000000000..f1a3af4e545 --- /dev/null +++ b/.changeset/genesis-system-account-nonce.md @@ -0,0 +1,5 @@ +--- +"hardhat": minor +--- + +Fixed the EIP-4788 and EIP-2935 system accounts to have nonce `1` in the genesis state, matching their on-chain deployments. The genesis block hash of local Cancun or later networks therefore differs from previous Hardhat versions. The hashes of all later blocks change as well. diff --git a/.changeset/interval-mining-logging-deadlock.md b/.changeset/interval-mining-logging-deadlock.md new file mode 100644 index 00000000000..b10c2055830 --- /dev/null +++ b/.changeset/interval-mining-logging-deadlock.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed a deadlock that hung the process when a Hardhat Network provider with interval mining and logging enabled was destroyed. diff --git a/.changeset/interval-mining-range-validation.md b/.changeset/interval-mining-range-validation.md new file mode 100644 index 00000000000..93fc41b88d0 --- /dev/null +++ b/.changeset/interval-mining-range-validation.md @@ -0,0 +1,8 @@ +--- +"hardhat": minor +--- + +Fixed interval mining accepting a `mining.interval` range that it could not honour: + +- A range must now satisfy `1 <= min <= max`. An invalid range is rejected when the config is loaded, when the provider is created and when `evm_setIntervalMining` is called. The config error names `networks.hardhat.mining.interval` and the offending range. +- BREAKING CHANGE: `[0, 0]` and `[0, N]` ranges are no longer accepted. Use a range with a minimum of at least `1`, such as `[1, N]`, instead. Set `mining.interval` to `0` to disable interval mining. diff --git a/.changeset/log-block-timestamp.md b/.changeset/log-block-timestamp.md new file mode 100644 index 00000000000..57ea247df72 --- /dev/null +++ b/.changeset/log-block-timestamp.md @@ -0,0 +1,5 @@ +--- +"hardhat": minor +--- + +Added the `blockTimestamp` field to logs. Logs returned by `eth_getLogs`, `eth_getFilterLogs`, `eth_getFilterChanges` and `eth_subscribe("logs")` carry it, as do the logs in transaction receipts. When forking, the field is passed through from the remote node and is absent if the node does not serve it. diff --git a/.changeset/node-log-value-formatting.md b/.changeset/node-log-value-formatting.md new file mode 100644 index 00000000000..1261280a80e --- /dev/null +++ b/.changeset/node-log-value-formatting.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed the transaction `Value` in the `hardhat node` logs dropping leading zeros of the fractional part, which logged `0.01 ETH` as `0.1 ETH`. Whole amounts no longer end with a trailing dot. diff --git a/.changeset/precompile-stack-traces.md b/.changeset/precompile-stack-traces.md new file mode 100644 index 00000000000..728bbcf2c6a --- /dev/null +++ b/.changeset/precompile-stack-traces.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed Solidity stack traces after a precompile call. A failing precompile call is now reported as a precompile error, and later calls in the same function point at the right line. diff --git a/.changeset/proxy-call-logging.md b/.changeset/proxy-call-logging.md new file mode 100644 index 00000000000..7e1bd87b596 --- /dev/null +++ b/.changeset/proxy-call-logging.md @@ -0,0 +1,5 @@ +--- +"hardhat": patch +--- + +Fixed calls through proxy contracts being logged as ``. A selector that is missing from the called contract is now resolved against the implementation behind the proxy. The call is labeled with the full delegation chain, such as `Proxy>Implementation#setValue`. diff --git a/.changeset/require-node-22.md b/.changeset/require-node-22.md new file mode 100644 index 00000000000..b5a7af672b2 --- /dev/null +++ b/.changeset/require-node-22.md @@ -0,0 +1,7 @@ +--- +"hardhat": minor +--- + +Updated the minimal supported version of Node to v22, because EDR declares `engines.node >= 22`. Node 20 reached end of life on 2026-04-30. + +On Node 20, Hardhat prints its unsupported-version warning and keeps running. Hardhat's own `package.json` declares no `engines`, so installing it is not blocked. Package managers warn that `@nomicfoundation/edr` requires Node 22, and those that enforce `engines`, such as Yarn 1, refuse the install. EDR's loader has no Node version check, so EDR itself still loads on Node 20, but that combination is untested. diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index fd50e4acb9a..0f0c6bcc8af 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,9 +1,9 @@ { "name": "Hardhat", - "image": "mcr.microsoft.com/devcontainers/base:bullseye", + "image": "mcr.microsoft.com/devcontainers/base:bookworm", "features": { "ghcr.io/devcontainers/features/node:1": { - "version": "20" + "version": "22" } }, "postCreateCommand": "scripts/setup.sh", diff --git a/.nvmrc b/.nvmrc index 209e3ef4b62..2bd5a0a98a3 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -20 +22 diff --git a/packages/hardhat-core/package.json b/packages/hardhat-core/package.json index 6709f39987b..b18c361f2b3 100644 --- a/packages/hardhat-core/package.json +++ b/packages/hardhat-core/package.json @@ -102,7 +102,7 @@ "dependencies": { "@ethereumjs/util": "^9.1.0", "@ethersproject/abi": "^5.1.2", - "@nomicfoundation/edr": "0.12.0-next.23", + "@nomicfoundation/edr": "0.25.1", "@nomicfoundation/solidity-analyzer": "^0.1.0", "@sentry/node": "^5.18.1", "adm-zip": "^0.6.0", diff --git a/packages/hardhat-core/src/internal/cli/constants.ts b/packages/hardhat-core/src/internal/cli/constants.ts index 18627391282..a5e554dcd4b 100644 --- a/packages/hardhat-core/src/internal/cli/constants.ts +++ b/packages/hardhat-core/src/internal/cli/constants.ts @@ -1 +1 @@ -export const SUPPORTED_NODE_VERSIONS = ["^20.0.0", "^22.0.0", "^24.0.0"]; +export const SUPPORTED_NODE_VERSIONS = ["^22.0.0", "^24.0.0"]; diff --git a/packages/hardhat-core/src/internal/cli/project-creation.ts b/packages/hardhat-core/src/internal/cli/project-creation.ts index 480f0185d61..25d0f6147f7 100644 --- a/packages/hardhat-core/src/internal/cli/project-creation.ts +++ b/packages/hardhat-core/src/internal/cli/project-creation.ts @@ -83,7 +83,7 @@ const TYPESCRIPT_DEPENDENCIES: Dependencies = { const TYPESCRIPT_PEER_DEPENDENCIES: Dependencies = { "@types/chai": "^4.2.0", "@types/mocha": ">=9.1.0", - "@types/node": ">=20.0.0", + "@types/node": ">=22.0.0", "ts-node": ">=8.0.0", }; diff --git a/packages/hardhat-core/src/internal/core/config/config-validation.ts b/packages/hardhat-core/src/internal/core/config/config-validation.ts index 0838235dcbf..ddfd6b95c80 100644 --- a/packages/hardhat-core/src/internal/core/config/config-validation.ts +++ b/packages/hardhat-core/src/internal/core/config/config-validation.ts @@ -64,6 +64,36 @@ function getErrorMessage(path: string, value: any, expectedType: string) { )} for ${path} - Expected a value of type ${expectedType}.`; } +/** + * The smallest minimum of a `mining.interval` range, in milliseconds, that + * EDR accepts. + */ +const MIN_MINING_INTERVAL_RANGE_START = 1; + +function validateMiningIntervalRange( + interval: unknown, + network: string, + errors: string[] +) { + if ( + !Array.isArray(interval) || + interval.length !== 2 || + typeof interval[0] !== "number" || + typeof interval[1] !== "number" + ) { + return; + } + + const [min, max] = interval; + if (min < MIN_MINING_INTERVAL_RANGE_START || min > max) { + errors.push( + `Invalid value ${stringify( + interval + )} for HardhatConfig.networks.${network}.mining.interval - Expected a range [min, max] with ${MIN_MINING_INTERVAL_RANGE_START} <= min <= max.` + ); + } +} + function getPrivateKeyError(index: number, network: string, message: string) { return `Invalid account: #${index} for network: ${network} - ${message}`; } @@ -460,6 +490,12 @@ export function getValidationErrors(config: any): string[] { ); } + validateMiningIntervalRange( + hardhatNetwork.mining?.interval, + HARDHAT_NETWORK_NAME, + errors + ); + const hardfork = hardhatNetwork.hardfork ?? defaultHardhatNetworkParams.hardfork; if (hardforkGte(hardfork, HardforkName.LONDON)) { diff --git a/packages/hardhat-core/src/internal/hardhat-network/provider/output.ts b/packages/hardhat-core/src/internal/hardhat-network/provider/output.ts index 54d624eaa12..55532b13bd4 100644 --- a/packages/hardhat-core/src/internal/hardhat-network/provider/output.ts +++ b/packages/hardhat-core/src/internal/hardhat-network/provider/output.ts @@ -137,6 +137,7 @@ export interface RpcStructLog { storage?: Record; memSize?: number; error?: object; + returnData?: string; } export interface RpcDebugTraceOutput { diff --git a/packages/hardhat-core/src/internal/hardhat-network/provider/provider.ts b/packages/hardhat-core/src/internal/hardhat-network/provider/provider.ts index 0c4f0b297a9..7d6a6e74530 100644 --- a/packages/hardhat-core/src/internal/hardhat-network/provider/provider.ts +++ b/packages/hardhat-core/src/internal/hardhat-network/provider/provider.ts @@ -21,7 +21,12 @@ import type { AccountOverride, } from "@nomicfoundation/edr"; import { privateToAddress } from "@ethereumjs/util"; -import { ContractDecoder, precompileP256Verify } from "@nomicfoundation/edr"; +import { + ContractDecoder, + IncludeTraces, + precompileP256Verify, + StackSnapshotType, +} from "@nomicfoundation/edr"; import picocolors from "picocolors"; import debug from "debug"; import { EventEmitter } from "events"; @@ -67,13 +72,12 @@ import { MempoolOrder, } from "./node-types"; import { - edrRpcDebugTraceToHardhat, + edrRpcDebugTraceToHardhat2, edrTracingMessageResultToMinimalEVMResult, edrTracingMessageToMinimalMessage, edrTracingStepToMinimalInterpreterStep, ethereumjsIntervalMiningConfigToEdr, ethereumjsMempoolOrderToEdrMineOrdering, - ethereumsjsHardforkToEdrSpecId, httpHeadersToEdr, } from "./utils/convertToEdr"; import { LoggerConfig, printLine, replaceLastLine } from "./modules/logger"; @@ -130,8 +134,6 @@ interface HardhatNetworkProviderConfig { enableRip7212: boolean; } -class EdrProviderEventAdapter extends EventEmitter {} - type CallOverrideCallback = ( address: Buffer, data: Buffer @@ -157,11 +159,14 @@ export class EdrProviderWrapper _vm: MinimalEthereumJsVm; }, private readonly _subscriptionConfig: SubscriptionConfig, - // Store the initial `genesisAccounts`, `cacheDir`, and `chainOverrides` for `hardhat_reset` - // calls, in case there is switching between local and fork configurations. + // Store the initial `genesisAccounts`, `cacheDir`, `chainOverrides`, and local-network + // genesis values for `hardhat_reset` calls, in case there is switching between local + // and fork configurations. private readonly _originalGenesisAccounts: GenesisAccount[], private readonly _originalCacheDir: string | undefined, - private readonly _originalChainOverrides: ChainOverride[] | undefined + private readonly _originalChainOverrides: ChainOverride[] | undefined, + private readonly _originalGenesisBlockGasLimit: bigint, + private readonly _originalGenesisBlockTime: bigint | undefined ) { super(); } @@ -188,9 +193,7 @@ export class EdrProviderWrapper ([hardfork, blockNumber]) => { return { condition: { blockNumber: BigInt(blockNumber) }, - hardfork: ethereumsjsHardforkToEdrSpecId( - getHardforkName(hardfork) - ), + hardfork: getHardforkName(hardfork), }; } ), @@ -200,9 +203,15 @@ export class EdrProviderWrapper const cacheDir = config.forkCachePath; - let fork; + const genesisBlockGasLimit = BigInt(config.blockGasLimit); + const genesisBlockTime = + config.initialDate !== undefined + ? BigInt(Math.floor(config.initialDate.getTime() / 1000)) + : undefined; + + let network; if (config.forkConfig !== undefined) { - fork = { + network = { blockNumber: config.forkConfig.blockNumber !== undefined ? BigInt(config.forkConfig.blockNumber) @@ -212,26 +221,28 @@ export class EdrProviderWrapper httpHeaders: httpHeadersToEdr(config.forkConfig.httpHeaders), url: config.forkConfig.jsonRpcUrl, }; + } else { + network = { + genesisBlockGasLimit, + genesisBlockTime, + }; } - const initialDate = - config.initialDate !== undefined - ? BigInt(Math.floor(config.initialDate.getTime() / 1000)) - : undefined; - - // To accommodate construction ordering, we need an adapter to forward events - // from the EdrProvider callback to the wrapper's listener - const eventAdapter = new EdrProviderEventAdapter(); + // EDR holds `subscriptionCallback` through a threadsafe function, which V8 + // cannot see through. A strong reference to the wrapper from that callback + // would root the wrapper, and with it the provider whose OS thread is only + // released once the provider is finalized. + // eslint-disable-next-line prefer-const + let wrapperWeakRef: WeakRef | undefined; const printLineFn = loggerConfig.printLineFn ?? printLine; const replaceLastLineFn = loggerConfig.replaceLastLineFn ?? replaceLastLine; const hardforkName = getHardforkName(config.hardfork); - const edrHardfork = ethereumsjsHardforkToEdrSpecId(hardforkName); const [genesisState, ownedAccounts] = _genesisStateAndOwnedAccounts( - fork !== undefined, - edrHardfork, + config.forkConfig !== undefined, + hardforkName, config.genesisAccounts ); @@ -241,20 +252,29 @@ export class EdrProviderWrapper : [precompileP256Verify()] : []; + // Turn off the Osaka EIP-7825 per transaction gas limit for HH2 + // when being run from `solidity-coverage`. + // We detect the magic number that `solidity-coverage` sets the block + // gas limit to, see https://github.com/sc-forks/solidity-coverage/blob/8e52fd7eae73803edf50c5af2faeeca8e5a57e27/lib/api.js#L55 + // We turn it off the transaction gas limit by setting it + // to a large number (the same number `solidity-coverage` uses for + // setting gas). + const transactionGasCap = + config.blockGasLimit === 0x1fffffffffffff + ? BigInt(0xfffffffffffff) + : undefined; + const edrProviderConfig = { allowBlocksWithSameTimestamp: config.allowBlocksWithSameTimestamp ?? false, allowUnlimitedContractSize: config.allowUnlimitedContractSize, bailOnCallFailure: config.throwOnCallFailures, bailOnTransactionFailure: config.throwOnTransactionFailures, - blockGasLimit: BigInt(config.blockGasLimit), chainId: BigInt(config.chainId), coinbase: Buffer.from(coinbase.slice(2), "hex"), precompileOverrides, - fork, genesisState, - hardfork: edrHardfork, - initialDate, + hardfork: hardforkName, initialBaseFeePerGas: config.initialBaseFeePerGas !== undefined ? BigInt(config.initialBaseFeePerGas!) @@ -262,25 +282,20 @@ export class EdrProviderWrapper minGasPrice: config.minGasPrice, mining: { autoMine: config.automine, + blockGasLimit: BigInt(config.blockGasLimit), interval: ethereumjsIntervalMiningConfigToEdr(config.intervalMining), memPool: { order: ethereumjsMempoolOrderToEdrMineOrdering(config.mempoolOrder), }, }, + network, networkId: BigInt(config.networkId), - observability: {}, + observability: { + includeCallTraces: IncludeTraces.All, + recordStack: StackSnapshotType.Top, + }, ownedAccounts, - // Turn off the Osaka EIP-7825 per transaction gas limit for HH2 - // when being run from `solidity-coverage`. - // We detect the magic number that `solidity-coverage` sets the block - // gas limit to, see https://github.com/sc-forks/solidity-coverage/blob/8e52fd7eae73803edf50c5af2faeeca8e5a57e27/lib/api.js#L55 - // We turn it off the transaction gas limit by setting it - // to a large number (the same number `solidity-coverage` uses for - // setting gas). - transactionGasCap: - config.blockGasLimit === 0x1fffffffffffff - ? BigInt(0xfffffffffffff) - : undefined, + transactionGasCap, }; const edrLoggerConfig = { @@ -303,7 +318,7 @@ export class EdrProviderWrapper const edrSubscriptionConfig = { subscriptionCallback: (event: SubscriptionEvent) => { - eventAdapter.emit("ethEvent", event); + wrapperWeakRef?.deref()?._ethEventListener(event); }, }; @@ -332,14 +347,12 @@ export class EdrProviderWrapper edrSubscriptionConfig, config.genesisAccounts, cacheDir, - chainOverrides + chainOverrides, + genesisBlockGasLimit, + genesisBlockTime ); - // Pass through all events from the provider - eventAdapter.addListener( - "ethEvent", - wrapper._ethEventListener.bind(wrapper) - ); + wrapperWeakRef = new WeakRef(wrapper); return wrapper; } @@ -371,13 +384,20 @@ export class EdrProviderWrapper ); } + const requestParams = isDebugTraceMethod(args.method) + ? withHardhat2MemoryDefault( + args.method, + withoutEmptyTracer(args.method, params) + ) + : params; const stringifiedArgs = JSON.stringify({ method: args.method, - params, + params: requestParams, }); + const provider = this._provider; const responseObject: Response = - await this._provider.handleRequest(stringifiedArgs); + await provider.handleRequest(stringifiedArgs); let response; if (typeof responseObject.data === "string") { @@ -391,11 +411,8 @@ export class EdrProviderWrapper this._node._vm.events.eventNames().length > 0; if (needsTraces) { - const rawTraces = responseObject.traces; - for (const rawTrace of rawTraces) { - // For other consumers in JS we need to marshall the entire trace over FFI - const trace = rawTrace.trace; - + const rawTraces = responseObject.traces(); + for (const trace of rawTraces) { // beforeTx event if (this._node._vm.events.listenerCount("beforeTx") > 0) { this._node._vm.events.emit("beforeTx"); @@ -412,7 +429,7 @@ export class EdrProviderWrapper } } // afterMessage event - else if ("executionResult" in traceItem) { + else if ("execResult" in traceItem) { if (this._node._vm.evm.events.listenerCount("afterMessage") > 0) { this._node._vm.evm.events.emit( "afterMessage", @@ -441,20 +458,34 @@ export class EdrProviderWrapper if (isErrorResponse(response)) { let error; - let stackTrace: SolidityStackTrace | null = null; - try { - stackTrace = responseObject.stackTrace(); - } catch (e) { - log("Failed to get stack trace: %O", e); - } + const stackTrace = responseObject.stackTrace(); - if (stackTrace !== null) { - error = encodeSolidityStackTrace(response.error.message, stackTrace); + if (stackTrace?.kind === "StackTrace") { + error = encodeSolidityStackTrace( + response.error.message, + // Cheatcode entries only occur in Solidity tests, never in + // provider requests, so the cast cannot see one. + stackTrace.entries as SolidityStackTrace + ); // Pass data and transaction hash from the original error (error as any).data = response.error.data?.data ?? undefined; (error as any).transactionHash = response.error.data?.transactionHash ?? undefined; } else { + if (stackTrace !== null) { + switch (stackTrace.kind) { + case "UnexpectedError": + log( + "Failed to get stack trace due to error: %O", + stackTrace.errorMessage + ); + break; + case "HeuristicFailed": + log("Failed to get stack trace due to failing heuristics"); + break; + } + } + if (response.error.code === InvalidArgumentsError.CODE) { error = new InvalidArgumentsError(response.error.message); } else { @@ -478,16 +509,79 @@ export class EdrProviderWrapper // e.g. `HardhatNetwork/2.19.0/@nomicfoundation/edr/0.2.0-dev` if (args.method === "web3_clientVersion") { return clientVersion(response.result); - } else if ( - args.method === "debug_traceTransaction" || - args.method === "debug_traceCall" - ) { - return edrRpcDebugTraceToHardhat(response.result); + } else if (isDebugTraceMethod(args.method)) { + return this._debugTraceResultToHardhat2( + provider, + args.method, + requestParams, + response.result + ); } else { return response.result; } } + private async _debugTraceResultToHardhat2( + provider: EdrProviderT, + method: DebugTraceMethod, + params: any[], + result: any + ): Promise { + const options = debugTraceOptions(method, params); + if (!usesDefaultTracer(options)) { + return result; + } + + const storageEnabled = options?.disableStorage !== true; + const rootAddress = storageEnabled + ? await this._debugTraceRootAddress(provider, method, params) + : undefined; + + return edrRpcDebugTraceToHardhat2(result, storageEnabled, rootAddress); + } + + /** Returns the address whose code the traced transaction runs. */ + private async _debugTraceRootAddress( + provider: EdrProviderT, + method: DebugTraceMethod, + params: any[] + ): Promise { + if (method === "debug_traceCall") { + return params[0]?.to ?? undefined; + } + + const transactionHash = params[0]; + const responseObject = await provider.handleRequest( + JSON.stringify({ + method: "eth_getTransactionByHash", + params: [transactionHash], + }) + ); + const response = + typeof responseObject.data === "string" + ? JSON.parse(responseObject.data) + : responseObject.data; + + if (isErrorResponse(response)) { + log( + "Failed to look up the root address of transaction %s, so its trace uses a placeholder storage context: %O", + transactionHash, + response.error.message + ); + return undefined; + } + + if (response.result === null || response.result === undefined) { + log( + "Transaction %s was not found, so its trace uses a placeholder storage context", + transactionHash + ); + return undefined; + } + + return response.result.to ?? undefined; + } + private async _addCompilationResult( solcVersion: string, input: CompilerInput, @@ -518,18 +612,19 @@ export class EdrProviderWrapper this._providerConfig.genesisState = genesisState; this._providerConfig.ownedAccounts = ownedAccounts; + const currentNetworkConfig = this._providerConfig.network; + const currentlyForked = "url" in currentNetworkConfig; + if (forkConfig !== undefined) { - const cacheDir = - this._providerConfig.fork === undefined - ? this._originalCacheDir - : this._providerConfig.fork?.cacheDir; + const cacheDir = currentlyForked + ? currentNetworkConfig.cacheDir + : this._originalCacheDir; - const chainOverrides = - this._providerConfig.fork === undefined - ? this._originalChainOverrides - : this._providerConfig.fork?.chainOverrides; + const chainOverrides = currentlyForked + ? currentNetworkConfig.chainOverrides + : this._originalChainOverrides; - this._providerConfig.fork = { + this._providerConfig.network = { blockNumber: forkConfig.blockNumber !== undefined ? BigInt(forkConfig.blockNumber) @@ -540,7 +635,18 @@ export class EdrProviderWrapper url: forkConfig.jsonRpcUrl, }; } else { - this._providerConfig.fork = undefined; + const genesisBlockGasLimit = currentlyForked + ? this._originalGenesisBlockGasLimit + : currentNetworkConfig.genesisBlockGasLimit; + + const genesisBlockTime = currentlyForked + ? this._originalGenesisBlockTime + : currentNetworkConfig.genesisBlockTime; + + this._providerConfig.network = { + genesisBlockGasLimit, + genesisBlockTime, + }; } const context = await getGlobalEdrContext(); @@ -609,6 +715,77 @@ export class EdrProviderWrapper } } +type DebugTraceMethod = "debug_traceTransaction" | "debug_traceCall"; + +const DEBUG_TRACE_OPTIONS_INDEX: Record = { + debug_traceTransaction: 1, + debug_traceCall: 2, +}; + +function isDebugTraceMethod(method: string): method is DebugTraceMethod { + return method === "debug_traceTransaction" || method === "debug_traceCall"; +} + +function debugTraceOptions(method: DebugTraceMethod, params: any[]): any { + return params[DEBUG_TRACE_OPTIONS_INDEX[method]]; +} + +function usesDefaultTracer(options: any): boolean { + return ( + options === undefined || + options === null || + (typeof options === "object" && + (options.tracer === undefined || options.tracer === null)) + ); +} + +/** + * Drops an empty `tracer`, which selects the default tracer per the execution + * API spec. Some EDR versions reject it as a JavaScript tracer. + */ +function withoutEmptyTracer(method: DebugTraceMethod, params: any[]): any[] { + const options = debugTraceOptions(method, params); + if (options?.tracer !== "") { + return params; + } + + const { tracer: _emptyTracer, ...optionsWithoutTracer } = options; + const paramsWithoutTracer = [...params]; + paramsWithoutTracer[DEBUG_TRACE_OPTIONS_INDEX[method]] = optionsWithoutTracer; + return paramsWithoutTracer; +} + +/** + * Sets `enableMemory` from `disableMemory` unless the options set it. Setting + * it here keeps the default independent of how an EDR version reads + * `disableMemory`. + */ +function withHardhat2MemoryDefault( + method: DebugTraceMethod, + params: any[] +): any[] { + const options = debugTraceOptions(method, params); + if ( + params.length === 0 || + !usesDefaultTracer(options) || + options?.enableMemory !== undefined + ) { + return params; + } + + const optionsIndex = DEBUG_TRACE_OPTIONS_INDEX[method]; + const paramsWithOptions = [...params]; + while (paramsWithOptions.length < optionsIndex) { + paramsWithOptions.push(null); + } + paramsWithOptions[optionsIndex] = { + ...options, + enableMemory: options?.disableMemory !== true, + }; + + return paramsWithOptions; +} + async function clientVersion(edrClientVersion: string): Promise { const hardhatPackage = await getPackageJson(); const edrVersion = edrClientVersion.split("/")[1]; diff --git a/packages/hardhat-core/src/internal/hardhat-network/provider/utils/convertToEdr.ts b/packages/hardhat-core/src/internal/hardhat-network/provider/utils/convertToEdr.ts index 7fc17b29c04..e09a5930464 100644 --- a/packages/hardhat-core/src/internal/hardhat-network/provider/utils/convertToEdr.ts +++ b/packages/hardhat-core/src/internal/hardhat-network/provider/utils/convertToEdr.ts @@ -1,38 +1,14 @@ import type { - SpecId, MineOrdering, IntervalRange, - DebugTraceResult, TracingMessage, TracingMessageResult, TracingStep, HttpHeader, } from "@nomicfoundation/edr"; -import { - FRONTIER, - HOMESTEAD, - DAO_FORK, - TANGERINE, - SPURIOUS_DRAGON, - BYZANTIUM, - CONSTANTINOPLE, - PETERSBURG, - ISTANBUL, - MUIR_GLACIER, - BERLIN, - LONDON, - ARROW_GLACIER, - GRAY_GLACIER, - MERGE, - SHANGHAI, - CANCUN, - PRAGUE, - OSAKA, -} from "@nomicfoundation/edr"; import { Address } from "@ethereumjs/util"; import { requireNapiRsModule } from "../../../../common/napi-rs"; -import { HardforkName } from "../../../util/hardforks"; import { IntervalMiningConfig, MempoolOrder } from "../node-types"; import { RpcDebugTraceOutput, RpcStructLog } from "../output"; import { @@ -43,104 +19,6 @@ import { /* eslint-disable @nomicfoundation/hardhat-internal-rules/only-hardhat-error */ -export function ethereumsjsHardforkToEdrSpecId(hardfork: HardforkName): string { - switch (hardfork) { - case HardforkName.FRONTIER: - return FRONTIER; - case HardforkName.HOMESTEAD: - return HOMESTEAD; - case HardforkName.DAO: - return DAO_FORK; - case HardforkName.TANGERINE_WHISTLE: - return TANGERINE; - case HardforkName.SPURIOUS_DRAGON: - return SPURIOUS_DRAGON; - case HardforkName.BYZANTIUM: - return BYZANTIUM; - case HardforkName.CONSTANTINOPLE: - return CONSTANTINOPLE; - case HardforkName.PETERSBURG: - return PETERSBURG; - case HardforkName.ISTANBUL: - return ISTANBUL; - case HardforkName.MUIR_GLACIER: - return MUIR_GLACIER; - case HardforkName.BERLIN: - return BERLIN; - case HardforkName.LONDON: - return LONDON; - case HardforkName.ARROW_GLACIER: - return ARROW_GLACIER; - case HardforkName.GRAY_GLACIER: - return GRAY_GLACIER; - case HardforkName.MERGE: - return MERGE; - case HardforkName.SHANGHAI: - return SHANGHAI; - case HardforkName.CANCUN: - return CANCUN; - case HardforkName.PRAGUE: - return PRAGUE; - case HardforkName.OSAKA: - return OSAKA; - default: - const _exhaustiveCheck: never = hardfork; - throw new Error( - `Unknown hardfork name '${hardfork as string}', this shouldn't happen` - ); - } -} - -export function edrSpecIdToEthereumHardfork(specId: SpecId): HardforkName { - const { SpecId } = requireNapiRsModule( - "@nomicfoundation/edr" - ) as typeof import("@nomicfoundation/edr"); - - switch (specId) { - case SpecId.Frontier: - return HardforkName.FRONTIER; - case SpecId.Homestead: - return HardforkName.HOMESTEAD; - case SpecId.DaoFork: - return HardforkName.DAO; - case SpecId.Tangerine: - return HardforkName.TANGERINE_WHISTLE; - case SpecId.SpuriousDragon: - return HardforkName.SPURIOUS_DRAGON; - case SpecId.Byzantium: - return HardforkName.BYZANTIUM; - case SpecId.Constantinople: - return HardforkName.CONSTANTINOPLE; - case SpecId.Petersburg: - return HardforkName.PETERSBURG; - case SpecId.Istanbul: - return HardforkName.ISTANBUL; - case SpecId.MuirGlacier: - return HardforkName.MUIR_GLACIER; - case SpecId.Berlin: - return HardforkName.BERLIN; - case SpecId.London: - return HardforkName.LONDON; - case SpecId.ArrowGlacier: - return HardforkName.ARROW_GLACIER; - case SpecId.GrayGlacier: - return HardforkName.GRAY_GLACIER; - case SpecId.Merge: - return HardforkName.MERGE; - case SpecId.Shanghai: - return HardforkName.SHANGHAI; - case SpecId.Cancun: - return HardforkName.CANCUN; - case SpecId.Prague: - return HardforkName.PRAGUE; - case SpecId.Osaka: - return HardforkName.OSAKA; - - default: - throw new Error(`Unknown spec id '${specId}', this shouldn't happen`); - } -} - export function ethereumjsIntervalMiningConfigToEdr( config: IntervalMiningConfig ): bigint | IntervalRange | undefined { @@ -174,113 +52,43 @@ export function ethereumjsMempoolOrderToEdrMineOrdering( } } -export function edrRpcDebugTraceToHardhat( - rpcDebugTrace: DebugTraceResult -): RpcDebugTraceOutput { - const structLogs = rpcDebugTrace.structLogs.map((log) => { - const result: RpcStructLog = { - depth: Number(log.depth), - gas: Number(log.gas), - gasCost: Number(log.gasCost), - op: log.opName, - pc: Number(log.pc), - }; - - if (log.memory !== undefined) { - result.memory = log.memory; - } - - if (log.stack !== undefined) { - // Remove 0x prefix which is required by EIP-3155, but not expected by Hardhat. - result.stack = log.stack?.map((item) => item.slice(2)); - } - - if (log.storage !== undefined) { - result.storage = Object.fromEntries( - Object.entries(log.storage).map(([key, value]) => { - return [key.slice(2), value.slice(2)]; - }) - ); - } - - if (log.error !== undefined) { - result.error = { - message: log.error, - }; - } - - return result; - }); - - // REVM trace adds initial STOP that Hardhat doesn't expect - if (structLogs.length > 0 && structLogs[0].op === "STOP") { - structLogs.shift(); - } - - let returnValue = rpcDebugTrace.output?.toString() ?? ""; - if (returnValue === "0x") { - returnValue = ""; - } - - return { - failed: !rpcDebugTrace.pass, - gas: Number(rpcDebugTrace.gasUsed), - returnValue, - structLogs, - }; -} - export function edrTracingStepToMinimalInterpreterStep( step: TracingStep ): MinimalInterpreterStep { const minimalInterpreterStep: MinimalInterpreterStep = { - pc: Number(step.pc), + pc: step.pc, depth: step.depth, opcode: { - name: step.opcode, + name: step.opcode.name, }, stack: step.stack, + memory: step.memory, }; - if (step.memory !== undefined) { - minimalInterpreterStep.memory = step.memory; - } - return minimalInterpreterStep; } export function edrTracingMessageResultToMinimalEVMResult( tracingMessageResult: TracingMessageResult ): MinimalEVMResult { - const { result, contractAddress } = tracingMessageResult.executionResult; - - // only SuccessResult has logs - const success = "logs" in result; + const execResult = tracingMessageResult.execResult; const minimalEVMResult: MinimalEVMResult = { execResult: { - executionGasUsed: result.gasUsed, - success, + success: execResult.success, + executionGasUsed: execResult.executionGasUsed, + contractAddress: + execResult.contractAddress !== undefined + ? new Address(execResult.contractAddress) + : undefined, + reason: execResult.reason, + output: + execResult.output !== undefined + ? Buffer.from(execResult.output) + : undefined, }, }; - // only success and exceptional halt have reason - if ("reason" in result) { - minimalEVMResult.execResult.reason = result.reason; - } - if ("output" in result) { - const { output } = result; - if (output instanceof Uint8Array) { - minimalEVMResult.execResult.output = Buffer.from(output); - } else { - minimalEVMResult.execResult.output = Buffer.from(output.returnValue); - } - } - - if (contractAddress !== undefined) { - minimalEVMResult.execResult.contractAddress = new Address(contractAddress); - } - return minimalEVMResult; } @@ -318,3 +126,242 @@ export function httpHeadersToEdr(input?: { return httpHeaders; } + +/** A struct log entry of EDR's geth-style default tracer output. */ +export interface EdrGethStructLog { + pc: number; + op: string; + gas: number; + gasCost: number; + depth: number; + error?: string; + stack?: string[]; + returnData?: string; + memory?: string[]; + storage?: Record; + refund?: number; +} + +/** EDR's geth-style default tracer output. */ +export interface EdrGethDefaultTrace { + failed: boolean; + gas: number; + returnValue: string; + structLogs: EdrGethStructLog[]; +} + +const HEX_PREFIX = "0x"; +const WORD_HEX_LENGTH = 64; +const ADDRESS_HEX_LENGTH = 40; + +/** + * The address that a failed CREATE or CREATE2 pushes, in the unprefixed form + * that `stackItemToAddress` returns. + */ +const FAILED_CREATE_ADDRESS = "0".repeat(ADDRESS_HEX_LENGTH); + +const CALL_OPCODES_WITH_OWN_STORAGE = new Set(["CALL", "STATICCALL"]); +const CALL_OPCODES_WITH_CALLER_STORAGE = new Set(["DELEGATECALL", "CALLCODE"]); +const CREATE_OPCODES = new Set(["CREATE", "CREATE2"]); + +/** + * The target address sits second from the top of the stack, below the gas. + * This holds for CALL, CALLCODE, DELEGATECALL and STATICCALL. + */ +const CALL_ADDRESS_STACK_OFFSET = 2; + +function stripHexPrefix(hex: string): string { + return hex.startsWith(HEX_PREFIX) ? hex.slice(HEX_PREFIX.length) : hex; +} + +function edrStackItemToHardhat2(item: string): string { + return stripHexPrefix(item).padStart(WORD_HEX_LENGTH, "0"); +} + +function edrStorageToHardhat2( + storage: Record +): Record { + return Object.fromEntries( + Object.entries(storage).map(([key, value]) => [ + stripHexPrefix(key), + stripHexPrefix(value), + ]) + ); +} + +function stackItemToAddress(item: string): string { + return edrStackItemToHardhat2(item).slice(-ADDRESS_HEX_LENGTH); +} + +function normalizeAddress(address: string): string { + return stripHexPrefix(address).toLowerCase(); +} + +/** + * Tracks the storage that Hardhat 2 reported on every step. + * + * EDR reports storage only on SLOAD and SSTORE steps. Each report holds every + * slot the executing contract has accessed so far in the transaction. This + * class repeats that snapshot on every step, keyed by the storage context of + * each call frame. The context of a CALL or STATICCALL is its target + * address, read from the stack. DELEGATECALL and CALLCODE keep the caller's + * context. A CREATE context is renamed to the created address once the frame + * returns. Without the stack, each called frame gets a new context, so its + * storage values can be stale until the next SLOAD or SSTORE. + */ +class StorageTracker { + private readonly _storageByContext = new Map< + string, + Record + >(); + + // The storage context of each active call frame, indexed by depth - 1. + private readonly _contexts: string[]; + + // The storage context of the frame the previous step entered, if any. + private _nextContext: string | undefined; + + // The context of each CREATE awaiting its address, keyed by the depth of + // the CREATE step. + private readonly _pendingCreateContexts = new Map(); + + constructor(rootContext: string) { + this._contexts = [rootContext]; + } + + public storageAt( + log: EdrGethStructLog, + stepIndex: number + ): Record { + this._enterOrLeaveFrames(log, stepIndex); + + const context = this._contexts[this._contexts.length - 1]; + if (log.storage !== undefined) { + this._storageByContext.set(context, edrStorageToHardhat2(log.storage)); + } + + this._nextContext = this._childContext(log, context, stepIndex); + + return { ...(this._storageByContext.get(context) ?? {}) }; + } + + private _enterOrLeaveFrames(log: EdrGethStructLog, stepIndex: number): void { + if (log.depth > this._contexts.length) { + // Without the stack, the frame's storage context is unknown. + this._contexts.push(this._nextContext ?? `frame:${stepIndex}`); + return; + } + + while (log.depth < this._contexts.length) { + this._contexts.pop(); + } + + const createContext = this._pendingCreateContexts.get(log.depth); + if (createContext !== undefined) { + this._pendingCreateContexts.delete(log.depth); + this._renameCreateContext(createContext, log.stack); + } + } + + private _renameCreateContext( + createContext: string, + stack: string[] | undefined + ): void { + const createdStackItem = stack?.[stack.length - 1]; + const storage = this._storageByContext.get(createContext); + if (createdStackItem === undefined || storage === undefined) { + return; + } + + const createdAddress = stackItemToAddress(createdStackItem); + if (createdAddress === FAILED_CREATE_ADDRESS) { + return; + } + + this._storageByContext.delete(createContext); + this._storageByContext.set(createdAddress, storage); + } + + private _childContext( + log: EdrGethStructLog, + context: string, + stepIndex: number + ): string | undefined { + if (CALL_OPCODES_WITH_CALLER_STORAGE.has(log.op)) { + return context; + } + + if (CALL_OPCODES_WITH_OWN_STORAGE.has(log.op)) { + const target = log.stack?.[log.stack.length - CALL_ADDRESS_STACK_OFFSET]; + return target === undefined ? undefined : stackItemToAddress(target); + } + + if (CREATE_OPCODES.has(log.op)) { + const createContext = `create:${stepIndex}`; + this._pendingCreateContexts.set(log.depth, createContext); + return createContext; + } + + return undefined; + } +} + +/** + * Converts EDR's geth-style default tracer output to Hardhat 2's debug trace + * format. + * + * @param trace The output of `debug_traceTransaction` or `debug_traceCall`. + * @param storageEnabled Whether the request captured storage. + * @param rootAddress The address whose code the transaction runs. Omit it for + * a contract creation, whose constructor cannot be re-entered. + */ +export function edrRpcDebugTraceToHardhat2( + trace: EdrGethDefaultTrace, + storageEnabled: boolean, + rootAddress?: string +): RpcDebugTraceOutput { + const storageTracker = storageEnabled + ? new StorageTracker( + rootAddress !== undefined ? normalizeAddress(rootAddress) : "root" + ) + : undefined; + + const structLogs = trace.structLogs.map((log, stepIndex) => { + const result: RpcStructLog = { + depth: log.depth, + gas: log.gas, + gasCost: log.gasCost, + op: log.op, + pc: log.pc, + }; + + if (log.memory !== undefined) { + result.memory = log.memory.map(stripHexPrefix); + } + + if (log.stack !== undefined) { + result.stack = log.stack.map(edrStackItemToHardhat2); + } + + if (storageTracker !== undefined) { + result.storage = storageTracker.storageAt(log, stepIndex); + } + + if (log.error !== undefined) { + result.error = { message: log.error }; + } + + if (log.returnData !== undefined) { + result.returnData = log.returnData; + } + + return result; + }); + + return { + failed: trace.failed, + gas: trace.gas, + returnValue: trace.returnValue === HEX_PREFIX ? "" : trace.returnValue, + structLogs, + }; +} diff --git a/packages/hardhat-core/test/builtin-tasks/compile.ts b/packages/hardhat-core/test/builtin-tasks/compile.ts index f89635e1237..b27c5eb1b80 100644 --- a/packages/hardhat-core/test/builtin-tasks/compile.ts +++ b/packages/hardhat-core/test/builtin-tasks/compile.ts @@ -1,4 +1,4 @@ -import { getLatestSupportedSolcVersion } from "@nomicfoundation/edr"; +import { latestSupportedSolidityVersion } from "@nomicfoundation/edr"; import { assert, expect } from "chai"; import ci from "ci-info"; import * as fsExtra from "fs-extra"; @@ -57,7 +57,7 @@ describe("compile task", function () { // Test to check that the last version of solc is being tested const userConfigSolcVersion = this.env.userConfig.solidity; - const lastSolcVersion = getLatestSupportedSolcVersion(); + const lastSolcVersion = latestSupportedSolidityVersion(); assert.equal( userConfigSolcVersion, diff --git a/packages/hardhat-core/test/helpers/compilation.ts b/packages/hardhat-core/test/helpers/compilation.ts index 88cf339bd8f..1cb00c1f7a7 100644 --- a/packages/hardhat-core/test/helpers/compilation.ts +++ b/packages/hardhat-core/test/helpers/compilation.ts @@ -1,4 +1,4 @@ -import { getLatestSupportedSolcVersion } from "@nomicfoundation/edr"; +import { latestSupportedSolidityVersion } from "@nomicfoundation/edr"; import semver from "semver"; import { @@ -159,7 +159,7 @@ async function downloadCompiler(solidityVersion: string): Promise { } export const getNextUnsupportedVersion = () => - semver.inc(getLatestSupportedSolcVersion(), "patch")!; + semver.inc(latestSupportedSolidityVersion(), "patch")!; export const getNextNextUnsupportedVersion = () => semver.inc(getNextUnsupportedVersion(), "patch")!; diff --git a/packages/hardhat-core/test/internal/cli/is-node-version-to-warn-on.ts b/packages/hardhat-core/test/internal/cli/is-node-version-to-warn-on.ts index 70a0b9e8b67..06be0f6c805 100644 --- a/packages/hardhat-core/test/internal/cli/is-node-version-to-warn-on.ts +++ b/packages/hardhat-core/test/internal/cli/is-node-version-to-warn-on.ts @@ -3,9 +3,6 @@ import { isNodeVersionToWarnOn } from "../../../src/internal/cli/is-node-version describe("isNodeVersionToWarnOn", function () { it("Should not warn on supported versions", function () { - assert.isFalse(isNodeVersionToWarnOn("v20.0.0")); - assert.isFalse(isNodeVersionToWarnOn("v20.14.0")); - assert.isFalse(isNodeVersionToWarnOn("v22.0.0")); assert.isFalse(isNodeVersionToWarnOn("v22.3.0")); @@ -39,6 +36,9 @@ describe("isNodeVersionToWarnOn", function () { assert(isNodeVersionToWarnOn("v18.0.0")); assert(isNodeVersionToWarnOn("v18.20.3")); + + assert(isNodeVersionToWarnOn("v20.0.0")); + assert(isNodeVersionToWarnOn("v20.14.0")); }); it("Should warn on odd number releases", function () { diff --git a/packages/hardhat-core/test/internal/core/config/config-validation.ts b/packages/hardhat-core/test/internal/core/config/config-validation.ts index fdc46e5627b..2523be628da 100644 --- a/packages/hardhat-core/test/internal/core/config/config-validation.ts +++ b/packages/hardhat-core/test/internal/core/config/config-validation.ts @@ -1109,6 +1109,44 @@ describe("Config validation", function () { }); }); + describe("Mining interval range", function () { + const INTERVAL_PATH = `HardhatConfig.networks.${HARDHAT_NETWORK_NAME}.mining.interval`; + + function validateInterval(interval: [number, number]) { + validateConfig({ + networks: { + [HARDHAT_NETWORK_NAME]: { + mining: { interval }, + }, + }, + }); + } + + it("Should reject a range with a minimum of 0", function () { + expectHardhatError( + () => validateInterval([0, 5]), + ERRORS.GENERAL.INVALID_CONFIG, + `Invalid value [0,5] for ${INTERVAL_PATH}` + ); + }); + + it("Should reject a range with a minimum above its maximum", function () { + expectHardhatError( + () => validateInterval([5, 2]), + ERRORS.GENERAL.INVALID_CONFIG, + `Invalid value [5,2] for ${INTERVAL_PATH}` + ); + }); + + it("Should accept a range with equal minimum and maximum of 1", function () { + validateInterval([1, 1]); + }); + + it("Should accept a range with a minimum of 1", function () { + validateInterval([1, 5]); + }); + }); + describe("Hardhat network's coinbase", function () { it("Should fail if it's not a valid address", function () { expectHardhatError( diff --git a/packages/hardhat-core/test/internal/hardhat-network/provider/trace-event-bridge.ts b/packages/hardhat-core/test/internal/hardhat-network/provider/trace-event-bridge.ts new file mode 100644 index 00000000000..a80bb0a7f5d --- /dev/null +++ b/packages/hardhat-core/test/internal/hardhat-network/provider/trace-event-bridge.ts @@ -0,0 +1,102 @@ +import { assert } from "chai"; + +import { numberToRpcQuantity } from "../../../../src/internal/core/jsonrpc/types/base-types"; +import { EIP1193Provider, EthereumProvider } from "../../../../types"; +import { DEFAULT_ACCOUNTS_ADDRESSES, PROVIDERS } from "../helpers/providers"; + +interface VmEventCounts { + steps: number; + beforeMessages: number; + afterMessages: number; +} + +const TX_GAS = numberToRpcQuantity(0x100000); +const SENDER = DEFAULT_ACCOUNTS_ADDRESSES[0]; + +/** Init code that runs PUSH1 1, PUSH1 2, PUSH1 3 and STOP. */ +const FOUR_STEP_INIT_CODE = "0x60016002600300"; + +/** The single message of `FOUR_STEP_INIT_CODE` and its four steps. */ +const FOUR_STEP_EVENT_COUNTS: VmEventCounts = { + steps: 4, + beforeMessages: 1, + afterMessages: 1, +}; + +/** + * Init code that pushes five zeros as the return and argument ranges and + * the value, then pushes the identity precompile's address and 0xffff gas. + * It then runs CALL and STOP. + */ +const IDENTITY_PRECOMPILE_CALL_INIT_CODE = + "0x60006000600060006000600461fffff100"; + +/** + * The creation message and the precompile call message. A precompile runs no + * steps, so all nine steps belong to the init code. + */ +const IDENTITY_PRECOMPILE_CALL_EVENT_COUNTS: VmEventCounts = { + steps: 9, + beforeMessages: 2, + afterMessages: 2, +}; + +async function sendTransactionCountingVmEvents( + hardhatNetworkProvider: EIP1193Provider, + provider: EthereumProvider, + data: string +): Promise { + const counts: VmEventCounts = { + steps: 0, + beforeMessages: 0, + afterMessages: 0, + }; + const vmEvents = (hardhatNetworkProvider as any)._node._vm.evm.events; + vmEvents.on("step", () => { + counts.steps += 1; + }); + vmEvents.on("beforeMessage", () => { + counts.beforeMessages += 1; + }); + vmEvents.on("afterMessage", () => { + counts.afterMessages += 1; + }); + + await provider.send("eth_sendTransaction", [ + { from: SENDER, data, gas: TX_GAS }, + ]); + + // The minimal VM emits through an AsyncEventEmitter, whose listeners run on + // a later tick. + await new Promise((resolve) => setImmediate(resolve)); + + return counts; +} + +describe("Trace-event bridge", function () { + PROVIDERS.forEach(({ name, useProvider }) => { + describe(`${name} provider`, function () { + useProvider(); + + it("emits step, beforeMessage and afterMessage events for a transaction", async function () { + const counts = await sendTransactionCountingVmEvents( + this.hardhatNetworkProvider, + this.provider, + FOUR_STEP_INIT_CODE + ); + + assert.deepEqual(counts, FOUR_STEP_EVENT_COUNTS); + }); + + it("emits beforeMessage and afterMessage events for a precompile call", async function () { + const counts = await sendTransactionCountingVmEvents( + this.hardhatNetworkProvider, + this.provider, + IDENTITY_PRECOMPILE_CALL_INIT_CODE + ); + + assert.deepEqual(counts, IDENTITY_PRECOMPILE_CALL_EVENT_COUNTS); + }); + }); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1d8084f2865..aa7ae42ed1f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -201,8 +201,8 @@ importers: specifier: ^5.1.2 version: 5.8.0 '@nomicfoundation/edr': - specifier: 0.12.0-next.23 - version: 0.12.0-next.23 + specifier: 0.25.1 + version: 0.25.1 '@nomicfoundation/solidity-analyzer': specifier: ^0.1.0 version: 0.1.2 @@ -3070,37 +3070,51 @@ packages: resolution: {integrity: sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==} engines: {node: '>=12.4.0'} - '@nomicfoundation/edr-darwin-arm64@0.12.0-next.23': - resolution: {integrity: sha512-Amh7mRoDzZyJJ4efqoePqdoZOzharmSOttZuJDlVE5yy07BoE8hL6ZRpa5fNYn0LCqn/KoWs8OHANWxhKDGhvQ==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-darwin-arm64@0.25.1': + resolution: {integrity: sha512-ywk18Qzbrr9blWxfP9NGvCMnpqV7hHdHP1GYqNEuImA3550mpTvnmQLPO1r3a2KffHsmuyQPBbf658JLoS57ww==} + engines: {node: '>= 22'} + cpu: [arm64] + os: [darwin] - '@nomicfoundation/edr-darwin-x64@0.12.0-next.23': - resolution: {integrity: sha512-9wn489FIQm7m0UCD+HhktjWx6vskZzeZD9oDc2k9ZvbBzdXwPp5tiDqUBJ+eQpByAzCDfteAJwRn2lQCE0U+Iw==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-darwin-x64@0.25.1': + resolution: {integrity: sha512-Wcl2P1U4+UiMKFomEM8ATZeUAIQswcMwrPN0E0fLBdSp2/k5y2l59Y1hqFPS/wwS7kfBpRvUPNBGh1hH6KKOLQ==} + engines: {node: '>= 22'} + cpu: [x64] + os: [darwin] - '@nomicfoundation/edr-linux-arm64-gnu@0.12.0-next.23': - resolution: {integrity: sha512-nlk5EejSzEUfEngv0Jkhqq3/wINIfF2ED9wAofc22w/V1DV99ASh9l3/e/MIHOQFecIZ9MDqt0Em9/oDyB1Uew==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-linux-arm64-gnu@0.25.1': + resolution: {integrity: sha512-oss7sbqksybp03RSZLsmv9GEKeA4+OwGdUxXoPsSewztRE66aPWjgMVEANtLpB7291WxWZHpmhQnSoCgO/us9w==} + engines: {node: '>= 22'} + cpu: [arm64] + os: [linux] - '@nomicfoundation/edr-linux-arm64-musl@0.12.0-next.23': - resolution: {integrity: sha512-SJuPBp3Rc6vM92UtVTUxZQ/QlLhLfwTftt2XUiYohmGKB3RjGzpgduEFMCA0LEnucUckU6UHrJNFHiDm77C4PQ==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-linux-arm64-musl@0.25.1': + resolution: {integrity: sha512-+6r+ykQfLXDCSEaomx56M97QLNxcKoKrWVliN3bpG11hw52ASngi6z31Z0/JBl5GHfsAtuUmVWk8KnUucXhFFw==} + engines: {node: '>= 22'} + cpu: [arm64] + os: [linux] - '@nomicfoundation/edr-linux-x64-gnu@0.12.0-next.23': - resolution: {integrity: sha512-NU+Qs3u7Qt6t3bJFdmmjd5CsvgI2bPPzO31KifM2Ez96/jsXYho5debtTQnimlb5NAqiHTSlxjh/F8ROcptmeQ==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-linux-x64-gnu@0.25.1': + resolution: {integrity: sha512-xo3yaYosl66AHs3VoQ+nTybaICiTf5x9TwTwuHkHYbsd6I9HWSp4bAk6JLTDQgV+l3VxQ54s1tElXmT6bUQX+Q==} + engines: {node: '>= 22'} + cpu: [x64] + os: [linux] - '@nomicfoundation/edr-linux-x64-musl@0.12.0-next.23': - resolution: {integrity: sha512-F78fZA2h6/ssiCSZOovlgIu0dUeI7ItKPsDDF3UUlIibef052GCXmliMinC90jVPbrjUADMd1BUwjfI0Z8OllQ==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-linux-x64-musl@0.25.1': + resolution: {integrity: sha512-gz/FHo8/t4qd2bH21aPh2JPvSwvgMQBQO+6AJ8SufamjyxsUlFxW8fM6lTfwNXYfYT8+82hYl1/HdvgxkutDkA==} + engines: {node: '>= 22'} + cpu: [x64] + os: [linux] - '@nomicfoundation/edr-win32-x64-msvc@0.12.0-next.23': - resolution: {integrity: sha512-IfJZQJn7d/YyqhmguBIGoCKjE9dKjbu6V6iNEPApfwf5JyyjHYyyfkLU4rf7hygj57bfH4sl1jtQ6r8HnT62lw==} - engines: {node: '>= 20'} + '@nomicfoundation/edr-win32-x64-msvc@0.25.1': + resolution: {integrity: sha512-VDVWK4GITq9Udzf7zGLJLw01YJoje3hLC9j8n+0fP4cVIEKYwVtY3/iyQ9zbUDD7p3Gz0cE9rtlYDlyIu5TFwA==} + engines: {node: '>= 22'} + cpu: [x64] + os: [win32] - '@nomicfoundation/edr@0.12.0-next.23': - resolution: {integrity: sha512-F2/6HZh8Q9RsgkOIkRrckldbhPjIZY7d4mT9LYuW68miwGQ5l7CkAgcz9fRRiurA0+YJhtsbx/EyrD9DmX9BOw==} - engines: {node: '>= 20'} + '@nomicfoundation/edr@0.25.1': + resolution: {integrity: sha512-yMCUTiEEdyuWN9na9RvKBD9du+C0fmnZUqVVQaJwATAY6qUyCZ3tkf4abnwEWt8s3oAfMx19HJiODmUnQgVjOQ==} + engines: {node: '>= 22'} '@nomicfoundation/solidity-analyzer-darwin-arm64@0.1.2': resolution: {integrity: sha512-JaqcWPDZENCvm++lFFGjrDd8mxtf+CtLd2MiXvMNTBD33dContTZ9TWETwNFwg7JTJT5Q9HEecH7FA+HTSsIUw==} @@ -10094,29 +10108,36 @@ snapshots: '@nolyfill/is-core-module@1.0.39': {} - '@nomicfoundation/edr-darwin-arm64@0.12.0-next.23': {} + '@nomicfoundation/edr-darwin-arm64@0.25.1': + optional: true - '@nomicfoundation/edr-darwin-x64@0.12.0-next.23': {} + '@nomicfoundation/edr-darwin-x64@0.25.1': + optional: true - '@nomicfoundation/edr-linux-arm64-gnu@0.12.0-next.23': {} + '@nomicfoundation/edr-linux-arm64-gnu@0.25.1': + optional: true - '@nomicfoundation/edr-linux-arm64-musl@0.12.0-next.23': {} + '@nomicfoundation/edr-linux-arm64-musl@0.25.1': + optional: true - '@nomicfoundation/edr-linux-x64-gnu@0.12.0-next.23': {} + '@nomicfoundation/edr-linux-x64-gnu@0.25.1': + optional: true - '@nomicfoundation/edr-linux-x64-musl@0.12.0-next.23': {} + '@nomicfoundation/edr-linux-x64-musl@0.25.1': + optional: true - '@nomicfoundation/edr-win32-x64-msvc@0.12.0-next.23': {} + '@nomicfoundation/edr-win32-x64-msvc@0.25.1': + optional: true - '@nomicfoundation/edr@0.12.0-next.23': - dependencies: - '@nomicfoundation/edr-darwin-arm64': 0.12.0-next.23 - '@nomicfoundation/edr-darwin-x64': 0.12.0-next.23 - '@nomicfoundation/edr-linux-arm64-gnu': 0.12.0-next.23 - '@nomicfoundation/edr-linux-arm64-musl': 0.12.0-next.23 - '@nomicfoundation/edr-linux-x64-gnu': 0.12.0-next.23 - '@nomicfoundation/edr-linux-x64-musl': 0.12.0-next.23 - '@nomicfoundation/edr-win32-x64-msvc': 0.12.0-next.23 + '@nomicfoundation/edr@0.25.1': + optionalDependencies: + '@nomicfoundation/edr-darwin-arm64': 0.25.1 + '@nomicfoundation/edr-darwin-x64': 0.25.1 + '@nomicfoundation/edr-linux-arm64-gnu': 0.25.1 + '@nomicfoundation/edr-linux-arm64-musl': 0.25.1 + '@nomicfoundation/edr-linux-x64-gnu': 0.25.1 + '@nomicfoundation/edr-linux-x64-musl': 0.25.1 + '@nomicfoundation/edr-win32-x64-msvc': 0.25.1 '@nomicfoundation/solidity-analyzer-darwin-arm64@0.1.2': optional: true