anchor-safe-math

Crates.ioanchor-safe-math
lib.rsanchor-safe-math
version0.5.1
sourcesrc
created_at2022-01-31 12:12:58.42718
updated_at2024-09-12 09:21:17.672215
descriptionSafe Math wrapper for the primitive numberic types used in an Anchor project
homepagehttps://github.com/Apocentre/anchor-safe-math
repositoryhttps://github.com/Apocentre/anchor-safe-math
max_upload_size
id524546
size6,946
Pavlos Polianidis (ppoliani)

documentation

https://docs.rs/anchor-safe-math/

README

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

Commit count: 20

cargo fmt