Skip to content

Commit

Permalink
Metadata tests and remove spaces from types.
Browse files Browse the repository at this point in the history
  • Loading branch information
ascjones committed Nov 26, 2024
1 parent 5b4e2f1 commit 18b7d6d
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 70 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions substrate/frame/examples/view-functions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,22 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false }
log = { workspace = true }
scale-info = { version = "2.11.1", default-features = false, features = ["derive"] }
frame-metadata = { features = ["current"], workspace = true }

frame-support = { path = "../../support", default-features = false }
frame-system = { path = "../../system", default-features = false }

sp-io = { path = "../../../primitives/io", default-features = false }
sp-metadata-ir = { path = "../../../primitives/metadata-ir", default-features = false }
sp-runtime = { path = "../../../primitives/runtime", default-features = false }
sp-std = { path = "../../../primitives/std", default-features = false }
sp-core = { default-features = false, path = "../../../primitives/core" }

frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true }

[dev-dependencies]
pretty_assertions = { version = "1.3.0" }

[features]
default = ["std"]
std = [
Expand Down
1 change: 0 additions & 1 deletion substrate/frame/examples/view-functions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
//! work.
#![cfg_attr(not(feature = "std"), no_std)]

pub mod mock;
pub mod tests;

use frame_support::Parameter;
Expand Down
55 changes: 0 additions & 55 deletions substrate/frame/examples/view-functions/src/mock.rs

This file was deleted.

119 changes: 117 additions & 2 deletions substrate/frame/examples/view-functions/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,60 @@
#![cfg(test)]

use crate::{
mock::*,
pallet::{self, Pallet},
pallet2,
};
use codec::{Decode, Encode};
use frame_support::traits::ViewFunction;
use scale_info::{
form::PortableForm,
meta_type,
};

use frame_metadata::RuntimeMetadata;
use frame_support::{
derive_impl,
traits::ViewFunction,
pallet_prelude::PalletInfoAccess,
};
use sp_io::hashing::twox_128;
use sp_runtime::testing::TestXt;
use sp_metadata_ir::{
ViewFunctionGroupIR,
ViewFunctionMetadataIR,
ViewFunctionArgMetadataIR,
};

pub type AccountId = u32;
pub type Balance = u32;

type Block = frame_system::mocking::MockBlock<Runtime>;
frame_support::construct_runtime!(
pub enum Runtime {
System: frame_system,
ViewFunctionsExample: pallet,
ViewFunctionsInstance: pallet2,
ViewFunctionsInstance1: pallet2::<Instance1>,
}
);

pub type Extrinsic = TestXt<RuntimeCall, ()>;

#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type Block = Block;
}

impl pallet::Config for Runtime {}
impl pallet2::Config<pallet2::Instance1> for Runtime {}

impl pallet2::Config for Runtime {}

pub fn new_test_ext() -> sp_io::TestExternalities {
use sp_runtime::BuildStorage;

let t = RuntimeGenesisConfig { system: Default::default() }.build_storage().unwrap();
t.into()
}

#[test]
fn pallet_get_value_query() {
Expand Down Expand Up @@ -70,6 +118,73 @@ fn pallet_multiple_instances() {
});
}

#[test]
fn metadata_ir_definitions() {
new_test_ext().execute_with(|| {
let metadata_ir = Runtime::metadata_ir();
let pallet1 = metadata_ir.view_functions.groups.iter()
.find(|pallet| pallet.name == "ViewFunctionsExample").unwrap();

fn view_fn_id(preifx_hash: [u8; 16], view_fn_signature: &str) -> [u8; 32] {
let mut id = [0u8; 32];
id[..16].copy_from_slice(&preifx_hash);
id[16..].copy_from_slice(&twox_128(view_fn_signature.as_bytes()));
id
}


let get_value_id = view_fn_id(
<ViewFunctionsExample as PalletInfoAccess>::name_hash(),
"get_value() -> Option<u32>",
);

let get_value_with_arg_id = view_fn_id(
<ViewFunctionsExample as PalletInfoAccess>::name_hash(),
"get_value_with_arg(u32) -> Option<u32>",
);

pretty_assertions::assert_eq!(
pallet1.view_functions,
vec![
ViewFunctionMetadataIR {
name: "get_value",
id: get_value_id,
args: vec![],
output: meta_type::<Option<u32>>(),
docs: vec![" Query value no args."],
},
ViewFunctionMetadataIR {
name: "get_value_with_arg",
id: get_value_with_arg_id,
args: vec![
ViewFunctionArgMetadataIR {
name: "key",
ty: meta_type::<u32>(),
},
],
output: meta_type::<Option<u32>>(),
docs: vec![" Query value with args."],
},
]
);
});
}

#[test]
fn metadata_encoded_to_custom_value() {
new_test_ext().execute_with(|| { ;
let metadata = sp_metadata_ir::into_latest(Runtime::metadata_ir());
// metadata is currently experimental so lives as a custom value.
let frame_metadata::RuntimeMetadata::V15(v15) = metadata.1 else {
panic!("Expected metadata v15")
};
let custom_value = v15.custom.map.get("view_functions_experimental").expect("Expected custom value");
let view_function_groups: Vec<ViewFunctionGroupIR<PortableForm>> =
Decode::decode(&mut &custom_value.value[..]).unwrap();
assert_eq!(view_function_groups.len(), 4);
});
}

fn test_dispatch_view_function<Q, V>(query: &Q, expected: V)
where
Q: ViewFunction + Encode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,14 @@ impl ViewFunctionDef {
.args_names_types()
.1
.iter()
.map(|ty| quote::quote!(#ty).to_string())
.map(|ty| quote::quote!(#ty).to_string().replace(" ", ""))
.collect::<Vec<_>>()
.join(",");
let return_type = &self.return_type;
let return_type = quote::quote!(#return_type).to_string().replace(" ", "");
let view_fn_signature = format!(
"{view_function_name}({arg_types}) -> {return_type}",
view_function_name = &self.name,
return_type = quote::quote!(#return_type),
);

// hash the signature string
Expand Down
10 changes: 5 additions & 5 deletions substrate/primitives/metadata-ir/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use codec::{Compact, Encode};
use codec::{Compact, Decode, Encode};
use scale_info::{
form::{Form, MetaForm, PortableForm},
prelude::{collections::BTreeMap, vec::Vec},
Expand Down Expand Up @@ -121,7 +121,7 @@ impl IntoPortable for RuntimeApiMethodParamMetadataIR {
}

/// Metadata of the top level runtime view function dispatch.
#[derive(Clone, PartialEq, Eq, Encode, Debug)]
#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug)]
pub struct RuntimeViewFunctionsIR<T: Form = MetaForm> {
/// The type implementing the runtime query dispatch.
pub ty: T::Type,
Expand All @@ -132,7 +132,7 @@ pub struct RuntimeViewFunctionsIR<T: Form = MetaForm> {
/// Metadata of a runtime view function group.
///
/// For example, view functions associated with a pallet would form a view function group.
#[derive(Clone, PartialEq, Eq, Encode, Debug)]
#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug)]
pub struct ViewFunctionGroupIR<T: Form = MetaForm> {
/// Name of the view function group.
pub name: T::String,
Expand All @@ -155,7 +155,7 @@ impl IntoPortable for ViewFunctionGroupIR {
}

/// Metadata of a runtime view function.
#[derive(Clone, PartialEq, Eq, Encode, Debug)]
#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug)]
pub struct ViewFunctionMetadataIR<T: Form = MetaForm> {
/// Query name.
pub name: T::String,
Expand Down Expand Up @@ -184,7 +184,7 @@ impl IntoPortable for ViewFunctionMetadataIR {
}

/// Metadata of a runtime method argument.
#[derive(Clone, PartialEq, Eq, Encode, Debug)]
#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug)]
pub struct ViewFunctionArgMetadataIR<T: Form = MetaForm> {
/// Query argument name.
pub name: T::String,
Expand Down
9 changes: 4 additions & 5 deletions substrate/primitives/metadata-ir/src/v15.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,14 @@ impl From<MetadataIR> for RuntimeMetadataV15 {
registry.map_into_portable(ir.apis.into_iter().map(Into::<RuntimeApiMetadata>::into));
let outer_enums = Into::<OuterEnums>::into(ir.outer_enums).into_portable(&mut registry);

// todo: add tests.
let view_function_interfaces =
let view_function_groups =
registry.map_into_portable(ir.view_functions.groups.into_iter());
let view_functions_custom_metadata = CustomValueMetadata {
ty: ir.view_functions.ty,
value: codec::Encode::encode(&view_function_interfaces),
value: codec::Encode::encode(&view_function_groups),
};
let mut custom_map = scale_info::prelude::collections::BTreeMap::new();
custom_map.insert("view_functions", view_functions_custom_metadata);
let mut custom_map = alloc::collections::BTreeMap::new();
custom_map.insert("view_functions_experimental", view_functions_custom_metadata);
let custom = CustomMetadata { map: custom_map }.into_portable(&mut registry);

Self { types: registry.into(), pallets, extrinsic, ty, apis, outer_enums, custom }
Expand Down

0 comments on commit 18b7d6d

Please sign in to comment.