1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#![allow(deprecated)]
use schemars::JsonSchema;
use std::fmt;
use crate::Binary;
use super::{attr, Attribute, CosmosMsg, Empty, Response};
#[deprecated(
since = "0.14.0",
note = "Use mutating helpers on Response/InitResponse/HandleResponse/MigrateResponse directly."
)]
#[derive(Clone, Debug, PartialEq)]
pub struct Context<T = Empty>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
messages: Vec<CosmosMsg<T>>,
attributes: Vec<Attribute>,
data: Option<Binary>,
}
impl<T> Default for Context<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn default() -> Self {
Context {
messages: vec![],
attributes: vec![],
data: None,
}
}
}
impl<T> Context<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
pub fn new() -> Self {
Self::default()
}
pub fn add_attribute<K: ToString, V: ToString>(&mut self, key: K, value: V) {
self.attributes.push(attr(key, value));
}
pub fn add_message<U: Into<CosmosMsg<T>>>(&mut self, msg: U) {
self.messages.push(msg.into());
}
pub fn set_data<U: Into<Binary>>(&mut self, data: U) {
self.data = Some(data.into());
}
}
impl<T> From<Context<T>> for Response<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn from(ctx: Context<T>) -> Self {
Response {
submessages: vec![],
messages: ctx.messages,
attributes: ctx.attributes,
data: ctx.data,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{coins, BankMsg, Response};
#[test]
fn empty_context() {
let ctx = Context::new();
let init: Response = ctx.into();
assert_eq!(init, Response::default());
}
#[test]
fn full_context() {
let mut ctx = Context::new();
ctx.add_attribute("sender", &String::from("john"));
ctx.add_attribute("action", "test");
ctx.add_message(BankMsg::Send {
to_address: String::from("foo"),
amount: coins(128, "uint"),
});
ctx.set_data(b"banana");
let expected_msgs = vec![CosmosMsg::Bank(BankMsg::Send {
to_address: String::from("foo"),
amount: coins(128, "uint"),
})];
let expected_attributes = vec![attr("sender", "john"), attr("action", "test")];
let expected_data = Some(Binary::from(b"banana"));
let response: Response = ctx.into();
assert_eq!(&response.messages, &expected_msgs);
assert_eq!(&response.attributes, &expected_attributes);
assert_eq!(&response.data, &expected_data);
}
}