Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/example-project/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@
# Hardhat files
/artifacts
/cache
/ignition

# Deployment state is regenerated per run; the modules themselves are source
/ignition/deployments
32 changes: 32 additions & 0 deletions packages/example-project/contracts/mocks/TestToken.sol
Original file line number Diff line number Diff line change
@@ -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;
}
}
13 changes: 13 additions & 0 deletions packages/example-project/ignition/modules/Counter.ts
Original file line number Diff line number Diff line change
@@ -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 };
});
2 changes: 1 addition & 1 deletion packages/plugin/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
23 changes: 8 additions & 15 deletions packages/plugin/src/artifacts.ts
Original file line number Diff line number Diff line change
@@ -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[];
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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
Expand Down
34 changes: 14 additions & 20 deletions packages/plugin/src/deployment-tracker.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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;
}

Expand Down
108 changes: 108 additions & 0 deletions packages/plugin/src/source-resolver.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>;
input?: {
sources?: Record<string, { content?: string }>;
};
}

/**
* 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<string>();

/**
* 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;
}
Loading