Skip to content
Open
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 .changeset/solc-prerelease-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"hardhat": minor
"@nomicfoundation/hardhat-utils": minor
---

Added support for solc prereleases (e.g. `0.9.0-pre.1`). A prerelease is only used when its full version is set explicitly in the Solidity config, and is matched against version pragmas the same way solc does: as lower than the release it precedes.
29 changes: 26 additions & 3 deletions packages/hardhat-utils/src/fast-semver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,48 @@

export type SemverVersion = [major: number, minor: number, patch: number];

const VERSION_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?$/;
const VERSION_REGEX =
/^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;

export interface ParseVersionOptions {
/**
* If `true`, a `-prerelease` suffix is accepted and stripped, so that
* `1.2.3-rc.1` parses as `[1, 2, 3]`. Defaults to `false`.
*
* This is meant for callers that gate features on the `MAJOR.MINOR.PATCH`
* triple, where a prerelease is expected to behave like the release it
* precedes. It must not be used to order versions, as the prerelease
* information is lost.
*/
allowPrerelease?: boolean;
}

/**
* Parses a strict `MAJOR.MINOR.PATCH` version string into a `SemverVersion`
* tuple.
*
* An optional `+build` suffix is accepted and stripped silently. A
* `-prerelease` suffix is rejected.
* `-prerelease` suffix is rejected, unless `options.allowPrerelease` is set,
* in which case it is stripped too.
*
* @param version The version string to parse.
* @param options Parsing options.
* @returns The parsed `SemverVersion`, or `undefined` if the input does not
* match the strict `\d+\.\d+\.\d+` shape.
*/
export function parseVersion(version: string): SemverVersion | undefined {
export function parseVersion(
version: string,
options: ParseVersionOptions = {},
): SemverVersion | undefined {
const match = VERSION_REGEX.exec(version);
if (match === null) {
return undefined;
}

if (match[4] !== undefined && options.allowPrerelease !== true) {
return undefined;
}

return [Number(match[1]), Number(match[2]), Number(match[3])];
}

Expand Down
13 changes: 13 additions & 0 deletions packages/hardhat-utils/test/fast-semver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ describe("fast-semver", () => {
assert.equal(parseVersion("1.2.3-0"), undefined);
});

it("Should strip a -prerelease suffix when allowPrerelease is set", () => {
const options = { allowPrerelease: true };
assert.deepEqual(parseVersion("1.2.3-rc.1", options), [1, 2, 3]);
assert.deepEqual(parseVersion("0.9.0-pre.1", options), [0, 9, 0]);
assert.deepEqual(
parseVersion("0.9.0-pre.1+commit.91c99213", options),
[0, 9, 0],
);
assert.deepEqual(parseVersion("1.2.3", options), [1, 2, 3]);
assert.equal(parseVersion("1.2.3-", options), undefined);
assert.equal(parseVersion("v1.2.3-rc.1", options), undefined);
});

it("Should reject invalid inputs", () => {
assert.equal(parseVersion("v1.2.3"), undefined);
assert.equal(parseVersion("1.2"), undefined);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ export function instrumentSolidityFileForCompilationJob({
`Invalid latest supported solidity version: ${latestSupportedVersion}`,
);
let instrumentationVersion = compilationJobSolcVersion;
const parsedInstrumentationVersion = parseVersion(instrumentationVersion);
const parsedInstrumentationVersion = parseVersion(instrumentationVersion, {
allowPrerelease: true,
});
Comment on lines +46 to +48

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am happy that pre-release version info isn't relevant for coverage. EDR will fallback to the latest solc version (used for parsing info for slang) if an unknown version is passed.

assertHardhatInvariant(
parsedInstrumentationVersion !== undefined,
`Invalid solc version: ${instrumentationVersion}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export class NativeCompiler implements Compiler {
// Logic to make sure that solc default import callback is not being used.
// If solcVersion is not defined or <= 0.6.8, do not add extra args.
if (this.version !== undefined) {
const parsed = parseVersion(this.version);
const parsed = parseVersion(this.version, { allowPrerelease: true });
if (parsed === undefined) {
throw new HardhatError(
HardhatError.ERRORS.CORE.SOLIDITY.INVALID_SOLC_VERSION,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ interface CompilerBuild {
prerelease?: string;
}

/**
* Returns the version string that users have to configure to select `build`.
*
* Releases are selected by their plain version (e.g. `0.8.31`), while
* prereleases have to be selected explicitly, including their prerelease tag
* (e.g. `0.9.0-pre.1`). This way, a prerelease is never picked unless the user
* opts into it.
*/
function getBuildVersion(build: CompilerBuild): string {
return build.prerelease === undefined
? build.version
: `${build.version}-${build.prerelease}`;
}

interface CompilerList {
builds: CompilerBuild[];
releases: { [version: string]: string };
Expand Down Expand Up @@ -293,9 +307,7 @@ export class CompilerDownloaderImplementation implements CompilerDownloader {

const list = await this.#readCompilerList(listPath);

const build = list.builds.find(
(b) => b.version === version && b.prerelease === undefined,
);
const build = list.builds.find((b) => getBuildVersion(b) === version);

if (build === undefined) {
throw new HardhatError(
Expand Down Expand Up @@ -326,7 +338,7 @@ export class CompilerDownloaderImplementation implements CompilerDownloader {
return this.#getCompilerDownloadPathFromBuild(build);
}

return path.join(this.#compilersDir, build.version, "solc.exe");
return path.join(this.#compilersDir, getBuildVersion(build), "solc.exe");
}

// some window builds are zipped, some are not
Expand All @@ -353,11 +365,7 @@ export class CompilerDownloaderImplementation implements CompilerDownloader {

const list = await this.#readCompilerList(listPath);

const listVersions = new Set(
list.builds
.filter((b) => b.prerelease === undefined)
.map((b) => b.version),
);
const listVersions = new Set(list.builds.map(getBuildVersion));

for (const version of versions) {
if (!listVersions.has(version)) {
Expand Down Expand Up @@ -450,7 +458,7 @@ export class CompilerDownloaderImplementation implements CompilerDownloader {
const defaultUrl = `${COMPILER_REPOSITORY_URL}/${this.#platform}`;
const url = `${build.url ?? defaultUrl}/${build.path}`;

log(`Downloading compiler ${build.version} from ${url}`);
log(`Downloading compiler ${getBuildVersion(build)} from ${url}`);

// Download to a temporary path, we move into place after verifying the checksum
const downloadPath = `${this.#getCompilerDownloadPathFromBuild(build)}.tmp`;
Expand Down Expand Up @@ -491,7 +499,7 @@ export class CompilerDownloaderImplementation implements CompilerDownloader {
downloadPath: string,
): Promise<boolean> {
if (this.#isZippedWindowsBuild(build)) {
const solcFolder = path.join(this.#compilersDir, build.version);
const solcFolder = path.join(this.#compilersDir, getBuildVersion(build));
await ensureDir(solcFolder);

const zip = new AdmZip(downloadPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export type CompileWrapper = (input: string) => string;
export default function wrapper(solc: Solc): SolcWrapper {
const version = bindVersion(solc);
const rawVersion = version();
const parsedVersion = parseVersion(rawVersion);
const parsedVersion = parseVersion(rawVersion, { allowPrerelease: true });
assertHardhatInvariant(
parsedVersion !== undefined,
`Invalid solc version: ${rawVersion}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ import { intersects, maxSatisfying, satisfies } from "semver";

import { CompilationJobCreationErrorReason } from "../../../../types/solidity/build-system.js";

/**
* By default, `semver` never matches a prerelease against a range unless the
* range itself has a prerelease on the same `MAJOR.MINOR.PATCH`. Solc
* prereleases are only ever selected when the user explicitly configures one
* (e.g. `0.9.0-pre.1`), so we include them in the matching. This mirrors solc,
* which accepts a prerelease if its version satisfies the pragma, treating
* it as lower than the release it precedes.
*/
const SEMVER_OPTIONS = { includePrerelease: true };

export class SolcConfigSelector {
readonly #buildProfileName: string;
readonly #buildProfile: SolidityBuildProfileConfig;
Expand Down Expand Up @@ -66,7 +76,9 @@ export class SolcConfigSelector {

// if there's an override, we only check that
if (overriddenCompiler !== undefined) {
if (!satisfies(overriddenCompiler.version, versionRange)) {
if (
!satisfies(overriddenCompiler.version, versionRange, SEMVER_OPTIONS)
) {
return this.#getCompilationJobCreationError(
root,
subgraph,
Expand All @@ -80,7 +92,11 @@ export class SolcConfigSelector {

// if there's no override, we find a compiler that matches the version range
const compilerVersions = this.#buildProfile.compilers.map((x) => x.version);
const matchingVersion = maxSatisfying(compilerVersions, versionRange);
const matchingVersion = maxSatisfying(
compilerVersions,
versionRange,
SEMVER_OPTIONS,
);

if (matchingVersion === null) {
return this.#getCompilationJobCreationError(
Expand Down Expand Up @@ -129,7 +145,10 @@ export class SolcConfigSelector {

if (overridden) {
// The root may not be compatible with the override version
if (maxSatisfying(compilerVersions, rootVersionRange) === null) {
if (
maxSatisfying(compilerVersions, rootVersionRange, SEMVER_OPTIONS) ===
null
) {
return {
success: false,
reason:
Expand All @@ -149,7 +168,9 @@ export class SolcConfigSelector {
const depOwnRange =
transitiveDependency.dependency.content.versionPragmas.join(" ");

if (maxSatisfying(compilerVersions, depOwnRange) === null) {
if (
maxSatisfying(compilerVersions, depOwnRange, SEMVER_OPTIONS) === null
) {
return {
success: false,
reason:
Expand All @@ -173,7 +194,9 @@ export class SolcConfigSelector {

// Non-overridden case: we first check if the root is compatible with any
// configured compiler
if (maxSatisfying(compilerVersions, rootVersionRange) === null) {
if (
maxSatisfying(compilerVersions, rootVersionRange, SEMVER_OPTIONS) === null
) {
return {
success: false,
reason:
Expand All @@ -200,7 +223,9 @@ export class SolcConfigSelector {

// A transitive dependency can have a pragma that's incompatible with
// all the configured compilers
if (maxSatisfying(compilerVersions, depOwnRange) === null) {
if (
maxSatisfying(compilerVersions, depOwnRange, SEMVER_OPTIONS) === null
) {
return {
success: false,
reason:
Expand All @@ -214,7 +239,13 @@ export class SolcConfigSelector {

// The root and the version ranges to get to this transitive dependency
// may be contradictory, so no version ever can satisfy them.
if (!intersects(rootVersionRange, transitiveDependencyVersionRange)) {
if (
!intersects(
rootVersionRange,
transitiveDependencyVersionRange,
SEMVER_OPTIONS,
)
) {
return {
success: false,
reason: CompilationJobCreationErrorReason.IMPORT_OF_INCOMPATIBLE_FILE,
Expand All @@ -228,7 +259,9 @@ export class SolcConfigSelector {
// The root and the version ranges to get to this transitive dependency
// may not be compatible with any configured compiler.
const combinedRange = `${rootVersionRange} ${transitiveDependencyVersionRange}`;
if (maxSatisfying(compilerVersions, combinedRange) === null) {
if (
maxSatisfying(compilerVersions, combinedRange, SEMVER_OPTIONS) === null
) {
return {
success: false,
reason:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const FIRST_ARM64_MIRROR_SOLC_VERSION: SemverVersion = [0, 5, 0];
* Determines if a solc version has an official ARM64 Linux build.
*/
export function hasOfficialArm64Build(version: string): boolean {
const parsed = parseVersion(version);
const parsed = parseVersion(version, { allowPrerelease: true });
if (parsed === undefined) {
throw new HardhatError(
HardhatError.ERRORS.CORE.SOLIDITY.INVALID_SOLC_VERSION,
Expand All @@ -35,7 +35,7 @@ export function hasOfficialArm64Build(version: string): boolean {
* in the community mirror (versions 0.5.0–0.8.30).
*/
export function hasArm64MirrorBuild(version: string): boolean {
const parsed = parseVersion(version);
const parsed = parseVersion(version, { allowPrerelease: true });
if (parsed === undefined) {
throw new HardhatError(
HardhatError.ERRORS.CORE.SOLIDITY.INVALID_SOLC_VERSION,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,30 @@ describe(
assert.equal(compiler.version, "0.8.31");
assert.equal(compiler.longVersion, "0.8.31+commit.fd3a2265");
});

it("should not select a prerelease unless it is explicitly requested", async () => {
// 0.8.35-pre.1 is in the list, but `0.8.35` refers to the release
await downloader.updateCompilerListIfNeeded(new Set(["0.8.35"]));
await downloader.downloadCompiler("0.8.35");
const compiler = await downloader.getCompiler("0.8.35");

assert.ok(compiler !== undefined, "Compiler should be defined");
assert.equal(compiler.version, "0.8.35");
assert.ok(
!compiler.longVersion.includes("-pre"),
`Unexpected prerelease ${compiler.longVersion}`,
);
});

it("should download and get an explicitly requested prerelease", async () => {
await downloader.updateCompilerListIfNeeded(new Set(["0.9.0-pre.1"]));
await downloader.downloadCompiler("0.9.0-pre.1");
const compiler = await downloader.getCompiler("0.9.0-pre.1");

assert.ok(compiler !== undefined, "Compiler should be defined");
assert.equal(compiler.version, "0.9.0-pre.1");
assert.equal(compiler.longVersion, "0.9.0-pre.1+commit.91c99213");
});
});

describe("when on windows", function () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,53 @@ describe("SolcConfigSelector", () => {
});
});

describe("Prerelease compilers", () => {
it("should select a configured prerelease that satisfies the version range", () => {
root.content.versionPragmas = [">=0.8.0"];
buildProfile.compilers.push({ version: "0.9.0-pre.1", settings: {} });

const selector = new SolcConfigSelector(buildProfileName, buildProfile);
const config =
selector.selectBestSolcConfigForSingleRootGraph(dependencyGraph);

assert.deepEqual(config, {
success: true,
config: buildProfile.compilers[0],
});
});

it("should accept a prerelease override that satisfies the version range", () => {
root.content.versionPragmas = [">=0.8.0 <0.10.0"];
buildProfile.overrides[root.inputSourceName] = {
version: "0.9.0-pre.1",
settings: {},
};

const selector = new SolcConfigSelector(buildProfileName, buildProfile);
const config =
selector.selectBestSolcConfigForSingleRootGraph(dependencyGraph);

assert.deepEqual(config, {
success: true,
config: buildProfile.overrides[root.inputSourceName],
});
});

it("should treat a prerelease as lower than its release, like solc does", () => {
buildProfile.compilers.push({ version: "0.9.0-pre.1", settings: {} });

for (const pragma of ["^0.8.0", ">=0.9.0", "^0.9.0"]) {
root.content.versionPragmas = [pragma];

const selector = new SolcConfigSelector(buildProfileName, buildProfile);
const config =
selector.selectBestSolcConfigForSingleRootGraph(dependencyGraph);

assert.equal(config.success, false, `${pragma} should not match`);
}
});
});

describe("Edge cases", () => {
it("Should still return an error in the presence of cycles", () => {
const dependency1 = createProjectResolvedFile("dependency1.sol", [
Expand Down
Loading