pub trait Canonize {
type Output: Humanize;
// Required method
fn canonize(self, api: &dyn Api) -> StdResult<Self::Output>;
}
Expand description
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);