11

I'm trying to use BoundedVec from frame_support for one of my storage items like this,

pub(super) type Payloads<T: Config> = StorageMap<_, Blake2_128Concat, T::BlockNumber, Vec<Payload>, ValueQuery>;

However I'm confused how to implement BoundedVec here instead of Vec as I tried something like this which failed

pub(super) type Payloads<T: Config> = StorageMap<_, Blake2_128Concat, T::BlockNumber, BoundedVec<Payload, 100>, ValueQuery>;

Giving me the error, error[E0747]: constant provided when a type was expected

Can someone who has already worked on this, give me an example of how to use BoundedVec?

2 Answers 2

6

Having a look at the pallet-preimage shows how it can be done, the Substrate repo contains examples almost anything that you would want to do with it 😊.

The storage item:

/// The preimages stored by this pallet.
#[pallet::storage]
pub(super) type PreimageFor<T: Config> =
    StorageMap<_, Identity, T::Hash, BoundedVec<u8, T::MaxSize>>;

The config which defines the MaxSize type:

#[pallet::config]
pub trait Config: frame_system::Config {
    /// Max size allowed for a preimage.
    type MaxSize: Get<u32>;
}

And the runtime where the concrete value is injected:

parameter_types! {
    pub const PreimageMaxSize: u32 = 4096 * 1024;
}

impl pallet_preimage::Config for Runtime {
    type MaxSize = PreimageMaxSize;
}
1
  • type MaxSize: Get<u16> cannot work. only Get<u32> works. Thanks
    – Russo
    Commented Mar 10, 2023 at 7:43
7

BoundedVec is defined here in the Substrate code base as below:

#[derive(Encode, scale_info::TypeInfo)]
#[scale_info(skip_type_params(S))]
pub struct BoundedVec<T, S>(Vec<T>, PhantomData<S>);

As the compiler message shows, it's expecting a type for the second generic parameter. You can use it as BoundedVec<Payload, ConstU32<100>> as you can also find in the BoundedVec tests, which would make your type declaration:

pub(super) type Payloads<T: Config> = StorageMap<_, Blake2_128Concat, T::BlockNumber, BoundedVec<Payload, ConstU32<100>>, ValueQuery>;
2
  • 1
    Ah yes the error makes sense now: use type ConstU32<100> rather than the constant value 100.
    – Squirrel
    Commented Mar 22, 2022 at 11:13
  • ConstU16<100> cannot do. Only ConstU32<100> works. Thanks
    – Russo
    Commented Mar 10, 2023 at 7:38

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.