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