Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Add ensure_ops methods (as checked_ops but returning ArithmeticError instead) #12754

@lemunozm

Description

@lemunozm

Hi! Because of the high safety standards needed in these contexts, mathematical operations tend to be made using the checked version. The checked version follows the same pattern in most cases:

a.checked_<operation>(b).ok_or(ArithmeticError::<Variant>)?

This has two issues:

  • Your algorithm becomes more difficult to read. When the code tends to be mathematical, readability is even more important. If it's difficult to read, it's very easy to have human errors and it makes auditories more difficult to do.
  • The concrete ArithmeticError returned is not easy to know. Depending on the value, it can differ. For example, a - b, could give Underflow, but also Overflow if b is a huge negative value.

In our parachain we've resolved both issues by creating an ensure_<operation> method family that reduces the code boilerplate and returns the correct ArithmeticError instead of an Option. The previous line could be rewritten in a more readable way:

a.ensure_<operation>(b)?

I think this can be useful for many other projects, so my intention is to move our ensure module (docs here) to sp_runtime::traits::ensure or any better place you recommend if you agree on this addition.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    J0-enhancementAn additional feature request.Z6-mentorAn easy task where a mentor is available. Please indicate in the issue who the mentor could be.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions