I need to be sure that the on_initialize
handler for a specific module runs before the same handler before all other modules in my runtime.
a) How do ensure this?
b) Is there some compile or runtime check I can enforce to absolutely guarantee that this will be respected?
The on_initialize
function for each Substrate runtime module is called via the Executive module, which handles all of the top-level stuff; essentially just executing blocks/extrinsics.
Every time a block is executed (execute_block
), first initialize_block
is called which ultimately calls the on_initalize
block for the AllModules
type:
srml/executive/src/lib.rs
<AllModules as OnInitialize<System::BlockNumber>>::on_initialize(*block_number);
The AllModules
type is a tuple of the different module identifiers in your runtime. It generated by the construct_runtime!
macro and lists the modules in the order you defined them in the macro.. For example, for the given construct_runtime!
definition:
construct_runtime!(
pub enum Runtime with Log(InternalLog: DigestItem<Hash, AuthorityId, AuthoritySignature>) where
Block = Block,
NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: system::{default, Log(ChangesTrieRoot)},
Timestamp: timestamp::{Module, Call, Storage, Config<T>, Inherent},
Consensus: consensus::{Module, Call, Storage, Config<T>, Log(AuthoritiesChange), Inherent},
Aura: aura::{Module},
Indices: indices,
Balances: balances,
Sudo: sudo,
// Used for the module template in `./template.rs`
TemplateModule: template::{Module, Call, Storage, Event<T>},
TemplateModule1: template1::{Module, Call, Storage, Event<T>},
TemplateModule2: template2::{Module, Call, Storage, Event<T>},
}
);
You will get the following AllModules
type:
type AllModules = (Timestamp, Consensus, Aura, Indices, Balances, Sudo, TemplateModule, TemplateModule1, TemplateModule2);
Thus, the on_initialize
function is called in order which you define the modules in your runtime. There is nothing you need to do to "ensure this will be respected", since code flow is serial and deterministic here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With