referrerpolicy=no-referrer-when-downgrade

Attribute Macro view_functions

Source
#[view_functions]
Expand description

Allows defining view functions on a pallet.

A pallet view function is a read-only function providing access to the state of the pallet from both outside and inside the runtime. It should provide a stable interface for querying the state of the pallet, avoiding direct storage access and upgrading along with the runtime.

§Syntax

View functions methods must be read-only and always return some output. A view_functions impl block only allows methods to be defined inside of it.

§Example

#[frame_support::pallet]
pub mod pallet {
	use frame_support::pallet_prelude::*;

 	#[pallet::config]
 	pub trait Config: frame_system::Config {}

 	#[pallet::pallet]
 	pub struct Pallet<T>(_);

    #[pallet::storage]
	pub type SomeMap<T: Config> = StorageMap<_, Twox64Concat, u32, u32, OptionQuery>;

    #[pallet::view_functions]
    impl<T: Config> Pallet<T> {
		/// Retrieve a map storage value by key.
        pub fn get_value_with_arg(key: u32) -> Option<u32> {
			SomeMap::<T>::get(key)
		}
    }
}

§Usage and implementation details

To allow outside access to pallet view functions, you need to add a runtime API that accepts view function queries and dispatches them to the right pallet. You can do that by implementing the RuntimeViewFunction trait for the runtime inside an impl_runtime_apis! block.

The RuntimeViewFunction trait implements a hashing-based dispatching mechanism to dispatch view functions to the right method in the right pallet based on their IDs. A view function ID depends both on its pallet and on its method signature, so it remains stable as long as those two elements are not modified. In general, pallet view functions should expose a stable interface and changes to the method signature are strongly discouraged. For more details on the dispatching mechanism, see the DispatchViewFunction trait.


Documentation for this macro can be found at frame_support::pallet_macros::view_functions.