From 2e0a04ecd4b1f5fbb17762273599b2b13cd364e3 Mon Sep 17 00:00:00 2001 From: Gonzalo Bustos Date: Tue, 12 Aug 2025 11:45:46 -0300 Subject: [PATCH 1/3] feat: attempt to compile zk --- batch-compile-zk.sh | 77 +++ foundryup-zksync | 677 +++++++++++++++++++ package.json | 6 +- scripts/zk-compilation/new-zk-compilation.ts | 125 ++++ scripts/zk-compilation/zk-compilation.ts | 118 ++++ yarn.lock | 41 +- 6 files changed, 1040 insertions(+), 4 deletions(-) create mode 100755 batch-compile-zk.sh create mode 100755 foundryup-zksync create mode 100644 scripts/zk-compilation/new-zk-compilation.ts create mode 100644 scripts/zk-compilation/zk-compilation.ts diff --git a/batch-compile-zk.sh b/batch-compile-zk.sh new file mode 100755 index 000000000..bce1ce558 --- /dev/null +++ b/batch-compile-zk.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +set -euo pipefail + +CONTRACTS_DIR="contracts" +COMPILED=() # array of compiled contract absolute paths + +# To track compiled contracts quickly +declare -A compiled_map + +compiled_count=0 +total_contracts=0 + +# Find all contracts under contracts directory +mapfile -t all_contracts < <(find "$CONTRACTS_DIR" -type f -name "*.sol") + +total_contracts=${#all_contracts[@]} + +echo "Found $total_contracts contracts under $CONTRACTS_DIR" + +# Resolve imports and compile recursively +compile_contract() { + local contract_path="$1" + # Normalize path to absolute + contract_path=$(realpath "$contract_path") + + # Check if already compiled + if [[ ${compiled_map["$contract_path"]+exists} ]]; then + return + fi + + # Parse imports (assumes imports are relative paths or absolute within repo) + # Matches: import "path"; + local imports=() + while IFS= read -r line; do + line=$(echo "$line" | xargs) + if echo "$line" | grep -qE '^import[[:space:]]+"[^"]+"[[:space:]]*;'; then + imp=$(echo "$line" | sed -E 's|^import[[:space:]]+"([^"]+)".*|\1|') + local contract_dir + contract_dir=$(dirname "$contract_path") + + local imp_path + if [[ "$imp" == /* ]]; then + imp_path="$imp" + else + imp_path="$contract_dir/$imp" + fi + + imp_path=$(realpath "$imp_path") + + if [[ -f "$imp_path" ]]; then + imports+=("$imp_path") + else + echo "Warning: import $imp_path not found for $contract_path" + fi + fi + done < "$contract_path" + + + # Recursively compile dependencies first + for dep in "${imports[@]}"; do + compile_contract "$dep" + done + + # Now compile this contract individually with zk flag + echo "Compiling $contract_path ..." + forge build --zksync --contracts "$contract_path" + compiled_map["$contract_path"]=1 + ((compiled_count++)) + echo "Compiled $compiled_count / $total_contracts contracts." +} + +# Iterate over all contracts found and compile them (will skip already compiled) +for contract in "${all_contracts[@]}"; do + compile_contract "$contract" +done + +echo "Compilation done. Total contracts compiled: $compiled_count" diff --git a/foundryup-zksync b/foundryup-zksync new file mode 100755 index 000000000..b0834b6e9 --- /dev/null +++ b/foundryup-zksync @@ -0,0 +1,677 @@ +#!/usr/bin/env bash +set -eo pipefail + +# NOTE: if you make modifications to this script, please increment the version number. +# WARNING: the SemVer pattern: major.minor.patch must be followed as we use it to determine if the script is up to date. +FOUNDRYUP_INSTALLER_VERSION="1.3.0" + +BASE_DIR=${XDG_CONFIG_HOME:-$HOME} +FOUNDRY_DIR=${FOUNDRY_DIR:-"$BASE_DIR/.foundry"} +FOUNDRY_VERSIONS_DIR="$FOUNDRY_DIR/versions" +FOUNDRY_BIN_DIR="$FOUNDRY_DIR/bin" +FOUNDRY_MAN_DIR="$FOUNDRY_DIR/share/man/man1" +FOUNDRY_BIN_URL="https://raw.githubusercontent.com/foundry-rs/foundry/master/foundryup/foundryup" +FOUNDRY_BIN_PATH="$FOUNDRY_BIN_DIR/foundryup" +FOUNDRYUP_JOBS="" +FOUNDRYUP_IGNORE_VERIFICATION=false + +BINS=(forge cast) + +export RUSTFLAGS="${RUSTFLAGS:--C target-cpu=native}" + +main() { + need_cmd git + need_cmd curl + + while [[ -n $1 ]]; do + case $1 in + --) shift; break;; + + -v|--version) shift; version;; + -U|--update) shift; update;; + -r|--repo) shift; FOUNDRYUP_REPO=$1;; + -b|--branch) shift; FOUNDRYUP_BRANCH=$1;; + -i|--install) shift; FOUNDRYUP_VERSION=$1;; + -l|--list) shift; list;; + -u|--use) shift; FOUNDRYUP_VERSION=$1; use;; + -p|--path) shift; FOUNDRYUP_LOCAL_REPO=$1;; + -P|--pr) shift; FOUNDRYUP_PR=$1;; + -C|--commit) shift; FOUNDRYUP_COMMIT=$1;; + -j|--jobs) shift; FOUNDRYUP_JOBS=$1;; + -f|--force) FOUNDRYUP_IGNORE_VERIFICATION=true;; + --arch) shift; FOUNDRYUP_ARCH=$1;; + --platform) shift; FOUNDRYUP_PLATFORM=$1;; + -h|--help) + usage + exit 0 + ;; + *) + warn "unknown option: $1" + usage + exit 1 + esac; shift + done + + CARGO_BUILD_ARGS=(--release) + + if [ -n "$FOUNDRYUP_JOBS" ]; then + CARGO_BUILD_ARGS+=(--jobs "$FOUNDRYUP_JOBS") + fi + + # Print the banner after successfully parsing args + banner + + # Check if the foundryup installer is up to date, warn the user if not + check_installer_up_to_date + + if [ -n "$FOUNDRYUP_PR" ]; then + if [ -z "$FOUNDRYUP_BRANCH" ]; then + FOUNDRYUP_BRANCH="refs/pull/$FOUNDRYUP_PR/head" + else + err "can't use --pr and --branch at the same time" + fi + fi + + check_bins_in_use + + # Installs foundry from a local repository if --path parameter is provided + if [[ -n "$FOUNDRYUP_LOCAL_REPO" ]]; then + need_cmd cargo + + # Ignore branches/versions as we do not want to modify local git state + if [ -n "$FOUNDRYUP_REPO" ] || [ -n "$FOUNDRYUP_BRANCH" ] || [ -n "$FOUNDRYUP_VERSION" ]; then + warn "--branch, --install, --use, and --repo arguments are ignored during local install" + fi + + # Enter local repo and build + say "installing from $FOUNDRYUP_LOCAL_REPO" + cd "$FOUNDRYUP_LOCAL_REPO" + ensure cargo build --bins "${CARGO_BUILD_ARGS[@]}" + + for bin in "${BINS[@]}"; do + # Remove prior installations if they exist + rm -f "$FOUNDRY_BIN_DIR/$bin" + # Symlink from local repo binaries to bin dir + ensure ln -s "$PWD/target/release/$bin" "$FOUNDRY_BIN_DIR/$bin" + done + + say "done" + exit 0 + fi + + FOUNDRYUP_REPO=${FOUNDRYUP_REPO:-matter-labs/foundry-zksync} + + # Install by downloading binaries + if [[ "$FOUNDRYUP_REPO" == "matter-labs/foundry-zksync" && -z "$FOUNDRYUP_BRANCH" && -z "$FOUNDRYUP_COMMIT" ]]; then + # If --version not specified, fetch the latest release tag from GitHub + if [ -z "$FOUNDRYUP_VERSION" ]; then + # No --version passed -> Use the "latest" semantic-release tag + LATEST_TAG=$(curl -s https://api.github.com/repos/${FOUNDRYUP_REPO}/releases/latest | \ + sed -n 's/.*"tag_name": "\([^"]*\)".*/\1/p') + if [ -z "$LATEST_TAG" ]; then + err "could not fetch the latest release tag for $FOUNDRYUP_REPO!" + fi + FOUNDRYUP_TAG="$LATEST_TAG" + + else + # --version was specified; check if it's nightly or a numeric version, etc. + if [[ "$FOUNDRYUP_VERSION" == "nightly" ]]; then + say "Installing the nightly build" + FOUNDRYUP_TAG="nightly" + elif [[ "$FOUNDRYUP_VERSION" =~ ^foundry-zksync-v ]]; then + # user passed full "foundry-zksync-v0.0.4" + FOUNDRYUP_TAG="$FOUNDRYUP_VERSION" + elif [[ "$FOUNDRYUP_VERSION" =~ ^v ]]; then + # user passed "v0.0.4" + FOUNDRYUP_TAG="foundry-zksync-$FOUNDRYUP_VERSION" + else + # user passed "0.0.4" + FOUNDRYUP_TAG="foundry-zksync-v$FOUNDRYUP_VERSION" + fi + + say "installing foundry-zksync ($FOUNDRYUP_TAG)" + fi + + uname_s=$(uname -s) + PLATFORM=$(tolower "${FOUNDRYUP_PLATFORM:-$uname_s}") + EXT="tar.gz" + case $PLATFORM in + linux|alpine) ;; + darwin|mac*) + PLATFORM="darwin" + ;; + mingw*|win*) + EXT="zip" + PLATFORM="win32" + ;; + *) + err "unsupported platform: $PLATFORM" + ;; + esac + + uname_m=$(uname -m) + ARCHITECTURE=$(tolower "${FOUNDRYUP_ARCH:-$uname_m}") + if [ "${ARCHITECTURE}" = "x86_64" ]; then + # Redirect stderr to /dev/null to avoid printing errors if non Rosetta. + if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" = "1" ]; then + ARCHITECTURE="arm64" # Rosetta. + else + ARCHITECTURE="amd64" # Intel. + fi + elif [ "${ARCHITECTURE}" = "arm64" ] ||[ "${ARCHITECTURE}" = "aarch64" ] ; then + ARCHITECTURE="arm64" # Arm. + else + ARCHITECTURE="amd64" # Amd. + fi + + # Compute the URL of the release tarball in the Foundry repository. + ARCHIVE_TAG=$(echo "$FOUNDRYUP_TAG" | tr '-' '_') + RELEASE_URL="https://github.com/${FOUNDRYUP_REPO}/releases/download/${FOUNDRYUP_TAG}/" + BIN_ARCHIVE_URL="${RELEASE_URL}${ARCHIVE_TAG}_${PLATFORM}_${ARCHITECTURE}.$EXT" + MAN_TAG=$(echo "$FOUNDRYUP_TAG" | sed 's/^foundry-zksync-//') + MAN_TARBALL_URL="${RELEASE_URL}foundry_zksync_man_${MAN_TAG}.tar.gz" + # TODO(zk): Migrate logic for verification of binaries from upstream script + + # Download and extract the binaries archive + say "downloading latest forge, and cast" + if [ "$PLATFORM" = "win32" ]; then + tmp="$(mktemp -d 2>/dev/null || echo ".")/foundry-zksync.zip" + ensure download "$BIN_ARCHIVE_URL" "$tmp" + ensure unzip "$tmp" -d "$FOUNDRY_VERSIONS_DIR/$FOUNDRYUP_TAG" + rm -f "$tmp" + else + ensure mkdir -p "$FOUNDRY_VERSIONS_DIR/$ARCHIVE_TAG" + ensure download "$BIN_ARCHIVE_URL" | ensure tar -xzC "$FOUNDRY_VERSIONS_DIR/$ARCHIVE_TAG" + fi + + # Optionally download the manuals + if check_cmd tar; then + say "downloading manpages" + mkdir -p "$FOUNDRY_MAN_DIR" + download "$MAN_TARBALL_URL" | tar -xzC "$FOUNDRY_MAN_DIR" + else + say 'skipping manpage download: missing "tar"' + fi + + if [ "$FOUNDRYUP_IGNORE_VERIFICATION" = true ]; then + say "skipped SHA verification for downloaded binaries due to --force flag" + else + # Verify the downloaded binaries against the attestation file. + # If the attestation file was not found or is empty, we skip the verification. + if $attestation_missing; then + say "no attestation found for these binaries, skipping SHA verification for downloaded binaries" + else + say "verifying downloaded binaries against the attestation file" + + failed=false + for bin in "${BINS[@]}"; do + expected="" + for i in "${!HASH_NAMES[@]}"; do + if [ "${HASH_NAMES[$i]}" = "$bin" ] || [ "${HASH_NAMES[$i]}" = "$bin.exe" ]; then + expected="${HASH_VALUES[$i]}" + break + fi + done + + path="$FOUNDRY_VERSIONS_DIR/$FOUNDRYUP_TAG/$bin" + + if [ -z "$expected" ]; then + say "no expected hash for $bin" + failed=true + continue + fi + + if [ ! -x "$path" ]; then + say "binary $bin not found at $path" + failed=true + continue + fi + + actual=$(compute_sha256 "$path") + if [ "$actual" != "$expected" ]; then + say "$bin hash verification failed:" + say " expected: $expected" + say " actual: $actual" + failed=true + else + say "$bin verified ✓" + fi + done + + if $failed; then + err "one or more binaries failed post-installation verification" + fi + fi + fi + + for bin in "${BINS[@]}"; do + bin_path="$FOUNDRY_BIN_DIR/$bin" + cp $FOUNDRY_VERSIONS_DIR/$ARCHIVE_TAG/$bin $bin_path + + # Print installed msg + say "installed - $(ensure "$bin_path" --version)" + + # Check if the default path of the binary is not in FOUNDRY_BIN_DIR + which_path="$(command -v "$bin" || true)" + if [ -n "$which_path" ] && [ "$which_path" != "$bin_path" ]; then + warn "" + cat 1>&2 < "$FOUNDRY_MAN_DIR/$bin.1" + done + fi + + say "done" + fi +} + +usage() { + cat 1>&2 < + +OPTIONS: + -h, --help Print help information + -v, --version Print the version of foundryup + -U, --update Update foundryup to the latest version + -i, --install Install a specific version from built binaries + -l, --list List versions installed from built binaries + -u, --use Use a specific installed version from built binaries + -b, --branch Build and install a specific branch + -P, --pr Build and install a specific Pull Request + -C, --commit Build and install a specific commit + -r, --repo Build and install from a remote GitHub repo (uses default branch if no other options are set) + -p, --path Build and install a local repository + -j, --jobs Number of CPUs to use for building Foundry (default: all CPUs) + -f, --force Skip SHA verification for downloaded binaries (INSECURE - use with caution) + --arch Install a specific architecture (supports amd64 and arm64) + --platform Install a specific platform (supports win32, linux, darwin and alpine) +EOF +} + +version() { + say "$FOUNDRYUP_INSTALLER_VERSION" + exit 0 +} + +update() { + say "updating foundryup..." + + current_version="$FOUNDRYUP_INSTALLER_VERSION" + + # Download the new version. + tmp_file="$(mktemp)" + ensure download "$FOUNDRY_BIN_URL" "$tmp_file" + + # Extract new version from downloaded file. + new_version=$(grep -Eo 'FOUNDRYUP_INSTALLER_VERSION="[0-9]+\.[0-9]+\.[0-9]+"' "$tmp_file" | cut -d'"' -f2) + + # If the new version could not be determined, exit gracefully. + # This prevents from upgrading to an empty or invalid version. + if [ -z "$new_version" ]; then + warn "could not determine new foundryup version. Exiting." + rm -f "$tmp_file" + exit 0 + fi + + # If the new version is not greater than the current version, skip the update. + # This is to prevent downgrades or unnecessary updates. + if ! version_gt "$new_version" "$current_version"; then + say "foundryup is already up to date (installed: $current_version, remote: $new_version)." + rm -f "$tmp_file" + exit 0 + fi + + # Overwrite existing foundryup + ensure mv "$tmp_file" "$FOUNDRY_BIN_PATH" + ensure chmod +x "$FOUNDRY_BIN_PATH" + + say "successfully updated foundryup: $current_version → $new_version" + exit 0 +} + +list() { + if [ -d "$FOUNDRY_VERSIONS_DIR" ]; then + for VERSION in $FOUNDRY_VERSIONS_DIR/*; do + say "${VERSION##*/}" + for bin in "${BINS[@]}"; do + bin_path="$VERSION/$bin" + say "- $(ensure "$bin_path" -V)" + done + printf "\n" + done + else + for bin in "${BINS[@]}"; do + bin_path="$FOUNDRY_BIN_DIR/$bin" + say "- $(ensure "$bin_path" -V)" + done + fi + exit 0 +} + +use() { + [ -z "$FOUNDRYUP_VERSION" ] && err "no version provided" + FOUNDRY_VERSION_DIR="$FOUNDRY_VERSIONS_DIR/$FOUNDRYUP_VERSION" + if [ -d "$FOUNDRY_VERSION_DIR" ]; then + + check_bins_in_use + + for bin in "${BINS[@]}"; do + bin_path="$FOUNDRY_BIN_DIR/$bin" + cp "$FOUNDRY_VERSION_DIR/$bin" "$bin_path" + # Print usage msg + say "use - $(ensure "$bin_path" -V)" + + # Check if the default path of the binary is not in FOUNDRY_BIN_DIR + which_path="$(command -v "$bin" || true)" + if [ -n "$which_path" ] && [ "$which_path" != "$bin_path" ]; then + warn "" + cat 1>&2 <&2 +} + +err() { + say "$1" >&2 + exit 1 +} + +tolower() { + echo "$1" | awk '{print tolower($0)}' +} + +compute_sha256() { + if check_cmd sha256sum; then + sha256sum "$1" | cut -d' ' -f1 + else + shasum -a 256 "$1" | awk '{print $1}' + fi +} + +need_cmd() { + if ! check_cmd "$1"; then + err "need '$1' (command not found)" + fi +} + +check_cmd() { + command -v "$1" &>/dev/null +} + +check_installer_up_to_date() { + say "checking if foundryup is up to date..." + + if check_cmd curl; then + remote_version=$(curl -fsSL "$FOUNDRY_BIN_URL" | grep -Eo 'FOUNDRYUP_INSTALLER_VERSION="[0-9]+\.[0-9]+\.[0-9]+"' | cut -d'"' -f2) + else + remote_version=$(wget -qO- "$FOUNDRY_BIN_URL" | grep -Eo 'FOUNDRYUP_INSTALLER_VERSION="[0-9]+\.[0-9]+\.[0-9]+"' | cut -d'"' -f2) + fi + + if [ -z "$remote_version" ]; then + warn "Could not determine remote foundryup version. Skipping version check." + return 0 + fi + + if version_gt "$remote_version" "$FOUNDRYUP_INSTALLER_VERSION"; then + printf ' +Your installation of foundryup is out of date. + +Installed: %s → Latest: %s + +To update, run: + + foundryup --update + +Updating is highly recommended as it gives you access to the latest features and bug fixes. + +' "$FOUNDRYUP_INSTALLER_VERSION" "$remote_version" >&2 + else + say "foundryup is up to date." + fi +} + +# Compares two version strings in the format "major.minor.patch". +# Returns 0 if $1 is greater than $2, 1 if $1 is less than $2, and 1 if they are equal. +# +# Assumes that the version strings are well-formed and contain three numeric components separated by dots. +# +# Example: version_gt "1.2.3" "1.2.4" +# returns 1 (1.2.3 < 1.2.4) +# version_gt "1.2.3" "1.2.3" +# returns 1 (1.2.3 == 1.2.3) +# version_gt "1.2.4" "1.2.3" +# returns 0 (1.2.4 > 1.2.3) +version_gt() { + [ "$1" = "$2" ] && return 1 + + IFS=. read -r major1 minor1 patch1 </dev/null; then + err "Error: '$bin' is currently running. Please stop the process and try again." + fi + done + else + warn "Make sure no foundry process is running during the install process!" + fi +} + +# Run a command that should never fail. If the command fails execution +# will immediately terminate with an error showing the failing command. +ensure() { + if ! "$@"; then err "command failed: $*"; fi +} + +# Downloads $1 into $2 or stdout +download() { + if [ -n "$2" ]; then + # output into $2 + if check_cmd curl; then + curl -#o "$2" -L "$1" + else + wget --show-progress -qO "$2" "$1" + fi + else + # output to stdout + if check_cmd curl; then + curl -#L "$1" + else + wget --show-progress -qO- "$1" + fi + fi +} + +# Banner prompt for Foundry +banner() { + printf ' + +.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx + + ╔═╗ ╔═╗ ╦ ╦ ╔╗╔ ╔╦╗ ╦═╗ ╦ ╦ Portable and modular toolkit + ╠╣ ║ ║ ║ ║ ║║║ ║║ ╠╦╝ ╚╦╝ for ZKsync Application Development + ╚ ╚═╝ ╚═╝ ╝╚╝ ═╩╝ ╩╚═ ╩ written in Rust. + +.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx + +Fork of : https://github.com/foundry-rs/ +Repo : https://github.com/matter-labs/foundry-zksync/ +Book : https://foundry-book.zksync.io/ + +.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx.xOx + +' + +} + +main "$@" diff --git a/package.json b/package.json index a8e9bbf2b..99a753026 100644 --- a/package.json +++ b/package.json @@ -70,5 +70,9 @@ "access": "public", "registry": "https://registry.npmjs.org" }, - "access": "public" + "access": "public", + "dependencies": { + "@solidity-parser/parser": "^0.20.2", + "toml": "^3.0.0" + } } diff --git a/scripts/zk-compilation/new-zk-compilation.ts b/scripts/zk-compilation/new-zk-compilation.ts new file mode 100644 index 000000000..8055d6a28 --- /dev/null +++ b/scripts/zk-compilation/new-zk-compilation.ts @@ -0,0 +1,125 @@ +// batch-compile-zk.ts +import fs from "fs"; +import path from "path"; +import { execSync } from "child_process"; +import toml from "toml"; +import { parse } from "@solidity-parser/parser"; + +const CONTRACTS_DIR = "contracts"; +const BATCH_SIZE = 20; // adjust as needed +const ZK_SOLC_BIN = "zk-solc"; // must be installed and in PATH +const BUILD_DIR = "zk-out"; + +// Load remappings from foundry.toml +function loadRemappings(): Record { + const foundryTomlPath = path.resolve("foundry.toml"); + if (!fs.existsSync(foundryTomlPath)) { + throw new Error("foundry.toml not found"); + } + const tomlData = toml.parse(fs.readFileSync(foundryTomlPath, "utf-8")); + const remappings: Record = {}; + + if (tomlData.profile?.default?.remappings || tomlData.remappings) { + const remapList: string[] = tomlData.profile?.default?.remappings || tomlData.remappings || []; + remapList.forEach((r) => { + const [prefix, target] = r.split("="); + remappings[prefix.trim()] = target.trim(); + }); + } + return remappings; +} + +// Find all Solidity files in contracts/ +function getAllContracts(): string[] { + const files: string[] = []; + function walk(dir: string) { + fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) walk(fullPath); + else if (entry.isFile() && entry.name.endsWith(".sol")) files.push(fullPath); + }); + } + walk(CONTRACTS_DIR); + return files; +} + +// Parse imports for a Solidity file +function getImports(filePath: string): string[] { + const content = fs.readFileSync(filePath, "utf-8"); + let imports: string[] = []; + try { + const ast = parse(content, { tolerant: true }); + ast.children.forEach((node: any) => { + if (node.type === "ImportDirective") { + imports.push(node.path); + } + }); + } catch (err) { + console.error(`Failed to parse ${filePath}:`, err); + } + return imports; +} + +// Resolve import path to actual file +function resolveImport(importPath: string, remappings: Record): string { + for (const prefix in remappings) { + if (importPath.startsWith(prefix)) { + return path.resolve(remappings[prefix], importPath.slice(prefix.length)); + } + } + return path.resolve(CONTRACTS_DIR, importPath); +} + +// Build dependency graph +function buildDependencyGraph(files: string[], remappings: Record) { + const graph: Record> = {}; + files.forEach((file) => { + const imports = getImports(file).map((imp) => resolveImport(imp, remappings)); + graph[file] = new Set(imports.filter((f) => fs.existsSync(f) && f.endsWith(".sol"))); + }); + return graph; +} + +// Topological sort +function topoSort(graph: Record>): string[] { + const visited = new Set(); + const result: string[] = []; + + function visit(node: string) { + if (visited.has(node)) return; + visited.add(node); + (graph[node] || []).forEach(visit); + result.push(node); + } + + Object.keys(graph).forEach(visit); + return result; +} + +// Batch compile +function batchCompile(files: string[]) { + console.log(`Compiling ${files.length} contracts in batches of ${BATCH_SIZE}...`); + for (let i = 0; i < files.length; i++) { + const contract = files[i]; + console.log(`\n[${i + 1}/${files.length}] Compiling ${contract} ...`); + try { + execSync( + `forge build --zksync --contracts ${contract}`, + { stdio: "inherit" } + ); + } catch (err) { + console.error(`Error compiling ${contract}:`, err); + process.exit(1); + } + } +} + +function main() { + const remappings = loadRemappings(); + const allFiles = getAllContracts(); + const depGraph = buildDependencyGraph(allFiles, remappings); + const sortedFiles = topoSort(depGraph); + batchCompile(sortedFiles); +} + +main(); diff --git a/scripts/zk-compilation/zk-compilation.ts b/scripts/zk-compilation/zk-compilation.ts new file mode 100644 index 000000000..946261534 --- /dev/null +++ b/scripts/zk-compilation/zk-compilation.ts @@ -0,0 +1,118 @@ +import fs from "fs-extra"; +import path from "path"; +import { execSync } from "child_process"; + +// === Directories === +const contractsDir = path.resolve(__dirname, "../contracts"); +const zkArtifactsDir = path.resolve(__dirname, "../zk-artifacts"); +const zkBundleDir = path.resolve(__dirname, "../zk_contract_artifacts"); + +// === Recursively find all .sol files === +async function getAllSolidityFiles(dir: string): Promise { + const dirents = await fs.readdir(dir, { withFileTypes: true }); + const files = await Promise.all( + dirents.map(async (dirent) => { + const res = path.join(dir, dirent.name); + return dirent.isDirectory() ? await getAllSolidityFiles(res) : res; + }), + ); + return files.flat().filter(file => file.endsWith(".sol")); +} + +// === Build dependency graph based on import statements === +async function buildDependencyGraph(files: string[]): Promise> { + const graph = new Map(); + const importRegex = /import\s+["'](.+)["'];/g; + + for (const file of files) { + const content = await fs.readFile(file, "utf8"); + const imports: string[] = []; + + let match: RegExpExecArray | null; + while ((match = importRegex.exec(content)) !== null) { + const importPath = match[1]; + const resolvedPath = path.resolve(path.dirname(file), importPath); + imports.push(resolvedPath); + } + + graph.set(path.resolve(file), imports); + } + + return graph; +} + +// === Topological sort === +function topologicalSort(graph: Map): string[] { + const visited = new Set(); + const result: string[] = []; + + function visit(file: string) { + if (visited.has(file)) return; + visited.add(file); + + const deps = graph.get(file) || []; + for (const dep of deps) { + visit(dep); + } + + result.push(file); + } + + for (const file of graph.keys()) { + visit(file); + } + + return result; +} + +// === Compile a single contract with zk-solc === +function compileZK(contractPath: string) { + console.log(`🛠 Compiling: ${contractPath}`); + try { + execSync( + `zk-solc --sol ${contractPath} --circuit --out ${zkArtifactsDir}`, + { stdio: "inherit" } + ); + } catch (err) { + console.error(`❌ Failed to compile ${contractPath}:`, (err as Error).message); + } +} + +// === Copy compiled artifacts to bundle directory === +async function bundleArtifacts() { + await fs.ensureDir(zkBundleDir); + const artifactFiles = await fs.readdir(zkArtifactsDir); + for (const file of artifactFiles) { + const src = path.join(zkArtifactsDir, file); + const dst = path.join(zkBundleDir, file); + await fs.copy(src, dst); + } + console.log(`📦 ZK artifacts bundled to: ${zkBundleDir}`); +} + +// === Main === +async function main() { + console.log("🔍 Searching for Solidity files..."); + const allSolFiles = await getAllSolidityFiles(contractsDir); + + console.log("🧩 Building dependency graph..."); + const dependencyGraph = await buildDependencyGraph(allSolFiles); + + console.log("📐 Sorting contracts by dependency..."); + const sortedContracts = topologicalSort(dependencyGraph); + + console.log("🚀 Compiling contracts..."); + for (const contract of sortedContracts) { + compileZK(contract); + } + + console.log("📦 Bundling artifacts..."); + await bundleArtifacts(); + + console.log("✅ ZK compilation complete."); +} + +main().catch((err) => { + console.error("🔥 Script failed:", err); + process.exit(1); +}); diff --git a/yarn.lock b/yarn.lock index b446e0d3c..4dc2d0a2a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -534,6 +534,11 @@ resolved "https://registry.yarnpkg.com/@solidity-parser/parser/-/parser-0.17.0.tgz#52a2fcc97ff609f72011014e4c5b485ec52243ef" integrity sha512-Nko8R0/kUo391jsEHHxrGM07QFdnPGvlmox4rmH0kNiNAashItAilhy4Mv4pK5gQmW5f4sXAF58fwJbmlkGcVw== +"@solidity-parser/parser@^0.20.2": + version "0.20.2" + resolved "https://registry.yarnpkg.com/@solidity-parser/parser/-/parser-0.20.2.tgz#e07053488ed60dae1b54f6fe37bb6d2c5fe146a7" + integrity sha512-rbu0bzwNvMcwAjH86hiEAcOeRI2EeK8zCkHDrFykh/Al8mvJeFmjy3UrE7GYQjNwOgbGUUtCn5/k8CB8zIu7QA== + "@thirdweb-dev/dynamic-contracts@^1.2.4": version "1.2.5" resolved "https://registry.yarnpkg.com/@thirdweb-dev/dynamic-contracts/-/dynamic-contracts-1.2.5.tgz#f9735c0d46198e7bf2f98c277f0a9a79c54da1e8" @@ -2511,7 +2516,16 @@ string-format@^2.0.0: resolved "https://registry.yarnpkg.com/string-format/-/string-format-2.0.0.tgz#f2df2e7097440d3b65de31b6d40d54c96eaffb9b" integrity sha512-bbEs3scLeYNXLecRRuk6uJxdXUSj6le/8rNPHChIJTn2V79aXVTR1EH2OH5zLKKoz0V02fOUKZZcw01pLUShZA== -"string-width-cjs@npm:string-width@^4.2.0", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -2536,7 +2550,14 @@ string_decoder@^1.1.1: dependencies: safe-buffer "~5.2.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -2641,6 +2662,11 @@ to-regex-range@^5.0.1: dependencies: is-number "^7.0.0" +toml@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/toml/-/toml-3.0.0.tgz#342160f1af1904ec9d204d03a5d61222d762c5ee" + integrity sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w== + tr46@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/tr46/-/tr46-1.0.1.tgz#a8b13fd6bfd2489519674ccde55ba3693b706d09" @@ -2848,7 +2874,16 @@ workerpool@6.2.0: resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.2.0.tgz#827d93c9ba23ee2019c3ffaff5c27fccea289e8b" integrity sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== From 637180a2b5c275dd1260dabc3e5c04ee64bbc953 Mon Sep 17 00:00:00 2001 From: Gonzalo Bustos Date: Wed, 13 Aug 2025 08:35:12 -0300 Subject: [PATCH 2/3] fix: zk compilation --- package.json | 3 +- scripts/zk-compilation/new-zk-compilation.ts | 125 ------------ scripts/zk-compilation/zk-compilation.ts | 202 +++++++++++-------- tsconfig.json | 2 +- 4 files changed, 122 insertions(+), 210 deletions(-) delete mode 100644 scripts/zk-compilation/new-zk-compilation.ts diff --git a/package.json b/package.json index 99a753026..779e58546 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,8 @@ "gas": "forge snapshot --isolate --mc Benchmark --gas-report --diff .gas-snapshot > gasreport.txt", "forge:snapshot": "forge snapshot --check", "aabenchmark": "forge test --mc AABenchmarkPrepare && forge test --mc ProfileThirdwebAccount -vvv", - "release": "npm publish" + "release": "npm publish", + "compile-zk": "npx ts-node scripts/zk-compilation/zk-compilation.ts" }, "publishConfig": { "access": "public", diff --git a/scripts/zk-compilation/new-zk-compilation.ts b/scripts/zk-compilation/new-zk-compilation.ts deleted file mode 100644 index 8055d6a28..000000000 --- a/scripts/zk-compilation/new-zk-compilation.ts +++ /dev/null @@ -1,125 +0,0 @@ -// batch-compile-zk.ts -import fs from "fs"; -import path from "path"; -import { execSync } from "child_process"; -import toml from "toml"; -import { parse } from "@solidity-parser/parser"; - -const CONTRACTS_DIR = "contracts"; -const BATCH_SIZE = 20; // adjust as needed -const ZK_SOLC_BIN = "zk-solc"; // must be installed and in PATH -const BUILD_DIR = "zk-out"; - -// Load remappings from foundry.toml -function loadRemappings(): Record { - const foundryTomlPath = path.resolve("foundry.toml"); - if (!fs.existsSync(foundryTomlPath)) { - throw new Error("foundry.toml not found"); - } - const tomlData = toml.parse(fs.readFileSync(foundryTomlPath, "utf-8")); - const remappings: Record = {}; - - if (tomlData.profile?.default?.remappings || tomlData.remappings) { - const remapList: string[] = tomlData.profile?.default?.remappings || tomlData.remappings || []; - remapList.forEach((r) => { - const [prefix, target] = r.split("="); - remappings[prefix.trim()] = target.trim(); - }); - } - return remappings; -} - -// Find all Solidity files in contracts/ -function getAllContracts(): string[] { - const files: string[] = []; - function walk(dir: string) { - fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => { - const fullPath = path.join(dir, entry.name); - if (entry.isDirectory()) walk(fullPath); - else if (entry.isFile() && entry.name.endsWith(".sol")) files.push(fullPath); - }); - } - walk(CONTRACTS_DIR); - return files; -} - -// Parse imports for a Solidity file -function getImports(filePath: string): string[] { - const content = fs.readFileSync(filePath, "utf-8"); - let imports: string[] = []; - try { - const ast = parse(content, { tolerant: true }); - ast.children.forEach((node: any) => { - if (node.type === "ImportDirective") { - imports.push(node.path); - } - }); - } catch (err) { - console.error(`Failed to parse ${filePath}:`, err); - } - return imports; -} - -// Resolve import path to actual file -function resolveImport(importPath: string, remappings: Record): string { - for (const prefix in remappings) { - if (importPath.startsWith(prefix)) { - return path.resolve(remappings[prefix], importPath.slice(prefix.length)); - } - } - return path.resolve(CONTRACTS_DIR, importPath); -} - -// Build dependency graph -function buildDependencyGraph(files: string[], remappings: Record) { - const graph: Record> = {}; - files.forEach((file) => { - const imports = getImports(file).map((imp) => resolveImport(imp, remappings)); - graph[file] = new Set(imports.filter((f) => fs.existsSync(f) && f.endsWith(".sol"))); - }); - return graph; -} - -// Topological sort -function topoSort(graph: Record>): string[] { - const visited = new Set(); - const result: string[] = []; - - function visit(node: string) { - if (visited.has(node)) return; - visited.add(node); - (graph[node] || []).forEach(visit); - result.push(node); - } - - Object.keys(graph).forEach(visit); - return result; -} - -// Batch compile -function batchCompile(files: string[]) { - console.log(`Compiling ${files.length} contracts in batches of ${BATCH_SIZE}...`); - for (let i = 0; i < files.length; i++) { - const contract = files[i]; - console.log(`\n[${i + 1}/${files.length}] Compiling ${contract} ...`); - try { - execSync( - `forge build --zksync --contracts ${contract}`, - { stdio: "inherit" } - ); - } catch (err) { - console.error(`Error compiling ${contract}:`, err); - process.exit(1); - } - } -} - -function main() { - const remappings = loadRemappings(); - const allFiles = getAllContracts(); - const depGraph = buildDependencyGraph(allFiles, remappings); - const sortedFiles = topoSort(depGraph); - batchCompile(sortedFiles); -} - -main(); diff --git a/scripts/zk-compilation/zk-compilation.ts b/scripts/zk-compilation/zk-compilation.ts index 946261534..6b31e93e2 100644 --- a/scripts/zk-compilation/zk-compilation.ts +++ b/scripts/zk-compilation/zk-compilation.ts @@ -1,118 +1,154 @@ -import fs from "fs-extra"; +#!/usr/bin/env ts-node + +import fs from "fs"; import path from "path"; import { execSync } from "child_process"; +import toml from "toml"; + +type DependencyGraph = Record>; + +const contractsDir = path.resolve("contracts"); +const outDir = path.resolve("out"); +const foundryTomlPath = path.resolve("foundry.toml"); + +// ===== Load remappings from foundry.toml ===== +function loadRemappings(): Record { + const tomlContent = fs.readFileSync(foundryTomlPath, "utf8"); + const parsed = toml.parse(tomlContent); + const remappingsArray: string[] = parsed.remappings || []; + const remappings: Record = {}; -// === Directories === -const contractsDir = path.resolve(__dirname, "../contracts"); -const zkArtifactsDir = path.resolve(__dirname, "../zk-artifacts"); -const zkBundleDir = path.resolve(__dirname, "../zk_contract_artifacts"); - -// === Recursively find all .sol files === -async function getAllSolidityFiles(dir: string): Promise { - const dirents = await fs.readdir(dir, { withFileTypes: true }); - const files = await Promise.all( - dirents.map(async (dirent) => { - const res = path.join(dir, dirent.name); - return dirent.isDirectory() ? await getAllSolidityFiles(res) : res; - }), - ); - return files.flat().filter(file => file.endsWith(".sol")); + for (const mapping of remappingsArray) { + const [key, val] = mapping.split("="); + remappings[key.trim()] = val.trim(); + } + + return remappings; } -// === Build dependency graph based on import statements === -async function buildDependencyGraph(files: string[]): Promise> { - const graph = new Map(); - const importRegex = /import\s+["'](.+)["'];/g; +const remappings = loadRemappings(); - for (const file of files) { - const content = await fs.readFile(file, "utf8"); - const imports: string[] = []; - - let match: RegExpExecArray | null; - while ((match = importRegex.exec(content)) !== null) { - const importPath = match[1]; - const resolvedPath = path.resolve(path.dirname(file), importPath); - imports.push(resolvedPath); +// ===== Utility: Resolve imports with remappings ===== +function resolveImport(importPath: string): string { + for (const [prefix, target] of Object.entries(remappings)) { + if (importPath.startsWith(prefix)) { + return path.resolve(target, importPath.replace(prefix, "")); } + } + if (importPath.startsWith(".")) { + return path.resolve(importPath); + } + return importPath; // leave unresolved if external +} - graph.set(path.resolve(file), imports); +// ===== Find all .sol files ===== +function findSolFiles(dir: string): string[] { + let results: string[] = []; + for (const file of fs.readdirSync(dir)) { + const full = path.join(dir, file); + if (fs.statSync(full).isDirectory()) { + results = results.concat(findSolFiles(full)); + } else if (file.endsWith(".sol")) { + results.push(full); + } } + return results; +} +// ===== Parse imports from a Solidity file ===== +function parseImports(filePath: string): string[] { + const content = fs.readFileSync(filePath, "utf8"); + const regex = /^\s*import\s+["']([^"']+)["'];/gm; + const imports: string[] = []; + let match; + while ((match = regex.exec(content)) !== null) { + imports.push(match[1]); + } + return imports; +} + +// ===== Build dependency graph ===== +function buildDependencyGraph(files: string[]): DependencyGraph { + const graph: DependencyGraph = {}; + for (const file of files) { + const imports = parseImports(file).map(resolveImport); + graph[file] = new Set(); + for (const imp of imports) { + if (imp.endsWith(".sol") && fs.existsSync(imp)) { + graph[file].add(path.resolve(imp)); + } + } + } return graph; } -// === Topological sort === -function topologicalSort(graph: Map): string[] { +// ===== Topological sort ===== +function topologicalSort(graph: DependencyGraph): string[] { const visited = new Set(); const result: string[] = []; - function visit(file: string) { - if (visited.has(file)) return; - visited.add(file); - - const deps = graph.get(file) || []; - for (const dep of deps) { + function visit(node: string) { + if (visited.has(node)) return; + visited.add(node); + for (const dep of graph[node] || []) { visit(dep); } - - result.push(file); + result.push(node); } - for (const file of graph.keys()) { - visit(file); + for (const node of Object.keys(graph)) { + visit(node); } - return result; } -// === Compile a single contract with zk-solc === -function compileZK(contractPath: string) { - console.log(`🛠 Compiling: ${contractPath}`); - try { - execSync( - `zk-solc --sol ${contractPath} --circuit --out ${zkArtifactsDir}`, - { stdio: "inherit" } - ); - } catch (err) { - console.error(`❌ Failed to compile ${contractPath}:`, (err as Error).message); +// ===== Compile contracts in order (with error logging) ===== +function compileContractsInOrder(sortedFiles: string[]) { + const compiled = new Set(); + const failedContracts: string[] = []; + + for (const file of sortedFiles) { + if (compiled.has(file)) continue; + + console.log(`\n=== Compiling ${file} ===`); + try { + execSync( + `forge build ${file} --zksync --out ${outDir}`, + { stdio: "inherit" } + ); + compiled.add(file); + } catch (err) { + console.error(`❌ Error compiling ${file}:`, (err as Error).message); + failedContracts.push(file); + // Continue with next file instead of exiting + } } -} -// === Copy compiled artifacts to bundle directory === -async function bundleArtifacts() { - await fs.ensureDir(zkBundleDir); - const artifactFiles = await fs.readdir(zkArtifactsDir); - for (const file of artifactFiles) { - const src = path.join(zkArtifactsDir, file); - const dst = path.join(zkBundleDir, file); - await fs.copy(src, dst); + if (failedContracts.length > 0) { + console.log("\n=== Compilation finished with errors ==="); + failedContracts.forEach((f) => console.log(` - ${f}`)); + } else { + console.log("\n🎉 All contracts compiled successfully"); } - console.log(`📦 ZK artifacts bundled to: ${zkBundleDir}`); } -// === Main === -async function main() { - console.log("🔍 Searching for Solidity files..."); - const allSolFiles = await getAllSolidityFiles(contractsDir); - - console.log("🧩 Building dependency graph..."); - const dependencyGraph = await buildDependencyGraph(allSolFiles); +// ===== Main ===== +function main() { + if (!fs.existsSync(outDir)) fs.mkdirSync(outDir); - console.log("📐 Sorting contracts by dependency..."); - const sortedContracts = topologicalSort(dependencyGraph); + console.log("Scanning Solidity contracts..."); + const allFiles = findSolFiles(contractsDir); + console.log(`Found ${allFiles.length} contracts.`); - console.log("🚀 Compiling contracts..."); - for (const contract of sortedContracts) { - compileZK(contract); - } + console.log("Building dependency graph..."); + const graph = buildDependencyGraph(allFiles); - console.log("📦 Bundling artifacts..."); - await bundleArtifacts(); + console.log("Sorting contracts (topological order)..."); + const sortedFiles = topologicalSort(graph); + console.log(`Compilation order:`); + sortedFiles.forEach((f, i) => console.log(`${i + 1}. ${f}`)); - console.log("✅ ZK compilation complete."); + compileContractsInOrder(sortedFiles); } -main().catch((err) => { - console.error("🔥 Script failed:", err); - process.exit(1); -}); +main(); diff --git a/tsconfig.json b/tsconfig.json index 26726ee42..87c6e1735 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -31,7 +31,7 @@ "forceConsistentCasingInFileNames": true, // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc` "noEmit": true, - "target": "es5", + "target": "es2015", "module": "commonjs", }, "ts-node": { From afac1ee34642eb2a3240ac1a529832147c37a794 Mon Sep 17 00:00:00 2001 From: Gonzalo Bustos Date: Wed, 13 Aug 2025 08:37:29 -0300 Subject: [PATCH 3/3] fix: remove sh script --- batch-compile-zk.sh | 77 --------------------------------------------- 1 file changed, 77 deletions(-) delete mode 100755 batch-compile-zk.sh diff --git a/batch-compile-zk.sh b/batch-compile-zk.sh deleted file mode 100755 index bce1ce558..000000000 --- a/batch-compile-zk.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -CONTRACTS_DIR="contracts" -COMPILED=() # array of compiled contract absolute paths - -# To track compiled contracts quickly -declare -A compiled_map - -compiled_count=0 -total_contracts=0 - -# Find all contracts under contracts directory -mapfile -t all_contracts < <(find "$CONTRACTS_DIR" -type f -name "*.sol") - -total_contracts=${#all_contracts[@]} - -echo "Found $total_contracts contracts under $CONTRACTS_DIR" - -# Resolve imports and compile recursively -compile_contract() { - local contract_path="$1" - # Normalize path to absolute - contract_path=$(realpath "$contract_path") - - # Check if already compiled - if [[ ${compiled_map["$contract_path"]+exists} ]]; then - return - fi - - # Parse imports (assumes imports are relative paths or absolute within repo) - # Matches: import "path"; - local imports=() - while IFS= read -r line; do - line=$(echo "$line" | xargs) - if echo "$line" | grep -qE '^import[[:space:]]+"[^"]+"[[:space:]]*;'; then - imp=$(echo "$line" | sed -E 's|^import[[:space:]]+"([^"]+)".*|\1|') - local contract_dir - contract_dir=$(dirname "$contract_path") - - local imp_path - if [[ "$imp" == /* ]]; then - imp_path="$imp" - else - imp_path="$contract_dir/$imp" - fi - - imp_path=$(realpath "$imp_path") - - if [[ -f "$imp_path" ]]; then - imports+=("$imp_path") - else - echo "Warning: import $imp_path not found for $contract_path" - fi - fi - done < "$contract_path" - - - # Recursively compile dependencies first - for dep in "${imports[@]}"; do - compile_contract "$dep" - done - - # Now compile this contract individually with zk flag - echo "Compiling $contract_path ..." - forge build --zksync --contracts "$contract_path" - compiled_map["$contract_path"]=1 - ((compiled_count++)) - echo "Compiled $compiled_count / $total_contracts contracts." -} - -# Iterate over all contracts found and compile them (will skip already compiled) -for contract in "${all_contracts[@]}"; do - compile_contract "$contract" -done - -echo "Compilation done. Total contracts compiled: $compiled_count"