Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Unit variant to execute and query fns #196

Merged
merged 7 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 47 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 @@

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 @@ -26,6 +26,12 @@
/// test doc-comment
t: T,
},
FourthMessage,
#[cfg_attr(feature = "interface", payable)]
FifthMessage,
SixthMessage(u64, String),
#[cfg_attr(feature = "interface", payable)]
SeventhMessage(Uint128, String),
}

#[cw_serde]
Expand All @@ -43,6 +49,10 @@
/// test doc-comment
t: T,
},
#[returns(String)]
ThirdQuery,
#[returns(u64)]
FourthQuery(u64, String),
}

#[cw_serde]
Expand All @@ -66,7 +76,7 @@
pub fn execute(
_deps: DepsMut,
_env: Env,
_info: MessageInfo,
info: MessageInfo,
msg: ExecuteMsg,
) -> StdResult<Response> {
match msg {
Expand All @@ -77,6 +87,25 @@
ExecuteMsg::ThirdMessage { .. } => {
Ok(Response::new().add_attribute("action", "third message passed"))
}
ExecuteMsg::FourthMessage => {
Ok(Response::new().add_attribute("action", "fourth message passed"))
}
ExecuteMsg::FifthMessage => {
if info.funds.is_empty() {
return Err(StdError::generic_err("Coins missing"));

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

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract/src/lib.rs#L95

Added line #L95 was not covered by tests
}
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 @@ -86,6 +115,8 @@
match msg {
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 @@ -105,18 +136,32 @@
mod test {
use super::MockContract as LocalMockContract;
use super::*;
use cosmwasm_std::coins;
use cw_orch::prelude::*;
#[test]
fn compiles() -> Result<(), CwOrchError> {
// 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 * 2, "ujuno"))?;
let contract = LocalMockContract::new("mock-contract", mock.clone());

contract.upload()?;
contract.instantiate(&InstantiateMsg {}, None, None)?;
contract.first_message()?;
contract.second_message("s".to_string(), &[]).unwrap_err();
contract.fourth_message().unwrap();
Kayanski marked this conversation as resolved.
Show resolved Hide resolved
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
23 changes: 22 additions & 1 deletion contracts/mock_contract_u64/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
pub fn execute(
_deps: DepsMut,
_env: Env,
_info: MessageInfo,
info: MessageInfo,
msg: ExecuteMsg<u64>,
) -> StdResult<Response> {
match msg {
Expand All @@ -31,6 +31,25 @@
ExecuteMsg::ThirdMessage { .. } => {
Ok(Response::new().add_attribute("action", "third message passed"))
}
ExecuteMsg::FourthMessage => {
Ok(Response::new().add_attribute("action", "fourth message passed"))

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

View check run for this annotation

Codecov / codecov/patch

contracts/mock_contract_u64/src/lib.rs#L35

Added line #L35 was not covered by tests
}
ExecuteMsg::FifthMessage => {
if info.funds.is_empty() {
return Err(StdError::generic_err("Coins missing"));
}
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 @@ -40,6 +59,8 @@
match msg {
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
64 changes: 53 additions & 11 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 @@ -40,9 +41,55 @@ pub fn execute_fns_derive(input: DeriveInput) -> TokenStream {
variant_func_name.set_span(variant_name.span());

let is_payable = payable(&variant);

let (maybe_coins_attr, passed_coins) = if is_payable {
(quote!(coins: &[::cosmwasm_std::Coin]),quote!(Some(coins)))
} else {
(quote!(),quote!(None))
};

match &mut variant.fields {
Fields::Unnamed(_) => None,
Fields::Unit => 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 => {

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
LexiographicMatching::default().visit_fields_named_mut(variant_fields);
Expand All @@ -51,25 +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 (maybe_coins_attr, passed_coins) = if is_payable {
(quote!(coins: &[::cosmwasm_std::Coin]),quote!(Some(coins)))
} else {
(quote!(),quote!(None))
};
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
62 changes: 50 additions & 12 deletions 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,8 +39,44 @@ 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::Unit => 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> {
let msg = #name::#variant_name;
self.query(&msg #maybe_into)
}
)
},
Fields::Named(variant_fields) => {
// sort fields on field name
LexiographicMatching::default().visit_fields_named_mut(variant_fields);
Expand All @@ -53,18 +90,17 @@ pub fn query_fns_derive(input: ItemEnum) -> TokenStream {

let variant_attr = variant_fields.iter();
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_idents,)*
};
self.query(&msg #maybe_into)
}
)
}
#[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_idents,)*
};
self.query(&msg #maybe_into)
}
)
}
}
);
});

let derived_trait = quote!(
pub trait #bname<Chain: ::cw_orch::prelude::CwEnv, #type_generics>: ::cw_orch::prelude::CwOrchQuery<Chain, QueryMsg = #entrypoint_msg_type #ty_generics > #where_clause {
Expand Down Expand Up @@ -97,5 +133,7 @@ pub fn query_fns_derive(input: ItemEnum) -> TokenStream {
#derived_trait_impl
);

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

Kayanski marked this conversation as resolved.
Show resolved Hide resolved
expand.into()
}
Loading