Skip to main content

ab_contracts_tooling/
build.rs

1//! Build an ELF `cdylib` with the contract
2
3use crate::target_specification::TARGET_SPECIFICATION_NAME;
4use anyhow::Context;
5use cargo_metadata::MetadataCommand;
6use std::env;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use tracing::debug;
10
11/// Options for building a contract
12#[derive(Debug)]
13pub struct BuildOptions<'a> {
14    /// Package to build.
15    ///
16    /// A package in the current directory is built if not specified explicitly.
17    pub package: Option<&'a str>,
18    /// Comma separated list of features to activate
19    pub features: Option<&'a str>,
20    /// Do not activate the `default` feature
21    pub no_default_features: bool,
22    /// Build artifacts with the specified profile
23    pub profile: &'a str,
24    /// Path to the target specification JSON file
25    pub target_specification_path: &'a Path,
26    /// Custom target directory to use instead of the default one
27    pub target_dir: Option<&'a Path>,
28}
29
30/// Build a `cdylib` with the contract and return the path to the resulting ELF file
31pub fn build_cdylib(options: BuildOptions<'_>) -> anyhow::Result<PathBuf> {
32    let BuildOptions {
33        package,
34        features,
35        no_default_features,
36        profile,
37        target_specification_path,
38        target_dir,
39    } = options;
40
41    let mut command_builder = Command::new("cargo");
42    command_builder
43        .env_remove("RUSTFLAGS")
44        .env_remove("CARGO_ENCODED_RUSTFLAGS")
45        // Remove Clippy's wrapper in place that makes Cargo fingerprint contract artifacts
46        // differently under `cargo clippy` than under `cargo build`, rebuilding all of them on
47        // every switch between the two
48        .env_remove("RUSTC_WORKSPACE_WRAPPER")
49        // Hack for enabling RISC-V Zknh backend in `sha2` crate since it is a nightly-only feature,
50        // and they really don't like using normal features for it.
51        .env(
52            "RUSTFLAGS",
53            r#"--cfg sha2_backend="riscv-zknh" --cfg sha2_backend_riscv_zknh="compact""#,
54        )
55        .args([
56            "rustc",
57            "-Zbuild-std=core",
58            "--crate-type",
59            "cdylib",
60            "-Zjson-target-spec",
61            "--target",
62            target_specification_path
63                .to_str()
64                .context("Path to target specification file is not valid UTF-8")?,
65        ]);
66
67    if env::var("MIRI_SYSROOT").is_ok() {
68        command_builder
69            .env_remove("RUSTC")
70            .env_remove("RUSTC_WRAPPER");
71    }
72
73    if let Some(package) = package {
74        command_builder.args([
75            "--package",
76            package,
77            "--features",
78            &format!("{package}/guest"),
79        ]);
80    } else {
81        command_builder.args(["--features", "guest"]);
82    }
83    if let Some(features) = features {
84        command_builder.args(["--features", features]);
85    }
86    if no_default_features {
87        command_builder.arg("--no-default-features");
88    }
89
90    command_builder.args(["--profile", profile]);
91
92    let metadata = MetadataCommand::new()
93        .exec()
94        .context("Failed to fetch cargo metadata")?;
95
96    let target_directory = if let Some(target_dir) = target_dir {
97        command_builder.args([
98            "--target-dir",
99            target_dir
100                .to_str()
101                .context("Path to target directory is not valid UTF-8")?,
102        ]);
103        target_dir
104    } else {
105        metadata.target_directory.as_std_path()
106    };
107
108    let cdylib_path = target_directory
109        .join(TARGET_SPECIFICATION_NAME)
110        .join(if profile == "dev" { "debug" } else { profile })
111        .join({
112            let package_name = if let Some(package) = package {
113                package
114            } else {
115                let current_dir = env::current_dir().context("Failed to get current directory")?;
116                let current_manifest = current_dir.join("Cargo.toml");
117                metadata
118                    .packages
119                    .iter()
120                    .find_map(|package| {
121                        if package.manifest_path == current_manifest {
122                            Some(&package.name)
123                        } else {
124                            None
125                        }
126                    })
127                    .context("Failed to find package name")?
128            };
129
130            format!("{}.contract.so", package_name.replace('-', "_"))
131        });
132
133    debug!(
134        ?package,
135        ?features,
136        ?profile,
137        ?target_specification_path,
138        cdylib_path = ?cdylib_path,
139        command = ?command_builder,
140        "Building ELF `cdylib` contract"
141    );
142
143    let status = command_builder
144        .status()
145        .context("Failed to build a contract")?;
146
147    if !status.success() {
148        return Err(anyhow::anyhow!("Failed to build a contract"));
149    }
150
151    Ok(cdylib_path)
152}