Skip to content
Merged
2 changes: 1 addition & 1 deletion .github/actions/gas-compare/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ runs:
gh pr diff '${{ github.event.number }}' --repo '${{ github.repository }}' --name-only > changed.txt
# Produce small report if the diff touches any contracts, otherwise fall back to full report
if [ -s changed.txt ]; then
node scripts/list-dependencies.js --src=contracts,contracts-exposed --ext=.sol < changed.txt > diff.json
node scripts/list-dependencies.js --root=. --src=contracts,contracts-exposed --ext=.sol < changed.txt > diff.json
filter=(--filtered diff.json)
else
filter=()
Expand Down
8 changes: 4 additions & 4 deletions .github/actions/setup/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ inputs:
runs:
using: composite
steps:
- name: "Determine versions to install"
- name: 'Determine versions to install'
id: versions
shell: bash
run: |
Expand All @@ -44,9 +44,9 @@ runs:
|| echo "python=${{ inputs.python }}"
) > $GITHUB_OUTPUT
env:
NODE_DEFAULT_VERSION: "24.x"
FOUNDRY_DEFAULT_VERSION: "stable"
PYTHON_DEFAULT_VERSION: "3.13"
NODE_DEFAULT_VERSION: '24.x'
FOUNDRY_DEFAULT_VERSION: 'stable'
PYTHON_DEFAULT_VERSION: '3.13'
# Node & npm setup
- name: Install Node (${{ steps.versions.outputs.node }})
if: inputs.node != 'off'
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ jobs:
uses: ./.github/actions/setup
- run: bash scripts/git-user-config.sh
- run: node scripts/update-docs-branch.js
- run: git push --all origin
- run: git push --all origin
8 changes: 7 additions & 1 deletion docs/templates/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,13 @@ function getAllLinks(items) {

export const withPrelude = opts => {
const links = getAllLinks(opts.data.site.items);
const contents = opts.fn();
// Index entries are rendered as `{xref-<anchor>}[<text>]`, which requires the attribute to be
// defined in the prelude below. Only items documented in this component have one: members
// inherited from another component (@openzeppelin/contracts) have no page here, and asciidoctor
// would drop the reference. Strip the xref from those and keep the plain link text.
const contents = opts
.fn()
.replace(/^(\* )\{(xref-[^}]+)\}\[(.*)\]$/gm, (entry, bullet, key, text) => (key in links ? entry : bullet + text));
const neededLinks = contents
.match(/\{[-._a-z0-9]+\}/gi)
.map(m => m.replace(/^\{(.+)\}$/, '$1'))
Expand Down
29 changes: 21 additions & 8 deletions hardhat/hardhat-transpiler/tasks/transpile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { HardhatRuntimeEnvironment } from 'hardhat/types/hre';
import { transpile } from '@openzeppelin/upgrade-safe-transpiler/dist/index.js';
import { findAlreadyInitializable } from '@openzeppelin/upgrade-safe-transpiler/dist/find-already-initializable.js';

interface TranspileOptions {
import { prepareDependencies } from './with-dependencies.ts';

export interface TranspileOptions {
initializablePath?: string;
deleteOriginals?: boolean;
skipWithInit?: boolean;
Expand All @@ -15,6 +17,8 @@ interface TranspileOptions {
namespaced?: boolean;
namespaceExclude?: string[];
peerProject?: string;
// Transpile a project that builds on contracts it does not own. See `./with-dependencies.ts`.
upgradeablePackages?: Record<string, string>;
}

// Transform each key of `obj` with `fn`, keeping values intact.
Expand All @@ -30,6 +34,10 @@ function filterRecord<U>(obj: Record<string, U>, fn: (key: string, value: U) =>
export default async function ({ settings }: { settings?: string }, hre: HardhatRuntimeEnvironment) {
assert(settings, 'Transpile settings file must be provided');
const options: TranspileOptions = await fs.readFile(settings, 'utf-8').then(JSON.parse);
assert(
options.upgradeablePackages === undefined || options.peerProject !== undefined,
'Transpiling dependencies requires a peer project',
);

const { contractRootPaths } = await hre.tasks.getTask('build').run({ noTests: true, noExpose: true });
const compilationJobs = await hre.solidity.getCompilationJobs(contractRootPaths);
Expand All @@ -56,31 +64,34 @@ export default async function ({ settings }: { settings?: string }, hre: Hardhat

const mainSources = hre.config.paths.sources.solidity.at(0)!;
const mainSourcesRel = path.relative(hre.config.paths.root, mainSources);
const withDependencies = options.upgradeablePackages !== undefined;

// Adjust paths to match transpiler expectations
// Adjust paths to match transpiler expectations. Dependency sources are kept when transpiling with dependencies.
input.sources = filterRecord(
transformKeys(input.sources, k => k.replace(/^project\//, '')),
k => k.startsWith(mainSourcesRel + '/'),
k => withDependencies || k.startsWith(mainSourcesRel + '/'),
);
output.sources = filterRecord(
transformKeys(output.sources, k => k.replace(/^project\//, '')),
k => k.startsWith(mainSourcesRel + '/'),
k => withDependencies || k.startsWith(mainSourcesRel + '/'),
);
output.contracts = filterRecord(
transformKeys(output.contracts, k => k.replace(/^project\//, '')),
k => k.startsWith(mainSourcesRel + '/'),
k => withDependencies || k.startsWith(mainSourcesRel + '/'),
);
Object.values(output.sources).forEach((s: any) => {
s.ast.absolutePath = s.ast.absolutePath.replace(/^project\//, '');
});

const deps = withDependencies ? prepareDependencies(input, output, options, mainSourcesRel) : undefined;

// Run transpilation on the first source folder
const transpiled = await transpile(
input,
output,
{ root: hre.config.paths.root, sources: mainSources },
{ ...options, solcVersion },
);
{ ...options, ...deps?.optionsOverride, solcVersion },
).then(files => deps?.postProcess(files) ?? files);

// Write transpiled files to disk
await Promise.all(
Expand All @@ -93,7 +104,8 @@ export default async function ({ settings }: { settings?: string }, hre: Hardhat

// Delete originals files
if (options.deleteOriginals) {
const alreadyInitializable = findAlreadyInitializable(output, options.initializablePath);
const alreadyInitializable =
deps?.alreadyInitializable ?? findAlreadyInitializable(output, options.initializablePath);

// keep all newly transpiled files, plus any already-initializable files (even if not transpiled, to avoid deleting them)
([] as string[])
Expand All @@ -110,6 +122,7 @@ export default async function ({ settings }: { settings?: string }, hre: Hardhat
}

Object.keys(output.sources)
.filter(k => k.startsWith(mainSourcesRel + '/'))
.map(s => path.join(hre.config.paths.root, s.replace(/^project\//, '')))
.forEach(p => seen.add(p));

Expand Down
152 changes: 152 additions & 0 deletions hardhat/hardhat-transpiler/tasks/with-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import assert from 'node:assert';
import path from 'node:path';

import { findAlreadyInitializable } from '@openzeppelin/upgrade-safe-transpiler/dist/find-already-initializable.js';
import type { OutputFile } from '@openzeppelin/upgrade-safe-transpiler/dist/index.js';

import type { TranspileOptions } from './transpile.ts';

/**
* Transpiling a project that builds on contracts it does not own.
*
* Enabled by the `upgradeablePackages` option, which maps the import prefixes of the dependencies whose stateful
* contracts have an upgradeable variant in another package (e.g. `{ "@openzeppelin/contracts/":
* "@openzeppelin/contracts-upgradeable/" }`).
*
* Dependency sources are kept in the transpilation so that their symbols can be resolved, but their transpiled output
* is discarded. Imports in the transpiled files are rewritten so that stateful contracts are imported from the
* upgradeable package, and stateless declarations (interfaces, libraries, ...) from their original location. In this
* mode, `peerProject` is required and is prepended to the source name of local files (e.g. `@openzeppelin/community-`
* for `contracts/` to be imported from `@openzeppelin/community-contracts/`), and `initializablePath` is an import
* path (e.g. `@openzeppelin/contracts/proxy/utils/Initializable.sol`).
*/

// Remove the `project/` prefix that Hardhat 3 adds to the source names of local files.
const stripProject = (sourceName: string) => sourceName.replace(/^project\//, '');

// Find the entry of `mapping` whose key is the longest prefix of `str`, and replace that prefix with the value.
function replacePrefix(str: string, mapping: [string, string][]): string {
const match = mapping.toSorted(([a], [b]) => b.length - a.length).find(([from]) => str.startsWith(from));
return match ? match[1] + str.slice(match[0].length) : str;
}

// Placeholder for the peer project. It lets imports from the peer project be identified and resolved once the
// transpilation is done.
const PEER_PLACEHOLDER = '__peer__';

/**
* Adjusts the compiler output in place, and returns what the task must apply around the transpilation: the contracts
* that already inherit from `Initializable`, the transpiler options to override, and the post-processing of the
* transpiled files.
*/
export function prepareDependencies(input: any, output: any, options: TranspileOptions, mainSourcesRel: string) {
const isLocal = (file: string) => file.startsWith(mainSourcesRel + '/');

// Import paths are resolved to source names (and back) using the remappings of the project's root.
const remappings: [string, string][] = (input.settings.remappings ?? [])
.map((r: string) => r.match(/^([^:]*):([^=]*)=(.*)$/)!)
.filter(([, context]: string[]) => context === 'project/')
Comment on lines +47 to +48
.map(([, , prefix, target]: string[]) => [prefix, stripProject(target)]);

const toSourceName = (importPath: string) => replacePrefix(importPath, remappings);
const toImportPath = (sourceName: string) =>
replacePrefix(
sourceName,
remappings.map(([prefix, target]) => [target, prefix]),
);

// Unlike the source units, the import directives refer to source names that still include the `project/` prefix.
// Transpiling with a peer project also requires every import to list its symbols. Dependencies are only transpiled
// for their symbols to be resolved, and their output is discarded, so their unaliased imports are expanded to every
// exported symbol.
for (const { ast } of Object.values(output.sources) as any[]) {
for (const node of ast.nodes) {
if (node.nodeType !== 'ImportDirective') continue;
node.absolutePath = stripProject(node.absolutePath);
if (!isLocal(ast.absolutePath) && node.symbolAliases.length === 0 && node.unitAlias === '') {
const { exportedSymbols } = output.sources[stripProject(node.absolutePath)].ast;
node.symbolAliases = Object.keys(exportedSymbols).map(name => ({ foreign: { name }, local: null }));
}
}
}

// Contracts that already inherit from `Initializable` are left untouched. The transpiler would exclude them from the
// transformation, but dependencies must stay included for their symbols to be resolved. Instead, only local files
// are excluded, and `initializablePath` is not given to the transpiler. The transpiler then imports `Initializable`
// from its default location in the peer project, which is redirected to `initializablePath`.
const alreadyInitializable: string[] = findAlreadyInitializable(
output,
options.initializablePath && toSourceName(options.initializablePath),
);

// Maps an import path produced by the transpiler to its final location.
const resolveImport = (file: string, importPath: string): string => {
if (importPath === path.join(PEER_PLACEHOLDER, mainSourcesRel, 'Initializable.sol') && options.initializablePath) {
return options.initializablePath;
} else if (importPath.startsWith(PEER_PLACEHOLDER + '/')) {
const sourceName = importPath.slice(PEER_PLACEHOLDER.length + 1);
return isLocal(sourceName) ? options.peerProject! + sourceName : toImportPath(sourceName);
} else if (importPath.startsWith('.')) {
return importPath;
} else {
assert(
Object.keys(options.upgradeablePackages ?? {}).some(prefix => importPath.startsWith(prefix)),
`${file} imports a stateful contract from ${importPath}, which has no upgradeable variant`,
);
return replacePrefix(importPath, Object.entries(options.upgradeablePackages ?? {}));
}
};

const withInitPath = path.join(mainSourcesRel, 'mocks', 'WithInit.sol');

return {
alreadyInitializable,

// `initializablePath` and `upgradeablePackages` are handled here and must not reach the transpiler.
optionsOverride: {
initializablePath: undefined,
upgradeablePackages: undefined,
exclude: [...(options.exclude ?? []), ...alreadyInitializable.filter(isLocal)],
peerProject: PEER_PLACEHOLDER + '/',
} satisfies Partial<TranspileOptions>,

// Only keep the output for the main sources, and rewrite its imports.
postProcess: (files: OutputFile[]): OutputFile[] =>
files
.filter(t => isLocal(t.path))
.map(t => ({
...t,
source:
t.path === withInitPath
? filterWithInit(t.path, t.source, isLocal)
: t.source.replace(/^(import\s[^;]*?["'])([^"']+)(["'];)/gm, (_, pre, importPath, post) =>
[pre, resolveImport(t.path, importPath), post].join(''),
),
})),
};
}

// The generated `WithInit` file contains a block for every transformed contract, including those from dependencies.
// Only the blocks corresponding to local contracts are kept. Their imports are restricted to the contract and the
// user-defined types of its constructor arguments, to avoid clashes between symbols the imported files bring into
// scope.
const ELEMENTARY_TYPES = /^(address|bool|string|bytes\d*|u?int\d*|u?fixed[\dx]*)$/;

function filterWithInit(file: string, source: string, isLocal: (file: string) => boolean): string {
const [header, ...blocks] = source.split(/^(?=import ")/m);
const kept = blocks
.map(block => {
const [, importPath, name, params] = block.match(
/^import "([^"]+)";\s+contract \w+ is (\w+) {\s+constructor\(([^)]*)\)/,
)!;
const types = params
.split(',')
.map(param => param.trim().match(/^\w+/)?.[0])
.filter(type => type && !ELEMENTARY_TYPES.test(type));
Comment on lines +142 to +145
const symbols = [...new Set([name, ...types])];
return { importPath, block: block.replace(/^import "/, `import {${symbols.join(', ')}} from "`) };
})
.filter(({ importPath }) => isLocal(path.join(path.dirname(file), importPath)))
.map(({ block }) => block);
return [header, ...kept].join('');
}
Loading