3

I can't find anything on how to use the compact encoding of integers with Option<...>. Is this possible?

And to elaborate, if I do something like this:

#[pallet::call]
... {
    fn my_dispatchable(origin: OriginFor<T>, #[pallet::compact] my_option: Option<u128>) -> DispatchResult {
        // ...
    }
}

Then I get the following error:

the trait `From<parity_scale_codec::Compact<std::option::Option<u128>>>` is not implemented for `std::option::Option<u128>`

This sounds like it's not possible to compactly encode options of integers. Why?

1 Answer 1

3

This happens because you apply #[pallet::compact] attribute to the type Option<u128>. u128 can be represented as compact. Option<u128> can't though, since it's an option.

In this case, to make it work you will need to remove the #[pallet::compact] attribute and then change the type to Option<Compact<u128>>. Compact is a usual tuple struct and you can extract the value by the reading .0.

9
  • Ok, I figured as much, but how would using an Option of a compact integer look like in Rust?
    – mkl
    Commented Apr 28, 2022 at 20:52
  • Well, @mkl, there is no magic. The rule is always either 0 or 1 followed by the encoding of the T type in case of Some, irregardless what type T is. I updated the answer with an example.
    – pepyakin
    Commented Apr 28, 2022 at 21:03
  • What I meant is: How do I actually do this in substrate (using pallet::compact, for example)?
    – mkl
    Commented Apr 28, 2022 at 21:29
  • Ok, I see, I misinterpreted you. However, it is still not clear what you are asking. Do you mean you want to know how to, e.g., declare a variable that is an Option with an integer, that when encoded, will be represented in compact encoding when Some?
    – pepyakin
    Commented Apr 28, 2022 at 21:36
  • I'd like to use a compactly encoded Option as parameter for an extrinsic.
    – mkl
    Commented Apr 28, 2022 at 21: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.