4

There seems to be different approaches to declaring constants for a pallet's runtime implementation.

  1. A common approach for example is:
// In pallet/example/src/lib.rs
#[pallet::config]
pub trait Config: frame_system::Config {
        // --snip --
        const SOME_CONSTANT: u32;
}

// In runtime/src/lib.rs
impl pallet_example::Config for Runtime {
        const SOME_CONSTANT: u32 = 42;
}
  1. Another way is to use ConstU32. For example:
// In pallet/example/src/lib.rs
#[pallet::config]
pub trait Config: frame_system::Config {
        // --snip --
        #[pallet::constant]
        type SomeConstant: Get<u32>;
}

// In runtime/src/lib.rs
impl pallet_example::Config for Runtime {
    type SomeConstant = ConstU32<42>;
}
  1. A third approach would be to use the parameter_types types macro, which is most commonly used to declare constants of custom types, but can also be used for any other type.

How do I know which approach to use? Why would I choose one over the other?

2 Answers 2

4

Associated constants are not used that much in FRAME. I mean you can use them, but it makes it harder to write tests. With the Get trait you have the possibility to "cheat" in tests by implementing it for a thread local type.

For ConstU32 vs parameter_types!. ConstU32 just came later with the stabilization of const generics. Code wise there is no real difference. However, ConstU32 for sure is "shorter".

3
  • > With the Get trait you have the possibility to "cheat" in tests by implementing it for a thread local type. Can you elaborate this a bit more please Jun 26, 2022 at 8:05
  • In unit test, how to get the value of ConstU32 ?
    – gfan
    Sep 5, 2022 at 15:34
  • ```your_const_vall::get()` should do it? Make sure to have the Get trait imported.
    – bkchr
    Sep 5, 2022 at 17:07
4

Also, for things like BoundedVec, it is not currently possible to use an associated constant because const generics are not fully supported: https://github.com/paritytech/substrate/pull/9865

I think there are a lot of places we would actually use a const, but can't really do that yet.

1
  • 3
    Yes we do a lot of stuff at runtime that is basically fixed at compile time because const support is basically non existent for generic code as of today. Feb 19, 2022 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.