Skip to content

Commit

Permalink
Added unnamed variant to execute fns
Browse files Browse the repository at this point in the history
  • Loading branch information
Kayanski committed Aug 24, 2023
1 parent dda4215 commit 0cafc1c
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 10 deletions.
26 changes: 24 additions & 2 deletions contracts/mock_contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ mod custom_resp;

use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::{
to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult,
to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdError, StdResult, Uint128,
};
use serde::Serialize;

Expand All @@ -29,6 +29,9 @@ where
FourthMessage,
#[cfg_attr(feature = "interface", payable)]
FifthMessage,
SixthMessage(u64, String),
#[cfg_attr(feature = "interface", payable)]
SeventhMessage(Uint128, String),
}

#[cw_serde]
Expand All @@ -48,6 +51,8 @@ where
},
#[returns(String)]
ThirdQuery,
#[returns(u64)]
FourthQuery(u64, String),
}

#[cw_serde]
Expand Down Expand Up @@ -91,6 +96,16 @@ pub fn execute(
}
Ok(Response::new().add_attribute("action", "fourth message passed"))
}
ExecuteMsg::SixthMessage(_, _) => {
Ok(Response::new().add_attribute("action", "sixth message passed"))
}
ExecuteMsg::SeventhMessage(amount, denom) => {
let c = info.funds[0].clone();
if c.amount != amount && c.denom.ne(&denom) {
return Err(StdError::generic_err("Coins don't match message"));

Check warning on line 105 in contracts/mock_contract/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract/src/lib.rs#L105

Added line #L105 was not covered by tests
}
Ok(Response::new().add_attribute("action", "fourth message passed"))
}
}
}

Expand All @@ -101,6 +116,7 @@ pub fn query(_deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
QueryMsg::FirstQuery {} => to_binary("first query passed"),
QueryMsg::SecondQuery { .. } => Err(StdError::generic_err("Query not available")),
QueryMsg::ThirdQuery => to_binary("third query passed"),
QueryMsg::FourthQuery(_, _) => to_binary(&4u64),
}
}

Expand All @@ -127,7 +143,7 @@ mod test {
// We need to check we can still call the execute msgs conveniently
let sender = Addr::unchecked("sender");
let mock = Mock::new(&sender);
mock.set_balance(&sender, coins(156, "ujuno"))?;
mock.set_balance(&sender, coins(156 * 2, "ujuno"))?;
let contract = LocalMockContract::new("mock-contract", mock.clone());

contract.upload()?;
Expand All @@ -136,10 +152,16 @@ mod test {
contract.second_message("s".to_string(), &[]).unwrap_err();
contract.fourth_message().unwrap();
contract.fifth_message(&coins(156, "ujuno")).unwrap();
contract.sixth_message(45, "moneys".to_string()).unwrap();

contract
.seventh_message(156u128.into(), "ujuno".to_string(), &coins(156, "ujuno"))
.unwrap();

contract.first_query().unwrap();
contract.second_query("arg".to_string()).unwrap_err();
contract.third_query().unwrap();
contract.fourth_query(45u64, "moneys".to_string()).unwrap();

Ok(())
}
Expand Down
11 changes: 11 additions & 0 deletions contracts/mock_contract_u64/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ pub fn execute(
}
Ok(Response::new().add_attribute("action", "fourth message passed"))

Check warning on line 41 in contracts/mock_contract_u64/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract_u64/src/lib.rs#L38-L41

Added lines #L38 - L41 were not covered by tests
}
ExecuteMsg::SixthMessage(_, _) => {
Ok(Response::new().add_attribute("action", "sixth message passed"))

Check warning on line 44 in contracts/mock_contract_u64/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract_u64/src/lib.rs#L44

Added line #L44 was not covered by tests
}
ExecuteMsg::SeventhMessage(amount, denom) => {
let c = info.funds[0].clone();
if c.amount != amount && c.denom.ne(&denom) {
return Err(StdError::generic_err("Coins don't match message"));
}
Ok(Response::new().add_attribute("action", "fourth message passed"))

Check warning on line 51 in contracts/mock_contract_u64/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract_u64/src/lib.rs#L46-L51

Added lines #L46 - L51 were not covered by tests
}
}
}

Expand All @@ -50,6 +60,7 @@ pub fn query(_deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
QueryMsg::FirstQuery {} => to_binary("first query passed"),
QueryMsg::SecondQuery { .. } => Err(StdError::generic_err("Query not available")),
QueryMsg::ThirdQuery => to_binary("third query passed"),
QueryMsg::FourthQuery(_, _) => to_binary("fourth query passed"),

Check warning on line 63 in contracts/mock_contract_u64/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract_u64/src/lib.rs#L62-L63

Added lines #L62 - L63 were not covered by tests
}
}

Expand Down
46 changes: 39 additions & 7 deletions packages/cw-orch-fns-derive/src/execute_fns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ extern crate proc_macro;
use crate::helpers::{process_fn_name, process_impl_into, LexiographicMatching};
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{visit_mut::VisitMut, DeriveInput, Fields, Ident};

Expand Down Expand Up @@ -31,7 +32,7 @@ pub fn execute_fns_derive(input: DeriveInput) -> TokenStream {
unimplemented!();
};

let variant_fns = variants.into_iter().filter_map( |mut variant|{
let variant_fns = variants.into_iter().map( |mut variant|{
let variant_name = variant.ident.clone();

// We rename the variant if it has a fn_name attribute associated with it
Expand All @@ -48,15 +49,46 @@ pub fn execute_fns_derive(input: DeriveInput) -> TokenStream {
};

match &mut variant.fields {
Fields::Unnamed(_) => None,
Fields::Unnamed(variant_fields) => {
// This is dangerous because of field ordering. Though, if people use like that, they know what to expect anyway

let mut variant_idents = variant_fields.unnamed.clone();
// remove any attributes for use in fn arguments
variant_idents.iter_mut().for_each(|f: &mut syn::Field| f.attrs = vec![]);


// We need to figure out a parameter name for all fields associated to their types
// They will be numbered from 0 to n-1
let variant_ident_content_names = variant_idents
.iter()
.enumerate()
.map(|(i, _)| Ident::new(&format!("arg{}", i), Span::call_site()));

let variant_attr = variant_idents.clone().into_iter()
.enumerate()
.map(|(i, mut id)| {
id.ident = Some(Ident::new(&format!("arg{}", i), Span::call_site()));
id
});

quote!(
#[allow(clippy::too_many_arguments)]
fn #variant_func_name(&self, #(#variant_attr,)* #maybe_coins_attr) -> Result<::cw_orch::prelude::TxResponse<Chain>, ::cw_orch::prelude::CwOrchError> {
let msg = #name::#variant_name (
#(#variant_ident_content_names,)*
);
<Self as ::cw_orch::prelude::CwOrchExecute<Chain>>::execute(self, &msg #maybe_into,#passed_coins)
}
)
},
Fields::Unit => {

Some(quote!(
quote!(
fn #variant_func_name(&self, #maybe_coins_attr) -> Result<::cw_orch::prelude::TxResponse<Chain>, ::cw_orch::prelude::CwOrchError> {
let msg = #name::#variant_name;
<Self as ::cw_orch::prelude::CwOrchExecute<Chain>>::execute(self, &msg #maybe_into,#passed_coins)
}
))
)
}
Fields::Named(variant_fields) => {
// sort fields on field name
Expand All @@ -66,20 +98,20 @@ pub fn execute_fns_derive(input: DeriveInput) -> TokenStream {
let mut variant_idents = variant_fields.named.clone();

// remove any attributes for use in fn arguments
variant_idents.iter_mut().for_each(|f| f.attrs = vec![]);
variant_idents.iter_mut().for_each(|f: &mut syn::Field| f.attrs = vec![]);

let variant_ident_content_names = variant_idents.iter().map(|f|f.ident.clone().unwrap());

let variant_attr = variant_idents.iter();
Some(quote!(
quote!(
#[allow(clippy::too_many_arguments)]
fn #variant_func_name(&self, #(#variant_attr,)* #maybe_coins_attr) -> Result<::cw_orch::prelude::TxResponse<Chain>, ::cw_orch::prelude::CwOrchError> {
let msg = #name::#variant_name {
#(#variant_ident_content_names,)*
};
<Self as ::cw_orch::prelude::CwOrchExecute<Chain>>::execute(self, &msg #maybe_into,#passed_coins)
}
))
)
}
}
});
Expand Down
34 changes: 33 additions & 1 deletion packages/cw-orch-fns-derive/src/query_fns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ extern crate proc_macro;
use crate::helpers::{process_fn_name, process_impl_into, LexiographicMatching};
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{format_ident, quote};
use syn::{visit_mut::VisitMut, Fields, Ident, ItemEnum, Type};

Expand Down Expand Up @@ -38,7 +39,36 @@ pub fn query_fns_derive(input: ItemEnum) -> TokenStream {
variant_func_name.set_span(variant_name.span());

match &mut variant.fields {
Fields::Unnamed(_) => panic!("Expected named variant"),
Fields::Unnamed(variant_fields) => {
let mut variant_idents = variant_fields.unnamed.clone();

// remove attributes from fields
variant_idents.iter_mut().for_each(|f| f.attrs = vec![]);

// Parse these fields as arguments to function

// We need to figure out a parameter name for all fields associated to their types
// They will be numbered from 0 to n-1
let variant_ident_content_names = variant_idents
.iter()
.enumerate()
.map(|(i, _)| Ident::new(&format!("arg{}", i), Span::call_site()));

let variant_attr = variant_idents.clone().into_iter()
.enumerate()
.map(|(i, mut id)| {
id.ident = Some(Ident::new(&format!("arg{}", i), Span::call_site()));
id
});

quote!(
#[allow(clippy::too_many_arguments)]
fn #variant_func_name(&self, #(#variant_attr,)*) -> ::core::result::Result<#response, ::cw_orch::prelude::CwOrchError> {
let msg = #name::#variant_name (#(#variant_ident_content_names,)*);
self.query(&msg #maybe_into)
}
)
}
Fields::Unit => {
quote!(
fn #variant_func_name(&self) -> ::core::result::Result<#response, ::cw_orch::prelude::CwOrchError> {
Expand Down Expand Up @@ -103,5 +133,7 @@ pub fn query_fns_derive(input: ItemEnum) -> TokenStream {
#derived_trait_impl
);

// panic!("{}", expand);

expand.into()
}

0 comments on commit 0cafc1c

Please sign in to comment.