Skip to main content

walletkit/
error.rs

1//! The public error taxonomy (SPEC §5.5). Per-port `{Trait}Error`s remain the internal
2//! contracts; `WalletKitError` is the one umbrella every `Wallet` operation returns,
3//! classified for retry with a machine-readable [`ErrorKind`].
4
5use crate::core::accounts::AccountError;
6use crate::core::deps::{
7    EnsError, GasOracleError, NonceManagerError, PolicyEngineError, ReadError, RpcError,
8    SignerError, StateStoreError, SubmissionError,
9};
10use crate::core::wallet::{ExecutorError, PolicyRejection, TransactionManagerError};
11use alloy_primitives::Address;
12use std::time::Duration;
13
14/// Machine-readable retry classification.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ErrorKind {
17    /// A transient failure — retrying the same request may succeed.
18    Retryable,
19    /// A permanent failure — retrying will not help.
20    Terminal,
21    /// The tx may already be in flight or the chain moved — reconcile before acting.
22    NeedsReconcile,
23}
24
25/// The one error every `Wallet` operation surfaces.
26#[derive(Debug, thiserror::Error)]
27#[non_exhaustive]
28pub enum WalletKitError {
29    /// An RPC call failed.
30    #[error(transparent)]
31    Rpc(RpcError),
32    /// Signing failed (gate trip, malformed payload, or backend error).
33    #[error(transparent)]
34    Signer(SignerError),
35    /// Policy denied the intent — carries the exact rule + offending field.
36    #[error(transparent)]
37    Policy(PolicyRejection),
38    /// The policy engine failed operationally (load/eval), distinct from a denial.
39    #[error(transparent)]
40    PolicyEngine(PolicyEngineError),
41    /// Fee estimation or bumping failed.
42    #[error(transparent)]
43    Gas(GasOracleError),
44    /// Nonce allocation or reconciliation failed.
45    #[error(transparent)]
46    Nonce(NonceManagerError),
47    /// Broadcasting the transaction failed.
48    #[error(transparent)]
49    Submission(SubmissionError),
50    /// A durable-store operation failed.
51    #[error(transparent)]
52    Store(StateStoreError),
53    /// A chain read failed (RPC transport or on-chain decode).
54    #[error(transparent)]
55    Read(ReadError),
56    /// An ENS resolution failed (transport, offchain-required, or resolution error).
57    #[error(transparent)]
58    Ens(EnsError),
59    /// An account-management operation failed (bad phrase/path, derivation, RNG, or a
60    /// discovery read).
61    #[error(transparent)]
62    Account(AccountError),
63    /// Pre-send simulation rejected the intent (it would revert).
64    #[error("simulation rejected: {reason}")]
65    Simulation {
66        /// The decoded revert/rejection reason.
67        reason: String,
68    },
69    /// The signer's address does not control the intent's account.
70    #[error("signer {signer} does not control the intent account {intent}")]
71    AccountMismatch {
72        /// The intent's declared account.
73        intent: Address,
74        /// The signer's actual address.
75        signer: Address,
76    },
77    /// A cancel could not proceed: the handle is unknown or already settled.
78    #[error("cannot cancel: {reason}")]
79    Cancel {
80        /// Why the cancel could not proceed.
81        reason: &'static str,
82    },
83    /// A convenience-constructor setup failure: a malformed RPC URL or a transport that
84    /// could not be built.
85    #[error("connection setup failed: {0}")]
86    Connect(String),
87}
88
89impl WalletKitError {
90    /// The retry classification a caller should branch on.
91    pub fn kind(&self) -> ErrorKind {
92        match self {
93            Self::Rpc(e) => rpc_kind(e),
94            Self::Gas(GasOracleError::Rpc(e)) => rpc_kind(e),
95            Self::Gas(GasOracleError::CeilingExceeded { .. }) => ErrorKind::Terminal,
96            Self::Nonce(NonceManagerError::Rpc(e)) => rpc_kind(e),
97            Self::Nonce(NonceManagerError::Store(e)) => store_kind(e),
98            Self::Submission(e) => submission_kind(e),
99            Self::Store(e) => store_kind(e),
100            Self::Read(ReadError::Rpc(e)) => rpc_kind(e),
101            Self::Read(ReadError::Decode { .. }) => ErrorKind::Terminal,
102            Self::Ens(EnsError::Rpc(e)) => rpc_kind(e),
103            Self::Ens(EnsError::OffchainLookupRequired | EnsError::Resolution { .. }) => {
104                ErrorKind::Terminal
105            }
106            Self::Account(e) => account_kind(e),
107            Self::Signer(_)
108            | Self::Policy(_)
109            | Self::PolicyEngine(_)
110            | Self::Simulation { .. }
111            | Self::AccountMismatch { .. }
112            | Self::Cancel { .. }
113            | Self::Connect(_) => ErrorKind::Terminal,
114        }
115    }
116
117    /// Whether an immediate retry of the same request is worthwhile.
118    pub fn is_retryable(&self) -> bool {
119        self.kind() == ErrorKind::Retryable
120    }
121
122    /// A suggested minimum backoff. `None` until the Transport surfaces server
123    /// `Retry-After`/rate-limit hints; until then [`is_retryable`](Self::is_retryable) is
124    /// the signal and the host paces retries.
125    pub fn retry_after(&self) -> Option<Duration> {
126        None
127    }
128
129    /// A short operator hint, when one is more useful than the error message alone.
130    pub fn remediation(&self) -> Option<&'static str> {
131        match self {
132            Self::AccountMismatch { .. } => {
133                Some("sign with the key that controls the intent account")
134            }
135            Self::Gas(GasOracleError::CeilingExceeded { .. }) => {
136                Some("raise gas_ceiling or wait for the base fee to fall")
137            }
138            Self::Signer(
139                SignerError::ApprovalExpired
140                | SignerError::ApprovalMismatch
141                | SignerError::FeesExceedApproval,
142            ) => Some("re-submit the intent to obtain a fresh policy approval"),
143            Self::Simulation { .. } => {
144                Some("the transaction would revert — inspect calldata and account state")
145            }
146            Self::Cancel { .. } => {
147                Some("the transaction already settled or was never tracked — nothing to cancel")
148            }
149            _ => None,
150        }
151    }
152
153    /// The structured rejection when policy denied the intent.
154    pub fn policy_rejection(&self) -> Option<&PolicyRejection> {
155        match self {
156            Self::Policy(r) => Some(r),
157            _ => None,
158        }
159    }
160}
161
162fn rpc_kind(e: &RpcError) -> ErrorKind {
163    match e {
164        RpcError::Call {
165            transient: true, ..
166        } => ErrorKind::Retryable,
167        RpcError::Call {
168            transient: false, ..
169        } => ErrorKind::Terminal,
170    }
171}
172
173fn submission_kind(e: &SubmissionError) -> ErrorKind {
174    if e.is_already_accepted() {
175        ErrorKind::NeedsReconcile
176    } else if e.is_transient() || e.is_underpriced() {
177        ErrorKind::Retryable
178    } else {
179        ErrorKind::Terminal
180    }
181}
182
183fn account_kind(e: &AccountError) -> ErrorKind {
184    // A discovery read/RPC failure follows the transport's retry classification; a bad
185    // phrase/path/derivation/RNG failure is terminal.
186    match e {
187        AccountError::Rpc(e) | AccountError::Read(ReadError::Rpc(e)) => rpc_kind(e),
188        _ => ErrorKind::Terminal,
189    }
190}
191
192fn store_kind(e: &StateStoreError) -> ErrorKind {
193    match e {
194        StateStoreError::Backend { .. } | StateStoreError::Task(_) => ErrorKind::Retryable,
195        StateStoreError::Serialization { .. } | StateStoreError::Fenced => ErrorKind::Terminal,
196    }
197}
198
199impl From<TransactionManagerError> for WalletKitError {
200    fn from(e: TransactionManagerError) -> Self {
201        use TransactionManagerError as E;
202        match e {
203            E::AccountMismatch { intent, signer } => Self::AccountMismatch { intent, signer },
204            E::SimulationRejected { reason } => Self::Simulation { reason },
205            E::UnknownHandle => Self::Cancel {
206                reason: "no tracked transaction for this handle id",
207            },
208            E::CancelTerminal => Self::Cancel {
209                reason: "the transaction already settled",
210            },
211            E::Denied(r) => Self::Policy(r),
212            E::Rpc(e) => Self::Rpc(e),
213            E::Gas(e) => Self::Gas(e),
214            E::Policy(e) => Self::PolicyEngine(e),
215            E::Nonce(e) => Self::Nonce(e),
216            E::Signer(e) => Self::Signer(e),
217            E::Store(e) => Self::Store(e),
218            E::Submission(e) => Self::Submission(e),
219        }
220    }
221}
222
223impl From<ExecutorError> for WalletKitError {
224    fn from(e: ExecutorError) -> Self {
225        use ExecutorError as E;
226        match e {
227            E::Rpc(e) => Self::Rpc(e),
228            E::Gas(e) => Self::Gas(e),
229            E::Policy(e) => Self::PolicyEngine(e),
230            E::Nonce(e) => Self::Nonce(e),
231            E::Signer(e) => Self::Signer(e),
232            E::Store(e) => Self::Store(e),
233            E::Submission(e) => Self::Submission(e),
234        }
235    }
236}
237
238impl From<StateStoreError> for WalletKitError {
239    fn from(e: StateStoreError) -> Self {
240        Self::Store(e)
241    }
242}
243
244impl From<ReadError> for WalletKitError {
245    fn from(e: ReadError) -> Self {
246        Self::Read(e)
247    }
248}
249
250impl From<EnsError> for WalletKitError {
251    fn from(e: EnsError) -> Self {
252        Self::Ens(e)
253    }
254}
255
256impl From<AccountError> for WalletKitError {
257    fn from(e: AccountError) -> Self {
258        Self::Account(e)
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn transient_rpc_is_retryable_with_no_backoff_yet() {
268        let e = WalletKitError::Rpc(RpcError::Call {
269            message: "timeout".into(),
270            transient: true,
271        });
272        assert_eq!(e.kind(), ErrorKind::Retryable);
273        assert!(e.is_retryable());
274        assert_eq!(e.retry_after(), None);
275    }
276
277    #[test]
278    fn non_transient_rpc_is_terminal() {
279        let e = WalletKitError::Rpc(RpcError::Call {
280            message: "method not found".into(),
281            transient: false,
282        });
283        assert_eq!(e.kind(), ErrorKind::Terminal);
284        assert!(!e.is_retryable());
285    }
286
287    #[test]
288    fn already_known_submission_needs_reconcile() {
289        // "already known" is a canonical already-accepted message -> reconcile, don't fail.
290        let e = WalletKitError::Submission(SubmissionError::Rpc(RpcError::Call {
291            message: "already known".into(),
292            transient: false,
293        }));
294        assert_eq!(e.kind(), ErrorKind::NeedsReconcile);
295    }
296
297    #[test]
298    fn ceiling_exceeded_is_terminal_with_remediation() {
299        let e = WalletKitError::Gas(GasOracleError::CeilingExceeded {
300            ceiling: 100,
301            needed: 200,
302        });
303        assert_eq!(e.kind(), ErrorKind::Terminal);
304        assert!(e.remediation().is_some());
305    }
306
307    #[test]
308    fn denial_exposes_the_structured_rejection() {
309        let rejection = PolicyRejection {
310            rule: "spend_limit".into(),
311            field: Some("value".into()),
312            reason: "exceeds cap".into(),
313        };
314        let e = WalletKitError::from(TransactionManagerError::Denied(rejection));
315        assert_eq!(e.kind(), ErrorKind::Terminal);
316        let r = e.policy_rejection().expect("policy rejection present");
317        assert_eq!(r.rule, "spend_limit");
318        assert_eq!(r.field.as_deref(), Some("value"));
319    }
320
321    #[test]
322    fn account_errors_classify_by_cause() {
323        // A bad phrase is terminal; a discovery RPC failure follows the transport class.
324        assert_eq!(
325            WalletKitError::Account(AccountError::InvalidPhrase).kind(),
326            ErrorKind::Terminal
327        );
328        assert_eq!(
329            WalletKitError::Account(AccountError::Rpc(RpcError::Call {
330                message: "timeout".into(),
331                transient: true,
332            }))
333            .kind(),
334            ErrorKind::Retryable
335        );
336    }
337
338    #[test]
339    fn from_txmgr_flattens_domain_variants() {
340        let acct = Address::ZERO;
341        let e = WalletKitError::from(TransactionManagerError::AccountMismatch {
342            intent: acct,
343            signer: acct,
344        });
345        assert!(matches!(e, WalletKitError::AccountMismatch { .. }));
346        let e = WalletKitError::from(TransactionManagerError::SimulationRejected {
347            reason: "revert".into(),
348        });
349        assert!(matches!(e, WalletKitError::Simulation { .. }));
350    }
351}