Configure a runtime constant
The basics for defining a constant in your runtime.
#
GoalDefine a runtime constant value that becomes reset on on_finalize
.
#
Use casesUse a constant to keep track of the amount of times a function is called during a single block cycle.
#
OverviewDeclaring a constant value in a runtime is a useful tool to either define fixed values or define values that change dynamically
according to some factor. This guide steps through the process of creating pallet constants that are used to reset a u32
value in storage. This value, we'll call SingleValue
, can also be modified using a method called add_value
.
The purpose of this guide is to demonstrate the utiltiy of configuring constants by hardcoding them as well as making them more dynamic.
#
Steps#
1. Define the constants in your palletMaxAddend
will be the value displayed in metadata.ClearFrequency
keeps track of the block numbers and will be used to resetSingleValue
:
#
2. Declare your storage items and eventsUsing the storage attribute macro, declare SingleValue
which will be the value that gets modified every block cycle.
Define your pallet's events:
Add an error that handles operation overflow:
on_finalize
#
3. Configure SingleValue
is set to 0 every ClearFrequency
number of blocks in the on_finalize
function that
runs at the end of block execution. Specify this logic under the #[pallet::hooks]
attribute:
#
4. Create a method that allows users to specify the valueThe add_value
method increases SingleValue
so long as each call adds to less than the MaxAddend
value.
For this method, make sure to:
- Include checks.
- Keep track of the previous value.
- Check for overflow.
- Update
SingleValue
.
#
5. Supply the constant value for runtimeIn runtime/src/lib.rs
, declare the values for your pallet's runtime implementation of MaxAddend
and ClearFrequency
: