substreams_antelope_abigen/
lib.rs

1pub mod abi;
2pub mod action;
3pub mod assert;
4pub mod build;
5pub mod contract;
6pub mod decoder;
7pub mod field;
8pub mod rust;
9pub mod ty;
10pub mod type_alias;
11pub mod types;
12
13pub use build::Abigen;
14
15use anyhow::format_err;
16use std::{
17    env, fs,
18    io::{BufReader, Read},
19    path::{Path, PathBuf},
20};
21
22use abi::ABI;
23use substreams_antelope_core::errors::Error;
24
25pub fn generate_abi_code<S: AsRef<str>>(path: S) -> Result<proc_macro2::TokenStream, anyhow::Error> {
26    let normalized_path = normalize_path(path.as_ref())?;
27    let source_file = fs::File::open(normalized_path).map_err(|_| Error::AbiLoadError)?;
28    let mut reader = BufReader::new(source_file);
29    let mut contents = String::new();
30    reader.read_to_string(&mut contents)?;
31
32    let (contract, account_name) = match ABI::try_from(contents.as_str()) {
33        Ok(c) => (c, None),
34        Err(_) => {
35            let w = abi::WrappedABI::try_from(contents.as_str())?;
36            (w.abi, Some(w.account_name))
37        }
38    };
39    let c = contract::Contract::from(contract);
40    Ok(c.generate(account_name))
41}
42
43pub fn normalize_path<S: AsRef<Path>>(relative_path: S) -> Result<PathBuf, anyhow::Error> {
44    // workaround for https://github.com/rust-lang/rust/issues/43860
45    let cargo_toml_directory = env::var("CARGO_MANIFEST_DIR").map_err(|_| format_err!("Cannot find manifest file"))?;
46    let mut path: PathBuf = cargo_toml_directory.into();
47    path.push(relative_path);
48    Ok(path)
49}