decode_constant

Function decode_constant 

Source
pub fn decode_constant<'info, 'resolver, Info, Resolver, V>(
    pallet_name: &str,
    constant_name: &str,
    info: &'info Info,
    type_resolver: &'resolver V::TypeResolver,
    visitor: V,
) -> Result<V::Value<'info, 'resolver>, ConstantDecodeError<Info::TypeId>>
where Info: ConstantTypeInfo, Info::TypeId: Clone + Debug, Resolver: TypeResolver<TypeId = Info::TypeId>, V: Visitor<TypeResolver = Resolver>, V::Error: Debug,
Expand description

Decode a constant from the provided information.

§Examples

Decode a constant into a scale_value::Value`:

use frame_decode::constants::decode_constant;
use frame_metadata::RuntimeMetadata;
use scale_value::scale::ValueVisitor;
use parity_scale_codec::Decode;

let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
let RuntimeMetadata::V14(metadata) = RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap() else { return };

let ed = decode_constant(
    "Balances",
    "ExistentialDeposit",
    &metadata,
    &metadata.types,
    ValueVisitor::new()
).unwrap();

println!("{ed}");

Or we can just take the constant info and decode it “manually” (in this case, remember to also check whether the bytes are fully consumed; leftover bytes indicate a failure to properly decode them):

use frame_decode::constants::{ConstantTypeInfo, decode_constant_with_info};
use frame_metadata::RuntimeMetadata;
use scale_decode::DecodeAsType;
use scale_value::Value;
use parity_scale_codec::Decode;

let metadata_bytes = std::fs::read("artifacts/metadata_10000000_9180.scale").unwrap();
let RuntimeMetadata::V14(metadata) = RuntimeMetadata::decode(&mut &*metadata_bytes).unwrap() else { return };

let ed_info = metadata.constant_info("Balances", "ExistentialDeposit").unwrap();

let ed_bytes = ed_info.bytes;
let ed_type = ed_info.type_id;

let ed = Value::decode_as_type(&mut &*ed_bytes, ed_type, &metadata.types).unwrap();
println!("{ed}");