Skip to content
Draft
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
6 changes: 6 additions & 0 deletions .github/actions/setup/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ runs:
if: inputs.node != 'off' && steps.cache.outputs.cache-hit != 'true' && steps.cache-restore.outputs.cache-hit != 'true'
shell: bash
run: npm ci
# The cache only holds node_modules: local packages (built by `npm ci` through their `prepare` script) must be
# rebuilt when it is restored.
- name: Build local packages
if: inputs.node != 'off' && (steps.cache.outputs.cache-hit == 'true' || steps.cache-restore.outputs.cache-hit == 'true')
shell: bash
run: npm run plugins:prepare
# Foundry setup
- name: Install Foundry (${{ steps.versions.outputs.foundry }})
if: inputs.foundry != 'off'
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ permissions:

env:
NODE_OPTIONS: --max_old_space_size=8192
# npm replaces NODE_OPTIONS with its `node-options` setting (see .npmrc), so it must repeat them.
npm_config_node_options: --conditions=source --max_old_space_size=8192

jobs:
lint:
Expand Down
42 changes: 42 additions & 0 deletions .github/workflows/plugins.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: plugins

on:
push:
branches:
- master
- next-v*
- release-v*
paths:
- 'hardhat/**'
- 'package.json'
- 'package-lock.json'
- '.github/actions/setup/action.yml'
- '.github/workflows/plugins.yml'
pull_request:
paths:
- 'hardhat/**'
- 'package.json'
- 'package-lock.json'
- '.github/actions/setup/action.yml'
- '.github/workflows/plugins.yml'
workflow_dispatch: {}

concurrency:
group: plugins-${{ github.ref }}
cancel-in-progress: true

permissions:
contents: read

jobs:
tests:
runs-on: ubuntu-latest
env:
FORCE_COLOR: 1
steps:
- uses: actions/checkout@v7
# Builds (and type-checks) the plugins, either through `npm ci` or `npm run plugins:prepare` on a cache hit.
- name: Set up environment
uses: ./.github/actions/setup
- name: Run plugin tests
run: npm run plugins:test
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ coverageEnv
# Dependency directory
node_modules

# Build output of the local hardhat plugins
hardhat/*/dist

# Debug log from npm
npm-debug.log

Expand Down
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Resolve the local hardhat plugins (hardhat/*) to their TypeScript sources rather than their build output.
node-options=--conditions=source
2 changes: 1 addition & 1 deletion docs/config.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path';
import fs from 'fs';

/** @type import('../hardhat/hardhat-solidity-docgen/internal/config.ts').UserConfig */
/** @type import('../hardhat/hardhat-solidity-docgen/src/internal/config.ts').UserConfig */
export default {
outputDir: 'docs/modules/api/pages',
templates: 'docs/templates',
Expand Down
8 changes: 4 additions & 4 deletions hardhat.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import hardhatIgnoreWarnings from 'hardhat-ignore-warnings';
import hardhatMocha from '@nomicfoundation/hardhat-mocha';
import hardhatNetworkHelpers from '@nomicfoundation/hardhat-network-helpers';
import hardhatPredeploy from 'hardhat-predeploy';
import hardhatDocgen from './hardhat/hardhat-solidity-docgen/plugin.ts';
import hardhatExposed from './hardhat/hardhat-exposed/plugin.ts';
import hardhatTranspiler from './hardhat/hardhat-transpiler/plugin.ts';
import hardhatOzContractsHelpers from './hardhat/hardhat-oz-contracts-helpers/plugin.ts';
import hardhatDocgen from 'hardhat-solidity-docgen';
import hardhatExposed from 'hardhat-exposed';
import hardhatTranspiler from 'hardhat-transpiler';
import hardhatOzContractsHelpers from 'hardhat-oz-contracts-helpers';
import './hardhat/async-test-sanity.ts';

// Parameters
Expand Down
2 changes: 2 additions & 0 deletions hardhat/hardhat-exposed/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
node_modules/
50 changes: 50 additions & 0 deletions hardhat/hardhat-exposed/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "hardhat-exposed",
"version": "0.4.0",
"description": "Automatically expose internal functions for smart contract testing",
"license": "MIT",
"author": "OpenZeppelin Community <maintainers@openzeppelin.org>",
"repository": {
"type": "git",
"url": "git+https://github.com/OpenZeppelin/openzeppelin-contracts.git",
"directory": "hardhat/hardhat-exposed"
},
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"source": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"files": [
"/dist",
"/src"
],
"scripts": {
"clean": "rimraf dist",
"prepare": "npm run clean && tsc",
"test": "mocha --node-option experimental-transform-types --timeout 60000 'test/**/*.test.js'"
},
"dependencies": {
"@nomicfoundation/hardhat-utils": "^4.3.0",
"solidity-ast": "^0.4.61"
},
"devDependencies": {
"@types/node": "^25.9.4",
"chai": "^5.3.3",
"hardhat": "^3.9.1",
"mocha": "^12.0.2",
"rimraf": "^6.1.2",
"typescript": "^7.0.2"
},
"peerDependencies": {
"hardhat": "^3.9.1"
},
"engines": {
"node": ">=22.18.0"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function getExposed(
);

for (const [sourceName, inputSourceName] of Object.entries(solidityBuildInfo.userSourceNameMap)) {
const ast = solcOutput.sources[inputSourceName].ast;
const ast = solcOutput.sources[inputSourceName]!.ast;

const exposedFile = getExposedFile(sourceName, inputSourceName, ast, deref, config, applicableRemappings);
if (exposedFile !== undefined) {
Expand All @@ -59,7 +59,7 @@ export function getExposed(
deref,
projectSourcePrefixes,
)) {
const ast = solcOutput.sources[inputSourceName].ast;
const ast = solcOutput.sources[inputSourceName]!.ast;

// sourceName is a fallback path for vendored `project/` deps not covered by a remapping.
const exposedFile = getExposedFile(
Expand Down Expand Up @@ -95,7 +95,7 @@ function getImportedContracts(
const res = new Map<string, Set<ContractDefinition>>();

for (const inputSourceName of userInputSourceNames) {
const queue = new Set(findAll('ImportDirective', solcOutput.sources[inputSourceName].ast));
const queue = new Set(findAll('ImportDirective', solcOutput.sources[inputSourceName]!.ast));

for (const imp of queue) {
if (isCoveredByUserSources(imp.absolutePath)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ export interface BuildOverrideArguments {
}

export default async function build(
args: BuildOverrideArguments,
taskArguments: TaskArguments,
hre: HardhatRuntimeEnvironment,
runSuper: (taskArguments: TaskArguments) => Promise<any>,
) {
// The arguments of the built-in `build` task are not part of the override's declared type.
const args = taskArguments as BuildOverrideArguments;

if (!args.noExpose) {
await hre.tasks.getTask('generate-exposed-contracts').run({ force: 'force' in args ? args.force : false });

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { expect } from 'chai';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import hardhatExposed from '../plugin.ts';
import hardhatExposed from '../src/index.ts';

const contract = name => `// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
Expand Down
182 changes: 182 additions & 0 deletions hardhat/hardhat-exposed/test/manifest.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { expect } from 'chai';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import { ExposedManifest } from '../src/internal/manifest.ts';

// Unit tests for the stale-exposed-file bookkeeping. The manifest is pure fs/path, so everything runs against a
// throwaway temp directory: `rootDir` stands in for the project root, `outDir` for `contracts-exposed`.
describe('hardhat-exposed: manifest', function () {
let rootDir;
let outDir;

// Absolute path of a (pretend) root source and of its exposed file, mirroring the real layout.
const root = p => path.join(rootDir, p);
const exposed = p => path.join(outDir, p);
// Create an exposed file on disk so prune has something real to delete.
const write = abs => {
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, '// exposed\n');
};
const exists = abs => fs.existsSync(abs);

beforeEach(function () {
rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'oz-exposed-'));
outDir = path.join(rootDir, 'contracts-exposed');
});

afterEach(function () {
fs.rmSync(rootDir, { recursive: true, force: true });
});

describe('load', function () {
it('returns undefined when the manifest is missing', function () {
expect(ExposedManifest.load(rootDir, outDir)).to.equal(undefined);
});

it('returns undefined when the manifest is malformed', function () {
for (const bad of ['[]', '42', 'not json', '{"a.sol": 123}', '{"a.sol": [1]}']) {
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, 'manifest.json'), bad);
expect(ExposedManifest.load(rootDir, outDir), bad).to.equal(undefined);
}
});

it('round-trips a persisted manifest', function () {
const rootA = root('contracts/A.sol');
const exposedA = exposed('contracts/A.sol');
write(exposedA);

const m = ExposedManifest.empty(rootDir, outDir);
m.setGenerated([rootA], new Map([[exposedA, [rootA]]]));
m.prune([rootA]); // persists manifest.json

// Reloaded manifest knows about the file: de-exposing the root deletes it.
const reloaded = ExposedManifest.load(rootDir, outDir);
expect(reloaded).to.not.equal(undefined);
reloaded.prune([]);
expect(exists(exposedA)).to.equal(false);
});
});

describe('prune', function () {
it("deletes a root's own exposed file once the root is no longer exposed", function () {
const rootA = root('contracts/A.sol');
const exposedA = exposed('contracts/A.sol');
write(exposedA);

const m = ExposedManifest.empty(rootDir, outDir);
m.setGenerated([rootA], new Map([[exposedA, [rootA]]]));

m.prune([rootA]); // still exposed
expect(exists(exposedA)).to.equal(true);

m.prune([]); // de-exposed / removed
expect(exists(exposedA)).to.equal(false);
});

it('keeps a shared file while any owner survives, deletes it once all are gone', function () {
const rootA = root('contracts/A.sol');
const rootB = root('contracts/B.sol');
const exposedA = exposed('contracts/A.sol');
const exposedB = exposed('contracts/B.sol');
const exposedShared = exposed('contracts/Shared.sol');
[exposedA, exposedB, exposedShared].forEach(write);

const m = ExposedManifest.empty(rootDir, outDir);
m.setGenerated(
[rootA, rootB],
new Map([
[exposedA, [rootA]],
[exposedB, [rootB]],
[exposedShared, [rootA, rootB]], // attributed to all roots of the job
]),
);

m.prune([rootA, rootB]);
[exposedA, exposedB, exposedShared].forEach(f => expect(exists(f), f).to.equal(true));

m.prune([rootA]); // B gone
expect(exists(exposedB)).to.equal(false);
expect(exists(exposedShared)).to.equal(true); // A still owns it
expect(exists(exposedA)).to.equal(true);

m.prune([]); // A gone too
expect(exists(exposedShared)).to.equal(false);
expect(exists(exposedA)).to.equal(false);
});

it('removes directories left empty, but never the output directory itself', function () {
const rootERC20 = root('contracts/token/ERC20.sol');
const exposedERC20 = exposed('contracts/token/ERC20.sol');
write(exposedERC20);

const m = ExposedManifest.empty(rootDir, outDir);
m.setGenerated([rootERC20], new Map([[exposedERC20, [rootERC20]]]));
m.prune([]);

expect(exists(exposedERC20)).to.equal(false);
expect(exists(exposed('contracts/token'))).to.equal(false); // emptied dirs pruned
expect(exists(exposed('contracts'))).to.equal(false);
expect(exists(outDir)).to.equal(true); // kept (holds manifest.json)
});

it('never deletes a tracked file outside the output directory', function () {
const rootReal = root('contracts/Real.sol');
const outsideFile = root('contracts/Real.sol'); // a real source, not under outDir
write(outsideFile);

const m = ExposedManifest.empty(rootDir, outDir);
m.setGenerated([rootReal], new Map([[outsideFile, [rootReal]]]));
m.prune([]); // would delete, but the guard refuses paths outside outDir

expect(exists(outsideFile)).to.equal(true);
});
});

describe('setGenerated', function () {
it('drops a shared file a regenerated root no longer produces', function () {
const rootA = root('contracts/A.sol');
const exposedA = exposed('contracts/A.sol');
const exposedShared = exposed('contracts/Shared.sol');
[exposedA, exposedShared].forEach(write);

const m = ExposedManifest.empty(rootDir, outDir);
// Run 1: A imports Shared -> owns both.
m.setGenerated(
[rootA],
new Map([
[exposedA, [rootA]],
[exposedShared, [rootA]],
]),
);
m.prune([rootA]);
expect(exists(exposedShared)).to.equal(true);

// Run 2: A no longer imports Shared -> only produces its own wrapper.
m.setGenerated([rootA], new Map([[exposedA, [rootA]]]));
m.prune([rootA]);

expect(exists(exposedShared)).to.equal(false); // released by A, now orphaned
expect(exists(exposedA)).to.equal(true);
});
});

describe('hasMissingFiles', function () {
it('is false when all tracked files exist, true once one is deleted', function () {
const rootA = root('contracts/A.sol');
const exposedA = exposed('contracts/A.sol');
write(exposedA);

const m = ExposedManifest.empty(rootDir, outDir);
m.setGenerated([rootA], new Map([[exposedA, [rootA]]]));
m.prune([rootA]);

expect(m.hasMissingFiles()).to.equal(false);

fs.rmSync(exposedA); // someone cleaned part of the output dir
expect(m.hasMissingFiles()).to.equal(true);
});
});
});
Loading
Loading