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 d299f5c6853..af91d98d1a6 100644 --- a/packages/hardhat-core/src/internal/hardhat-network/provider/provider.ts +++ b/packages/hardhat-core/src/internal/hardhat-network/provider/provider.ts @@ -67,7 +67,6 @@ import { MempoolOrder, } from "./node-types"; import { - edrRpcDebugTraceToHardhat, edrTracingMessageResultToMinimalEVMResult, edrTracingMessageToMinimalMessage, edrTracingStepToMinimalInterpreterStep, @@ -157,11 +156,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(); } @@ -200,9 +202,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,13 +220,13 @@ 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(); @@ -230,7 +238,7 @@ export class EdrProviderWrapper const edrHardfork = ethereumsjsHardforkToEdrSpecId(hardforkName); const [genesisState, ownedAccounts] = _genesisStateAndOwnedAccounts( - fork !== undefined, + config.forkConfig !== undefined, edrHardfork, config.genesisAccounts ); @@ -247,14 +255,12 @@ export class EdrProviderWrapper allowUnlimitedContractSize: config.allowUnlimitedContractSize, bailOnCallFailure: config.throwOnCallFailures, bailOnTransactionFailure: config.throwOnTransactionFailures, - blockGasLimit: BigInt(config.blockGasLimit), chainId: BigInt(config.chainId), coinbase: Buffer.from(coinbase.slice(2), "hex"), + defaultTransactionGasLimit: BigInt(config.blockGasLimit), precompileOverrides, - fork, genesisState, hardfork: edrHardfork, - initialDate, initialBaseFeePerGas: config.initialBaseFeePerGas !== undefined ? BigInt(config.initialBaseFeePerGas!) @@ -262,11 +268,13 @@ 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: {}, ownedAccounts, @@ -332,7 +340,9 @@ export class EdrProviderWrapper edrSubscriptionConfig, config.genesisAccounts, cacheDir, - chainOverrides + chainOverrides, + genesisBlockGasLimit, + genesisBlockTime ); // Pass through all events from the provider @@ -392,11 +402,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"); @@ -413,7 +420,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", @@ -442,20 +449,37 @@ 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); - } - - if (stackTrace !== null) { - error = encodeSolidityStackTrace(response.error.message, stackTrace); + const stackTrace = responseObject.stackTrace(); + + if (stackTrace?.kind === "StackTrace") { + error = encodeSolidityStackTrace( + response.error.message, + // EDR's `SolidityStackTraceEntry` union includes + // `CheatcodeErrorStackTraceEntry`, which Hardhat's local copy + // doesn't know about. Cheatcodes only fire from solidity-test + // runs, never from the network-provider path; the cast is safe + // at runtime. + 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 { @@ -479,11 +503,6 @@ 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 { return response.result; } @@ -519,18 +538,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) @@ -541,7 +561,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(); 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..c6be433f86f 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 @@ -174,113 +174,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; } 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 0ec5f3a4b3c..fde07acfd13 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 { @@ -161,7 +161,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")!;