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
2 changes: 2 additions & 0 deletions .github/workflows/contracts-upgrade-version-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ jobs:
- .github/workflows/contracts-upgrade-version-check.yml
- ci/check-upgrade-versions.ts
- ci/merge-address-constants.ts
- ci/upgrade-version-check-lib.ts
- host-contracts/**
gateway-contracts:
- .github/workflows/contracts-upgrade-version-check.yml
- ci/check-upgrade-versions.ts
- ci/merge-address-constants.ts
- ci/upgrade-version-check-lib.ts
- gateway-contracts/**

check:
Expand Down
125 changes: 11 additions & 114 deletions ci/check-upgrade-versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,136 +2,33 @@
// Checks that upgradeable contracts have proper version bumps when bytecode changes.
// Usage: bun ci/check-upgrade-versions.ts <baseline-pkg-dir> <pr-pkg-dir>

import { readFileSync, existsSync } from "fs";
import { execSync } from "child_process";
import { join } from "path";
import { collectUpgradeVersionResults } from "./upgrade-version-check-lib";

const [baselineDir, prDir] = process.argv.slice(2);
if (!baselineDir || !prDir) {
console.error("Usage: bun ci/check-upgrade-versions.ts <baseline-pkg-dir> <pr-pkg-dir>");
process.exit(1);
}

const manifestPath = join(prDir, "upgrade-manifest.json");
if (!existsSync(manifestPath)) {
console.error(`::error::upgrade-manifest.json not found in ${prDir}`);
process.exit(1);
}

const VERSION_RE = /(?<name>REINITIALIZER_VERSION|MAJOR_VERSION|MINOR_VERSION|PATCH_VERSION)\s*=\s*(?<value>\d+)/g;

function extractVersions(filePath: string) {
const source = readFileSync(filePath, "utf-8");
const versions: Record<string, number> = {};
for (const { groups } of source.matchAll(VERSION_RE)) {
versions[groups!.name] = Number(groups!.value);
}
return { versions, source };
}

function forgeInspect(contract: string, root: string): string | null {
try {
const raw = execSync(`forge inspect "contracts/${contract}.sol:${contract}" --root "${root}" deployedBytecode`, {
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, NO_COLOR: "1" },
});
// Extract hex bytecode — forge may prepend ANSI codes or compilation progress to stdout
const match = raw.match(/0x[0-9a-fA-F]+/);
return match ? match[0] : null;
} catch (e: any) {
if (e.stderr) console.error(String(e.stderr));
return null;
}
}

const contracts: string[] = JSON.parse(readFileSync(manifestPath, "utf-8"));
const results = collectUpgradeVersionResults(baselineDir, prDir);
let errors = 0;

for (const name of contracts) {
console.log(`::group::Checking ${name}`);
for (const result of results) {
console.log(`::group::Checking ${result.name}`);
try {
const baseSol = join(baselineDir, "contracts", `${name}.sol`);
const prSol = join(prDir, "contracts", `${name}.sol`);

if (!existsSync(baseSol)) {
console.log(`Skipping ${name} (new contract, not in baseline)`);
continue;
}

if (!existsSync(prSol)) {
console.error(`::error::${name} listed in upgrade-manifest.json but missing in PR`);
errors++;
if (!result.baselineExists) {
console.log(`Skipping ${result.name} (new contract, not in baseline)`);
continue;
}

const { versions: baseV } = extractVersions(baseSol);
const { versions: prV, source: prSrc } = extractVersions(prSol);

let parseFailed = false;
for (const key of ["REINITIALIZER_VERSION", "MAJOR_VERSION", "MINOR_VERSION", "PATCH_VERSION"]) {
if (baseV[key] == null || prV[key] == null) {
console.error(`::error::Failed to parse ${key} for ${name}`);
errors++;
parseFailed = true;
}
}
if (parseFailed) continue;

const prBytecode = forgeInspect(name, prDir);
if (prBytecode == null) {
console.error(`::error::Failed to compile ${name} on PR`);
errors++;
continue;
}

const baseBytecode = forgeInspect(name, baselineDir);
if (baseBytecode == null) {
console.error(`::error::Failed to compile ${name} on baseline`);
errors++;
continue;
}
const bytecodeChanged = baseBytecode !== prBytecode;
const reinitChanged = baseV.REINITIALIZER_VERSION !== prV.REINITIALIZER_VERSION;
const versionChanged =
baseV.MAJOR_VERSION !== prV.MAJOR_VERSION ||
baseV.MINOR_VERSION !== prV.MINOR_VERSION ||
baseV.PATCH_VERSION !== prV.PATCH_VERSION;

if (!bytecodeChanged) {
console.log(`${name}: bytecode unchanged`);
if (reinitChanged) {
console.error(
`::error::${name} REINITIALIZER_VERSION bumped (${baseV.REINITIALIZER_VERSION} -> ${prV.REINITIALIZER_VERSION}) but bytecode is unchanged`,
);
errors++;
}
continue;
}

console.log(`${name}: bytecode CHANGED`);

if (!reinitChanged) {
console.error(
`::error::${name} bytecode changed but REINITIALIZER_VERSION was not bumped (still ${prV.REINITIALIZER_VERSION})`,
);
errors++;
if (result.bytecodeChanged) {
console.log(`${result.name}: bytecode CHANGED`);
} else {
// Convention: reinitializeV{N-1} for REINITIALIZER_VERSION=N
const expectedFn = `reinitializeV${prV.REINITIALIZER_VERSION - 1}`;
const uncommented = prSrc.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "");
if (!new RegExp(`function\\s+${expectedFn}\\s*\\(`).test(uncommented)) {
console.error(
`::error::${name} has REINITIALIZER_VERSION=${prV.REINITIALIZER_VERSION} but no ${expectedFn}() function found`,
);
errors++;
}
console.log(`${result.name}: bytecode unchanged`);
}

if (!versionChanged) {
console.error(
`::error::${name} bytecode changed but semantic version was not bumped (still v${prV.MAJOR_VERSION}.${prV.MINOR_VERSION}.${prV.PATCH_VERSION})`,
);
for (const error of result.errors) {
console.error(`::error::${error}`);
errors++;
}
} finally {
Expand Down
151 changes: 151 additions & 0 deletions ci/list-upgrades.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
#!/usr/bin/env bun

import { execSync } from "child_process";
import { mkdtempSync, rmSync } from "fs";
import { tmpdir } from "os";
import { dirname, join, resolve } from "path";

import { collectUpgradeVersionResults } from "./upgrade-version-check-lib";
import { CONTRACT_HINTS, PACKAGE_CONSTRAINTS } from "./upgrade-report-hints";

type PackageName = "host-contracts" | "gateway-contracts";

const PACKAGE_CONFIG: Record<PackageName, { extraDeps?: string }> = {
"host-contracts": { extraDeps: "forge soldeer install" },
"gateway-contracts": {},
};

function usage(): never {
console.error("Usage: bun ci/list-upgrades.ts --from <tag/ref> [--to <tag/ref>] [--package host-contracts|gateway-contracts]");
process.exit(1);
}

function parseArgs() {
const args = process.argv.slice(2);
let fromRef: string | undefined;
let toRef: string | undefined;
const packages: PackageName[] = [];

for (let idx = 0; idx < args.length; idx++) {
const arg = args[idx];
if (arg === "--from") {
fromRef = args[++idx];
} else if (arg === "--to") {
toRef = args[++idx];
} else if (arg === "--package") {
const value = args[++idx] as PackageName;
if (value !== "host-contracts" && value !== "gateway-contracts") usage();
packages.push(value);
} else {
usage();
}
}

if (!fromRef) usage();

return {
fromRef,
toRef,
packages: packages.length > 0 ? packages : (["host-contracts", "gateway-contracts"] as PackageName[]),
};
}

function run(cmd: string, cwd: string) {
execSync(cmd, { cwd, stdio: "inherit", env: { ...process.env, NO_COLOR: "1" } });
}

function addWorktree(repoRoot: string, path: string, ref: string) {
run(`git worktree add --detach "${path}" "${ref}"`, repoRoot);
}

function preparePackage(currentRepoRoot: string, targetRoot: string, baselineRoot: string, pkg: PackageName) {
const targetDir = join(targetRoot, pkg);
const baselineDir = join(baselineRoot, pkg);
const extraDeps = PACKAGE_CONFIG[pkg].extraDeps;

run("npm ci", targetDir);
run("npm ci", baselineDir);
if (extraDeps) {
run(extraDeps, targetDir);
run(extraDeps, baselineDir);
}
run("make ensure-addresses", targetDir);
run("make ensure-addresses", baselineDir);
run(`bun ci/merge-address-constants.ts "${join(baselineDir, "addresses")}" "${join(targetDir, "addresses")}"`, currentRepoRoot);
run(`cp "${join(targetDir, "foundry.toml")}" "${join(baselineDir, "foundry.toml")}"`, currentRepoRoot);
}

function printPackageReport(pkg: PackageName, repoRoot: string, baselineRoot: string) {
const results = collectUpgradeVersionResults(join(baselineRoot, pkg), join(repoRoot, pkg));
const changed = results.filter((result) => result.baselineExists && result.bytecodeChanged);
const unchanged = results.filter((result) => result.baselineExists && !result.bytecodeChanged);
const errors = results.flatMap((result) => result.errors.map((error) => `${result.name}: ${error}`));

console.log(`\n## ${pkg}`);

if (errors.length > 0) {
console.log("\nErrors:");
for (const error of errors) {
console.log(`- ${error}`);
}
process.exitCode = 1;
return;
}

console.log("\nNeed upgrade:");
for (const result of changed) {
console.log(`- ${result.name}`);
if (result.reinitializer) {
console.log(` reinitializer: ${result.reinitializer.signature}`);
console.log(` upgrade args: ${result.reinitializer.inputs.length > 0 ? "yes" : "no"}`);
const defaults = CONTRACT_HINTS[pkg][result.name]?.defaults;
if (defaults) {
console.log(" task defaults:");
for (const [name, value] of Object.entries(defaults)) {
console.log(` - ${name} = ${value}`);
}
} else if (result.reinitializer.inputs.length > 0) {
console.log(" note: check arg values with a repo owner");
}
}
}

console.log("\nNo upgrade needed:");
for (const result of unchanged) {
console.log(`- ${result.name}`);
}

const changedNames = new Set(changed.map((result) => result.name));
const activeConstraints = PACKAGE_CONSTRAINTS[pkg].filter((constraint) =>
constraint.contracts.every((contract) => changedNames.has(contract)),
);
if (activeConstraints.length > 0) {
console.log("\nAttention points:");
for (const constraint of activeConstraints) {
console.log(`- ${constraint.message}`);
}
}
}

const { fromRef, toRef, packages } = parseArgs();
const repoRoot = resolve(dirname(import.meta.dir));
const tempRoot = mkdtempSync(join(tmpdir(), "fhevm-upgrade-report-"));
const baselineRoot = join(tempRoot, "baseline");
const targetRoot = toRef ? join(tempRoot, "target") : repoRoot;

try {
addWorktree(repoRoot, baselineRoot, fromRef);
if (toRef) {
addWorktree(repoRoot, targetRoot, toRef);
}

for (const pkg of packages) {
preparePackage(repoRoot, targetRoot, baselineRoot, pkg);
printPackageReport(pkg, targetRoot, baselineRoot);
}
} finally {
try {
run("git worktree prune", repoRoot);
} catch {}
rmSync(tempRoot, { recursive: true, force: true });
}
31 changes: 31 additions & 0 deletions ci/upgrade-report-hints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export interface UpgradeReportHint {
defaults?: Record<string, string>;
}

export interface UpgradeConstraint {
contracts: string[];
message: string;
}

export const CONTRACT_HINTS: Record<string, Record<string, UpgradeReportHint>> = {
"host-contracts": {
HCULimit: {
defaults: {
hcuCapPerBlock: "281474976710655",
maxHcuDepthPerTx: "5000000",
maxHcuPerTx: "20000000",
},
},
},
"gateway-contracts": {},
};

export const PACKAGE_CONSTRAINTS: Record<string, UpgradeConstraint[]> = {
"host-contracts": [
{
contracts: ["HCULimit", "FHEVMExecutor"],
message: "HCULimit and FHEVMExecutor both changed. Check whether they must be upgraded atomically or back-to-back.",
},
],
"gateway-contracts": [],
};
Loading
Loading