1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
//! [`cosmwasm_std::Addr`]<->[`cosmwasm_std::CanonicalAddr`] conversion for types that contain addresses.

use crate::cosmwasm_std::{
    self, Addr, Api, Binary, BlockInfo, CanonicalAddr, Coin, Empty,
    StdResult, Uint64, Uint128, Uint256, Uint512, Decimal, Decimal256,
};

use super::sealed;

/// The trait that represents any type which contains a [`cosmwasm_std::Addr`]
/// and needs to be stored since [`cosmwasm_std::Addr`] is usually converted
/// to [`cosmwasm_std::CanonicalAddr`] first. The trait must be implemented on
/// the non-canonical version of the type and the output of [`Canonize::canonize`] must
/// return the canonical version of the same type which is represented by its sister trait
/// [`Humanize`]. This relationship is enforced on the type level since [`Canonize::Output`]
/// must implement [`Humanize`] and vice versa. 
/// 
/// This trait can be **derived** which does this automatically for you, provided that all fields of
/// the given type implement the trait as well. Works on both generic and non-generic structs and enums.
/// For non-generic types it generates a new type with the same name but with the word `Canon` postfix
/// and all of its members have whatever the [`Canonize::Output`] is for their type.
/// 
/// # Examples
/// 
/// ```
/// use fadroma::cosmwasm_std::{self, Addr, CanonicalAddr, Uint128, testing::mock_dependencies};
/// use fadroma::prelude::{Canonize, Humanize};
/// 
/// #[derive(Canonize, Clone, PartialEq, Debug)]
/// struct Account {
///     address: Addr,
///     balance: Uint128,
///     timestamp: u64
/// }
/// 
/// #[derive(Canonize, Clone, PartialEq, Debug)]
/// struct AccountGeneric<T> {
///     address: T,
///     balance: Uint128,
///     timestamp: u64
/// }
/// 
/// let deps = mock_dependencies();
/// let api = deps.as_ref().api;
/// 
/// let account = Account {
///     address: Addr::unchecked("address"),
///     balance: Uint128::new(100),
///     timestamp: 123
/// };
/// 
/// let canonical: AccountCanon = account.clone().canonize(api).unwrap();
/// let humanized = canonical.humanize(api).unwrap();
/// 
/// assert_eq!(account, humanized);
/// 
/// let account = AccountGeneric {
///     address: Addr::unchecked("address"),
///     balance: Uint128::new(100),
///     timestamp: 123
/// };
/// 
/// let canonical: AccountGeneric<CanonicalAddr> = account.clone().canonize(api).unwrap();
/// let humanized = canonical.humanize(api).unwrap();
/// 
/// assert_eq!(account, humanized);
/// ```
pub trait Canonize {
    type Output: Humanize;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output>;
}

/// The trait that represents the canonical version of the given type.
/// See [`Canonize`] for more info.
pub trait Humanize {
    type Output: Canonize;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output>;
}

/// Sealed marker trait for types that *may* represent
/// an address. The types that *may* be a valid address are
/// [`&str`] and [`String`] since they could potentially contain
/// an address. We use [`cosmwasm_std::Api::addr_validate`] or
/// [`cosmwasm_std::Api::addr_canonicalize`] to turn them into
/// [`cosmwasm_std::Addr`] and [`cosmwasm_std::CanonicalAddr`]
/// respectively, both of which definitely *do* contain
/// a valid address and therefore also satisfy this trait.
/// 
/// If you want to constrain your type to contain valid
/// addresses **only**, use [`Address`] instead.
pub trait MaybeAddress: sealed::Sealed { }

/// Sealed marker trait for types that represent a valid address.
/// Those can only be [`cosmwasm_std::Addr`] and [`cosmwasm_std::CanonicalAddr`]
/// and thus are the only types that implement the trait.
/// 
/// If you want to constrain your type to contain addresses
/// that *may* have not be validated (i.e [`&str`] and [`String`]),
/// use [`MaybeAddress`] instead.
pub trait Address: MaybeAddress { }

/// Attempting to canonicalize an empty address will fail.
/// This function skips calling [`cosmwasm_std::Api::addr_canonicalize`]
/// if the input is empty and returns `CanonicalAddr::default()` instead.
pub fn canonize_maybe_empty(api: &dyn Api, addr: &Addr) -> StdResult<CanonicalAddr> {
    Ok(if addr.as_str() == "" {
        CanonicalAddr(Binary(Vec::new()))
    } else {
        api.addr_canonicalize(addr.as_str())?
    })
}

/// Attempting to humanize an empty address will fail.
/// This function skips calling [`cosmwasm_std::Api::addr_humanize`] if the input is empty
/// and returns `Addr::default()` instead.
pub fn humanize_maybe_empty(api: &dyn Api, addr: &CanonicalAddr) -> StdResult<Addr> {
    Ok(if *addr == CanonicalAddr(Binary(Vec::new())) {
        Addr::unchecked("")
    } else {
        api.addr_humanize(addr)?
    })
}

/// Validates a collection of strings that are expected to be valid addresses.
#[inline]
pub fn validate_addresses(api: &dyn Api, mut addresses: Vec<String>) -> StdResult<Vec<Addr>> {
    addresses
        .drain(..)
        .map(|x| api.addr_validate(&x))
        .collect::<StdResult<Vec<Addr>>>()
}

impl Humanize for CanonicalAddr {
    type Output = Addr;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output> {
        humanize_maybe_empty(api, &self)
    }
}

impl Canonize for Addr {
    type Output = CanonicalAddr;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        canonize_maybe_empty(api, &self)
    }
}

impl Humanize for &CanonicalAddr {
    type Output = Addr;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output> {
        humanize_maybe_empty(api, self)
    }
}

impl Canonize for &Addr {
    type Output = CanonicalAddr;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        canonize_maybe_empty(api, self)
    }
}

impl Humanize for &[CanonicalAddr] {
    type Output = Vec<Addr>;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| x.humanize(api)).collect()
    }
}

impl Canonize for &[Addr] {
    type Output = Vec<CanonicalAddr>;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| x.canonize(api)).collect()
    }
}

impl Humanize for &[&CanonicalAddr] {
    type Output = Vec<Addr>;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| x.humanize(api)).collect()
    }
}

impl Canonize for &[&Addr] {
    type Output = Vec<CanonicalAddr>;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| x.canonize(api)).collect()
    }
}

impl Canonize for &[String] {
    type Output = Vec<CanonicalAddr>;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| api.addr_canonicalize(x)).collect()
    }
}

impl Canonize for &str {
    type Output = CanonicalAddr;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        api.addr_canonicalize(self)
    }
}

impl Canonize for &[&str] {
    type Output = Vec<CanonicalAddr>;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| api.addr_canonicalize(x)).collect()
    }
}

impl<T: Humanize> Humanize for Vec<T> {
    type Output = Vec<T::Output>;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| x.humanize(api)).collect()
    }
}

impl<T: Canonize> Canonize for Vec<T> {
    type Output = Vec<T::Output>;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        self.into_iter().map(|x| x.canonize(api)).collect()
    }
}

impl<T: Humanize> Humanize for Option<T> {
    type Output = Option<T::Output>;

    fn humanize(self, api: &dyn Api) -> StdResult<Self::Output> {
        match self {
            Some(item) => Ok(Some(item.humanize(api)?)),
            None => Ok(None),
        }
    }
}

impl<T: Canonize> Canonize for Option<T> {
    type Output = Option<T::Output>;

    fn canonize(self, api: &dyn Api) -> StdResult<Self::Output> {
        match self {
            Some(item) => Ok(Some(item.canonize(api)?)),
            None => Ok(None),
        }
    }
}

impl sealed::Sealed for &str { }
impl sealed::Sealed for String { }
impl sealed::Sealed for Addr { }
impl sealed::Sealed for CanonicalAddr { }

impl MaybeAddress for &str { }
impl MaybeAddress for String { }
impl MaybeAddress for Addr { }
impl MaybeAddress for CanonicalAddr { }

impl Address for Addr { }
impl Address for CanonicalAddr { }

/// Use on any type that **does not** contain a [`cosmwasm_std::Addr`].
/// The implementation simply returns `Ok(self)` without doing any
/// transformation.
#[macro_export]
macro_rules! impl_canonize_default {
    ($ty: ty) => {
        impl $crate::core::Humanize for $ty {
            type Output = Self;

            #[inline(always)]
            fn humanize(
                self,
                _api: &dyn cosmwasm_std::Api,
            ) -> cosmwasm_std::StdResult<Self::Output> {
                Ok(self)
            }
        }

        impl $crate::core::Canonize for $ty {
            type Output = Self;

            #[inline(always)]
            fn canonize(
                self,
                _api: &dyn cosmwasm_std::Api,
            ) -> cosmwasm_std::StdResult<Self::Output> {
                Ok(self)
            }
        }
    };
}

impl_canonize_default!(u8);
impl_canonize_default!(u16);
impl_canonize_default!(u32);
impl_canonize_default!(u64);
impl_canonize_default!(u128);
impl_canonize_default!(Uint64);
impl_canonize_default!(Uint128);
impl_canonize_default!(Uint256);
impl_canonize_default!(Uint512);
impl_canonize_default!(Decimal);
impl_canonize_default!(Decimal256);

impl_canonize_default!(i8);
impl_canonize_default!(i16);
impl_canonize_default!(i32);
impl_canonize_default!(i64);
impl_canonize_default!(i128);

impl_canonize_default!(String);
impl_canonize_default!(char);
impl_canonize_default!(bool);
impl_canonize_default!(isize);
impl_canonize_default!(usize);

impl_canonize_default!(Binary);
impl_canonize_default!(Coin);
impl_canonize_default!(BlockInfo);
impl_canonize_default!(Empty);