Skip to main content

pyde_rust_sdk/error/
mod.rs

1//! SDK error taxonomy.
2//!
3//! Every fallible operation in the SDK returns [`Result<T>`] — an
4//! alias for `std::result::Result<T, SdkError>`. The variants
5//! cluster by *layer*: transport ([`SdkError::Rpc`],
6//! [`SdkError::Connection`], [`SdkError::Timeout`]), authorization
7//! ([`SdkError::Signing`]), input validation
8//! ([`SdkError::InvalidAddress`], [`SdkError::InvalidArgument`]),
9//! and contract execution ([`SdkError::Reverted`],
10//! [`SdkError::InsufficientBalance`], [`SdkError::HostFn`]).
11//!
12//! [`SdkError::error_code`] scans the revert payload for a
13//! [HOST_FN_ABI §4][spec] error code so callers can branch on
14//! the typed reason (e.g. `ERR_FORBIDDEN`, `ERR_INSUFFICIENT_BALANCE`)
15//! without parsing strings by hand.
16//!
17//! For revert errors, [`SdkError::revert_category`] surfaces the
18//! engine's [`crate::types::RevertCategory`] (`EngineValidation` /
19//! `Contract` / `Vm`) so callers can branch on the *layer* that
20//! rejected the tx without parsing the message. The convenience
21//! predicates [`SdkError::is_engine_validation_revert`],
22//! [`SdkError::is_contract_revert`], and [`SdkError::is_vm_trap`]
23//! cover the common cases. [`SdkError::from_receipt`] converts a
24//! non-success [`crate::types::Receipt`] into the matching
25//! `SdkError` variant in one call.
26//!
27//! [spec]: https://book.pyde.network/companion/HOST_FN_ABI_SPEC#4-error-codes
28
29use thiserror::Error;
30
31use crate::types::{ErrorCode, Receipt, RevertCategory, RevertReason};
32
33/// Errors returned from SDK operations.
34///
35/// Each variant carries enough context to surface a useful message
36/// to a dapp's user. See [`SdkError::code`] for stable, programmatic
37/// codes suitable for client-side error branching.
38#[derive(Debug, Error)]
39pub enum SdkError {
40    /// JSON-RPC error returned by the node (method-level failure).
41    #[error("RPC error: {0}")]
42    Rpc(String),
43
44    /// Transport-layer failure — TCP/TLS handshake, DNS, connection
45    /// reset.
46    #[error("connection error: {0}")]
47    Connection(String),
48
49    /// Local signing failure (FALCON keygen, signature emission).
50    #[error("signing error: {0}")]
51    Signing(String),
52
53    /// A bounded wait elapsed without the expected event (typically
54    /// used by `wait_for_receipt` and `await_finalized`).
55    #[error("timeout: {0}")]
56    Timeout(String),
57
58    /// Transaction reverted on-chain. State changes rolled back;
59    /// gas is still charged per
60    /// [`crate::types::ReceiptStatus::Reverted`].
61    ///
62    /// `reason` carries the engine's structured revert reason
63    /// when available — `Some` for any
64    /// `status: "reverted"` receipt when the engine emits a structured reason, `None` when the SDK derived the revert
65    /// from `return_data` alone (older nodes / direct constructions).
66    /// Branch on [`Self::revert_category`] for control-flow
67    /// decisions; use `reason.message` for display.
68    #[error("{}", format_revert(.gas_used, .data, .reason.as_ref()))]
69    Reverted {
70        /// Gas charged before the revert.
71        gas_used: u64,
72        /// Return data emitted by `pyde::revert(...)` (UTF-8 if
73        /// possible).
74        data: Vec<u8>,
75        /// Structured revert reason from the engine when present.
76        /// `None` when the SDK only has the raw `data` bytes — call
77        /// [`Self::revert_reason`] to decode from `data`.
78        reason: Option<RevertReason>,
79    },
80
81    /// Sender's balance is too low to cover
82    /// `value + gas_limit × base_fee`. Surfaced both at mempool
83    /// admission and at execute-time.
84    #[error("insufficient balance: need {required}, have {available}")]
85    InsufficientBalance {
86        /// Minimum required (value + gas reservation).
87        required: u128,
88        /// Sender's actual balance.
89        available: u128,
90    },
91
92    /// A typed [HOST_FN_ABI §4][spec] error code surfaced from a
93    /// host function or a cross-contract call. Use when the SDK
94    /// can extract a specific `ERR_*` code rather than collapsing
95    /// to the generic [`SdkError::Reverted`] / [`SdkError::Rpc`].
96    ///
97    /// [spec]: https://book.pyde.network/companion/HOST_FN_ABI_SPEC#4-error-codes
98    #[error("{code}: {message}")]
99    HostFn {
100        /// The structured §4 code.
101        code: ErrorCode,
102        /// Caller-visible context the SDK / node attached.
103        message: String,
104    },
105
106    /// Caller passed a malformed address (wrong length, bad hex, or
107    /// reserved sentinel).
108    #[error("invalid address: {0}")]
109    InvalidAddress(String),
110
111    /// Caller passed an argument that failed pre-flight validation.
112    #[error("invalid argument: {0}")]
113    InvalidArgument(String),
114
115    /// Node returned a response the SDK could not deserialize
116    /// (typically indicates a node-side bug or version skew).
117    #[error("invalid response: {0}")]
118    InvalidResponse(String),
119
120    /// Catch-all for errors that don't fit a structured variant.
121    /// Prefer adding a new variant over leaning on this.
122    #[error("{0}")]
123    Other(String),
124}
125
126impl SdkError {
127    /// Stable programmatic code string suitable for client-side
128    /// branching.
129    ///
130    /// These mirror ethers-rs / alloy conventions so dapp devs can
131    /// reuse existing error-handling habits.
132    #[must_use]
133    pub fn code(&self) -> &'static str {
134        match self {
135            SdkError::Rpc(_) => "RPC_ERROR",
136            SdkError::Connection(_) => "CONNECTION_ERROR",
137            SdkError::Signing(_) => "SIGNING_ERROR",
138            SdkError::Timeout(_) => "TIMEOUT",
139            SdkError::Reverted { .. } => "CALL_EXCEPTION",
140            SdkError::InsufficientBalance { .. } => "INSUFFICIENT_FUNDS",
141            SdkError::HostFn { code, .. } => code.name(),
142            SdkError::InvalidAddress(_) => "INVALID_ARGUMENT",
143            SdkError::InvalidArgument(_) => "INVALID_ARGUMENT",
144            SdkError::InvalidResponse(_) => "INVALID_RESPONSE",
145            SdkError::Other(_) => "OTHER",
146        }
147    }
148
149    /// For revert errors, attempt to decode the human-readable
150    /// reason the contract author passed to `pyde::revert(...)`.
151    /// Returns `None` for non-revert errors or if the revert data
152    /// isn't a recognizable encoding.
153    ///
154    /// Recognizes three encodings (probed in order):
155    ///
156    /// 1. **Borsh-encoded `String`** — `[len:u32_le][utf8 bytes]`
157    ///    (what the `#[pyde::entry]` macro emits when an entry
158    ///    panics or calls `pyde::revert`).
159    /// 2. **Length-prefixed `u64`** — `[len:u64_le][utf8 bytes]`
160    ///    (legacy emitter shape some hand-written contracts still
161    ///    use).
162    /// 3. **Raw UTF-8** — fallback for contracts that emit revert
163    ///    reasons without any length prefix.
164    #[must_use]
165    pub fn revert_reason(&self) -> Option<String> {
166        if let SdkError::Reverted { data, .. } = self {
167            decode_revert_reason(data)
168        } else {
169            None
170        }
171    }
172
173    /// For revert errors, scan the revert payload for a
174    /// [HOST_FN_ABI §4](crate::types::error_code) code.
175    ///
176    /// Two extraction paths:
177    ///
178    /// 1. **Named token** — the message contains an exact
179    ///    `ERR_*` token (e.g. `"ERR_FORBIDDEN"`). The engine's
180    ///    `pyde::revert` helpers and the otigen runtime emit this
181    ///    shape.
182    /// 2. **Negative integer** — the message contains a parseable
183    ///    negative integer in the spec table (`"-5"`, `"code: -10"`).
184    ///
185    /// Returns `None` for non-revert errors or revert payloads
186    /// that don't contain a recognizable code.
187    #[must_use]
188    pub fn error_code(&self) -> Option<ErrorCode> {
189        match self {
190            SdkError::HostFn { code, .. } => Some(*code),
191            SdkError::Reverted { data, .. } => extract_error_code(data),
192            _ => None,
193        }
194    }
195
196    /// Convenience: `true` iff this error is a contract revert.
197    #[must_use]
198    pub fn is_revert(&self) -> bool {
199        matches!(self, SdkError::Reverted { .. })
200    }
201
202    /// Structured revert category populated by the engine. Returns
203    /// `None` for non-revert errors or revert errors constructed
204    /// from a receipt that didn't carry a structured reason.
205    ///
206    /// Branch on this — not [`Self::revert_reason`] — for
207    /// control flow:
208    ///
209    /// ```ignore
210    /// use pyde_rust_sdk::types::RevertCategory;
211    ///
212    /// match err.revert_category() {
213    ///     Some(RevertCategory::EngineValidation) => /* nonce/balance/etc */,
214    ///     Some(RevertCategory::Contract)         => /* user's contract said no */,
215    ///     Some(RevertCategory::Vm)               => /* trap / OOM / OOG */,
216    ///     _                                      => /* not a revert, or older engine */,
217    /// }
218    /// ```
219    #[must_use]
220    pub fn revert_category(&self) -> Option<&RevertCategory> {
221        match self {
222            SdkError::Reverted { reason, .. } => reason.as_ref().map(|r| &r.category),
223            _ => None,
224        }
225    }
226
227    /// `true` iff this revert error carries
228    /// `category == EngineValidation` (nonce, balance, fee,
229    /// access-list, dispatch decode).
230    #[must_use]
231    pub fn is_engine_validation_revert(&self) -> bool {
232        matches!(
233            self.revert_category(),
234            Some(RevertCategory::EngineValidation)
235        )
236    }
237
238    /// `true` iff this revert error carries `category == Contract`
239    /// (contract code called `revert(msg)`).
240    #[must_use]
241    pub fn is_contract_revert(&self) -> bool {
242        matches!(self.revert_category(), Some(RevertCategory::Contract))
243    }
244
245    /// `true` iff this revert error carries `category == Vm`
246    /// (wasmtime trap, OOB memory, executor-side gas exhaustion).
247    #[must_use]
248    pub fn is_vm_trap(&self) -> bool {
249        matches!(self.revert_category(), Some(RevertCategory::Vm))
250    }
251
252    /// Construct an [`SdkError`] from a [`Receipt`] whose
253    /// `status != Success`. Returns `None` for success
254    /// receipts (which aren't errors).
255    ///
256    /// Out-of-gas → [`SdkError::Reverted`] with synthesised
257    /// reason `Some({category: Vm, message: "out of gas"})`.
258    /// Reverted with structured reason → carried through.
259    /// Reverted without structured reason → bytes-only.
260    #[must_use]
261    pub fn from_receipt(receipt: &Receipt) -> Option<Self> {
262        use crate::types::ReceiptStatus;
263        let gas_used = receipt.try_gas().unwrap_or(0);
264        let data = receipt.try_return_bytes().unwrap_or_default();
265        match receipt.status {
266            ReceiptStatus::Success => None,
267            ReceiptStatus::OutOfGas => Some(SdkError::Reverted {
268                gas_used,
269                data,
270                reason: Some(RevertReason {
271                    category: RevertCategory::Vm,
272                    message: "out of gas".to_string(),
273                }),
274            }),
275            ReceiptStatus::Reverted => Some(SdkError::Reverted {
276                gas_used,
277                data,
278                reason: receipt.revert_reason.clone(),
279            }),
280        }
281    }
282}
283
284/// SDK-wide result alias. Every fallible function in the public
285/// API returns this.
286pub type Result<T> = std::result::Result<T, SdkError>;
287
288/// Attempt to decode a revert reason from raw return data.
289///
290/// See [`SdkError::revert_reason`] for the encoding table.
291fn decode_revert_reason(data: &[u8]) -> Option<String> {
292    if data.is_empty() {
293        return None;
294    }
295    // 1. Borsh-encoded String: [len:4 LE][utf8 bytes]
296    if data.len() >= 4 {
297        let len = u32::from_le_bytes(data[..4].try_into().ok()?) as usize;
298        if len > 0 && len <= data.len() - 4 {
299            if let Ok(s) = std::str::from_utf8(&data[4..4 + len]) {
300                if looks_printable(s) {
301                    return Some(s.to_string());
302                }
303            }
304        }
305    }
306    // 2. Length-prefixed u64: [len:8 LE][utf8 bytes]
307    if data.len() >= 8 {
308        let len = u64::from_le_bytes(data[..8].try_into().ok()?) as usize;
309        if len > 0 && len <= data.len() - 8 {
310            if let Ok(s) = std::str::from_utf8(&data[8..8 + len]) {
311                if looks_printable(s) {
312                    return Some(s.to_string());
313                }
314            }
315        }
316    }
317    // 3. Raw UTF-8 fallback.
318    if let Ok(s) = std::str::from_utf8(data) {
319        if s.len() <= 256 && looks_printable(s) {
320            return Some(s.to_string());
321        }
322    }
323    None
324}
325
326/// `true` if every character is printable (no control codes except
327/// newline). Filters out random binary that happens to decode as
328/// UTF-8 but is almost certainly not a human revert message.
329fn looks_printable(s: &str) -> bool {
330    !s.is_empty() && s.chars().all(|c| !c.is_control() || c == '\n')
331}
332
333/// Scan a revert payload for a HOST_FN_ABI §4 error code.
334///
335/// Two parses tried in order: named token (`ERR_FORBIDDEN`) and
336/// negative-integer parse.
337fn extract_error_code(data: &[u8]) -> Option<ErrorCode> {
338    let reason = decode_revert_reason(data)?;
339    extract_error_code_from_str(&reason)
340}
341
342fn extract_error_code_from_str(reason: &str) -> Option<ErrorCode> {
343    // Named-token scan. We check the longest names first to avoid
344    // accidentally matching a prefix (e.g. `ERR_CROSS_CALL_FAILED`
345    // vs `ERR_CROSS_CALL_OUT_OF_GAS`).
346    let codes = [
347        ErrorCode::AccessListViolation,
348        ErrorCode::CiphertextInvalid,
349        ErrorCode::CrossCallFailed,
350        ErrorCode::CrossCallOutOfGas,
351        ErrorCode::Forbidden,
352        ErrorCode::InsufficientBalance,
353        ErrorCode::Internal,
354        ErrorCode::InvalidAddress,
355        ErrorCode::InvalidFunctionName,
356        ErrorCode::InvalidInput,
357        ErrorCode::NotFound,
358        ErrorCode::OutOfGas,
359        ErrorCode::OutputBufferTooSmall,
360        ErrorCode::ParachainOnly,
361        ErrorCode::ReentrancyBlocked,
362        ErrorCode::SignatureInvalid,
363        ErrorCode::ValueTransferNotPayable,
364        ErrorCode::XCallRateLimited,
365    ];
366    // Sort by name length descending so longer matches win.
367    let mut sorted = codes;
368    sorted.sort_by_key(|c| std::cmp::Reverse(c.name().len()));
369    for code in sorted {
370        if reason.contains(code.name()) {
371            return Some(code);
372        }
373    }
374    // Integer-parse fallback: scan whitespace-separated tokens for
375    // a parseable `-<n>` that resolves under ErrorCode::from_i32.
376    for token in reason
377        .split(|c: char| !c.is_ascii_digit() && c != '-')
378        .filter(|t| !t.is_empty())
379    {
380        if let Ok(n) = token.parse::<i32>() {
381            if let Some(code) = ErrorCode::from_i32(n) {
382                return Some(code);
383            }
384        }
385    }
386    None
387}
388
389/// Format a revert error's display text. Prefers the engine's
390/// structured `reason` when present; falls back to decoding `data` bytes otherwise.
391fn format_revert(gas_used: &u64, data: &[u8], reason: Option<&RevertReason>) -> String {
392    if let Some(r) = reason {
393        return format!(
394            "transaction reverted [{:?}]: {} (gas={gas_used})",
395            r.category, r.message
396        );
397    }
398    if let Some(reason) = decode_revert_reason(data) {
399        format!("transaction reverted: {reason} (gas={gas_used})")
400    } else {
401        format!("transaction reverted (gas={gas_used})")
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
408
409    use super::*;
410
411    // ── decode_revert_reason ──────────────────────────────────
412
413    #[test]
414    fn revert_reason_empty_returns_none() {
415        assert!(decode_revert_reason(&[]).is_none());
416    }
417
418    #[test]
419    fn revert_reason_borsh_u32_string() {
420        // Borsh string: [len:u32_le][utf8]
421        let msg = "insufficient balance";
422        let mut payload = (msg.len() as u32).to_le_bytes().to_vec();
423        payload.extend_from_slice(msg.as_bytes());
424        assert_eq!(decode_revert_reason(&payload).as_deref(), Some(msg));
425    }
426
427    #[test]
428    fn revert_reason_legacy_u64_string() {
429        // Legacy: [len:u64_le][utf8]. To force the u64 path (not
430        // u32), use a length that wouldn't fit the u32 interpretation.
431        let msg = "legacy revert";
432        let bogus_u32 = u32::MAX.to_le_bytes(); // makes Borsh u32 reject
433        let mut payload = bogus_u32.to_vec();
434        payload.extend_from_slice(&(msg.len() as u32).to_le_bytes());
435        payload.extend_from_slice(msg.as_bytes());
436        // The u32 path bails on length > data.len()-4 → falls
437        // through to u64 which reads the full 8-byte prefix.
438        let len_u64 = msg.len() as u64;
439        let mut alt = len_u64.to_le_bytes().to_vec();
440        alt.extend_from_slice(msg.as_bytes());
441        assert_eq!(decode_revert_reason(&alt).as_deref(), Some(msg));
442    }
443
444    #[test]
445    fn revert_reason_raw_utf8_fallback() {
446        let msg = "bare utf8 message";
447        assert_eq!(decode_revert_reason(msg.as_bytes()).as_deref(), Some(msg));
448    }
449
450    #[test]
451    fn revert_reason_rejects_binary_garbage() {
452        // High-bit bytes that aren't valid UTF-8 → None.
453        let garbage = [0xFFu8, 0xFE, 0xFD, 0xFC];
454        assert!(decode_revert_reason(&garbage).is_none());
455    }
456
457    #[test]
458    fn revert_reason_rejects_long_random_utf8() {
459        // > 256 bytes of valid UTF-8 still rejected (likely binary
460        // that happens to decode).
461        let long = "x".repeat(300);
462        assert!(decode_revert_reason(long.as_bytes()).is_none());
463    }
464
465    #[test]
466    fn revert_reason_rejects_control_chars() {
467        let with_null = b"abc\x00def";
468        assert!(decode_revert_reason(with_null).is_none());
469    }
470
471    // ── extract_error_code ────────────────────────────────────
472
473    #[test]
474    fn error_code_from_named_token() {
475        let payload = b"token: ERR_FORBIDDEN -- sstore not allowed in view";
476        assert_eq!(extract_error_code(payload), Some(ErrorCode::Forbidden));
477    }
478
479    #[test]
480    fn error_code_from_longer_name_wins() {
481        // ERR_CROSS_CALL_OUT_OF_GAS contains ERR_CROSS_CALL_FAILED
482        // as a prefix substring of the prefix — we sort by length
483        // so the longer match wins.
484        let payload = b"sub-call: ERR_CROSS_CALL_OUT_OF_GAS";
485        assert_eq!(
486            extract_error_code(payload),
487            Some(ErrorCode::CrossCallOutOfGas)
488        );
489    }
490
491    #[test]
492    fn error_code_from_integer() {
493        let payload = b"reverted with code -5";
494        assert_eq!(extract_error_code(payload), Some(ErrorCode::Forbidden));
495    }
496
497    #[test]
498    fn error_code_from_negative_unknown_returns_none() {
499        let payload = b"random number -42 here";
500        assert!(extract_error_code(payload).is_none());
501    }
502
503    #[test]
504    fn error_code_no_match_returns_none() {
505        let payload = b"nothing matches here at all";
506        assert!(extract_error_code(payload).is_none());
507    }
508
509    // ── SdkError integration ──────────────────────────────────
510
511    #[test]
512    fn reverted_error_code_extracts_named_token() {
513        let err = SdkError::Reverted {
514            gas_used: 1000,
515            data: b"token: ERR_INSUFFICIENT_BALANCE".to_vec(),
516            reason: None,
517        };
518        assert_eq!(err.error_code(), Some(ErrorCode::InsufficientBalance));
519        assert!(err.is_revert());
520    }
521
522    #[test]
523    fn host_fn_variant_carries_typed_code() {
524        let err = SdkError::HostFn {
525            code: ErrorCode::ReentrancyBlocked,
526            message: "buy() reentered".into(),
527        };
528        assert_eq!(err.error_code(), Some(ErrorCode::ReentrancyBlocked));
529        assert_eq!(err.code(), "ERR_REENTRANCY_BLOCKED");
530        assert!(!err.is_revert());
531    }
532
533    #[test]
534    fn non_revert_variants_have_no_error_code() {
535        let err = SdkError::Rpc("-32602: bad params".into());
536        assert!(err.error_code().is_none());
537    }
538
539    #[test]
540    fn code_string_for_each_variant() {
541        // Spot-check every variant produces a stable label.
542        assert_eq!(SdkError::Rpc(String::new()).code(), "RPC_ERROR");
543        assert_eq!(
544            SdkError::Connection(String::new()).code(),
545            "CONNECTION_ERROR"
546        );
547        assert_eq!(SdkError::Signing(String::new()).code(), "SIGNING_ERROR");
548        assert_eq!(SdkError::Timeout(String::new()).code(), "TIMEOUT");
549        assert_eq!(
550            SdkError::Reverted {
551                gas_used: 0,
552                data: vec![],
553                reason: None,
554            }
555            .code(),
556            "CALL_EXCEPTION"
557        );
558        assert_eq!(
559            SdkError::InsufficientBalance {
560                required: 0,
561                available: 0
562            }
563            .code(),
564            "INSUFFICIENT_FUNDS"
565        );
566        assert_eq!(
567            SdkError::HostFn {
568                code: ErrorCode::Forbidden,
569                message: String::new()
570            }
571            .code(),
572            "ERR_FORBIDDEN"
573        );
574        assert_eq!(
575            SdkError::InvalidAddress(String::new()).code(),
576            "INVALID_ARGUMENT"
577        );
578        assert_eq!(
579            SdkError::InvalidArgument(String::new()).code(),
580            "INVALID_ARGUMENT"
581        );
582        assert_eq!(
583            SdkError::InvalidResponse(String::new()).code(),
584            "INVALID_RESPONSE"
585        );
586        assert_eq!(SdkError::Other(String::new()).code(), "OTHER");
587    }
588
589    // ── Structured revert_reason wiring ──────────────────────
590
591    #[test]
592    fn revert_category_accessors_branch_on_category() {
593        use crate::types::{RevertCategory, RevertReason};
594
595        let eng = SdkError::Reverted {
596            gas_used: 100,
597            data: vec![],
598            reason: Some(RevertReason {
599                category: RevertCategory::EngineValidation,
600                message: "nonce out of window".into(),
601            }),
602        };
603        assert!(matches!(
604            eng.revert_category(),
605            Some(RevertCategory::EngineValidation)
606        ));
607        assert!(eng.is_engine_validation_revert());
608        assert!(!eng.is_contract_revert());
609        assert!(!eng.is_vm_trap());
610
611        let con = SdkError::Reverted {
612            gas_used: 100,
613            data: vec![],
614            reason: Some(RevertReason {
615                category: RevertCategory::Contract,
616                message: "ERR_FORBIDDEN".into(),
617            }),
618        };
619        assert!(con.is_contract_revert());
620
621        let vm = SdkError::Reverted {
622            gas_used: 100,
623            data: vec![],
624            reason: Some(RevertReason {
625                category: RevertCategory::Vm,
626                message: "Trap(MemoryOutOfBounds)".into(),
627            }),
628        };
629        assert!(vm.is_vm_trap());
630
631        // No structured reason → accessors return None / false.
632        let bare = SdkError::Reverted {
633            gas_used: 100,
634            data: vec![],
635            reason: None,
636        };
637        assert!(bare.revert_category().is_none());
638        assert!(!bare.is_engine_validation_revert());
639    }
640
641    #[test]
642    fn format_revert_prefers_structured_reason() {
643        use crate::types::{RevertCategory, RevertReason};
644        let err = SdkError::Reverted {
645            gas_used: 42_000,
646            data: b"insufficient balance".to_vec(),
647            reason: Some(RevertReason {
648                category: RevertCategory::EngineValidation,
649                message: "insufficient balance for fee+value: needed=42000, available=21000".into(),
650            }),
651        };
652        let msg = format!("{err}");
653        assert!(msg.contains("EngineValidation"));
654        assert!(msg.contains("needed=42000"));
655        assert!(msg.contains("gas=42000"));
656    }
657
658    #[test]
659    fn from_receipt_maps_each_status() {
660        use crate::types::{Receipt, ReceiptStatus, RevertCategory, RevertReason};
661        fn receipt(status: ReceiptStatus, reason: Option<RevertReason>) -> Receipt {
662            Receipt {
663                tx_hash: "0x".into(),
664                wave_id: "0x1".into(),
665                tx_index: "0x0".into(),
666                nonce: "0x0".into(),
667                commit_reveal: false,
668                status,
669                gas_used: "0x5208".into(),
670                fee_paid: "0x5208".into(),
671                return_data: "0x".into(),
672                events: vec![],
673                revert_reason: reason,
674            }
675        }
676
677        // Success → None
678        assert!(SdkError::from_receipt(&receipt(ReceiptStatus::Success, None)).is_none());
679
680        // OutOfGas → synthesised Vm category
681        let err = SdkError::from_receipt(&receipt(ReceiptStatus::OutOfGas, None)).unwrap();
682        assert!(err.is_vm_trap());
683
684        // Reverted + structured reason → carried through
685        let err = SdkError::from_receipt(&receipt(
686            ReceiptStatus::Reverted,
687            Some(RevertReason {
688                category: RevertCategory::Contract,
689                message: "ERR_FORBIDDEN".into(),
690            }),
691        ))
692        .unwrap();
693        assert!(err.is_contract_revert());
694
695        // Reverted + no structured reason → bare (older engine)
696        let err = SdkError::from_receipt(&receipt(ReceiptStatus::Reverted, None)).unwrap();
697        assert!(err.is_revert());
698        assert!(err.revert_category().is_none());
699    }
700}