aptos-sdk 0.4.1

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! Error types for the Aptos SDK.
//!
//! This module provides a unified error type [`AptosError`] that encompasses
//! all possible errors that can occur when using the SDK.

use std::fmt;
use thiserror::Error;

/// A specialized Result type for Aptos SDK operations.
pub type AptosResult<T> = Result<T, AptosError>;

/// The main error type for the Aptos SDK.
///
/// This enum covers all possible error conditions that can occur when
/// interacting with the Aptos blockchain through this SDK.
///
/// # Security: Logging Errors
///
/// **WARNING:** The `Display` implementation on this type may include sensitive
/// information (e.g., partial key material, JWT tokens, or mnemonic phrases) in
/// its output. When logging errors, always use [`sanitized_message()`](AptosError::sanitized_message)
/// instead of `to_string()` or `Display`:
///
/// ```rust,ignore
/// // WRONG - may leak sensitive data:
/// log::error!("Failed: {}", err);
///
/// // CORRECT - redacts sensitive patterns:
/// log::error!("Failed: {}", err.sanitized_message());
/// ```
#[derive(Error, Debug)]
pub enum AptosError {
    /// Error occurred during HTTP communication
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),

    /// Error occurred during JSON serialization/deserialization
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    /// Error occurred during BCS serialization/deserialization
    #[error("BCS error: {0}")]
    Bcs(String),

    /// Error occurred during URL parsing
    #[error("URL error: {0}")]
    Url(#[from] url::ParseError),

    /// Error occurred during hex encoding/decoding
    #[error("Hex error: {0}")]
    Hex(#[from] const_hex::FromHexError),

    /// Invalid account address
    #[error("Invalid address: {0}")]
    InvalidAddress(String),

    /// Invalid public key
    #[error("Invalid public key: {0}")]
    InvalidPublicKey(String),

    /// Invalid private key
    #[error("Invalid private key: {0}")]
    InvalidPrivateKey(String),

    /// Invalid signature
    #[error("Invalid signature: {0}")]
    InvalidSignature(String),

    /// Signature verification failed
    #[error("Signature verification failed")]
    SignatureVerificationFailed,

    /// Invalid type tag format
    #[error("Invalid type tag: {0}")]
    InvalidTypeTag(String),

    /// Transaction building error
    #[error("Transaction error: {0}")]
    Transaction(String),

    /// Transaction simulation failed
    #[error("Simulation failed: {0}")]
    SimulationFailed(String),

    /// Transaction submission failed
    #[error("Submission failed: {0}")]
    SubmissionFailed(String),

    /// Transaction execution failed on chain
    #[error("Execution failed: {vm_status}")]
    ExecutionFailed {
        /// The VM status message explaining the failure
        vm_status: String,
    },

    /// Transaction timed out waiting for confirmation
    #[error("Transaction timed out after {timeout_secs} seconds")]
    TransactionTimeout {
        /// The hash of the transaction that timed out
        hash: String,
        /// How long we waited before timing out
        timeout_secs: u64,
    },

    /// API returned an error response
    #[error("API error ({status_code}): {message}")]
    Api {
        /// HTTP status code
        status_code: u16,
        /// Error message from the API
        message: String,
        /// Optional error code from the API
        error_code: Option<String>,
        /// Optional VM error code
        vm_error_code: Option<u64>,
    },

    /// Rate limited by the API
    #[error("Rate limited: retry after {retry_after_secs:?} seconds")]
    RateLimited {
        /// How long to wait before retrying (if provided)
        retry_after_secs: Option<u64>,
    },

    /// Resource not found
    #[error("Resource not found: {0}")]
    NotFound(String),

    /// Account not found
    #[error("Account not found: {0}")]
    AccountNotFound(String),

    /// Invalid mnemonic phrase
    #[error("Invalid mnemonic: {0}")]
    InvalidMnemonic(String),

    /// Invalid JWT
    #[error("Invalid JWT: {0}")]
    InvalidJwt(String),

    /// Key derivation error
    #[error("Key derivation error: {0}")]
    KeyDerivation(String),

    /// Insufficient signatures for multi-signature operation
    #[error("Insufficient signatures: need {required}, got {provided}")]
    InsufficientSignatures {
        /// Number of signatures required
        required: usize,
        /// Number of signatures provided
        provided: usize,
    },

    /// Feature not enabled
    #[error("Feature not enabled: {0}. Enable the '{0}' feature in Cargo.toml")]
    FeatureNotEnabled(String),

    /// Configuration error
    #[error("Configuration error: {0}")]
    Config(String),

    /// Internal SDK error (should not happen)
    #[error("Internal error: {0}")]
    Internal(String),

    /// Any other error
    #[error("{0}")]
    Other(#[from] anyhow::Error),
}

/// Maximum length for error messages to prevent excessive memory usage in logs.
const MAX_ERROR_MESSAGE_LENGTH: usize = 1000;

/// Patterns that might indicate sensitive information in error messages.
///
/// # Security
///
/// This list is used by [`AptosError::sanitized_message()`] to redact potentially
/// sensitive content from error messages before logging. The check is case-insensitive.
const SENSITIVE_PATTERNS: &[&str] = &[
    "private_key",
    "secret",
    "password",
    "mnemonic",
    "seed",
    "bearer",
    "authorization",
    "token",
    "jwt",
    "credential",
    "api_key",
    "apikey",
    "access_token",
    "refresh_token",
    "pepper",
];

impl AptosError {
    /// Creates a new BCS error
    pub fn bcs<E: fmt::Display>(err: E) -> Self {
        Self::Bcs(err.to_string())
    }

    /// Creates a new transaction error
    pub fn transaction<S: Into<String>>(msg: S) -> Self {
        Self::Transaction(msg.into())
    }

    /// Creates a new API error from response details
    pub fn api(status_code: u16, message: impl Into<String>) -> Self {
        Self::Api {
            status_code,
            message: message.into(),
            error_code: None,
            vm_error_code: None,
        }
    }

    /// Creates a new API error with additional details
    pub fn api_with_details(
        status_code: u16,
        message: impl Into<String>,
        error_code: Option<String>,
        vm_error_code: Option<u64>,
    ) -> Self {
        Self::Api {
            status_code,
            message: message.into(),
            error_code,
            vm_error_code,
        }
    }

    /// Returns true if this is a "not found" error
    pub fn is_not_found(&self) -> bool {
        matches!(
            self,
            Self::NotFound(_)
                | Self::AccountNotFound(_)
                | Self::Api {
                    status_code: 404,
                    ..
                }
        )
    }

    /// Returns true if this is a timeout error
    pub fn is_timeout(&self) -> bool {
        matches!(self, Self::TransactionTimeout { .. })
    }

    /// Returns true if this is a transient error that might succeed on retry
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Http(e) => e.is_timeout() || e.is_connect(),
            Self::Api { status_code, .. } => {
                matches!(status_code, 429 | 500 | 502 | 503 | 504)
            }
            Self::RateLimited { .. } => true,
            _ => false,
        }
    }

    /// Returns a sanitized version of the error message safe for logging.
    ///
    /// This method:
    /// - Removes control characters that could corrupt logs
    /// - Truncates very long messages to prevent log flooding
    /// - Redacts patterns that might indicate sensitive information
    ///
    /// # Example
    ///
    /// ```rust
    /// use aptos_sdk::AptosError;
    ///
    /// let err = AptosError::api(500, "Internal server error with details...");
    /// let safe_msg = err.sanitized_message();
    /// // safe_msg is guaranteed to be safe for logging
    /// ```
    pub fn sanitized_message(&self) -> String {
        let raw_message = self.to_string();
        Self::sanitize_string(&raw_message)
    }

    /// Sanitizes a string for safe logging.
    fn sanitize_string(s: &str) -> String {
        // Remove control characters (except newline and tab for readability)
        let cleaned: String = s
            .chars()
            .filter(|c| !c.is_control() || *c == '\n' || *c == '\t')
            .collect();

        // Check for sensitive patterns (case-insensitive)
        let lower = cleaned.to_lowercase();
        for pattern in SENSITIVE_PATTERNS {
            if lower.contains(pattern) {
                return format!("[REDACTED: message contained sensitive pattern '{pattern}']");
            }
        }

        // SECURITY: Redact URLs with query parameters, which may contain API keys
        // or other credentials not caught by keyword patterns above.
        // e.g., reqwest errors include the request URL.
        // Only redact when '?' appears within a URL token (after the scheme),
        // not just anywhere in the message.
        for scheme in ["http://", "https://"] {
            if let Some(scheme_pos) = lower.find(scheme) {
                // Look for '?' after the scheme, within the URL token
                // (URLs end at whitespace or common delimiters)
                let url_start = scheme_pos;
                let url_rest = &lower[url_start..];
                let url_end = url_rest
                    .find(|c: char| c.is_whitespace() || c == '>' || c == '"' || c == '\'')
                    .unwrap_or(url_rest.len());
                let url_token = &url_rest[..url_end];
                if url_token.contains('?') {
                    return "[REDACTED: message contained URL with query parameters]".into();
                }
            }
        }

        // Truncate if too long (find a valid UTF-8 boundary to avoid panic)
        if cleaned.len() > MAX_ERROR_MESSAGE_LENGTH {
            let mut end = MAX_ERROR_MESSAGE_LENGTH;
            while end > 0 && !cleaned.is_char_boundary(end) {
                end -= 1;
            }
            format!(
                "{}... [truncated, total length: {}]",
                &cleaned[..end],
                cleaned.len()
            )
        } else {
            cleaned
        }
    }

    /// Returns the error message suitable for display to end users.
    ///
    /// This is a more conservative sanitization that provides less detail
    /// but is safer for user-facing error messages.
    pub fn user_message(&self) -> &'static str {
        match self {
            Self::Http(_) => "Network error occurred",
            Self::Json(_) => "Failed to process response",
            Self::Bcs(_) => "Failed to process data",
            Self::Url(_) => "Invalid URL",
            Self::Hex(_) => "Invalid hex format",
            Self::InvalidAddress(_) => "Invalid account address",
            Self::InvalidPublicKey(_) => "Invalid public key",
            Self::InvalidPrivateKey(_) => "Invalid private key",
            Self::InvalidSignature(_) => "Invalid signature",
            Self::SignatureVerificationFailed => "Signature verification failed",
            Self::InvalidTypeTag(_) => "Invalid type format",
            Self::Transaction(_) => "Transaction error",
            Self::SimulationFailed(_) => "Transaction simulation failed",
            Self::SubmissionFailed(_) => "Transaction submission failed",
            Self::ExecutionFailed { .. } => "Transaction execution failed",
            Self::TransactionTimeout { .. } => "Transaction timed out",
            Self::NotFound(_)
            | Self::Api {
                status_code: 404, ..
            } => "Resource not found",
            Self::RateLimited { .. }
            | Self::Api {
                status_code: 429, ..
            } => "Rate limit exceeded",
            Self::Api { status_code, .. } if *status_code >= 500 => "Server error",
            Self::Api { .. } => "API error",
            Self::AccountNotFound(_) => "Account not found",
            Self::InvalidMnemonic(_) => "Invalid recovery phrase",
            Self::InvalidJwt(_) => "Invalid authentication token",
            Self::KeyDerivation(_) => "Key derivation failed",
            Self::InsufficientSignatures { .. } => "Insufficient signatures",
            Self::FeatureNotEnabled(_) => "Feature not enabled",
            Self::Config(_) => "Configuration error",
            Self::Internal(_) => "Internal error",
            Self::Other(_) => "An error occurred",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_display() {
        let err = AptosError::InvalidAddress("bad address".to_string());
        assert_eq!(err.to_string(), "Invalid address: bad address");
    }

    #[test]
    fn test_is_not_found() {
        assert!(AptosError::NotFound("test".to_string()).is_not_found());
        assert!(AptosError::AccountNotFound("0x1".to_string()).is_not_found());
        assert!(AptosError::api(404, "not found").is_not_found());
        assert!(!AptosError::api(500, "server error").is_not_found());
    }

    #[test]
    fn test_is_retryable() {
        assert!(AptosError::api(429, "rate limited").is_retryable());
        assert!(AptosError::api(503, "unavailable").is_retryable());
        assert!(AptosError::api(500, "internal error").is_retryable());
        assert!(AptosError::api(502, "bad gateway").is_retryable());
        assert!(AptosError::api(504, "timeout").is_retryable());
        assert!(!AptosError::api(400, "bad request").is_retryable());
    }

    #[test]
    fn test_is_timeout() {
        let err = AptosError::TransactionTimeout {
            hash: "0x123".to_string(),
            timeout_secs: 30,
        };
        assert!(err.is_timeout());
        assert!(!AptosError::InvalidAddress("test".to_string()).is_timeout());
    }

    #[test]
    fn test_bcs_error() {
        let err = AptosError::bcs("serialization failed");
        assert!(matches!(err, AptosError::Bcs(_)));
        assert!(err.to_string().contains("serialization failed"));
    }

    #[test]
    fn test_transaction_error() {
        let err = AptosError::transaction("invalid payload");
        assert!(matches!(err, AptosError::Transaction(_)));
        assert!(err.to_string().contains("invalid payload"));
    }

    #[test]
    fn test_api_error() {
        let err = AptosError::api(400, "bad request");
        assert!(err.to_string().contains("400"));
        assert!(err.to_string().contains("bad request"));
    }

    #[test]
    fn test_api_error_with_details() {
        let err = AptosError::api_with_details(
            400,
            "invalid argument",
            Some("INVALID_ARGUMENT".to_string()),
            Some(42),
        );
        if let AptosError::Api {
            status_code,
            message,
            error_code,
            vm_error_code,
        } = err
        {
            assert_eq!(status_code, 400);
            assert_eq!(message, "invalid argument");
            assert_eq!(error_code, Some("INVALID_ARGUMENT".to_string()));
            assert_eq!(vm_error_code, Some(42));
        } else {
            panic!("Expected Api error variant");
        }
    }

    #[test]
    fn test_various_error_displays() {
        assert!(
            AptosError::InvalidPublicKey("bad key".to_string())
                .to_string()
                .contains("public key")
        );
        assert!(
            AptosError::InvalidPrivateKey("bad key".to_string())
                .to_string()
                .contains("private key")
        );
        assert!(
            AptosError::InvalidSignature("bad sig".to_string())
                .to_string()
                .contains("signature")
        );
        assert!(
            AptosError::SignatureVerificationFailed
                .to_string()
                .contains("verification")
        );
        assert!(
            AptosError::InvalidTypeTag("bad tag".to_string())
                .to_string()
                .contains("type tag")
        );
        assert!(
            AptosError::SimulationFailed("error".to_string())
                .to_string()
                .contains("Simulation")
        );
        assert!(
            AptosError::SubmissionFailed("error".to_string())
                .to_string()
                .contains("Submission")
        );
    }

    #[test]
    fn test_execution_failed() {
        let err = AptosError::ExecutionFailed {
            vm_status: "ABORTED".to_string(),
        };
        assert!(err.to_string().contains("ABORTED"));
    }

    #[test]
    fn test_rate_limited() {
        let err = AptosError::RateLimited {
            retry_after_secs: Some(30),
        };
        assert!(err.to_string().contains("Rate limited"));
    }

    #[test]
    fn test_insufficient_signatures() {
        let err = AptosError::InsufficientSignatures {
            required: 3,
            provided: 1,
        };
        assert!(err.to_string().contains('3'));
        assert!(err.to_string().contains('1'));
    }

    #[test]
    fn test_feature_not_enabled() {
        let err = AptosError::FeatureNotEnabled("ed25519".to_string());
        assert!(err.to_string().contains("ed25519"));
        assert!(err.to_string().contains("Cargo.toml"));
    }

    #[test]
    fn test_config_error() {
        let err = AptosError::Config("invalid config".to_string());
        assert!(err.to_string().contains("Configuration"));
    }

    #[test]
    fn test_internal_error() {
        let err = AptosError::Internal("bug".to_string());
        assert!(err.to_string().contains("Internal"));
    }

    #[test]
    fn test_invalid_mnemonic() {
        let err = AptosError::InvalidMnemonic("bad phrase".to_string());
        assert!(err.to_string().contains("mnemonic"));
    }

    #[test]
    fn test_invalid_jwt() {
        let err = AptosError::InvalidJwt("bad token".to_string());
        assert!(err.to_string().contains("JWT"));
    }

    #[test]
    fn test_key_derivation() {
        let err = AptosError::KeyDerivation("failed".to_string());
        assert!(err.to_string().contains("derivation"));
    }

    #[test]
    fn test_sanitized_message_basic() {
        let err = AptosError::api(400, "bad request");
        let sanitized = err.sanitized_message();
        assert!(sanitized.contains("bad request"));
    }

    #[test]
    fn test_sanitized_message_truncates_long_messages() {
        let long_message = "x".repeat(2000);
        let err = AptosError::api(500, long_message);
        let sanitized = err.sanitized_message();
        assert!(sanitized.len() < 1200); // Should be truncated
        assert!(sanitized.contains("truncated"));
    }

    #[test]
    fn test_sanitized_message_removes_control_chars() {
        let err = AptosError::api(400, "bad\x00request\x1f");
        let sanitized = err.sanitized_message();
        assert!(!sanitized.contains('\x00'));
        assert!(!sanitized.contains('\x1f'));
    }

    #[test]
    fn test_sanitized_message_redacts_sensitive_patterns() {
        let err = AptosError::Internal("private_key: abc123".to_string());
        let sanitized = err.sanitized_message();
        assert!(sanitized.contains("REDACTED"));
        assert!(!sanitized.contains("abc123"));

        let err = AptosError::Internal("mnemonic phrase here".to_string());
        let sanitized = err.sanitized_message();
        assert!(sanitized.contains("REDACTED"));
    }

    #[test]
    fn test_user_message() {
        assert_eq!(
            AptosError::api(404, "not found").user_message(),
            "Resource not found"
        );
        assert_eq!(
            AptosError::api(429, "rate limited").user_message(),
            "Rate limit exceeded"
        );
        assert_eq!(
            AptosError::api(500, "internal error").user_message(),
            "Server error"
        );
        assert_eq!(
            AptosError::InvalidAddress("bad".to_string()).user_message(),
            "Invalid account address"
        );
    }

    #[test]
    fn test_user_message_all_variants() {
        // Test all user_message variants for coverage
        assert_eq!(
            AptosError::InvalidPublicKey("bad".to_string()).user_message(),
            "Invalid public key"
        );
        assert_eq!(
            AptosError::InvalidPrivateKey("bad".to_string()).user_message(),
            "Invalid private key"
        );
        assert_eq!(
            AptosError::InvalidSignature("bad".to_string()).user_message(),
            "Invalid signature"
        );
        assert_eq!(
            AptosError::SignatureVerificationFailed.user_message(),
            "Signature verification failed"
        );
        assert_eq!(
            AptosError::InvalidTypeTag("bad".to_string()).user_message(),
            "Invalid type format"
        );
        assert_eq!(
            AptosError::Transaction("bad".to_string()).user_message(),
            "Transaction error"
        );
        assert_eq!(
            AptosError::SimulationFailed("bad".to_string()).user_message(),
            "Transaction simulation failed"
        );
        assert_eq!(
            AptosError::SubmissionFailed("bad".to_string()).user_message(),
            "Transaction submission failed"
        );
        assert_eq!(
            AptosError::ExecutionFailed {
                vm_status: "ABORTED".to_string()
            }
            .user_message(),
            "Transaction execution failed"
        );
        assert_eq!(
            AptosError::TransactionTimeout {
                hash: "0x1".to_string(),
                timeout_secs: 30
            }
            .user_message(),
            "Transaction timed out"
        );
        assert_eq!(
            AptosError::NotFound("x".to_string()).user_message(),
            "Resource not found"
        );
        assert_eq!(
            AptosError::RateLimited {
                retry_after_secs: Some(30)
            }
            .user_message(),
            "Rate limit exceeded"
        );
        assert_eq!(
            AptosError::api(503, "unavailable").user_message(),
            "Server error"
        );
        assert_eq!(
            AptosError::api(400, "bad request").user_message(),
            "API error"
        );
        assert_eq!(
            AptosError::AccountNotFound("0x1".to_string()).user_message(),
            "Account not found"
        );
        assert_eq!(
            AptosError::InvalidMnemonic("bad".to_string()).user_message(),
            "Invalid recovery phrase"
        );
        assert_eq!(
            AptosError::InvalidJwt("bad".to_string()).user_message(),
            "Invalid authentication token"
        );
        assert_eq!(
            AptosError::KeyDerivation("bad".to_string()).user_message(),
            "Key derivation failed"
        );
        assert_eq!(
            AptosError::InsufficientSignatures {
                required: 3,
                provided: 1
            }
            .user_message(),
            "Insufficient signatures"
        );
        assert_eq!(
            AptosError::FeatureNotEnabled("ed25519".to_string()).user_message(),
            "Feature not enabled"
        );
        assert_eq!(
            AptosError::Config("bad".to_string()).user_message(),
            "Configuration error"
        );
        assert_eq!(
            AptosError::Internal("bug".to_string()).user_message(),
            "Internal error"
        );
        assert_eq!(
            AptosError::Other(anyhow::anyhow!("misc")).user_message(),
            "An error occurred"
        );
    }

    #[test]
    fn test_is_retryable_http_errors() {
        // We can't easily test reqwest errors, so just ensure non-http errors return false
        assert!(!AptosError::InvalidAddress("x".to_string()).is_retryable());
        assert!(!AptosError::Transaction("x".to_string()).is_retryable());
        assert!(!AptosError::NotFound("x".to_string()).is_retryable());
    }
}