2

i'm trying to create a blockchain runtime module using Substrate. I have defined a few data structures with the #[derive(MaxEncodedLen)] attribute, but I'm running into a problem when trying to compile the code. Specifically, the compiler is giving an error for structures containing Vec<u8>.

#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(AccountId, Data, Quantity))]
pub struct Collection<AccountId, Data, Quantity> {
    /// Class metadata
    pub metadata: Vec<u8>,
    //...
}

#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(AccountId))]
pub struct ShareProfitsInfo<AccountId> {
    /// Token metadata
    pub percentage: Vec<u8>,
    //...
}

#[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(AccountId, Data))]
pub struct NFT<AccountId, Data> {
    /// Token metadata
    pub metadata: Vec<u8>,
    //...
}

The compiler error message is:

no function or associated item named max_encoded_lenfound for structVec<u8>in the current scope function or associated item not found inVec<u8>`

As I understand, the MaxEncodedLen trait isn't implemented for Vec<u8>, but I'm not sure how to go about solving this issue. How can I implement MaxEncodedLen for my structures containing Vec<u8>?

1 Answer 1

3

Vec can never be MaxEncodedLen (MEL), since it does not have a sensible maximal encode length.
You can use BoundedVec<T, L>. It directly implements MaxEncodedLen and has a limited maximal length. Now inductively the T also needs to be MEL. The MEL of the BoundedVec can then be calculated at compile time.

For example BoundedVec<u8, ConstU32<32>> is a vector that can have at most 32 bytes. Its MEL will be slightly larger than 32 bytes though, because it has to prefix its length like all vectors do.
You can take a look at the convition-voting-pallet for a complete example of how to do it.

Your Answer

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

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