provwasm_std/
shim.rs

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    /// 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 = 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    /// Signed seconds of the span of time. Must be from -315,576,000,000
88    /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
89    /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
90    #[prost(int64, tag = "1")]
91    pub seconds: i64,
92    /// Signed fractions of a second at nanosecond resolution of the span
93    /// of time. Durations less than one second are represented with a 0
94    /// `seconds` field and a positive or negative `nanos` field. For durations
95    /// of one second or more, a non-zero value for the `nanos` field must be
96    /// of the same sign as the `seconds` field. Must be from -999,999,999
97    /// to +999,999,999 inclusive.
98    #[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    /// A URL/resource name that uniquely identifies the type of the serialized
145    /// protocol buffer message. This string must contain at least
146    /// one "/" character. The last segment of the URL's path must represent
147    /// the fully qualified name of the type (as in
148    /// `path/google.protobuf.Duration`). The name should be in a canonical form
149    /// (e.g., leading "." is not accepted).
150    ///
151    /// In practice, teams usually precompile into the binary all types that they
152    /// expect it to use in the context of Any. However, for URLs which use the
153    /// scheme `http`, `https`, or no scheme, one can optionally set up a type
154    /// server that maps type URLs to message definitions as follows:
155    ///
156    /// * If no scheme is provided, `https` is assumed.
157    /// * An HTTP GET on the URL must yield a \[google.protobuf.Type][\]
158    ///   value in binary format, or produce an error.
159    /// * Applications are allowed to cache lookup results based on the
160    ///   URL, or have them precompiled into a binary to avoid any
161    ///   lookup. Therefore, binary compatibility needs to be preserved
162    ///   on changes to types. (Use versioned type names to manage
163    ///   breaking changes.)
164    ///
165    /// Note: this functionality is not currently available in the official
166    /// protobuf release, and it is not used for type URLs beginning with
167    /// type.googleapis.com.
168    ///
169    /// Schemes other than `http`, `https` (or the empty scheme) might be
170    /// used with implementation specific semantics.
171    ///
172    #[prost(string, tag = "1")]
173    pub type_url: ::prost::alloc::string::String,
174    /// Must be a valid serialized protocol buffer of the above specified type.
175    #[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        // Get raw value from deserializer
200        let raw = match serde_cw_value::Value::deserialize(deserializer) {
201            Ok(raw) => raw,
202            Err(err) => {
203                return Err(err);
204            }
205        };
206
207        // Turn raw value into deserialize map value
208        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        // Get type url from map
214        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        // Get base64 encoded value from deserialize map
224        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        // Convert base64 encoded value into vector
234        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
294/// Convert a list of `Coin` from provenance proto generated `Coin` type to cosmwasm `Coin` type
295pub 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
301/// Convert a list of `Coin` from cosmwasm `Coin` type to proto generated `Coin` type
302pub 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}