apollo_utils/
responses.rs

1use cosmwasm_std::Response;
2
3/// Merge several Response objects into one. Currently ignores the data fields.
4///
5/// Returns a new Response object.
6pub fn merge_responses(responses: Vec<Response>) -> Response {
7    let mut merged = Response::default();
8    for response in responses {
9        merged = merged
10            .add_attributes(response.attributes)
11            .add_events(response.events)
12            .add_submessages(response.messages);
13        // merge data
14        if let Some(data) = response.data {
15            if merged.data.is_none() {
16                merged.data = Some(data);
17            } else {
18                panic!("Cannot merge multiple responses with data");
19            }
20        }
21    }
22    merged
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28    use cosmwasm_std::{coins, BankMsg};
29
30    #[test]
31    fn test_merge_empty_responses() {
32        let merged = merge_responses(vec![]);
33
34        assert!(merged.attributes.is_empty());
35        assert!(merged.events.is_empty());
36        assert!(merged.messages.is_empty());
37        assert!(merged.data.is_none());
38    }
39
40    #[test]
41    fn test_merge_responses() {
42        let resp1: Response = Response::new()
43            .add_attributes(vec![("key1", "value1"), ("send", "1uosmo")])
44            .add_messages(vec![BankMsg::Send {
45                to_address: String::from("recipient"),
46                amount: coins(1, "uosmo"),
47            }])
48            .set_data(b"data");
49        let resp2: Response = Response::new()
50            .add_attributes(vec![("key2", "value2"), ("send", "2uosmo")])
51            .add_message(BankMsg::Send {
52                to_address: String::from("recipient"),
53                amount: coins(2, "uosmo"),
54            });
55        let merged = merge_responses(vec![resp1, resp2]);
56
57        let expected_response: Response = Response::new()
58            .add_attributes(vec![
59                ("key1", "value1"),
60                ("send", "1uosmo"),
61                ("key2", "value2"),
62                ("send", "2uosmo"),
63            ])
64            .add_messages(vec![
65                BankMsg::Send {
66                    to_address: String::from("recipient"),
67                    amount: coins(1, "uosmo"),
68                },
69                BankMsg::Send {
70                    to_address: String::from("recipient"),
71                    amount: coins(2, "uosmo"),
72                },
73            ])
74            .set_data(b"data");
75        assert_eq!(merged, expected_response);
76    }
77
78    #[test]
79    #[should_panic(expected = "Cannot merge multiple responses with data")]
80    fn test_merge_multiple_responses_with_data() {
81        let resp1: Response = Response::new().set_data(b"data");
82        let resp2: Response = Response::new().set_data(b"data2");
83        merge_responses(vec![resp1, resp2]);
84    }
85}