Repository: CosmWasm/cw-multi-test
Pull request #139 (2024-03-08 15:16:49)

Refactored wasm trait
Refactored `Wasm` trait and made usage of `WasmSudo` message.


Patch:
diff --git a/src/app.rs b/src/app.rs
index ff1925c..0083c69 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -425,7 +425,10 @@ where
         contract_addr: U,
         msg: &T,
     ) -> AnyResult<AppResponse> {
-        let msg = to_json_binary(msg)?;
+        let msg = WasmSudo {
+            contract_addr: contract_addr.into(),
+            message: to_json_binary(msg)?,
+        };
 
         let Self {
             block,
@@ -435,9 +438,7 @@ where
         } = self;
 
         transactional(&mut *storage, |write_cache, _| {
-            router
-                .wasm
-                .sudo(&*api, contract_addr.into(), write_cache, router, block, msg)
+            router.wasm.sudo(&*api, write_cache, router, block, msg)
         })
     }
 
@@ -662,10 +663,7 @@ where
         msg: SudoMsg,
     ) -> AnyResult<AppResponse> {
         match msg {
-            SudoMsg::Wasm(msg) => {
-                self.wasm
-                    .sudo(api, msg.contract_addr, storage, self, block, msg.msg)
-            }
+            SudoMsg::Wasm(msg) => self.wasm.sudo(api, storage, self, block, msg),
             SudoMsg::Bank(msg) => self.bank.sudo(api, storage, self, block, msg),
             SudoMsg::Staking(msg) => self.staking.sudo(api, storage, self, block, msg),
             SudoMsg::Custom(_) => unimplemented!(),
diff --git a/src/wasm.rs b/src/wasm.rs
index 1431b2b..32f6205 100644
--- a/src/wasm.rs
+++ b/src/wasm.rs
@@ -39,7 +39,7 @@ pub struct WasmSudo {
     /// Address of a contract the privileged action will be sent to.
     pub contract_addr: Addr,
     /// Message representing privileged action to be executed by contract `sudo` entry-point.
-    pub msg: Binary,
+    pub message: Binary,
 }
 
 impl WasmSudo {
@@ -47,7 +47,7 @@ impl WasmSudo {
     pub fn new<T: Serialize>(contract_addr: &Addr, msg: &T) -> StdResult<WasmSudo> {
         Ok(WasmSudo {
             contract_addr: contract_addr.clone(),
-            msg: to_json_binary(msg)?,
+            message: to_json_binary(msg)?,
         })
     }
 }
@@ -82,16 +82,6 @@ struct CodeData {
 /// This trait is crucial for testing smart contracts written in languages that compile to WebAssembly,
 /// which is common in the Cosmos and CosmWasm ecosystems.
 pub trait Wasm<ExecC, QueryC> {
-    /// Handles all `WasmQuery` requests.
-    fn query(
-        &self,
-        api: &dyn Api,
-        storage: &dyn Storage,
-        querier: &dyn Querier,
-        block: &BlockInfo,
-        request: WasmQuery,
-    ) -> AnyResult<Binary>;
-
     /// Handles all `WasmMsg` messages.
     fn execute(
         &self,
@@ -103,15 +93,24 @@ pub trait Wasm<ExecC, QueryC> {
         msg: WasmMsg,
     ) -> AnyResult<AppResponse>;
 
+    /// Handles all `WasmQuery` requests.
+    fn query(
+        &self,
+        api: &dyn Api,
+        storage: &dyn Storage,
+        querier: &dyn Querier,
+        block: &BlockInfo,
+        request: WasmQuery,
+    ) -> AnyResult<Binary>;
+
     /// Handles all sudo messages, this is an admin interface and can not be called via `CosmosMsg`.
     fn sudo(
         &self,
         api: &dyn Api,
-        contract_addr: Addr,
         storage: &mut dyn Storage,
         router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
         block: &BlockInfo,
-        msg: Binary,
+        msg: WasmSudo,
     ) -> AnyResult<AppResponse>;
 
     /// Stores the contract's code and returns an identifier of the stored contract's code.
@@ -169,6 +168,22 @@ where
     ExecC: CustomMsg + DeserializeOwned + 'static,
     QueryC: CustomQuery + DeserializeOwned + 'static,
 {
+    fn execute(
+        &self,
+        api: &dyn Api,
+        storage: &mut dyn Storage,
+        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
+        block: &BlockInfo,
+        sender: Addr,
+        msg: WasmMsg,
+    ) -> AnyResult<AppResponse> {
+        self.execute_wasm(api, storage, router, block, sender.clone(), msg.clone())
+            .context(format!(
+                "Error executing WasmMsg:\n  sender: {}\n  {:?}",
+                sender, msg
+            ))
+    }
+
     fn query(
         &self,
         api: &dyn Api,
@@ -208,36 +223,25 @@ where
         }
     }
 
-    fn execute(
-        &self,
-        api: &dyn Api,
-        storage: &mut dyn Storage,
-        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
-        block: &BlockInfo,
-        sender: Addr,
-        msg: WasmMsg,
-    ) -> AnyResult<AppResponse> {
-        self.execute_wasm(api, storage, router, block, sender.clone(), msg.clone())
-            .context(format!(
-                "Error executing WasmMsg:\n  sender: {}\n  {:?}",
-                sender, msg
-            ))
-    }
-
     fn sudo(
         &self,
         api: &dyn Api,
-        contract: Addr,
         storage: &mut dyn Storage,
         router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
         block: &BlockInfo,
-        msg: Binary,
+        msg: WasmSudo,
     ) -> AnyResult<AppResponse> {
-        let custom_event = Event::new("sudo").add_attribute(CONTRACT_ATTR, &contract);
-
-        let res = self.call_sudo(contract.clone(), api, storage, router, block, msg.to_vec())?;
-        let (res, msgs) = self.build_app_response(&contract, custom_event, res);
-        self.process_response(api, router, storage, block, contract, res, msgs)
+        let custom_event = Event::new("sudo").add_attribute(CONTRACT_ATTR, &msg.contract_addr);
+        let res = self.call_sudo(
+            msg.contract_addr.clone(),
+            api,
+            storage,
+            router,
+            block,
+            msg.message.to_vec(),
+        )?;
+        let (res, msgs) = self.build_app_response(&msg.contract_addr, custom_event, res);
+        self.process_response(api, router, storage, block, msg.contract_addr, res, msgs)
     }
 
     /// Stores the contract's code in the in-memory lookup table.
@@ -445,6 +449,7 @@ where
     /// use cosmwasm_std::{Addr, Api, Storage};
     /// use cw_multi_test::{AddressGenerator, AppBuilder, no_init, WasmKeeper};
     /// use cw_multi_test::error::AnyResult;
+    /// # use cosmwasm_std::testing::MockApi;
     ///
     /// struct CustomAddressGenerator;
     ///
@@ -457,7 +462,7 @@ where
     ///         instance_id: u64,
     ///     ) -> AnyResult<Addr> {
     ///         // here implement your address generation logic
-    /// #       Ok(Addr::unchecked("test_address"))
+    /// #       Ok(MockApi::default().addr_make("test_address"))
     ///     }
     /// }
     ///


Test patch:
diff --git a/src/tests/test_app.rs b/src/tests/test_app.rs
index 95a0c82..1da7a99 100644
--- a/src/tests/test_app.rs
+++ b/src/tests/test_app.rs
@@ -564,7 +564,7 @@ fn sudo_works() {
     let msg = payout::SudoMsg { set_count: 49 };
     let sudo_msg = WasmSudo {
         contract_addr: payout_addr.clone(),
-        msg: to_json_binary(&msg).unwrap(),
+        message: to_json_binary(&msg).unwrap(),
     };
     app.sudo(sudo_msg.into()).unwrap();
 
diff --git a/tests/test_app_builder/test_with_api.rs b/tests/test_app_builder/test_with_api.rs
index a61861c..b2d24ac 100644
--- a/tests/test_app_builder/test_with_api.rs
+++ b/tests/test_app_builder/test_with_api.rs
@@ -1,4 +1,4 @@
-use cosmwasm_std::{Addr, Api, CanonicalAddr, HexBinary};
+use cosmwasm_std::{Api, CanonicalAddr, HexBinary};
 use cw_multi_test::MockApiBech32;
 use cw_multi_test::{no_init, AppBuilder};
 
@@ -15,10 +15,7 @@ fn building_app_with_custom_api_should_work() {
         .build(no_init);
 
     // check address validation function
-    assert_eq!(
-        app.api().addr_validate(human).unwrap(),
-        Addr::unchecked(human)
-    );
+    assert_eq!(app.api().addr_validate(human).unwrap().as_str(), human);
 
     // check if address can be canonicalized
     assert_eq!(
@@ -30,10 +27,11 @@ fn building_app_with_custom_api_should_work() {
     assert_eq!(
         app.api()
             .addr_humanize(&app.api().addr_canonicalize(human).unwrap())
-            .unwrap(),
-        Addr::unchecked(human)
+            .unwrap()
+            .as_str(),
+        human
     );
 
     // check extension function for creating Bech32 encoded addresses
-    assert_eq!(app.api().addr_make("creator"), Addr::unchecked(human));
+    assert_eq!(app.api().addr_make("creator").as_str(), human);
 }
diff --git a/tests/test_app_builder/test_with_wasm.rs b/tests/test_app_builder/test_with_wasm.rs
index 364a32b..9708d79 100644
--- a/tests/test_app_builder/test_with_wasm.rs
+++ b/tests/test_app_builder/test_with_wasm.rs
@@ -25,17 +25,6 @@ static WASM_RAW: Lazy<Vec<Record>> = Lazy::new(|| vec![(vec![154u8], vec![155u8]
 type MyWasmKeeper = MyKeeper<Empty, Empty, Empty>;
 
 impl<ExecT, QueryT> Wasm<ExecT, QueryT> for MyWasmKeeper {
-    fn query(
-        &self,
-        _api: &dyn Api,
-        _storage: &dyn Storage,
-        _querier: &dyn Querier,
-        _block: &BlockInfo,
-        _request: WasmQuery,
-    ) -> AnyResult<Binary> {
-        bail!(self.2);
-    }
-
     fn execute(
         &self,
         _api: &dyn Api,
@@ -48,14 +37,24 @@ impl<ExecT, QueryT> Wasm<ExecT, QueryT> for MyWasmKeeper {
         bail!(self.1);
     }
 
+    fn query(
+        &self,
+        _api: &dyn Api,
+        _storage: &dyn Storage,
+        _querier: &dyn Querier,
+        _block: &BlockInfo,
+        _request: WasmQuery,
+    ) -> AnyResult<Binary> {
+        bail!(self.2);
+    }
+
     fn sudo(
         &self,
         _api: &dyn Api,
-        _contract_addr: Addr,
         _storage: &mut dyn Storage,
         _router: &dyn CosmosRouter<ExecC = ExecT, QueryC = QueryT>,
         _block: &BlockInfo,
-        _msg: Binary,
+        _msg: WasmSudo,
     ) -> AnyResult<AppResponse> {
         bail!(self.3);
     }
@@ -140,7 +139,7 @@ fn building_app_with_custom_wasm_should_work() {
         app.sudo(
             WasmSudo {
                 contract_addr,
-                msg: Default::default()
+                message: Default::default()
             }
             .into()
         )