I have a set of enum types that define the format for interacting with a contract. Example:
enum ExecuteMsg {
BeforeTrade {},
AfterTrade { loan_fee: Uint128 },
SetVault { address: String },
}
Each contract has its own unique ExecuteMsg. I would like to derive a trait on these enums that generates a constructor function for each variant of the enum.
ExecuteMsg::execute_before_trade () -> json::Value
ExecuteMsg::execute_after_trade ( loan_fee: Uint128 ) -> json::Value
ExecuteMsg::execute_set_vault (address: String ) -> json::Value
I found a stack overflow explaining how to deconstruct an enum and generate functions based on that using procedural macros.
I'm stuck on deconstructing the variant fields and requiring them as function attributes.
let fields_in_variant = match &variant.fields {
Fields::Unnamed(_) => quote_spanned! {variant.span()=> (..) },
Fields::Unit => quote_spanned! { variant.span()=> },
Fields::Named(fields_temp) => {
// do something with these fields
quote_spanned! {variant.span()=> {..} }
}
};
// construct an identifier named execute_<variant_name> for function name
// We convert it to snake case using `to_case(Case::Snake)`
let mut variant_func_name =
format_ident!("execute_{}", variant_name.to_string().to_case(Case::Snake));
variant_func_name.set_span(variant_name.span());
// Here we construct the function for the current variant
variant_checker_functions.extend(quote_spanned! {variant.span()=>
fn #variant_func_name(&self, /* Require the variant fields */ ) -> json::Value {
...
}
});
How do I specify the required function attributes in the generated function?