1use ::serde::{ser, Deserialize, Deserializer, Serialize, Serializer};
2use chrono::{DateTime, NaiveDateTime, Utc};
3use cosmwasm_std::StdResult;
4use serde::de;
5use serde::de::Visitor;
6
7use std::fmt;
8use std::str::FromStr;
9
10use prost::Message;
11
12#[derive(Clone, Copy, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
13pub struct Timestamp {
14 #[prost(int64, tag = "1")]
18 pub seconds: i64,
19 #[prost(int32, tag = "2")]
24 pub nanos: i32,
25}
26
27impl Serialize for Timestamp {
28 fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
29 where
30 S: Serializer,
31 {
32 let mut ts = prost_types::Timestamp {
33 seconds: self.seconds,
34 nanos: self.nanos,
35 };
36 ts.normalize();
37 let dt = DateTime::from_timestamp(ts.seconds, ts.nanos as u32)
38 .expect("invalid or out-of-range datetime");
39 serializer.serialize_str(format!("{:?}", dt).as_str())
40 }
41}
42
43impl<'de> Deserialize<'de> for Timestamp {
44 fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
45 where
46 D: Deserializer<'de>,
47 {
48 struct TimestampVisitor;
49
50 impl<'de> Visitor<'de> for TimestampVisitor {
51 type Value = Timestamp;
52
53 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
54 formatter.write_str("Timestamp in RFC3339 format")
55 }
56
57 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
58 where
59 E: de::Error,
60 {
61 let utc: DateTime<Utc> = chrono::DateTime::from_str(value).map_err(|err| {
62 serde::de::Error::custom(format!(
63 "Failed to parse {} as datetime: {:?}",
64 value, err
65 ))
66 })?;
67 let ts = Timestamp::from(utc);
68 Ok(ts)
69 }
70 }
71 deserializer.deserialize_str(TimestampVisitor)
72 }
73}
74
75impl From<DateTime<Utc>> for Timestamp {
76 fn from(dt: DateTime<Utc>) -> Self {
77 Timestamp {
78 seconds: dt.timestamp(),
79 nanos: dt.timestamp_subsec_nanos() as i32,
80 }
81 }
82}
83
84#[derive(Clone, Copy, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
85pub struct Duration {
86 #[prost(int64, tag = "1")]
90 pub seconds: i64,
91 #[prost(int32, tag = "2")]
98 pub nanos: i32,
99}
100
101impl Serialize for Duration {
102 fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
103 where
104 S: Serializer,
105 {
106 let mut d = prost_types::Duration::from(self.to_owned());
107 d.normalize();
108
109 serializer.serialize_str(d.to_string().as_str())
110 }
111}
112
113impl<'de> Deserialize<'de> for Duration {
114 fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
115 where
116 D: Deserializer<'de>,
117 {
118 struct DurationVisitor;
119
120 impl<'de> Visitor<'de> for DurationVisitor {
121 type Value = Duration;
122
123 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
124 formatter.write_str("Timestamp in RFC3339 format")
125 }
126
127 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
128 where
129 E: de::Error,
130 {
131 value
132 .parse::<prost_types::Duration>()
133 .map(Into::into)
134 .map_err(de::Error::custom)
135 }
136 }
137 deserializer.deserialize_str(DurationVisitor)
138 }
139}
140
141#[derive(Clone, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
142pub struct Any {
143 #[prost(string, tag = "1")]
172 pub type_url: ::prost::alloc::string::String,
173 #[prost(bytes = "vec", tag = "2")]
175 pub value: ::prost::alloc::vec::Vec<u8>,
176}
177
178macro_rules! expand_as_any {
179 ($($ty:path,)*) => {
180
181 impl Serialize for Any {
182 fn serialize<S>(
183 &self,
184 serializer: S,
185 ) -> Result<<S as ::serde::Serializer>::Ok, <S as ::serde::Serializer>::Error>
186 where
187 S: ::serde::Serializer,
188 {
189 $(
190 if self.type_url == <$ty>::TYPE_URL {
191 let value: Result<$ty, <S as ::serde::Serializer>::Error> =
192 prost::Message::decode(self.value.as_slice()).map_err(ser::Error::custom);
193
194 if let Ok(value) = value {
195 return value.serialize(serializer);
196 }
197 }
198 )*
199
200 Err(serde::ser::Error::custom(
201 "data did not match any type that supports serialization as `Any`",
202 ))
203 }
204 }
205
206 impl<'de> Deserialize<'de> for Any {
207 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
208 where
209 D: serde::Deserializer<'de>,
210 {
211 let value = match serde_cw_value::Value::deserialize(deserializer) {
212 Ok(value) => value,
213 Err(err) => {
214 return Err(err);
215 }
216 };
217
218 let type_url = if let serde_cw_value::Value::Map(m) = value.clone() {
220 m.get(&serde_cw_value::Value::String("@type".to_string()))
221 .map(|t| match t.to_owned() {
222 serde_cw_value::Value::String(s) => Ok(s),
223 _ => Err(serde::de::Error::custom("type_url must be String")),
224 })
225 .transpose()
226 } else {
227 Err(serde::de::Error::custom("data must have map structure"))
228 }?;
229
230 match type_url {
231 Some(t) => {
233 $(
234 if t == <$ty>::TYPE_URL {
235 return <$ty>::deserialize(
236 serde_cw_value::ValueDeserializer::<serde_cw_value::DeserializerError>::new(
237 value.clone(),
238 ),
239 )
240 .map(|v| Any {
241 type_url: <$ty>::TYPE_URL.to_string(),
242 value: v.encode_to_vec(),
243 })
244 .map_err(serde::de::Error::custom);
245 }
246 )*
247 }
248 None => {
250 $(
251 if let Ok(v) = <$ty>::deserialize(
252 serde_cw_value::ValueDeserializer::<serde_cw_value::DeserializerError>::new(
253 value.clone(),
254 ),
255 ) {
256 return Ok(Any {
257 type_url: <$ty>::TYPE_URL.to_string(),
258 value: v.encode_to_vec(),
259 });
260 }
261 )*
262 }
263 };
264
265 Err(serde::de::Error::custom(
266 "data did not match any type that supports deserialization as `Any`",
267 ))
268 }
269 }
270
271 $(
272 impl TryFrom<Any> for $ty {
273 type Error = prost::DecodeError;
274
275 fn try_from(value: Any) -> Result<Self, Self::Error> {
276 prost::Message::decode(value.value.as_slice())
277 }
278 }
279 )*
280 };
281}
282
283expand_as_any!();
284
285macro_rules! impl_prost_types_exact_conversion {
286 ($t:ident | $($arg:ident),*) => {
287 impl From<$t> for prost_types::$t {
288 fn from(src: $t) -> Self {
289 prost_types::$t {
290 $(
291 $arg: src.$arg,
292 )*
293 }
294 }
295 }
296
297 impl From<prost_types::$t> for $t {
298 fn from(src: prost_types::$t) -> Self {
299 $t {
300 $(
301 $arg: src.$arg,
302 )*
303 }
304 }
305 }
306 };
307}
308
309impl_prost_types_exact_conversion! { Timestamp | seconds, nanos }
310impl_prost_types_exact_conversion! { Duration | seconds, nanos }
311impl_prost_types_exact_conversion! { Any | type_url, value }
312
313impl From<cosmwasm_std::Coin> for crate::types::cosmos::base::v1beta1::Coin {
314 fn from(cosmwasm_std::Coin { denom, amount }: cosmwasm_std::Coin) -> Self {
315 crate::types::cosmos::base::v1beta1::Coin {
316 denom,
317 amount: amount.into(),
318 }
319 }
320}
321
322impl TryFrom<crate::types::cosmos::base::v1beta1::Coin> for cosmwasm_std::Coin {
323 type Error = cosmwasm_std::StdError;
324
325 fn try_from(
326 crate::types::cosmos::base::v1beta1::Coin { denom, amount }: crate::types::cosmos::base::v1beta1::Coin,
327 ) -> cosmwasm_std::StdResult<Self> {
328 Ok(cosmwasm_std::Coin {
329 denom,
330 amount: amount.parse()?,
331 })
332 }
333}
334
335pub fn try_proto_to_cosmwasm_coins(
337 coins: impl IntoIterator<Item = crate::types::cosmos::base::v1beta1::Coin>,
338) -> StdResult<Vec<cosmwasm_std::Coin>> {
339 coins.into_iter().map(|c| c.try_into()).collect()
340}
341
342pub fn cosmwasm_to_proto_coins(
344 coins: impl IntoIterator<Item = cosmwasm_std::Coin>,
345) -> Vec<crate::types::cosmos::base::v1beta1::Coin> {
346 coins.into_iter().map(|c| c.into()).collect()
347}
348
349#[cfg(test)]
350mod tests {
351 use cosmwasm_std::Uint128;
352
353 use super::*;
354
355 #[test]
356 fn test_coins_conversion() {
357 let coins = vec![
358 cosmwasm_std::Coin {
359 denom: "uatom".to_string(),
360 amount: Uint128::new(100),
361 },
362 cosmwasm_std::Coin {
363 denom: "ucore".to_string(),
364 amount: Uint128::new(200),
365 },
366 ];
367
368 let proto_coins = cosmwasm_to_proto_coins(coins.clone());
369 let cosmwasm_coins = try_proto_to_cosmwasm_coins(proto_coins).unwrap();
370
371 assert_eq!(coins, cosmwasm_coins);
372 }
373}