Metadata V16: Implement support for Pallet View Functions (#1981)

* Support Pallet View Functions in Subxt

* fmt

* clippy

* Move a little view function logic to subxt_core

* clippy

* Add back check that prob isnt needed

* avoid vec macro in core

* Add view funciton test and apply various fixes to get it working

* Add test for dynamic view fn call and fix issues

* clippy

* fix test-runtime

* fmt

* remove export

* avoid vec for nostd core

* use const instead of fn for view fn call name

* Update to support latest unstable metadata

* Update metadata stripping tests for new v16 version
This commit is contained in:
James Wilson
2025-04-24 14:42:07 +01:00
committed by GitHub
parent 21b3f52191
commit 4524590821
28 changed files with 875 additions and 108 deletions
+69
View File
@@ -0,0 +1,69 @@
// Copyright 2019-2024 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
//! Encode View Function payloads, decode the associated values returned from them, and validate
//! static View Function payloads.
pub mod payload;
use crate::error::{Error, MetadataError};
use crate::metadata::{DecodeWithMetadata, Metadata};
use alloc::vec::Vec;
use payload::Payload;
/// Run the validation logic against some View Function payload you'd like to use. Returns `Ok(())`
/// if the payload is valid (or if it's not possible to check since the payload has no validation hash).
/// Return an error if the payload was not valid or something went wrong trying to validate it (ie
/// the View Function in question do not exist at all)
pub fn validate<P: Payload>(payload: &P, metadata: &Metadata) -> Result<(), Error> {
let Some(static_hash) = payload.validation_hash() else {
return Ok(());
};
let view_function = metadata
.view_function_by_query_id(payload.query_id())
.ok_or_else(|| MetadataError::ViewFunctionNotFound(*payload.query_id()))?;
if static_hash != view_function.hash() {
return Err(MetadataError::IncompatibleCodegen.into());
}
Ok(())
}
/// The name of the Runtime API call which can execute
pub const CALL_NAME: &str = "RuntimeViewFunction_execute_view_function";
/// Encode the bytes that will be passed to the "execute_view_function" Runtime API call,
/// to execute the View Function represented by the given payload.
pub fn call_args<P: Payload>(payload: &P, metadata: &Metadata) -> Result<Vec<u8>, Error> {
let mut call_args = Vec::with_capacity(32);
call_args.extend_from_slice(payload.query_id());
let mut call_arg_params = Vec::new();
payload.encode_args_to(metadata, &mut call_arg_params)?;
use codec::Encode;
call_arg_params.encode_to(&mut call_args);
Ok(call_args)
}
/// Decode the value bytes at the location given by the provided View Function payload.
pub fn decode_value<P: Payload>(
bytes: &mut &[u8],
payload: &P,
metadata: &Metadata,
) -> Result<P::ReturnType, Error> {
let view_function = metadata
.view_function_by_query_id(payload.query_id())
.ok_or_else(|| MetadataError::ViewFunctionNotFound(*payload.query_id()))?;
let val = <P::ReturnType as DecodeWithMetadata>::decode_with_metadata(
&mut &bytes[..],
view_function.output_ty(),
metadata,
)?;
Ok(val)
}
+153
View File
@@ -0,0 +1,153 @@
// Copyright 2019-2024 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
//! This module contains the trait and types used to represent
//! View Function calls that can be made.
use alloc::vec::Vec;
use core::marker::PhantomData;
use derive_where::derive_where;
use scale_encode::EncodeAsFields;
use scale_value::Composite;
use crate::dynamic::DecodedValueThunk;
use crate::error::MetadataError;
use crate::Error;
use crate::metadata::{DecodeWithMetadata, Metadata};
/// This represents a View Function payload that can call into the runtime of node.
///
/// # Components
///
/// - associated return type
///
/// Resulting bytes of the call are interpreted into this type.
///
/// - query ID
///
/// The ID used to identify in the runtime which view function to call.
///
/// - encoded arguments
///
/// Each argument of the View Function must be scale-encoded.
pub trait Payload {
/// The return type of the function call.
// Note: `DecodeWithMetadata` is needed to decode the function call result
// with the `subxt::Metadata.
type ReturnType: DecodeWithMetadata;
/// The payload target.
fn query_id(&self) -> &[u8; 32];
/// Scale encode the arguments data.
fn encode_args_to(&self, metadata: &Metadata, out: &mut Vec<u8>) -> Result<(), Error>;
/// Encode arguments data and return the output. This is a convenience
/// wrapper around [`Payload::encode_args_to`].
fn encode_args(&self, metadata: &Metadata) -> Result<Vec<u8>, Error> {
let mut v = Vec::new();
self.encode_args_to(metadata, &mut v)?;
Ok(v)
}
/// Returns the statically generated validation hash.
fn validation_hash(&self) -> Option<[u8; 32]> {
None
}
}
/// A View Function payload containing the generic argument data
/// and interpreting the result of the call as `ReturnTy`.
///
/// This can be created from static values (ie those generated
/// via the `subxt` macro) or dynamic values via [`dynamic`].
#[derive_where(Clone, Debug, Eq, Ord, PartialEq, PartialOrd; ArgsData)]
pub struct DefaultPayload<ArgsData, ReturnTy> {
query_id: [u8; 32],
args_data: ArgsData,
validation_hash: Option<[u8; 32]>,
_marker: PhantomData<ReturnTy>,
}
/// A statically generated View Function payload.
pub type StaticPayload<ArgsData, ReturnTy> = DefaultPayload<ArgsData, ReturnTy>;
/// A dynamic View Function payload.
pub type DynamicPayload = DefaultPayload<Composite<()>, DecodedValueThunk>;
impl<ArgsData: EncodeAsFields, ReturnTy: DecodeWithMetadata> Payload
for DefaultPayload<ArgsData, ReturnTy>
{
type ReturnType = ReturnTy;
fn query_id(&self) -> &[u8; 32] {
&self.query_id
}
fn encode_args_to(&self, metadata: &Metadata, out: &mut Vec<u8>) -> Result<(), Error> {
let view_function = metadata
.view_function_by_query_id(&self.query_id)
.ok_or(MetadataError::ViewFunctionNotFound(self.query_id))?;
let mut fields = view_function
.inputs()
.map(|input| scale_encode::Field::named(input.ty, &input.name));
self.args_data
.encode_as_fields_to(&mut fields, metadata.types(), out)?;
Ok(())
}
fn validation_hash(&self) -> Option<[u8; 32]> {
self.validation_hash
}
}
impl<ReturnTy, ArgsData> DefaultPayload<ArgsData, ReturnTy> {
/// Create a new [`DefaultPayload`] for a View Function call.
pub fn new(query_id: [u8; 32], args_data: ArgsData) -> Self {
DefaultPayload {
query_id,
args_data,
validation_hash: None,
_marker: PhantomData,
}
}
/// Create a new static [`DefaultPayload`] for a View Function call
/// using static function name and scale-encoded argument data.
///
/// This is only expected to be used from codegen.
#[doc(hidden)]
pub fn new_static(
query_id: [u8; 32],
args_data: ArgsData,
hash: [u8; 32],
) -> DefaultPayload<ArgsData, ReturnTy> {
DefaultPayload {
query_id,
args_data,
validation_hash: Some(hash),
_marker: core::marker::PhantomData,
}
}
/// Do not validate this call prior to submitting it.
pub fn unvalidated(self) -> Self {
Self {
validation_hash: None,
..self
}
}
/// Returns the arguments data.
pub fn args_data(&self) -> &ArgsData {
&self.args_data
}
}
/// Create a new [`DynamicPayload`] to call a View Function.
pub fn dynamic(query_id: [u8; 32], args_data: impl Into<Composite<()>>) -> DynamicPayload {
DefaultPayload::new(query_id, args_data.into())
}