CosmWasm / cw-multi-test

CosmWasm multi-contract testing framework
Apache License 2.0
48 stars 42 forks source link

MultiTest does not support CosmosMsg::Stargate #88

Closed 99Kies closed 11 months ago

99Kies commented 1 year ago

my contract func code:

fn execute_grant(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    max_amount: Uint128,
) -> Result<Response, ContractError> {
    // Check if the sender is authorized to execute the function
    if !can_execute(deps.as_ref(), info.sender.as_ref())? {
        return Err(ContractError::Unauthorized {});
    }

    if FEEGRANTS.exists(deps.storage) {
        return Err(ContractError::FeeGrantAlreadyExists {});
    }

    let denom = "inj".to_string();

    let mut amount: Uint128 = Uint128::new(0);
    // Iterate through the funds and find the amount with the MACI denomination
    info.funds.iter().for_each(|fund| {
        if fund.denom == denom {
            amount = fund.amount;
        }
    });
    FEEGRANTS.save(deps.storage, &max_amount)?;

    let whitelist = WHITELIST.load(deps.storage)?;

    let base_amount = max_amount / Uint128::from(whitelist.users.len() as u128);

    let mut expiration_time: Option<SdkTimestamp> = None;

    let allowance = BasicAllowance {
        spend_limit: vec![SdkCoin {
            denom: denom,
            amount: base_amount.to_string(),
        }],
        expiration: None,
    };

    let allowed_allowance = AllowedMsgAllowance {
        allowance: Some(Any {
            type_url: BasicAllowance::TYPE_URL.to_string(),
            value: allowance.encode_to_vec(),
        }),
        allowed_messages: vec!["/cosmwasm.wasm.v1.MsgExecuteContract".to_string()],
    };

    let mut messages = vec![];
    for i in 0..whitelist.users.len() {
        let grant_msg = MsgGrantAllowance {
            granter: env.contract.address.to_string(),
            grantee: whitelist.users[i].addr.to_string(),
            allowance: Some(Any {
                type_url: AllowedMsgAllowance::TYPE_URL.to_string(),
                value: allowed_allowance.encode_to_vec(),
            }),
        };

        let message = CosmosMsg::Stargate {
            type_url: MsgGrantAllowance::TYPE_URL.to_string(),
            value: grant_msg.encode_to_vec().into(),
        };
        messages.push(message);
    }

    Ok(Response::default().add_messages(messages).add_attributes([
        ("action", "grant"),
        ("max_amount", max_amount.to_string().as_str()),
        ("bond_amount", amount.to_string().as_str()),
    ]))
}

when I execute cargo test test log:

 Caused by:     Cannot execute Stargate { type_url: "/cosmos.feegrant.v1beta1.MsgGrantAllowance", value: Binary(0a09636f6e7472616374301201301a4b0a272f636f736d6f732e6665656772616e742e763162657461312e4261736963416c6c6f77616e636512200a160a057065616b61120d35303030303030303030303030120608b5f3beed05) }) thread 'multitest::tests::test::instantiate_with_voting_time_and_test_grant_should_works' panicked at 'assertion failed: `(left == right)`   left: `Uint128(10000000000000)`,  right: `Uint128(0)`', src/multitest/tests.rs:1029:9
DariuszDepta commented 11 months ago

Hi @99Kies, could you check/verify if PR #106 fully addresses your needs? Or we should consider to add something more to it? Thanks in advance for your help!

99Kies commented 11 months ago

@DariuszDepta Sorry to late. I see the latest version is 0.19.0, but I'm still having the same problem with 0.19.0. image

this is my cargo.toml: https://github.com/DoraFactory/cosmwasm-maci/blob/add_plonk_support/maci/Cargo.toml#L75 this is my test code: https://github.com/DoraFactory/cosmwasm-maci/blob/add_plonk_support/maci/src/multitest/tests.rs#L1717-L1818

DariuszDepta commented 11 months ago

This issue can be fixed with version 0.20.0 of CosmWasm MultiTest. After publishing the version 0.20.0 we will provide a detailed explanation how to fix it.

DariuszDepta commented 11 months ago

Hi @99Kies, we have released version 0.20.0 of CosmWasm MultiTest with Stargate mocking capability. I have got your tests working after applying changes shown below as a diff patch on your branch origin/add_plonk_support. Let me know if it helped.

diff --git a/maci/Cargo.toml b/maci/Cargo.toml
index 6714a39..166d7d2 100644
--- a/maci/Cargo.toml
+++ b/maci/Cargo.toml
@@ -72,7 +72,7 @@ franklin-crypto = { git = "https://github.com/matter-labs/franklin-crypto", bran
 [dev-dependencies]
 anyhow = "1"
 assert_matches = "1"
-cw-multi-test = "0.19.0"
+cw-multi-test = { version = "0.20.0", features = ["cosmwasm_1_4"] }
 derivative = "2"
 serde_json = "1.0"
 num-bigint = "0.4.3"
diff --git a/maci/src/multitest/mod.rs b/maci/src/multitest/mod.rs
index 809c79b..3afaa2b 100644
--- a/maci/src/multitest/mod.rs
+++ b/maci/src/multitest/mod.rs
@@ -13,8 +13,12 @@ use crate::{
     contract::{execute, instantiate, query},
     msg::*,
 };
-use cosmwasm_std::{Addr, Coin, StdResult, Timestamp, Uint128, Uint256};
-use cw_multi_test::{App, AppResponse, ContractWrapper, Executor};
+use cosmwasm_std::testing::{MockApi, MockStorage};
+use cosmwasm_std::{Addr, Coin, Empty, StdResult, Timestamp, Uint128, Uint256};
+use cw_multi_test::{
+    no_init, AppBuilder, AppResponse, BankKeeper, ContractWrapper, DistributionKeeper, Executor,
+    FailingModule, GovFailingModule, IbcFailingModule, StakeKeeper, StargateAccepting, WasmKeeper,
+};
 use num_bigint::BigUint;

 pub fn uint256_from_decimal_string(decimal_string: &str) -> Uint256 {
@@ -35,6 +39,25 @@ pub const MOCK_CONTRACT_ADDR: &str = "cosmos2contract";
 // pub const ARCH_DEMON: &str = "aconst";
 // pub const ARCH_DECIMALS: u8 = 18;

+pub type App<ExecC = Empty, QueryC = Empty> = cw_multi_test::App<
+    BankKeeper,
+    MockApi,
+    MockStorage,
+    FailingModule<ExecC, QueryC, Empty>,
+    WasmKeeper<ExecC, QueryC>,
+    StakeKeeper,
+    DistributionKeeper,
+    IbcFailingModule,
+    GovFailingModule,
+    StargateAccepting,
+>;
+
+pub fn create_app() -> App {
+    AppBuilder::new()
+        .with_stargate(StargateAccepting)
+        .build(no_init)
+}
+
 #[derive(Clone, Debug, Copy)]
 pub struct MaciCodeId(u64);

diff --git a/maci/src/multitest/tests.rs b/maci/src/multitest/tests.rs
index 1cd2e15..f7be1f6 100644
--- a/maci/src/multitest/tests.rs
+++ b/maci/src/multitest/tests.rs
@@ -1,13 +1,13 @@
 #[cfg(test)]
 mod test {
-    use cosmwasm_std::{coins, Addr, Uint128, Uint256};
-
-    use cw_multi_test::{next_block, App};
-
     use crate::error::ContractError;
     use crate::msg::{Groth16ProofType, PlonkProofType};
-    use crate::multitest::{owner, uint256_from_decimal_string, user1, user2, MaciCodeId};
+    use crate::multitest::{
+        create_app, owner, uint256_from_decimal_string, user1, user2, MaciCodeId,
+    };
     use crate::state::{MessageData, Period, PeriodStatus, PubKey, RoundInfo};
+    use cosmwasm_std::{coins, Addr, Uint128, Uint256};
+    use cw_multi_test::{next_block, AppBuilder, StargateAccepting};
     use serde::{Deserialize, Serialize};
     use serde_json;
     use std::fs;
@@ -78,7 +78,7 @@ mod test {

         let data: MsgData = serde_json::from_str(&msg_content).expect("Failed to parse JSON");

-        let mut app = App::default();
+        let mut app = create_app();

         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Dora Maci";
@@ -357,7 +357,7 @@ mod test {
         let pubkey_data: UserPubkeyData =
             serde_json::from_str(&pubkey_content).expect("Failed to parse JSON");

-        let mut app = App::default();
+        let mut app = create_app();
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
@@ -641,7 +641,7 @@ mod test {
         let pubkey_data: UserPubkeyData =
             serde_json::from_str(&pubkey_content).expect("Failed to parse JSON");

-        let mut app = App::default();
+        let mut app = create_app();
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
@@ -868,7 +868,7 @@ mod test {
         let pubkey_data: UserPubkeyData =
             serde_json::from_str(&pubkey_content).expect("Failed to parse JSON");

-        let mut app = App::default();
+        let mut app = create_app();
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
@@ -1066,7 +1066,7 @@ mod test {

     // #[test]
     fn instantiate_with_wrong_voting_time_error() {
-        let mut app = App::default();
+        let mut app = create_app();
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
@@ -1112,7 +1112,7 @@ mod test {
         let pubkey_data: UserPubkeyData =
             serde_json::from_str(&pubkey_content).expect("Failed to parse JSON");

-        let mut app = App::default();
+        let mut app = create_app();
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
@@ -1396,7 +1396,7 @@ mod test {
         let pubkey_data: UserPubkeyData =
             serde_json::from_str(&pubkey_content).expect("Failed to parse JSON");

-        let mut app = App::default();
+        let mut app = create_app();
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
@@ -1731,12 +1731,15 @@ mod test {

         let data: MsgData = serde_json::from_str(&msg_content).expect("Failed to parse JSON");

-        let mut app = App::new(|router, _api, storage| {
-            router
-                .bank
-                .init_balance(storage, &owner(), coins(admin_coin_amount, DORA_DEMON))
-                .unwrap();
-        });
+        let mut app = AppBuilder::default()
+            .with_stargate(StargateAccepting)
+            .build(|router, _api, storage| {
+                router
+                    .bank
+                    .init_balance(storage, &owner(), coins(admin_coin_amount, DORA_DEMON))
+                    .unwrap();
+            });
+
         let code_id = MaciCodeId::store_code(&mut app);
         let label = "Group";
         let contract = code_id
99Kies commented 11 months ago

@DariuszDepta Hi, bro. Could you please create a pr for my repository?

99Kies commented 11 months ago

Awesome! I just tried this and it did work. Hopefully our repository can keep track of your commit contributions.

99Kies commented 11 months ago

And finally, an apology for being late. Thanks bro! @DariuszDepta you are best!👍