decode_storage_key_values

Function decode_storage_key_values 

Source
pub fn decode_storage_key_values<Values, Resolver>(
    key_bytes: &[u8],
    decoded_key: &StorageKey<Resolver::TypeId>,
    types: &Resolver,
) -> Result<Values, StorageKeyValueDecodeError>
where Values: IntoDecodableValues, Resolver: TypeResolver,
Expand description

Attempt to decode the values attached to parts of a storage key into the provided output type. decode_storage_key and related functions take a storage key and return information (in the form of StorageKey) which describes each of the parts of the key.

This function takes that information and returns a user-defined generic type which implements IntoDecodableValues, and attempts to decode some or all of the values from it (in order).

ยงExample

Here, we decode some storage keys from a block.

use frame_decode::storage::{ decode_storage_key, decode_storage_key_values };
use frame_decode::helpers::decode_with_visitor;
use frame_metadata::RuntimeMetadata;
use parity_scale_codec::Decode;
use scale_value::scale::ValueVisitor;

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 storage_keyval_bytes = std::fs::read("artifacts/storage_10000000_9180_system_account.json").unwrap();
let storage_keyval_hex: Vec<(String, String)> = serde_json::from_slice(&storage_keyval_bytes).unwrap();

for (key, _val) in storage_keyval_hex {
    let key_bytes = hex::decode(key.trim_start_matches("0x")).unwrap();

    // First decode the storage key, returning information about it:
    let storage_info = decode_storage_key(
        "System",
        "Account",
        &mut &*key_bytes,
        &metadata,
        &metadata.types
    ).unwrap();

    // Use this information to decode any values within the key. Here
    // we ask for the first (and here only) value present, which we know to
    // be decodable into a [u8; 32] because it's an AccountId32.
    let values: ([u8;32],) = decode_storage_key_values(
        &key_bytes,
        &storage_info,
        &metadata.types
    ).unwrap();

    println!("Account ID Hex: {}", hex::encode(&values.0));

    // If we don't know what we are decoding, we can target a Vec<scale_value::Value>
    // which allows arbitrary items to be decoded into it.
    let values: Vec<scale_value::Value> = decode_storage_key_values(
        &key_bytes,
        &storage_info,
        &metadata.types
    ).unwrap();

    println!("All values extracted from key:");
    for value in values {
        println!("  {value}");
    }
}