diff --git a/packages/example-project/.gitignore b/packages/example-project/.gitignore index 1c04d50..bf54d03 100644 --- a/packages/example-project/.gitignore +++ b/packages/example-project/.gitignore @@ -10,4 +10,6 @@ # Hardhat files /artifacts /cache -/ignition \ No newline at end of file + +# Deployment state is regenerated per run; the modules themselves are source +/ignition/deployments diff --git a/packages/example-project/contracts/Counter.sol b/packages/example-project/contracts/core/Counter.sol similarity index 100% rename from packages/example-project/contracts/Counter.sol rename to packages/example-project/contracts/core/Counter.sol diff --git a/packages/example-project/contracts/Counter.t.sol b/packages/example-project/contracts/core/Counter.t.sol similarity index 100% rename from packages/example-project/contracts/Counter.t.sol rename to packages/example-project/contracts/core/Counter.t.sol diff --git a/packages/example-project/contracts/mocks/TestToken.sol b/packages/example-project/contracts/mocks/TestToken.sol new file mode 100644 index 0000000..831429b --- /dev/null +++ b/packages/example-project/contracts/mocks/TestToken.sol @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; + +/// @dev Lives in a second subdirectory so the explorer's source view is +/// exercised against more than one nested path. +contract TestToken { + string public name = "Test Token"; + string public symbol = "TEST"; + uint8 public constant decimals = 18; + + uint public totalSupply; + mapping(address => uint) public balanceOf; + + event Transfer(address indexed from, address indexed to, uint value); + + constructor(uint initialSupply) { + totalSupply = initialSupply; + balanceOf[msg.sender] = initialSupply; + emit Transfer(address(0), msg.sender, initialSupply); + } + + function transfer(address to, uint value) public returns (bool) { + require(to != address(0), "transfer: zero address"); + require(balanceOf[msg.sender] >= value, "transfer: insufficient balance"); + + balanceOf[msg.sender] -= value; + balanceOf[to] += value; + + emit Transfer(msg.sender, to, value); + return true; + } +} diff --git a/packages/example-project/ignition/modules/Counter.ts b/packages/example-project/ignition/modules/Counter.ts new file mode 100644 index 0000000..e5865c7 --- /dev/null +++ b/packages/example-project/ignition/modules/Counter.ts @@ -0,0 +1,13 @@ +import { buildModule } from "@nomicfoundation/hardhat-ignition/modules"; + +export default buildModule("CounterModule", (m) => { + const counter = m.contract("Counter"); + + m.call(counter, "incBy", [5n]); + + // Deployed from contracts/mocks/ so the explorer is exercised against + // contracts sitting in more than one subdirectory. + const testToken = m.contract("TestToken", [1_000_000n * 10n ** 18n]); + + return { counter, testToken }; +}); diff --git a/packages/plugin/package.json b/packages/plugin/package.json index e2a19fc..f4d704a 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openscan/hardhat-plugin", - "version": "1.3.0", + "version": "1.3.1", "description": "Hardhat 3 plugin to use openscan explorer", "license": "MIT", "type": "module", diff --git a/packages/plugin/src/artifacts.ts b/packages/plugin/src/artifacts.ts index f12ab73..5b8539a 100644 --- a/packages/plugin/src/artifacts.ts +++ b/packages/plugin/src/artifacts.ts @@ -1,5 +1,6 @@ import { existsSync, readdirSync, readFileSync } from "node:fs"; import path from "node:path"; +import { resolveSourceCode } from "./source-resolver.js"; export interface ArtifactData { abi: unknown[]; @@ -83,9 +84,6 @@ export function loadArtifacts( // Build-info directory const buildInfoDir = path.join(deploymentPath, "build-info"); - // Contracts source directory - const contractsDir = path.join(projectRoot, "contracts"); - for (const artifactFile of artifactFiles) { const artifactPath = path.join(artifactsDir, artifactFile); @@ -131,18 +129,13 @@ export function loadArtifacts( } // Try to load source code - if (artifactData.sourceName && existsSync(contractsDir)) { - const sourceFileName = artifactData.sourceName.split("/").pop(); - if (sourceFileName) { - const sourcePath = path.join(contractsDir, sourceFileName); - if (existsSync(sourcePath)) { - try { - artifactData.sourceCode = readFileSync(sourcePath, "utf-8"); - } catch { - // Ignore source code errors - } - } - } + if (artifactData.sourceName) { + artifactData.sourceCode = resolveSourceCode({ + projectRoot, + sourceName: artifactData.sourceName, + inputSourceName: artifact.inputSourceName as string | undefined, + buildInfo: artifactData.buildInfo, + }); } // Store by lowercase address diff --git a/packages/plugin/src/deployment-tracker.ts b/packages/plugin/src/deployment-tracker.ts index 2cfa87f..66ceeed 100644 --- a/packages/plugin/src/deployment-tracker.ts +++ b/packages/plugin/src/deployment-tracker.ts @@ -1,10 +1,12 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; import path from "node:path"; import type { ArtifactData, AddressMap } from "./artifacts.js"; +import { resolveSourceCode } from "./source-resolver.js"; interface CompiledArtifact { contractName: string; sourceName: string; + inputSourceName?: string; abi: unknown[]; bytecode: string; buildInfoId?: string; @@ -51,6 +53,7 @@ export class DeploymentTracker { this.compiledArtifacts.push({ contractName: content.contractName as string, sourceName: (content.sourceName as string) ?? "", + inputSourceName: content.inputSourceName as string | undefined, abi: content.abi as unknown[], bytecode: content.bytecode as string, buildInfoId: content.buildInfoId as string | undefined, @@ -92,26 +95,7 @@ export class DeploymentTracker { deployments: [contractAddress], }; - // Try to load source code - if (artifact.sourceName) { - const sourceFileName = artifact.sourceName.split("/").pop(); - if (sourceFileName) { - const sourcePath = path.join( - this.projectRoot, - "contracts", - sourceFileName, - ); - if (existsSync(sourcePath)) { - try { - entry.sourceCode = readFileSync(sourcePath, "utf-8"); - } catch { - // ignore - } - } - } - } - - // Try to load build info + // Try to load build info (before source, which falls back to it) if (artifact.buildInfoId) { const buildInfoPath = path.join( this.projectRoot, @@ -128,6 +112,16 @@ export class DeploymentTracker { } } + // Try to load source code + if (artifact.sourceName) { + entry.sourceCode = resolveSourceCode({ + projectRoot: this.projectRoot, + sourceName: artifact.sourceName, + inputSourceName: artifact.inputSourceName, + buildInfo: entry.buildInfo, + }); + } + this.trackedDeployments[contractAddress.toLowerCase()] = entry; } diff --git a/packages/plugin/src/source-resolver.ts b/packages/plugin/src/source-resolver.ts new file mode 100644 index 0000000..698f729 --- /dev/null +++ b/packages/plugin/src/source-resolver.ts @@ -0,0 +1,108 @@ +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +/** + * The parts of a solc build info file we need to recover source text. + * + * Hardhat 3 writes source names into the standard JSON input under a + * "project/" (or "npm/") prefix, and records the mapping from the artifact's + * `sourceName` to that key in `userSourceNameMap`. + */ +interface SolcBuildInfo { + userSourceNameMap?: Record; + input?: { + sources?: Record; + }; +} + +/** + * Source names already warned about, so a missing source is reported once per + * process rather than on every request. The artifact loader re-reads the + * deployment on each page load, so an ungated warning would repeat endlessly. + */ +const warnedSourceNames = new Set(); + +/** + * Read source text out of a build info file's standard JSON input. + * + * @param sourceName - Project-relative source name from the artifact + * @param inputSourceName - Prefixed source name from the artifact, when present + * @param buildInfo - Parsed build info, shape unverified + * @returns Source text, or undefined if the input has no entry for it + */ +function readSourceFromBuildInfo( + sourceName: string, + inputSourceName: string | undefined, + buildInfo: unknown, +): string | undefined { + if (typeof buildInfo !== "object" || buildInfo === null) return undefined; + + const { userSourceNameMap, input } = buildInfo as SolcBuildInfo; + const sources = input?.sources; + if (!sources) return undefined; + + // Hardhat 3 artifacts carry the input source name directly; older build info + // keys its sources by the plain source name. + const candidates = [ + inputSourceName, + userSourceNameMap?.[sourceName], + sourceName, + ]; + + for (const candidate of candidates) { + if (!candidate) continue; + const content = sources[candidate]?.content; + if (typeof content === "string") return content; + } + + return undefined; +} + +/** + * Resolve a contract's Solidity source. + * + * `sourceName` is relative to the project root, so it is joined as-is - this + * works for contracts nested in subdirectories and for contracts compiled from + * outside `contracts/`. When the file is not on disk (moved or deleted since + * compilation, or an npm dependency rather than a project file), the source + * text is recovered from the build info that ships alongside the artifact. + * + * @param opts.projectRoot - Absolute path to the Hardhat project root + * @param opts.sourceName - Project-relative source name from the artifact + * @param opts.inputSourceName - Prefixed source name from the artifact, when present + * @param opts.buildInfo - Parsed build info for the artifact, when available + * @returns Source text, or undefined if it could not be resolved + */ +export function resolveSourceCode(opts: { + projectRoot: string; + sourceName: string; + inputSourceName?: string; + buildInfo?: unknown; +}): string | undefined { + const { projectRoot, sourceName, inputSourceName, buildInfo } = opts; + + const sourcePath = path.join(projectRoot, sourceName); + if (existsSync(sourcePath)) { + try { + return readFileSync(sourcePath, "utf-8"); + } catch { + // Fall through to build info + } + } + + const fromBuildInfo = readSourceFromBuildInfo( + sourceName, + inputSourceName, + buildInfo, + ); + if (fromBuildInfo !== undefined) return fromBuildInfo; + + if (!warnedSourceNames.has(sourceName)) { + warnedSourceNames.add(sourceName); + console.warn( + `[openscan] Source not found for ${sourceName} (looked in ${sourcePath} and build info)`, + ); + } + + return undefined; +}