Safe Math

We can use the checked traits in substrate-primitives to protect against overflow/underflow when incrementing/decrementing objects in our runtime. To follow the Substrate collectable tutorial example, use checked_add() to safely handle the possibility of overflow when incremementing a global counter. Note that this check is similar to SafeMath in Solidity.

use runtime_primitives::traits::CheckedAdd;

let all_people_count = Self::num_of_people();

let new_all_people_count = all_people_count.checked_add(1).ok_or("Overflow adding a new person")?;

ok_or() transforms an Option from Some(value) to Ok(value) or None to Err(error). The ? operator facilitates error propagation. In this case, using ok_or() is the same as writing

let new_all_people_count = match all_people_count.checked_add(1) {
    Some (c) => c,
    None => return Err("Overflow adding a new person"),


  • ? for error propagation
  • Permill, Perbill, Fixed64 types for large arithmetic
  • quantization benchmarks in the treasury tests to verify that large arithmetic stays in a comfortable error bound
  • ADD BACK IN NEW RECIPE: collide and the question of whether maps prevent key collisions? could discuss sort, sort_unstable, and the ordering traits here...