Skip to main content

solana_math/
error.rs

1//! Error types for `solana-math`.
2//!
3//! This module defines [`SafeMathError`], used by checked arithmetic and safe
4//! numeric conversion helpers.
5
6use thiserror::Error;
7
8/// Errors returned by safe arithmetic operations and numeric conversions.
9///
10/// Errors are numbered from the range 9000 - 9999 when used in conversions to custom program errors.
11#[derive(Debug, Error, PartialEq, Eq)]
12pub enum SafeMathError {
13    /// Arithmetic operation exceeded the maximum numeric bound of the target type.
14    #[error("Arithmetic operation resulted in a boundary overflow")]
15    Overflow = 9000,
16    /// Arithmetic operation went below the minimum numeric bound of the target type.
17    #[error("Arithmetic operation resulted in a boundary underflow")]
18    Underflow = 9001,
19    /// Integer could not be safely cast to the target numeric type.
20    #[error("Integer could not be safely casted to the target type")]
21    ConversionFailed = 9002,
22}
23
24// Anchor and Quasar both re-export the same `solana_program_error::ProgramError`
25// type. Prefer the Quasar impl when both features are enabled so `--all-features`
26// does not produce conflicting `From` implementations.
27#[cfg(all(feature = "anchor", not(feature = "quasar")))]
28impl From<SafeMathError> for anchor_lang::prelude::ProgramError {
29    fn from(e: SafeMathError) -> Self {
30        Self::Custom(e as u32)
31    }
32}
33
34#[cfg(feature = "quasar")]
35impl From<SafeMathError> for quasar_lang::prelude::ProgramError {
36    fn from(e: SafeMathError) -> Self {
37        Self::Custom(e as u32)
38    }
39}