1

I would like to store a string/message in substrate storage because I am writing a pallet, later on, I would like to use the Polkadot.js portal to write the message on the front-end and store it, and then later to react it.

Does Polkadot.js convert Vec to string automatically? If not how can I test it? Thank you!

3 Answers 3

5

Yes, the way to go is to store it as Vec<u8> and to use a BoundedVec to limit the max number of chars in order to not let users store the entire internet in your pallet.

The nicks pallet is a perfect starting point for you to explore this as it has this exact functionality to map readable strings to addresses.

Here is the storage config: https://github.com/paritytech/substrate/blob/master/frame/nicks/src/lib.rs#L112-L114

And here is the associated extrinsic:

https://github.com/paritytech/substrate/blob/master/frame/nicks/src/lib.rs#L139-L158

Yes, it's converted by polkadot.js into string!

2
  • 1
    to not let users store the entire internet in your pallet. I chuckled. Commented Dec 5, 2022 at 7:38
  • What is the maximum recommended length of the BoundedVec for a string? The nicks pallet used 16 bytes here, but can it be even more like 512 bytes?
    – Chralt
    Commented Jul 9, 2023 at 9:20
3

String is represented as Vec. So in your fn put vec parameter

0

Use arrays to store your String because arrays work great with those struct macros below...(BoundedVec will not work with most of them):

    #[derive(Default, Encode, Decode, Clone, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)]
    pub struct UserInfo {
        pub id: i64,
        pub username: [u8; 20],
    //BoundedVec<u8, T::StringLimit>,
    }

In your function argument, take input strings in Vec type, then pad the vector into arrays. See here: https://stackoverflow.com/questions/71578765/best-way-to-pad-a-vector-with-zero-bytes

Also you can get the expected string size from pallet Config:

let expected_len = T::StringLimit::get() as usize;

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.