9 个不稳定版本 (3 个破坏性更新)
0.5.0 | 2024年5月16日 |
---|---|
0.4.0 | 2024年1月6日 |
0.2.2 | 2023年2月28日 |
0.2.1 | 2022年7月7日 |
0.1.2 | 2022年1月31日 |
#24 in #anchor
6KB
67 行
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> {
...
}
与 u128
、u64
、u32
、u16
和 u8
兼容
lib.rs
:
Anchor Safe Math
anchor_safe_math
是一组辅助数值操作函数的集合,用于消除检查溢出、下溢和除以零错误时的冗余。
示例
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> {
...
}
依赖关系
~17–26MB
~442K SLoC