elys_std/
shim.rs

1use ::serde::{ser, Deserialize, Deserializer, Serialize, Serializer};
2use chrono::{DateTime, NaiveDateTime, Utc};
3use serde::de;
4use serde::de::Visitor;
5
6use std::fmt;
7use std::str::FromStr;
8
9use prost::Message;
10
11#[derive(Clone, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
12pub struct Timestamp {
13    /// Represents seconds of UTC time since Unix epoch
14    /// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
15    /// 9999-12-31T23:59:59Z inclusive.
16    #[prost(int64, tag = "1")]
17    pub seconds: i64,
18    /// Non-negative fractions of a second at nanosecond resolution. Negative
19    /// second values with fractions must still have non-negative nanos values
20    /// that count forward in time. Must be from 0 to 999,999,999
21    /// inclusive.
22    #[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 = NaiveDateTime::from_timestamp_opt(ts.seconds, ts.nanos as u32)
37            .expect("invalid or out-of-range datetime");
38        let dt: DateTime<Utc> = DateTime::from_naive_utc_and_offset(dt, Utc);
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#[derive(Clone, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
84pub struct Duration {
85    /// Signed seconds of the span of time. Must be from -315,576,000,000
86    /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
87    /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
88    #[prost(int64, tag = "1")]
89    pub seconds: i64,
90    /// Signed fractions of a second at nanosecond resolution of the span
91    /// of time. Durations less than one second are represented with a 0
92    /// `seconds` field and a positive or negative `nanos` field. For durations
93    /// of one second or more, a non-zero value for the `nanos` field must be
94    /// of the same sign as the `seconds` field. Must be from -999,999,999
95    /// to +999,999,999 inclusive.
96    #[prost(int32, tag = "2")]
97    pub nanos: i32,
98}
99
100impl Serialize for Duration {
101    fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
102    where
103        S: Serializer,
104    {
105        let mut d = prost_types::Duration::from(self.to_owned());
106        d.normalize();
107
108        serializer.serialize_str(d.to_string().as_str())
109    }
110}
111
112impl<'de> Deserialize<'de> for Duration {
113    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
114    where
115        D: Deserializer<'de>,
116    {
117        struct DurationVisitor;
118
119        impl<'de> Visitor<'de> for DurationVisitor {
120            type Value = Duration;
121
122            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
123                formatter.write_str("Timestamp in RFC3339 format")
124            }
125
126            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
127            where
128                E: de::Error,
129            {
130                value
131                    .parse::<prost_types::Duration>()
132                    .map(Into::into)
133                    .map_err(de::Error::custom)
134            }
135        }
136        deserializer.deserialize_str(DurationVisitor)
137    }
138}
139
140#[derive(Clone, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
141pub struct Any {
142    /// A URL/resource name that uniquely identifies the type of the serialized
143    /// protocol buffer message. This string must contain at least
144    /// one "/" character. The last segment of the URL's path must represent
145    /// the fully qualified name of the type (as in
146    /// `path/google.protobuf.Duration`). The name should be in a canonical form
147    /// (e.g., leading "." is not accepted).
148    ///
149    /// In practice, teams usually precompile into the binary all types that they
150    /// expect it to use in the context of Any. However, for URLs which use the
151    /// scheme `http`, `https`, or no scheme, one can optionally set up a type
152    /// server that maps type URLs to message definitions as follows:
153    ///
154    /// * If no scheme is provided, `https` is assumed.
155    /// * An HTTP GET on the URL must yield a \[google.protobuf.Type][\]
156    ///   value in binary format, or produce an error.
157    /// * Applications are allowed to cache lookup results based on the
158    ///   URL, or have them precompiled into a binary to avoid any
159    ///   lookup. Therefore, binary compatibility needs to be preserved
160    ///   on changes to types. (Use versioned type names to manage
161    ///   breaking changes.)
162    ///
163    /// Note: this functionality is not currently available in the official
164    /// protobuf release, and it is not used for type URLs beginning with
165    /// type.googleapis.com.
166    ///
167    /// Schemes other than `http`, `https` (or the empty scheme) might be
168    /// used with implementation specific semantics.
169    ///
170    #[prost(string, tag = "1")]
171    pub type_url: ::prost::alloc::string::String,
172    /// Must be a valid serialized protocol buffer of the above specified type.
173    #[prost(bytes = "vec", tag = "2")]
174    pub value: ::prost::alloc::vec::Vec<u8>,
175}
176
177macro_rules! expand_as_any {
178    ($($ty:path,)*) => {
179
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                // must be map er else error
219                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                    // @type found
232                    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                    // @type not found, try match the type structure
249                    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
283// [HACK] Register all types that can serde as Any manually for now.
284// must order by type that has more information for Any deserialization to
285// work correctly. Since after serialization, it currently loses @type tag.
286// And deserialization works by trying to iteratively match the structure.
287expand_as_any!();
288
289macro_rules! impl_prost_types_exact_conversion {
290    ($t:ident | $($arg:ident),*) => {
291        impl From<$t> for prost_types::$t {
292            fn from(src: $t) -> Self {
293                prost_types::$t {
294                    $(
295                        $arg: src.$arg,
296                    )*
297                }
298            }
299        }
300
301        impl From<prost_types::$t> for $t {
302            fn from(src: prost_types::$t) -> Self {
303                $t {
304                    $(
305                        $arg: src.$arg,
306                    )*
307                }
308            }
309        }
310    };
311}
312
313impl_prost_types_exact_conversion! { Timestamp | seconds, nanos }
314impl_prost_types_exact_conversion! { Duration | seconds, nanos }
315impl_prost_types_exact_conversion! { Any | type_url, value }
316
317impl From<cosmwasm_std::Coin> for crate::types::cosmos::base::v1beta1::Coin {
318    fn from(cosmwasm_std::Coin { denom, amount }: cosmwasm_std::Coin) -> Self {
319        crate::types::cosmos::base::v1beta1::Coin {
320            denom,
321            amount: amount.into(),
322        }
323    }
324}
325
326impl TryFrom<crate::types::cosmos::base::v1beta1::Coin> for cosmwasm_std::Coin {
327    type Error = cosmwasm_std::StdError;
328
329    fn try_from(
330        crate::types::cosmos::base::v1beta1::Coin { denom, amount }: crate::types::cosmos::base::v1beta1::Coin,
331    ) -> cosmwasm_std::StdResult<Self> {
332        Ok(cosmwasm_std::Coin {
333            denom,
334            amount: amount.parse()?,
335        })
336    }
337}