pub mod address;
use crate::{error::ConstantError, Metadata};
use address::Address;
use alloc::{borrow::ToOwned, string::ToString, vec::Vec};
use frame_decode::constants::ConstantTypeInfo;
use scale_decode::IntoVisitor;
pub fn validate<Addr: Address>(address: Addr, metadata: &Metadata) -> Result<(), ConstantError> {
if let Some(actual_hash) = address.validation_hash() {
let expected_hash = metadata
.pallet_by_name(address.pallet_name())
.ok_or_else(|| ConstantError::PalletNameNotFound(address.pallet_name().to_string()))?
.constant_hash(address.constant_name())
.ok_or_else(|| ConstantError::ConstantNameNotFound {
pallet_name: address.pallet_name().to_string(),
constant_name: address.constant_name().to_owned(),
})?;
if actual_hash != expected_hash {
return Err(ConstantError::IncompatibleCodegen);
}
}
Ok(())
}
pub fn get<Addr: Address>(
address: Addr,
metadata: &Metadata,
) -> Result<Addr::Target, ConstantError> {
validate(&address, metadata)?;
let constant = frame_decode::constants::decode_constant(
address.pallet_name(),
address.constant_name(),
metadata,
metadata.types(),
Addr::Target::into_visitor(),
)
.map_err(ConstantError::CouldNotDecodeConstant)?;
Ok(constant)
}
pub fn get_bytes<Addr: Address>(
address: Addr,
metadata: &Metadata,
) -> Result<Vec<u8>, ConstantError> {
validate(&address, metadata)?;
let constant = metadata
.constant_info(address.pallet_name(), address.constant_name())
.map_err(|e| ConstantError::ConstantInfoError(e.into_owned()))?;
Ok(constant.bytes.to_vec())
}