cw_multi_test/
executor.rs

1use crate::error::AnyResult;
2use cosmwasm_std::{
3    to_json_binary, Addr, Attribute, BankMsg, Binary, Coin, CosmosMsg, CustomMsg, Event,
4    SubMsgResponse, WasmMsg,
5};
6use cw_utils::{parse_execute_response_data, parse_instantiate_response_data};
7use serde::Serialize;
8use std::fmt::Debug;
9
10/// A set of data returned as a response of a contract entry point,
11/// such as `instantiate`, `execute` or `migrate`.
12#[derive(Default, Clone, Debug)]
13pub struct AppResponse {
14    /// Custom events separate from the main `wasm` one.
15    pub events: Vec<Event>,
16    /// The binary payload to include in the response.
17    pub data: Option<Binary>,
18}
19
20impl AppResponse {
21    /// Returns all custom attributes returned by the contract in the `idx` event.
22    ///
23    /// We assert the type is wasm, and skip the contract_address attribute.
24    #[track_caller]
25    pub fn custom_attrs(&self, idx: usize) -> &[Attribute] {
26        assert_eq!(self.events[idx].ty.as_str(), "wasm");
27        &self.events[idx].attributes[1..]
28    }
29
30    /// Checks if there is an Event that is a super-set of this.
31    ///
32    /// It has the same type, and all compared attributes are included in it as well.
33    /// You don't need to specify them all.
34    pub fn has_event(&self, expected: &Event) -> bool {
35        self.events.iter().any(|ev| {
36            expected.ty == ev.ty
37                && expected
38                    .attributes
39                    .iter()
40                    .all(|at| ev.attributes.contains(at))
41        })
42    }
43
44    /// Like [has_event](Self::has_event) but panics if there is no match.
45    #[track_caller]
46    pub fn assert_event(&self, expected: &Event) {
47        assert!(
48            self.has_event(expected),
49            "Expected to find an event {:?}, but received: {:?}",
50            expected,
51            self.events
52        );
53    }
54}
55
56/// They have the same shape, SubMsgResponse is what is returned in reply.
57/// This is just to make some test cases easier.
58impl From<SubMsgResponse> for AppResponse {
59    fn from(reply: SubMsgResponse) -> Self {
60        AppResponse {
61            #[allow(deprecated)]
62            data: reply.data,
63            events: reply.events,
64        }
65    }
66}
67/// A trait defining a default behavior of the message executor.
68///
69/// Defines the interface for executing transactions and contract interactions.
70/// It is a central component in the testing framework, managing the operational
71/// flow and ensuring that contract _calls_ are processed correctly.
72pub trait Executor<C>
73where
74    C: CustomMsg + 'static,
75{
76    /// Processes (executes) an arbitrary `CosmosMsg`.
77    /// This will create a cache before the execution,
78    /// so no state changes are persisted if this returns an error,
79    /// but all are persisted on success.
80    fn execute(&mut self, sender: Addr, msg: CosmosMsg<C>) -> AnyResult<AppResponse>;
81
82    /// Create a contract and get the new address.
83    /// This is just a helper around execute()
84    fn instantiate_contract<T: Serialize, U: Into<String>>(
85        &mut self,
86        code_id: u64,
87        sender: Addr,
88        init_msg: &T,
89        send_funds: &[Coin],
90        label: U,
91        admin: Option<String>,
92    ) -> AnyResult<Addr> {
93        // instantiate contract
94        let init_msg = to_json_binary(init_msg)?;
95        let msg = WasmMsg::Instantiate {
96            admin,
97            code_id,
98            msg: init_msg,
99            funds: send_funds.to_vec(),
100            label: label.into(),
101        };
102        let res = self.execute(sender, msg.into())?;
103        let data = parse_instantiate_response_data(res.data.unwrap_or_default().as_slice())?;
104        Ok(Addr::unchecked(data.contract_address))
105    }
106
107    /// Instantiates a new contract and returns its predictable address.
108    /// This is a helper function around [execute][Self::execute] function
109    /// with `WasmMsg::Instantiate2` message.
110    #[cfg(feature = "cosmwasm_1_2")]
111    fn instantiate2_contract<M, L, A, S>(
112        &mut self,
113        code_id: u64,
114        sender: Addr,
115        init_msg: &M,
116        funds: &[Coin],
117        label: L,
118        admin: A,
119        salt: S,
120    ) -> AnyResult<Addr>
121    where
122        M: Serialize,
123        L: Into<String>,
124        A: Into<Option<String>>,
125        S: Into<Binary>,
126    {
127        let msg = WasmMsg::Instantiate2 {
128            admin: admin.into(),
129            code_id,
130            msg: to_json_binary(init_msg)?,
131            funds: funds.to_vec(),
132            label: label.into(),
133            salt: salt.into(),
134        };
135        let execute_response = self.execute(sender, msg.into())?;
136        let instantiate_response =
137            parse_instantiate_response_data(execute_response.data.unwrap_or_default().as_slice())?;
138        Ok(Addr::unchecked(instantiate_response.contract_address))
139    }
140
141    /// Execute a contract and process all returned messages.
142    /// This is just a helper function around [execute()](Self::execute)
143    /// with `WasmMsg::Execute` message, but in this case we parse out the data field
144    /// to that what is returned by the contract (not the protobuf wrapper).
145    fn execute_contract<T: Serialize + Debug>(
146        &mut self,
147        sender: Addr,
148        contract_addr: Addr,
149        msg: &T,
150        send_funds: &[Coin],
151    ) -> AnyResult<AppResponse> {
152        let binary_msg = to_json_binary(msg)?;
153        let wrapped_msg = WasmMsg::Execute {
154            contract_addr: contract_addr.into_string(),
155            msg: binary_msg,
156            funds: send_funds.to_vec(),
157        };
158        let mut res = self.execute(sender, wrapped_msg.into())?;
159        res.data = res
160            .data
161            .and_then(|d| parse_execute_response_data(d.as_slice()).unwrap().data);
162        Ok(res)
163    }
164
165    /// Migrates a contract.
166    /// Sender must be registered admin.
167    /// This is just a helper function around [execute()](Self::execute)
168    /// with `WasmMsg::Migrate` message.
169    fn migrate_contract<T: Serialize>(
170        &mut self,
171        sender: Addr,
172        contract_addr: Addr,
173        msg: &T,
174        new_code_id: u64,
175    ) -> AnyResult<AppResponse> {
176        let msg = to_json_binary(msg)?;
177        let msg = WasmMsg::Migrate {
178            contract_addr: contract_addr.into(),
179            msg,
180            new_code_id,
181        };
182        self.execute(sender, msg.into())
183    }
184
185    /// Sends tokens to specified recipient.
186    /// This is just a helper function around [execute()](Self::execute)
187    /// with `BankMsg::Send` message.
188    fn send_tokens(
189        &mut self,
190        sender: Addr,
191        recipient: Addr,
192        amount: &[Coin],
193    ) -> AnyResult<AppResponse> {
194        let msg = BankMsg::Send {
195            to_address: recipient.to_string(),
196            amount: amount.to_vec(),
197        };
198        self.execute(sender, msg.into())
199    }
200}