coreum_wasm_sdk/
shim.rs

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    /// Represents seconds of UTC time since Unix epoch
15    /// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
16    /// 9999-12-31T23:59:59Z inclusive.
17    #[prost(int64, tag = "1")]
18    pub seconds: i64,
19    /// Non-negative fractions of a second at nanosecond resolution. Negative
20    /// second values with fractions must still have non-negative nanos values
21    /// that count forward in time. Must be from 0 to 999,999,999
22    /// inclusive.
23    #[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    /// Signed seconds of the span of time. Must be from -315,576,000,000
87    /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
88    /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
89    #[prost(int64, tag = "1")]
90    pub seconds: i64,
91    /// Signed fractions of a second at nanosecond resolution of the span
92    /// of time. Durations less than one second are represented with a 0
93    /// `seconds` field and a positive or negative `nanos` field. For durations
94    /// of one second or more, a non-zero value for the `nanos` field must be
95    /// of the same sign as the `seconds` field. Must be from -999,999,999
96    /// to +999,999,999 inclusive.
97    #[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    /// A URL/resource name that uniquely identifies the type of the serialized
144    /// protocol buffer message. This string must contain at least
145    /// one "/" character. The last segment of the URL's path must represent
146    /// the fully qualified name of the type (as in
147    /// `path/google.protobuf.Duration`). The name should be in a canonical form
148    /// (e.g., leading "." is not accepted).
149    ///
150    /// In practice, teams usually precompile into the binary all types that they
151    /// expect it to use in the context of Any. However, for URLs which use the
152    /// scheme `http`, `https`, or no scheme, one can optionally set up a type
153    /// server that maps type URLs to message definitions as follows:
154    ///
155    /// * If no scheme is provided, `https` is assumed.
156    /// * An HTTP GET on the URL must yield a \[google.protobuf.Type][\]
157    ///   value in binary format, or produce an error.
158    /// * Applications are allowed to cache lookup results based on the
159    ///   URL, or have them precompiled into a binary to avoid any
160    ///   lookup. Therefore, binary compatibility needs to be preserved
161    ///   on changes to types. (Use versioned type names to manage
162    ///   breaking changes.)
163    ///
164    /// Note: this functionality is not currently available in the official
165    /// protobuf release, and it is not used for type URLs beginning with
166    /// type.googleapis.com.
167    ///
168    /// Schemes other than `http`, `https` (or the empty scheme) might be
169    /// used with implementation specific semantics.
170    ///
171    #[prost(string, tag = "1")]
172    pub type_url: ::prost::alloc::string::String,
173    /// Must be a valid serialized protocol buffer of the above specified type.
174    #[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                // 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
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
335/// Convert a list of `Coin` from coreum proto generated proto `Coin` type to cosmwasm `Coin` type
336pub 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
342/// Convert a list of `Coin` from cosmwasm `Coin` type to coreum proto generated proto `Coin` type
343pub 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}