16

Are there any guiding principles that can be applied to decide whether to use Substrate's BoundedVec, WeakBoundedVec, or Vec in a runtime?

Is it a general rule of thumb to use the bounded variant whenever some worst-case upper bound of the vector can be determined or is there something else to consider?

Are there other advantages of using the bounded variant besides the effect of then having defined a maximum length (and thus setting a bound on the number of iterations) for the vector?

And what's the idea when to use BoundedVec vs. WeakBoundedVec?

2
  • 2
    There is also BoundedVec I believe? Commented Mar 24, 2022 at 12:50
  • @RosaryBeads Thanks! I've updated the title + description.
    – cmichi
    Commented Mar 24, 2022 at 16:32

1 Answer 1

10

Please don't use WeakBoundedVec ever, unless you are migrating code which you plan to fix in the future.

Instead use directly BoundedVec which ensures that any item placed in storage as a maximum upper bound.

WeakBoundedVec was an unfortunate necessity to migrate some existing logic to use BoundedVec logic, but where we could not return an error if the Vec was too large.

As you know (currently), FRAME does not allow you to return an error after modifying storage. As such, there was some code that was programmed in the past that was made to be infallible, but after the introduction of BoundedVecs, was no longer infallible.

When approaching this problem, we could either try to refactor everything, or we could introduce the WeakBoundedVec, and we chose the latter.

Vec is okay to use in the runtime, but never to put into storage, since it is unbounded by definition.

1
  • Do you know how much elements / bytes should at maximum be stored inside a BoundedVec?
    – Chralt
    Commented Mar 29, 2023 at 7:54

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.