In this step, we will start using #[pallet::genesis]
features.
- Let's look at our
test_state()
. Not so pretty. Also, when we launched a node, it had no initial balance when we ran a node. Can we do better? yes. - start by adding
#[pallet::genesis_config]
. The fields of this struct are the pieces of information that your pallet expects to receive from someone (eg. a genesis chain specification). For our case, we expect to get a list of accounts and balances. - Then,
#[pallet::genesis_build]
defines what your pallet should do with that. We will insert intoBalances
, and updateTotalIssuance
. - This function is called before your chain even launches. So if there is anything wrong, we simply panic and no need for nicer error handling.
Later on you will learn about avoiding panics in the runtime. In general, you should not panic.
GenesisConfig
is required to have aDefault
. We are simply happy with an empty vector for that, so we derive it.
Note that
frame::derive::DefaultNoBound
is simply preventing clashes with<T: Config>
. If the struct hadn't had<T: Config>
,derive(Default)
would have been just enough.
- Then, to using this in our test setup.
- First, we explore the approach where we create the
GenesisConfig
of each pallet, then amalgamate them inRuntimeGenesisConfig
(this is generated byconstruct_runtime
) and use that as our initial state. This is demonstrate ittest_state_new
. - we demonstrate an alternative syntax for that in
test_state_new_2
which is semantically the same. We leave it up to you to figure out why! - Finally, we create a builder pattern to do the same. This is a very common practice in Rust and is well-explained externally.
- Other than being more ergonomic, the benefit of our builder pattern is that it will flexibly support adding more accounts at genesis.
- We add a new test
ext_builder_works
to demonstrate this. - Moreover, it allows some additional code to be executed after each tests. We add some code that ensures total issuance is always checked, now we get even more coverage.
- We add a new test
duplicate_genesis_fails
to demonstrate the check we put into place. - We Migrate all existing tests to use the
ExtBuilder
.
TODO: Finally, we can add a few initial balances in the cli's chain spec as well. given the unclear status of the node for now I won't cover this, but the code in staging is demonstrating what needs to be done.