clockwork_anchor_generate_cpi_interface/lib.rs
1//! Generates a crate for cross-program invocations to an Anchor program from a JSON IDL.
2//!
3//! # Usage
4//!
5//! In a new crate, write:
6//!
7//! ```skip
8//! anchor_gen::generate_cpi_crate!("../../examples/govern-cpi/idl.json");
9//!
10//! declare_id!("GjphYQcbP1m3FuDyCTUJf2mUMxKPE3j6feWU1rxvC7Ps");
11//! ```
12//!
13//! This will generate a fully functional Rust CPI client for your IDL.
14//!
15//! More examples can be found in the [examples/](https://github.com/saber-hq/anchor-gen/tree/master/examples) directory.
16
17use clockwork_anchor_idl::GeneratorOptions;
18use darling::FromMeta;
19use proc_macro::TokenStream;
20use syn::parse_macro_input;
21
22/// Generates an Anchor CPI crate from a JSON file.
23///
24/// # Arguments
25///
26/// * `idl_path` - Path to a JSON IDL relative to the crate's the Cargo.toml.
27///
28/// # Examples
29///
30/// ```
31/// anchor_generate_cpi_interface::generate_cpi_interface!(idl_path = "../../examples/govern-cpi/idl.json");
32/// declare_id!("GjphYQcbP1m3FuDyCTUJf2mUMxKPE3j6feWU1rxvC7Ps");
33/// # fn main() -> Result<()> {
34/// let _my_governor = GovernanceParameters {
35/// quorum_votes: 0,
36/// timelock_delay_seconds: 0,
37/// voting_period: 0,
38/// voting_delay: 0,
39/// };
40/// # Ok(())
41/// # }
42/// ```
43#[proc_macro]
44pub fn generate_cpi_interface(input: proc_macro::TokenStream) -> TokenStream {
45 let attr_args = parse_macro_input!(input as syn::AttributeArgs);
46 let parsed = match GeneratorOptions::from_list(&attr_args) {
47 Ok(v) => v,
48 Err(e) => {
49 return TokenStream::from(e.write_errors());
50 }
51 };
52 parsed.to_generator().generate_cpi_interface().into()
53}