#anchor #solana #math #safe #primitive #wrapper #numeric

anchor-safe-math

Safe Math wrapper for the primitive numberic types used in an Anchor project

10 unstable releases (3 breaking)

0.5.1 Sep 12, 2024
0.5.0 May 16, 2024
0.4.0 Jan 6, 2024
0.2.2 Feb 28, 2023
0.1.2 Jan 31, 2022

#28 in #anchor

Custom license

6KB
67 lines

Anchor Safe Math

use anchor_lang::prelude::*;
use safe_math::{SafeMath};

#[program]
pub mod example {
  use super::*;

  pub fn instruction(ctx: Context<Instruction>, amount: u64) -> ProgramResult {
    let state = &mut ctx.accounts.state;

    // You can apply any of the following operations
    state.total_amount = state.total_amount.safe_add(amount)?;
    state.total_amount = state.total_amount.safe_sub(amount)?;
    state.total_amount = state.total_amount.safe_mul(amount)?;
    state.total_amount = state.total_amount.safe_div(amount)?;
    state.total_amount = state.total_amount.safe_pow(8_u32)?;
  }
}

#[derive(Accounts)]
pub struct Instruction<'info> {
  ...
}

Works with u128, u64, u32, u16 and u8


lib.rs:

Anchor Safe Math

anchor_safe_math is a collection of helper numeric operation functions that removes the verbosity of checking for overflow, underflow and division by zero errors.

Examples

use anchor_lang::prelude::;
use anchor_safe_math::{SafeMath};

#[program]
pub mod example {
  use super::*;

  pub fn instruction(ctx: Context<Instruction>, amount: u64) -> ProgramResult {
    let state = &mut ctx.accounts.state;

    // You can apply any of the following operations
    state.total_amount = state.total_amount.safe_add(amount)?;
    state.total_amount = state.total_amount.safe_sub(amount)?;
    state.total_amount = state.total_amount.safe_mul(amount)?;
    state.total_amount = state.total_amount.safe_div(amount)?;
    state.total_amount = state.total_amount.safe_pow(8_u32)?;
  }
}

#[derive(Accounts)]
pub struct Instruction<'info> {
  ...
}

Dependencies

~18–27MB
~454K SLoC