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