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

feat: add in grants query unit test #30

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions contracts/treasury/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ pub enum ContractError {
#[error(transparent)]
Std(#[from] cosmwasm_std::StdError),

#[error(transparent)]
System(#[from] cosmwasm_std::SystemError),

#[error(transparent)]
Encode(#[from] cosmos_sdk_proto::prost::EncodeError),

Expand Down
99 changes: 58 additions & 41 deletions contracts/treasury/src/execute.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use cosmos_sdk_proto::cosmos::authz::v1beta1::QueryGrantsRequest;
use cosmos_sdk_proto::cosmos::authz::v1beta1::{QueryGrantsRequest, QueryGrantsResponse};
use cosmos_sdk_proto::cosmos::feegrant::v1beta1::QueryAllowanceRequest;
use cosmos_sdk_proto::prost::Message;
use cosmos_sdk_proto::traits::MessageExt;
use cosmwasm_std::{Addr, CosmosMsg, DepsMut, Env, Event, MessageInfo, Order, Response};
use cosmwasm_std::{
to_json_vec, Addr, CosmosMsg, DepsMut, Empty, Env, Event, MessageInfo, Order, Response,
SystemResult,
};
use pbjson_types::Timestamp;
use serde_json::Value;

use crate::error::ContractError::{
AuthzGrantMismatch, AuthzGrantNoAuthorization, AuthzGrantNotFound, ConfigurationMismatch,
Unauthorized,
self, AuthzGrantMismatch, AuthzGrantNotFound, ConfigurationMismatch, Unauthorized,
};
use crate::error::ContractResult;
use crate::grant::allowance::format_allowance;
Expand Down Expand Up @@ -136,48 +139,62 @@ pub fn deploy_fee_grant(
pagination: None,
}
.to_bytes()?;
let authz_query_res =
deps.querier
.query::<Value>(&cosmwasm_std::QueryRequest::Stargate {
path: "/cosmos.authz.v1beta1.Query/Grants".to_string(),
data: authz_query_msg_bytes.into(),
})?;
let query_req = to_json_vec(&cosmwasm_std::QueryRequest::<Empty>::Stargate {
path: "/cosmos.authz.v1beta1.Query/Grants".to_string(),
data: authz_query_msg_bytes.into(),
})?;
let authz_query_res = deps.querier.raw_query(&query_req);

let grants = match authz_query_res {
SystemResult::Ok(cosmwasm_std::ContractResult::Ok(res)) => {
let res = QueryGrantsResponse::decode::<&[u8]>(res.as_slice());
match res {
Ok(res) => res.grants,
Err(err) => Err(err)?,
}
}
SystemResult::Ok(cosmwasm_std::ContractResult::Err(err)) => {
Err(ContractError::Std(cosmwasm_std::StdError::GenericErr {
msg: err,
}))?
}
SystemResult::Err(err) => Err(ContractError::System(err))?,
};

let grants = &authz_query_res["grants"];
// grant queries with a granter, grantee and type_url should always result
// in only one result, unless the grant is optional
if !grants.is_array() {
return Err(AuthzGrantNotFound { msg_type_url });
}
let grant = grants[0].clone();
if grant.is_null() {
return Err(AuthzGrantNotFound { msg_type_url });
}
let auth = &grant["authorization"];
if auth.is_null() {
return Err(AuthzGrantNoAuthorization);
}
if grant_config.authorization.ne(auth) {
return Err(AuthzGrantMismatch);
}
// if grants.clone().is_empty() && !grant_config.optional {
// if !grants.is_array() {
// return Err(AuthzGrantNotFound { msg_type_url });
// }
// let grant = grants[0].clone();
// if grant.is_null() {
// return Err(AuthzGrantNotFound { msg_type_url });
// } else {
// match grants.first() {
// None => return Err(AuthzGrantNotFound { msg_type_url }),
// Some(grant) => {
// match grant.clone().authorization {
// None => return Err(AuthzGrantNotFound { msg_type_url }),
// Some(auth) => {
// // the authorization must match the one in the config
// if grant_config.authorization.ne(&auth.into()) {
// return Err(AuthzGrantMismatch);
// }
// }
// }
// }
// }
// }
// let auth = &grant["authorization"];
// if auth.is_null() {
// return Err(AuthzGrantNoAuthorization);
// }
// if grant_config.authorization.ne(auth) {
// return Err(AuthzGrantMismatch);
// }
if grants.clone().is_empty() && !grant_config.optional {
return Err(AuthzGrantNotFound { msg_type_url });
} else {
match grants.first() {
None => return Err(AuthzGrantNotFound { msg_type_url }),
Some(grant) => {
match grant.clone().authorization {
None => return Err(AuthzGrantNotFound { msg_type_url }),
Some(auth) => {
// the authorization must match the one in the config
if grant_config.authorization.ne(&auth.into()) {
return Err(AuthzGrantMismatch);
}
}
}
}
}
}
}
// at this point, all the authz grants in the grant_config are verified

Expand Down
7 changes: 3 additions & 4 deletions contracts/treasury/src/grant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@ pub mod allowance;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::Binary;
use prost::bytes::Bytes;
use serde_json::Value;

#[cw_serde]
pub struct GrantConfig {
description: String,
pub authorization: Value,
pub description: String,
pub authorization: Any,
pub optional: bool,
}

#[cw_serde]
pub struct FeeConfig {
description: String,
pub description: String,
pub allowance: Option<Any>,
pub expiration: Option<u32>,
}
Expand Down
2 changes: 2 additions & 0 deletions contracts/treasury/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate core;

#[cfg(not(feature = "library"))]

Check warning on line 3 in contracts/treasury/src/lib.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unexpected `cfg` condition value: `library`
pub mod contract;
mod error;
mod execute;
Expand All @@ -10,5 +10,7 @@
mod grant;
mod query;

mod unit_test;

pub const CONTRACT_NAME: &str = "treasury";
pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
156 changes: 156 additions & 0 deletions contracts/treasury/src/unit_test/grants_query.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
#[cfg(test)]
pub mod unit_test {
use core::marker::PhantomData;
use cosmos_sdk_proto::cosmos::authz::v1beta1::{QueryGrantsRequest, QueryGrantsResponse};
use cosmos_sdk_proto::prost::Message;
use cosmwasm_std::testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage};
use cosmwasm_std::{
to_json_vec, Binary, ContractResult, CustomQuery, OwnedDeps, QueryRequest, SystemResult,
};
use serde::{Deserialize, Serialize};

use crate::contract::{execute, instantiate};
use crate::grant::{Any, FeeConfig, GrantConfig};
use crate::msg::{ExecuteMsg, InstantiateMsg};
use crate::unit_test::responses::GRANTS_QUERY_RESPONSE_BYTES;

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MyCustomQuery {
GrantsQuery(QueryGrantsRequest),
}
impl CustomQuery for MyCustomQuery {}

const GRANTER: &str = "granter";
const GRANTEE: &str = "grantee";

#[test]
fn test_query_grants_binary_response() {
let querier = MockQuerier::<MyCustomQuery>::with_custom_handler(
MockQuerier::<MyCustomQuery>::new(&[]),
custom_querier,
);

let mut owned = OwnedDeps::<_, _, _, MyCustomQuery> {
storage: MockStorage::default(),
api: MockApi::default(),
querier,
custom_query_type: PhantomData,
};
let deps = owned.as_mut();

let grant_config = GrantConfig {
description: "test fee grant".to_string(),
authorization: Any {
type_url: "/cosmos.bank.v1beta1.SendAuthorization".to_string(),
value: Binary::from_base64("ChAKBXV4aW9uEgcxMDAwMDAw").unwrap(),
},
optional: false,
};

let msg_type_url = "msg_type_url".to_string();
let query_msg = QueryGrantsRequest {
granter: GRANTER.to_string(),
grantee: GRANTEE.to_string(),
msg_type_url: msg_type_url.clone(),
pagination: None,
};

let custom_query = QueryRequest::Custom(MyCustomQuery::GrantsQuery(query_msg));
let query_res = deps.querier.raw_query(&to_json_vec(&custom_query).unwrap());
match query_res {
SystemResult::Ok(ContractResult::Ok(res)) => {
assert_eq!(res, GRANTS_QUERY_RESPONSE_BYTES);
let res = QueryGrantsResponse::decode::<&[u8]>(res.as_slice());
match res {
Ok(res) => {
assert_eq!(res.grants.len(), 1);
let authorization = res.grants[0].authorization.as_ref().unwrap();

assert_eq!(*authorization, grant_config.authorization.into());
}
Err(err) => {
panic!("Error in deserializing query result: {:?}", err);
}
}
}
SystemResult::Ok(ContractResult::Err(err)) => panic!("{:?}", err),
SystemResult::Err(err) => panic!("{:?}", err),
}
}
#[test]
fn test_query_grants_request() {
let querier = MockQuerier::<MyCustomQuery>::with_custom_handler(
MockQuerier::<MyCustomQuery>::new(&[]),
custom_querier,
);

let mut owned = OwnedDeps::<_, _, _, MyCustomQuery> {
storage: MockStorage::default(),
api: MockApi::default(),
querier,
custom_query_type: PhantomData,
};
let mut deps = owned.as_mut();
let env = mock_env();

let info = mock_info(&GRANTER, &[]);

let instantiate_msg = InstantiateMsg {
admin: None,
type_urls: vec!["/cosmos.bank.v1beta1.MsgSend".to_string()],
grant_configs: vec![GrantConfig {
description: "test fee grant".to_string(),
authorization: Any {
type_url: "/cosmos.bank.v1beta1.SendAuthorization".to_string(),
value: Binary::from_base64("ChAKBXV4aW9uEgcxMDAwMDAw").unwrap(),
},
optional: false,
}],
fee_config: FeeConfig {
description: "test fee grant".to_string(),
allowance: Some(Any {
type_url: "/cosmos.feegrant.v1beta1.BasicAllowance".to_string(),
value: Binary::from_base64("EgsI2b/mtAYQ4KOeNA==").unwrap(),
}),
expiration: Some(18000),
},
};

instantiate(
deps.branch().into_empty(),
env.clone(),
info.clone(),
instantiate_msg,
)
.expect("instantiate successful");

let execute_msg = ExecuteMsg::DeployFeeGrant {
authz_granter: deps.api.addr_validate(&GRANTER).unwrap(),
authz_grantee: deps.api.addr_validate(&GRANTEE).unwrap(),
};

let execute_res = execute(
deps.branch().into_empty(),
env.clone(),
info.clone(),
execute_msg,
);

match execute_res {
Ok(res) => assert_eq!(res.messages.len(), 1),
Err(err) => panic!("{:?}", err),
}
}

/// this function simulates a stargate request to the querier
fn custom_querier(request: &MyCustomQuery) -> SystemResult<ContractResult<Binary>> {
match request {
MyCustomQuery::GrantsQuery(_) => {
return cosmwasm_std::SystemResult::Ok(cosmwasm_std::ContractResult::Ok(
Binary::from(GRANTS_QUERY_RESPONSE_BYTES),
));
}
};
}
}
2 changes: 2 additions & 0 deletions contracts/treasury/src/unit_test/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod grants_query;
mod responses;
23 changes: 23 additions & 0 deletions contracts/treasury/src/unit_test/responses.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub const GRANTS_QUERY_RESPONSE: &str = "{\"grants\": [

Check warning on line 1 in contracts/treasury/src/unit_test/responses.rs

View workflow job for this annotation

GitHub Actions / Test Suite

constant `GRANTS_QUERY_RESPONSE` is never used
{
\"authorization\": {
\"@type\": \"/cosmos.staking.v1beta1.StakeAuthorization\",
\"max_tokens\": {
\"denom\": \"uxion\",
\"amount\": 1000
},
\"deny_list\": {
\"address\": []
},
\"authorization_type\": \"AUTHORIZATION_TYPE_UNDELEGATE\"
},
\"expiration\": \"2024-10-23T22:26:24Z\"
}
],
\"pagination\": null}";

pub const GRANTS_QUERY_RESPONSE_BYTES: &[u8] = &[

Check warning on line 19 in contracts/treasury/src/unit_test/responses.rs

View workflow job for this annotation

GitHub Actions / Test Suite

constant `GRANTS_QUERY_RESPONSE_BYTES` is never used
10, 62, 10, 60, 10, 38, 47, 99, 111, 115, 109, 111, 115, 46, 98, 97, 110, 107, 46, 118, 49, 98,
101, 116, 97, 49, 46, 83, 101, 110, 100, 65, 117, 116, 104, 111, 114, 105, 122, 97, 116, 105,
111, 110, 18, 18, 10, 16, 10, 5, 117, 120, 105, 111, 110, 18, 7, 49, 48, 48, 48, 48, 48, 48,
];
Loading