use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::{Binary, ReplyOn};
use super::{Attribute, CosmosMsg, Empty};
use crate::results::SubMsg;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Response<T = Empty>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
pub submessages: Vec<SubMsg<T>>,
pub messages: Vec<CosmosMsg<T>>,
pub attributes: Vec<Attribute>,
pub data: Option<Binary>,
}
impl<T> Default for Response<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn default() -> Self {
Response {
submessages: vec![],
messages: vec![],
attributes: vec![],
data: None,
}
}
}
impl<T> Response<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
pub fn new() -> Self {
Self::default()
}
pub fn add_attribute<K: Into<String>, V: Into<String>>(&mut self, key: K, value: V) {
self.attributes.push(Attribute {
key: key.into(),
value: value.into(),
});
}
pub fn add_message<U: Into<CosmosMsg<T>>>(&mut self, msg: U) {
self.messages.push(msg.into());
}
pub fn add_submessage<U: Into<CosmosMsg<T>>>(
&mut self,
id: u64,
msg: U,
gas_limit: Option<u64>,
reply_on: ReplyOn,
) {
let sub = SubMsg {
id,
msg: msg.into(),
gas_limit,
reply_on,
};
self.submessages.push(sub);
}
pub fn set_data<U: Into<Binary>>(&mut self, data: U) {
self.data = Some(data.into());
}
}
#[cfg(test)]
mod tests {
use super::super::BankMsg;
use super::*;
use crate::{coins, from_slice, to_vec};
#[test]
fn can_serialize_and_deserialize_init_response() {
let original = Response {
submessages: vec![SubMsg {
id: 12,
msg: BankMsg::Send {
to_address: String::from("checker"),
amount: coins(888, "moon"),
}
.into(),
gas_limit: Some(12345u64),
reply_on: ReplyOn::Always,
}],
messages: vec![BankMsg::Send {
to_address: String::from("you"),
amount: coins(1015, "earth"),
}
.into()],
attributes: vec![Attribute {
key: "action".to_string(),
value: "release".to_string(),
}],
data: Some(Binary::from([0xAA, 0xBB])),
};
let serialized = to_vec(&original).expect("encode contract result");
let deserialized: Response = from_slice(&serialized).expect("decode contract result");
assert_eq!(deserialized, original);
}
}