desmos_bindings/
shim.rs

1use ::serde::{ser::SerializeMap, Deserialize, Deserializer, Serialize, Serializer};
2use chrono::{DateTime, NaiveDateTime, Utc};
3use cosmwasm_std::Binary;
4use prost::Message;
5use serde::de;
6use serde::de::Visitor;
7use std::fmt;
8use std::str::FromStr;
9
10/// Timestamp represents a point in time independent of any time zone or local
11/// calendar, encoded as a count of seconds and fractions of seconds at
12/// nanosecond resolution.
13#[derive(Clone, 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 = NaiveDateTime::from_timestamp_opt(ts.seconds, ts.nanos as u32);
39        let dt: DateTime<Utc> = DateTime::from_utc(dt.unwrap_or_default(), Utc);
40        serializer.serialize_str(format!("{:?}", dt).as_str())
41    }
42}
43
44impl<'de> Deserialize<'de> for Timestamp {
45    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
46    where
47        D: Deserializer<'de>,
48    {
49        struct TimestampVisitor;
50
51        impl<'de> Visitor<'de> for TimestampVisitor {
52            type Value = Timestamp;
53
54            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
55                formatter.write_str("Timestamp in RFC3339 format")
56            }
57
58            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
59            where
60                E: de::Error,
61            {
62                let utc: DateTime<Utc> = chrono::DateTime::from_str(value).map_err(|err| {
63                    serde::de::Error::custom(format!(
64                        "Failed to parse {} as datetime: {:?}",
65                        value, err
66                    ))
67                })?;
68                let ts = Timestamp::from(utc);
69                Ok(ts)
70            }
71        }
72        deserializer.deserialize_str(TimestampVisitor)
73    }
74}
75
76impl From<DateTime<Utc>> for Timestamp {
77    fn from(dt: DateTime<Utc>) -> Self {
78        Timestamp {
79            seconds: dt.timestamp(),
80            nanos: dt.timestamp_subsec_nanos() as i32,
81        }
82    }
83}
84
85#[derive(Clone, 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<'de> Visitor<'de> 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/// Any contains an arbitrary serialized protocol buffer message along with a URL that describes the type of the serialized message.
143#[derive(Clone, PartialEq, Eq, ::prost::Message, schemars::JsonSchema)]
144pub struct Any {
145    /// A URL/resource name that uniquely identifies the type of the serialized
146    /// protocol buffer message. This string must contain at least
147    /// one "/" character. The last segment of the URL's path must represent
148    /// the fully qualified name of the type (as in
149    /// `path/google.protobuf.Duration`). The name should be in a canonical form
150    /// (e.g., leading "." is not accepted).
151    ///
152    /// In practice, teams usually precompile into the binary all types that they
153    /// expect it to use in the context of Any. However, for URLs which use the
154    /// scheme `http`, `https`, or no scheme, one can optionally set up a type
155    /// server that maps type URLs to message definitions as follows:
156    ///
157    /// * If no scheme is provided, `https` is assumed.
158    /// * An HTTP GET on the URL must yield a \[google.protobuf.Type][\]
159    ///   value in binary format, or produce an error.
160    /// * Applications are allowed to cache lookup results based on the
161    ///   URL, or have them precompiled into a binary to avoid any
162    ///   lookup. Therefore, binary compatibility needs to be preserved
163    ///   on changes to types. (Use versioned type names to manage
164    ///   breaking changes.)
165    ///
166    /// Note: this functionality is not currently available in the official
167    /// protobuf release, and it is not used for type URLs beginning with
168    /// type.googleapis.com.
169    ///
170    /// Schemes other than `http`, `https` (or the empty scheme) might be
171    /// used with implementation specific semantics.
172    ///
173    #[prost(string, tag = "1")]
174    pub type_url: ::prost::alloc::string::String,
175    /// Must be a valid serialized protocol buffer of the above specified type.
176    #[prost(bytes = "vec", tag = "2")]
177    pub value: ::prost::alloc::vec::Vec<u8>,
178}
179
180impl Serialize for Any {
181    fn serialize<S>(
182        &self,
183        serializer: S,
184    ) -> Result<<S as ::serde::Serializer>::Ok, <S as ::serde::Serializer>::Error>
185    where
186        S: ::serde::Serializer,
187    {
188        let mut map = serializer.serialize_map(Some(2))?;
189        map.serialize_entry("@type".into(), &self.type_url)?;
190        map.serialize_entry("value".into(), &Binary::from(self.value.clone()))?;
191        return map.end();
192    }
193}
194
195impl<'de> Deserialize<'de> for Any {
196    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
197    where
198        D: serde::Deserializer<'de>,
199    {
200        // Get raw value from deserializer
201        let raw = match serde_cw_value::Value::deserialize(deserializer) {
202            Ok(raw) => raw,
203            Err(err) => {
204                return Err(err);
205            }
206        };
207
208        // Turn raw value into deserialize map value
209        let map = match raw.clone() {
210            serde_cw_value::Value::Map(m) => Ok(m),
211            _ => Err(serde::de::Error::custom("data must have map structure")),
212        }?;
213
214        // Get type url from map
215        let type_url = map
216            .get(&serde_cw_value::Value::String("@type".to_string()))
217            .map(|t| match t.to_owned() {
218                serde_cw_value::Value::String(s) => Ok(s),
219                _ => Err(serde::de::Error::custom("type_url must be String")),
220            })
221            .transpose()?
222            .unwrap_or_default();
223
224        // Get base64 encoded value from deserialize map
225        let value_in_base64 = map
226            .get(&serde_cw_value::Value::String("value".to_string()))
227            .map(|t| match t.to_owned() {
228                serde_cw_value::Value::String(s) => Ok(s),
229                _ => Err(serde::de::Error::custom("value must be String")),
230            })
231            .transpose()?
232            .unwrap_or_default();
233
234        // Convert base64 encoded value into vector
235        let value = match Binary::from_base64(&value_in_base64) {
236            Ok(v) => Ok(v),
237            _ => Err(serde::de::Error::custom("value must be base64 encoded")),
238        }?
239        .to_vec();
240
241        return Ok(Any { type_url, value });
242    }
243}
244
245macro_rules! expand_as_any {
246    ($($ty:path,)*) => {
247        $(
248            impl TryFrom<Any> for $ty {
249                type Error = prost::DecodeError;
250
251                fn try_from(any: Any) -> Result<Self, Self::Error> {
252                    if any.type_url != <$ty>::TYPE_URL {
253                        return Err(prost::DecodeError::new("type url does not match".to_string()));
254                    }
255                    prost::Message::decode(any.value.as_slice())
256                }
257            }
258
259            impl Into<Any> for $ty {
260                fn into(self) -> Any {
261                    Any {
262                        type_url: <$ty>::TYPE_URL.to_string(),
263                        value: self.encode_to_vec(),
264                    }
265                }
266            }
267        )*
268    };
269}
270
271// [HACK] Register all types that can convert to Any manually for now.
272expand_as_any!(
273    // public keys
274    crate::proto::cosmos::crypto::ed25519::PubKey,
275    crate::proto::cosmos::crypto::secp256k1::PubKey,
276    crate::proto::cosmos::crypto::secp256r1::PubKey,
277    // authz module
278    crate::proto::cosmos::authz::v1beta1::GenericAuthorization,
279    // feegrant module
280    crate::proto::cosmos::feegrant::v1beta1::BasicAllowance,
281    crate::proto::cosmos::feegrant::v1beta1::PeriodicAllowance,
282    crate::proto::cosmos::feegrant::v1beta1::AllowedMsgAllowance,
283    // profiles module
284    crate::proto::desmos::profiles::v3::Profile,
285    crate::proto::desmos::profiles::v3::Bech32Address,
286    crate::proto::desmos::profiles::v3::HexAddress,
287    crate::proto::desmos::profiles::v3::Base58Address,
288    crate::proto::desmos::profiles::v3::SingleSignature,
289    crate::proto::desmos::profiles::v3::CosmosMultiSignature,
290    // posts module
291    crate::proto::desmos::posts::v3::Poll,
292    crate::proto::desmos::posts::v3::Media,
293    // reactions module
294    crate::proto::desmos::reactions::v1::FreeTextValue,
295    crate::proto::desmos::reactions::v1::RegisteredReactionValue,
296    // reports module
297    crate::proto::desmos::reports::v1::UserTarget,
298    crate::proto::desmos::reports::v1::PostTarget,
299    // subspaces module
300    crate::proto::desmos::subspaces::v3::UserGrantee,
301    crate::proto::desmos::subspaces::v3::GroupGrantee,
302    crate::proto::desmos::subspaces::v3::authz::GenericSubspaceAuthorization,
303);
304
305macro_rules! impl_prost_types_exact_conversion {
306    ($t:ident | $($arg:ident),*) => {
307        impl From<$t> for prost_types::$t {
308            fn from(src: $t) -> Self {
309                prost_types::$t {
310                    $(
311                        $arg: src.$arg,
312                    )*
313                }
314            }
315        }
316
317        impl From<prost_types::$t> for $t {
318            fn from(src: prost_types::$t) -> Self {
319                $t {
320                    $(
321                        $arg: src.$arg,
322                    )*
323                }
324            }
325        }
326    };
327}
328
329impl_prost_types_exact_conversion! { Timestamp | seconds, nanos }
330impl_prost_types_exact_conversion! { Duration | seconds, nanos }
331impl_prost_types_exact_conversion! { Any | type_url, value }
332
333impl From<cosmwasm_std::Coin> for crate::proto::cosmos::base::v1beta1::Coin {
334    fn from(cosmwasm_std::Coin { denom, amount }: cosmwasm_std::Coin) -> Self {
335        crate::proto::cosmos::base::v1beta1::Coin {
336            denom,
337            amount: amount.into(),
338        }
339    }
340}
341
342impl TryFrom<crate::proto::cosmos::base::v1beta1::Coin> for cosmwasm_std::Coin {
343    type Error = cosmwasm_std::StdError;
344
345    fn try_from(
346        crate::proto::cosmos::base::v1beta1::Coin { denom, amount }: crate::proto::cosmos::base::v1beta1::Coin,
347    ) -> cosmwasm_std::StdResult<Self> {
348        Ok(cosmwasm_std::Coin {
349            denom,
350            amount: amount.parse()?,
351        })
352    }
353}