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