qudag_exchange_core/
error.rs

1//! Error types for QuDAG Exchange Core
2//!
3//! Provides comprehensive error handling for all core operations
4
5#[cfg(not(feature = "std"))]
6use alloc::{format, string::String};
7
8use serde::{Deserialize, Serialize};
9
10/// Core error type for QuDAG Exchange operations
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub enum Error {
13    /// Insufficient balance for operation
14    InsufficientBalance {
15        /// Account that lacks balance
16        account: String,
17        /// Required amount
18        required: u64,
19        /// Available amount
20        available: u64,
21    },
22
23    /// Account not found
24    AccountNotFound(String),
25
26    /// Transaction validation failed
27    InvalidTransaction(String),
28
29    /// Signature verification failed
30    SignatureVerificationFailed,
31
32    /// Resource limit exceeded
33    ResourceLimitExceeded {
34        /// Type of resource
35        resource_type: String,
36        /// Limit that was exceeded
37        limit: u64,
38        /// Requested amount
39        requested: u64,
40    },
41
42    /// Consensus error
43    ConsensusError(String),
44
45    /// State corruption detected
46    StateCorruption(String),
47
48    /// Vault operation failed
49    VaultError(String),
50
51    /// Serialization/deserialization error
52    SerializationError(String),
53
54    /// Operation not supported
55    NotSupported(String),
56
57    /// Generic error with message
58    Other(String),
59}
60
61impl Error {
62    /// Create an insufficient balance error
63    pub fn insufficient_balance(account: impl Into<String>, required: u64, available: u64) -> Self {
64        Self::InsufficientBalance {
65            account: account.into(),
66            required,
67            available,
68        }
69    }
70
71    /// Create a resource limit exceeded error
72    pub fn resource_limit_exceeded(
73        resource_type: impl Into<String>,
74        limit: u64,
75        requested: u64,
76    ) -> Self {
77        Self::ResourceLimitExceeded {
78            resource_type: resource_type.into(),
79            limit,
80            requested,
81        }
82    }
83}
84
85#[cfg(feature = "std")]
86impl std::fmt::Display for Error {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        match self {
89            Self::InsufficientBalance {
90                account,
91                required,
92                available,
93            } => {
94                write!(
95                    f,
96                    "Insufficient balance for account {}: required {}, available {}",
97                    account, required, available
98                )
99            }
100            Self::AccountNotFound(id) => write!(f, "Account not found: {}", id),
101            Self::InvalidTransaction(msg) => write!(f, "Invalid transaction: {}", msg),
102            Self::SignatureVerificationFailed => write!(f, "Signature verification failed"),
103            Self::ResourceLimitExceeded {
104                resource_type,
105                limit,
106                requested,
107            } => {
108                write!(
109                    f,
110                    "Resource limit exceeded for {}: limit {}, requested {}",
111                    resource_type, limit, requested
112                )
113            }
114            Self::ConsensusError(msg) => write!(f, "Consensus error: {}", msg),
115            Self::StateCorruption(msg) => write!(f, "State corruption: {}", msg),
116            Self::VaultError(msg) => write!(f, "Vault error: {}", msg),
117            Self::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
118            Self::NotSupported(msg) => write!(f, "Operation not supported: {}", msg),
119            Self::Other(msg) => write!(f, "Error: {}", msg),
120        }
121    }
122}
123
124#[cfg(feature = "std")]
125impl std::error::Error for Error {}
126
127#[cfg(feature = "std")]
128impl From<bincode::Error> for Error {
129    fn from(err: bincode::Error) -> Self {
130        Self::SerializationError(err.to_string())
131    }
132}
133
134/// Result type alias for QuDAG Exchange operations
135pub type Result<T> = core::result::Result<T, Error>;
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn test_error_creation() {
143        let err = Error::insufficient_balance("alice", 100, 50);
144        match err {
145            Error::InsufficientBalance {
146                account,
147                required,
148                available,
149            } => {
150                assert_eq!(account, "alice");
151                assert_eq!(required, 100);
152                assert_eq!(available, 50);
153            }
154            _ => panic!("Wrong error type"),
155        }
156    }
157
158    #[test]
159    fn test_error_serialization() {
160        let err = Error::AccountNotFound("bob".to_string());
161        let serialized = bincode::serialize(&err).unwrap();
162        let deserialized: Error = bincode::deserialize(&serialized).unwrap();
163        assert_eq!(err, deserialized);
164    }
165}