sails_cli/
solgen.rs

1use anyhow::{Result, bail};
2use sails_sol_gen::generate_solidity_contract;
3use std::path::PathBuf;
4
5pub struct SolidityGenerator {
6    idl_path: PathBuf,
7    target_dir: PathBuf,
8    contract_name: Option<String>,
9}
10
11impl SolidityGenerator {
12    pub fn new(
13        idl_path: PathBuf,
14        target_dir: Option<PathBuf>,
15        contract_name: Option<String>,
16    ) -> Self {
17        Self {
18            idl_path,
19            target_dir: target_dir.unwrap_or_default(),
20            contract_name,
21        }
22    }
23
24    pub fn generate(&self) -> Result<()> {
25        let idl_content = std::fs::read_to_string(&self.idl_path)?;
26
27        let filename = if let Some(stem) = self.idl_path.file_stem() {
28            stem.to_string_lossy()
29        } else {
30            bail!("No filename found");
31        };
32
33        let unformatted_contract_name = self.contract_name.clone().unwrap_or(filename.to_string());
34
35        let contract = generate_solidity_contract(&idl_content, &unformatted_contract_name)?;
36
37        let target_file = self.target_dir.join(format!("{}.sol", &contract.name));
38
39        std::fs::write(&target_file, contract.data)?;
40
41        println!("Generated contract: {target_file:?}");
42
43        Ok(())
44    }
45}