I am using a BoundedVec as the id for a storage map, and intend to transform a u32 value into a compatible format. Is there a streamlined way to accomplish this, or should I split the u32 into smaller bits and insert them into the BoundedVec? If the latter is true, how should I go about this?

  • 1
    Why can you not use the u32 as map key directly? Aug 9, 2023 at 15:31
  • Currently, I have the storage setup with the u32 as the key, however, due to new requirements, the Ids may also include characters, hence the boundedvec (of u8). Instead of creating a separate storage for these new items, I am trying to modify the existing one. Then, I can distinguish the two different types either through an enum, or through a specific prefix.
    – frkmnt
    Aug 9, 2023 at 15:43
  • Okay I see, thanks. Aug 9, 2023 at 16:57

1 Answer 1


You can use the SCALE codec to encode types into Vec. Then the Vec can be converted into a BoundedVec.

For example a u32 (but it works the same for any other encodable type):

use codec::Encode;
use sp_core::ConstU32;
use sp_runtime::BoundedVec;

let value: u32 = 123;
let encoded: Vec<u8> = value.encode();
let bounded: BoundedVec<u8, ConstU32<4>> = encoded.try_into()?;

Note that the conversion from Vec to BoundedVec is fallible, in case that it does not fit into the bounded vec. There are also infallible functions like BoundedVec::truncate_from, but personally I would rather use the fallible version and return in an error case.

It is possible to use the MaxEncodedLen for testing to ensure that the BoundedVec is always long enough to hold the encoded values.

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.