Skip to main content

pallet_parameters/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#![cfg_attr(not(feature = "std"), no_std)]
19#![deny(missing_docs)]
20// Need to enable this one since we document feature-gated stuff.
21#![allow(rustdoc::broken_intra_doc_links)]
22
23//! # **⚠️ WARNING ⚠️**
24//!  
25//! <br>  
26//! <b>THIS CRATE IS NOT AUDITED AND SHOULD NOT BE USED IN PRODUCTION.</b>  
27//! <br>  
28//!
29//! # Parameters
30//!
31//! Allows to update configuration parameters at runtime.
32//!
33//! ## Pallet API
34//!
35//! This pallet exposes two APIs; one *inbound* side to update parameters, and one *outbound* side
36//! to access said parameters. Parameters themselves are defined in the runtime config and will be
37//! aggregated into an enum. Each parameter is addressed by a `key` and can have a default value.
38//! This is not done by the pallet but through the [`frame_support::dynamic_params::dynamic_params`]
39//! macro or alternatives.
40//!
41//! Note that this is incurring one storage read per access. This should not be a problem in most
42//! cases but must be considered in weight-restrained code.
43//!
44//! ### Inbound
45//!
46//! The inbound side solely consists of the [`Pallet::set_parameter`] extrinsic to update the value
47//! of a parameter. Each parameter can have their own admin origin as given by the
48//! [`Config::AdminOrigin`].
49//!
50//! ### Outbound
51//!
52//! The outbound side is runtime facing for the most part. More general, it provides a `Get`
53//! implementation and can be used in every spot where that is accepted. Two macros are in place:
54//! [`frame_support::dynamic_params::define_parameters` and
55//! [`frame_support::dynamic_params:dynamic_pallet_params`] to define and expose parameters in a
56//! typed manner.
57//!
58//! See the [`pallet`] module for more information about the interfaces this pallet exposes,
59//! including its configuration trait, dispatchables, storage items, events and errors.
60//!
61//! ## Overview
62//!
63//! This pallet is a good fit for updating parameters without a runtime upgrade. It is very handy to
64//! not require a runtime upgrade for a simple parameter change since runtime upgrades require a lot
65//! of diligence and always bear risks. It seems overkill to update the whole runtime for a simple
66//! parameter change. This pallet allows for fine-grained control over who can update what.
67//! The only down-side is that it trades off performance with convenience and should therefore only
68//! be used in places where that is proven to be uncritical. Values that are rarely accessed but
69//! change often would be a perfect fit.
70//!
71//! ### Example Configuration
72//!
73//! Here is an example of how to define some parameters, including their default values:
74#![doc = docify::embed!("src/tests/mock.rs", dynamic_params)]
75//! A permissioned origin can be define on a per-key basis like this:
76#![doc = docify::embed!("src/tests/mock.rs", custom_origin)]
77//! The pallet will also require a default value for benchmarking. Ideally this is the variant with
78//! the longest encoded length. Although in either case the PoV benchmarking will take the worst
79//! case over the whole enum.
80#![doc = docify::embed!("src/tests/mock.rs", benchmarking_default)]
81//! Now the aggregated parameter needs to be injected into the pallet config:
82#![doc = docify::embed!("src/tests/mock.rs", impl_config)]
83//! As last step, the parameters can now be used in other pallets 🙌
84#![doc = docify::embed!("src/tests/mock.rs", usage)]
85//! ### Examples Usage
86//!
87//! Now to demonstrate how the values can be updated:
88#![doc = docify::embed!("src/tests/unit.rs", set_parameters_example)]
89//! ## Low Level / Implementation Details
90//!
91//! The pallet stores the parameters in a storage map and implements the matching `Get<Value>` for
92//! each `Key` type. The `Get` then accesses the `Parameters` map to retrieve the value. An event is
93//! emitted every time that a value was updated. It is even emitted when the value is changed to the
94//! same.
95//!
96//! The key and value types themselves are defined by macros and aggregated into a runtime wide
97//! enum. This enum is then injected into the pallet. This allows it to be used without any changes
98//! to the pallet that the parameter will be utilized by.
99//!
100//! ### Design Goals
101//!
102//! 1. Easy to update without runtime upgrade.
103//! 2. Exposes metadata and docs for user convenience.
104//! 3. Can be permissioned on a per-key base.
105//!
106//! ### Design
107//!
108//! 1. Everything is done at runtime without the need for `const` values. `Get` allows for this -
109//! which is coincidentally an upside and a downside. 2. The types are defined through macros, which
110//! allows to expose metadata and docs. 3. Access control is done through the `EnsureOriginWithArg`
111//! trait, that allows to pass data along to the origin check. It gets passed in the key. The
112//! implementor can then match on the key and the origin to decide whether the origin is
113//! permissioned to set the value.
114
115use frame_support::pallet_prelude::*;
116use frame_system::pallet_prelude::*;
117
118use frame_support::traits::{
119	dynamic_params::{AggregatedKeyValue, IntoKey, Key, RuntimeParameterStore, TryIntoKey},
120	EnsureOriginWithArg,
121};
122
123mod benchmarking;
124#[cfg(test)]
125mod tests;
126mod weights;
127
128pub use pallet::*;
129pub use weights::WeightInfo;
130
131/// The key type of a parameter.
132type KeyOf<T> = <<T as Config>::RuntimeParameters as AggregatedKeyValue>::Key;
133
134/// The value type of a parameter.
135type ValueOf<T> = <<T as Config>::RuntimeParameters as AggregatedKeyValue>::Value;
136
137#[frame_support::pallet]
138pub mod pallet {
139	use super::*;
140
141	#[pallet::config(with_default)]
142	pub trait Config: frame_system::Config {
143		/// The overarching event type.
144		#[pallet::no_default_bounds]
145		#[allow(deprecated)]
146		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
147
148		/// The overarching KV type of the parameters.
149		///
150		/// Usually created by [`frame_support::dynamic_params`] or equivalent.
151		#[pallet::no_default_bounds]
152		type RuntimeParameters: AggregatedKeyValue;
153
154		/// The origin which may update a parameter.
155		///
156		/// The key of the parameter is passed in as second argument to allow for fine grained
157		/// control.
158		#[pallet::no_default_bounds]
159		type AdminOrigin: EnsureOriginWithArg<Self::RuntimeOrigin, KeyOf<Self>>;
160
161		/// Weight information for extrinsics in this module.
162		type WeightInfo: WeightInfo;
163	}
164
165	#[pallet::event]
166	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
167	pub enum Event<T: Config> {
168		/// A Parameter was set.
169		///
170		/// Is also emitted when the value was not changed.
171		Updated {
172			/// The key that was updated.
173			key: <T::RuntimeParameters as AggregatedKeyValue>::Key,
174			/// The old value before this call.
175			old_value: Option<<T::RuntimeParameters as AggregatedKeyValue>::Value>,
176			/// The new value after this call.
177			new_value: Option<<T::RuntimeParameters as AggregatedKeyValue>::Value>,
178		},
179	}
180
181	/// Stored parameters.
182	#[pallet::storage]
183	pub type Parameters<T: Config> =
184		StorageMap<_, Blake2_128Concat, KeyOf<T>, ValueOf<T>, OptionQuery>;
185
186	#[pallet::pallet]
187	pub struct Pallet<T>(_);
188
189	#[pallet::call]
190	impl<T: Config> Pallet<T> {
191		/// Set the value of a parameter.
192		///
193		/// The dispatch origin of this call must be `AdminOrigin` for the given `key`. Values be
194		/// deleted by setting them to `None`.
195		#[pallet::call_index(0)]
196		#[pallet::weight(T::WeightInfo::set_parameter())]
197		pub fn set_parameter(
198			origin: OriginFor<T>,
199			key_value: T::RuntimeParameters,
200		) -> DispatchResult {
201			let (key, new) = key_value.into_parts();
202			T::AdminOrigin::ensure_origin(origin, &key)?;
203
204			let mut old = None;
205			Parameters::<T>::mutate(&key, |v| {
206				old = v.clone();
207				*v = new.clone();
208			});
209
210			Self::deposit_event(Event::Updated { key, old_value: old, new_value: new });
211
212			Ok(())
213		}
214	}
215	/// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`].
216	pub mod config_preludes {
217		use super::*;
218		use frame_support::derive_impl;
219
220		/// A configuration for testing.
221		pub struct TestDefaultConfig;
222
223		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
224		impl frame_system::DefaultConfig for TestDefaultConfig {}
225
226		#[frame_support::register_default_impl(TestDefaultConfig)]
227		impl DefaultConfig for TestDefaultConfig {
228			#[inject_runtime_type]
229			type RuntimeEvent = ();
230			#[inject_runtime_type]
231			type RuntimeParameters = ();
232
233			type AdminOrigin = frame_support::traits::AsEnsureOriginWithArg<
234				frame_system::EnsureRoot<Self::AccountId>,
235			>;
236
237			type WeightInfo = ();
238		}
239	}
240}
241
242impl<T: Config> RuntimeParameterStore for Pallet<T> {
243	type AggregatedKeyValue = T::RuntimeParameters;
244
245	fn get<KV, K>(key: K) -> Option<K::Value>
246	where
247		KV: AggregatedKeyValue,
248		K: Key + Into<<KV as AggregatedKeyValue>::Key>,
249		<KV as AggregatedKeyValue>::Key: IntoKey<
250			<<Self as RuntimeParameterStore>::AggregatedKeyValue as AggregatedKeyValue>::Key,
251		>,
252		<<Self as RuntimeParameterStore>::AggregatedKeyValue as AggregatedKeyValue>::Value:
253			TryIntoKey<<KV as AggregatedKeyValue>::Value>,
254		<KV as AggregatedKeyValue>::Value: TryInto<K::WrappedValue>,
255	{
256		let key: <KV as AggregatedKeyValue>::Key = key.into();
257		let val = Parameters::<T>::get(key.into_key());
258		val.and_then(|v| {
259			let val: <KV as AggregatedKeyValue>::Value = v.try_into_key().ok()?;
260			let val: K::WrappedValue = val.try_into().ok()?;
261			let val = val.into();
262			Some(val)
263		})
264	}
265}