Skip to main content

sui_rpc_api/
error.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use sui_types::error::ErrorCategory;
5use tonic::Code;
6
7use crate::ledger_history::object_versions::ObjectRemovalKind;
8use crate::proto::google::rpc::{BadRequest, ErrorInfo, RetryInfo};
9use crate::proto::sui::rpc::v2::ExecutionError;
10use crate::proto::sui::rpc::v2::object_removal;
11pub use sui_rpc::proto::sui::rpc::v2::ErrorReason;
12
13pub type Result<T, E = RpcError> = std::result::Result<T, E>;
14
15/// An error encountered while serving an RPC request.
16///
17/// General error type used by top-level RPC service methods. The main purpose of this error type
18/// is to provide a convenient type for converting between internal errors and a response that
19/// needs to be sent to a calling client.
20#[derive(Debug)]
21pub struct RpcError {
22    code: Code,
23    message: Option<String>,
24    details: Option<Box<ErrorDetails>>,
25}
26
27impl RpcError {
28    pub fn new<T: Into<String>>(code: Code, message: T) -> Self {
29        Self {
30            code,
31            message: Some(message.into()),
32            details: None,
33        }
34    }
35
36    pub fn not_found() -> Self {
37        Self {
38            code: Code::NotFound,
39            message: None,
40            details: None,
41        }
42    }
43
44    pub fn code(&self) -> Code {
45        self.code
46    }
47
48    /// Whether this error carries an [`ErrorInfo`] with `reason`.
49    pub(crate) fn has_reason(&self, reason: ErrorReason) -> bool {
50        self.details
51            .as_ref()
52            .and_then(|details| details.error_info())
53            .is_some_and(|info| info.reason == reason.as_str_name())
54    }
55
56    pub fn with_details(mut self, details: ErrorDetails) -> Self {
57        self.details = Some(Box::new(details));
58        self
59    }
60
61    pub fn into_status_proto(self) -> crate::proto::google::rpc::Status {
62        crate::proto::google::rpc::Status {
63            code: self.code.into(),
64            message: self.message.unwrap_or_default(),
65            details: self
66                .details
67                .map(ErrorDetails::into_status_details)
68                .unwrap_or_default(),
69        }
70    }
71}
72
73impl std::fmt::Display for RpcError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match &self.message {
76            Some(m) => write!(f, "{}: {}", self.code, m),
77            None => write!(f, "{}", self.code),
78        }
79    }
80}
81
82impl std::error::Error for RpcError {}
83
84impl From<RpcError> for tonic::Status {
85    fn from(value: RpcError) -> Self {
86        use prost::Message;
87
88        let code = value.code;
89        let status = value.into_status_proto();
90        let details = status.encode_to_vec().into();
91        let message = status.message;
92
93        tonic::Status::with_details(code, message, details)
94    }
95}
96
97impl From<sui_types::storage::error::Error> for RpcError {
98    fn from(value: sui_types::storage::error::Error) -> Self {
99        use sui_types::storage::error::Kind;
100
101        let code = match value.kind() {
102            Kind::Missing => Code::NotFound,
103            _ => Code::Internal,
104        };
105
106        Self {
107            code,
108            message: Some(value.to_string()),
109            details: None,
110        }
111    }
112}
113
114impl From<anyhow::Error> for RpcError {
115    fn from(value: anyhow::Error) -> Self {
116        Self {
117            code: Code::Internal,
118            message: Some(value.to_string()),
119            details: None,
120        }
121    }
122}
123
124impl From<sui_types::sui_sdk_types_conversions::SdkTypeConversionError> for RpcError {
125    fn from(value: sui_types::sui_sdk_types_conversions::SdkTypeConversionError) -> Self {
126        Self {
127            code: Code::Internal,
128            message: Some(value.to_string()),
129            details: None,
130        }
131    }
132}
133
134impl From<bcs::Error> for RpcError {
135    fn from(value: bcs::Error) -> Self {
136        Self {
137            code: Code::Internal,
138            message: Some(value.to_string()),
139            details: None,
140        }
141    }
142}
143
144impl From<sui_types::transaction_driver_types::TransactionSubmissionError> for RpcError {
145    fn from(error: sui_types::transaction_driver_types::TransactionSubmissionError) -> Self {
146        use itertools::Itertools;
147        use sui_types::error::SuiErrorKind;
148        use sui_types::transaction_driver_types::TransactionSubmissionError::*;
149
150        match error {
151            InvalidUserSignature(err) => {
152                let message = {
153                    let err = match err.as_inner() {
154                        SuiErrorKind::UserInputError { error } => error.to_string(),
155                        _ => err.to_string(),
156                    };
157                    format!("Invalid user signature: {err}")
158                };
159
160                RpcError::new(Code::InvalidArgument, message)
161            }
162            TransactionDriverInternalError(err) => RpcError::new(Code::Internal, err.to_string()),
163            ObjectsDoubleUsed { conflicting_txes } => {
164                let new_map = conflicting_txes
165                    .into_iter()
166                    .map(|(digest, (pairs, _))| {
167                        (
168                            digest,
169                            pairs.into_iter().map(|(_, obj_ref)| obj_ref).collect(),
170                        )
171                    })
172                    .collect::<std::collections::BTreeMap<_, Vec<_>>>();
173
174                let message = format!(
175                    "Failed to sign transaction by a quorum of validators because of locked objects. Conflicting Transactions:\n{new_map:#?}",
176                );
177
178                RpcError::new(Code::FailedPrecondition, message)
179            }
180            TimeoutBeforeFinality | FailedWithTransientErrorAfterMaximumAttempts { .. } => {
181                // TODO add a Retry-After header
182                RpcError::new(
183                    Code::Unavailable,
184                    "timed-out before finality could be reached",
185                )
186            }
187            TimeoutBeforeFinalityWithErrors {
188                last_error,
189                attempts,
190                timeout,
191            } => {
192                // TODO add a Retry-After header
193                RpcError::new(
194                    Code::Unavailable,
195                    format!(
196                        "Transaction timed out before finality could be reached. Attempts: {attempts} & timeout: {timeout:?}. Last error: {last_error}"
197                    ),
198                )
199            }
200            NonRecoverableTransactionError { errors } => {
201                let new_errors: Vec<String> = errors
202                    .into_iter()
203                    // sort by total stake, descending, so users see the most prominent one first
204                    .sorted_by(|(_, a, _), (_, b, _)| b.cmp(a))
205                    .filter_map(|(err, _, _)| {
206                        match err.as_inner() {
207                            // Special handling of UserInputError:
208                            // ObjectNotFound and DependentPackageNotFound are considered
209                            // retryable errors but they have different treatment
210                            // in AuthorityAggregator.
211                            // The optimal fix would be to examine if the total stake
212                            // of ObjectNotFound/DependentPackageNotFound exceeds the
213                            // quorum threshold, but it takes a Committee here.
214                            // So, we take an easier route and consider them non-retryable
215                            // at all. Combining this with the sorting above, clients will
216                            // see the dominant error first.
217                            SuiErrorKind::UserInputError { error } => Some(error.to_string()),
218                            _ => {
219                                if err.is_retryable().0 {
220                                    None
221                                } else {
222                                    Some(err.to_string())
223                                }
224                            }
225                        }
226                    })
227                    .collect();
228
229                assert!(
230                    !new_errors.is_empty(),
231                    "NonRecoverableTransactionError should have at least one non-retryable error"
232                );
233
234                let error_list = new_errors.join(", ");
235                let error_msg = format!(
236                    "Transaction execution failed due to issues with transaction inputs, please review the errors and try again: {}.",
237                    error_list
238                );
239
240                RpcError::new(Code::InvalidArgument, error_msg)
241            }
242            TxAlreadyFinalizedWithDifferentUserSignatures => RpcError::new(
243                Code::Aborted,
244                "The transaction is already finalized but with different user signatures",
245            ),
246            SystemOverload { .. } | SystemOverloadRetryAfter { .. } => {
247                // TODO add a Retry-After header
248                RpcError::new(Code::Unavailable, "system is overloaded")
249            }
250            TransactionFailed { category, details } => RpcError::new(
251                // TODO(fastpath): add a Retry-After header.
252                match category {
253                    ErrorCategory::Internal => Code::Internal,
254                    ErrorCategory::Aborted => Code::Aborted,
255                    ErrorCategory::InvalidTransaction => Code::InvalidArgument,
256                    ErrorCategory::LockConflict => Code::FailedPrecondition,
257                    ErrorCategory::ValidatorOverloaded => Code::ResourceExhausted,
258                    ErrorCategory::Unavailable => Code::Unavailable,
259                },
260                details,
261            ),
262        }
263    }
264}
265
266impl From<crate::proto::google::rpc::bad_request::FieldViolation> for RpcError {
267    fn from(value: crate::proto::google::rpc::bad_request::FieldViolation) -> Self {
268        BadRequest::from(value).into()
269    }
270}
271
272impl From<BadRequest> for RpcError {
273    fn from(value: BadRequest) -> Self {
274        let message = value
275            .field_violations
276            .first()
277            .map(|violation| violation.description.clone());
278        let details = ErrorDetails::new().with_bad_request(value);
279
280        RpcError {
281            code: Code::InvalidArgument,
282            message,
283            details: Some(Box::new(details)),
284        }
285    }
286}
287
288#[derive(Clone, Debug, Default)]
289pub struct ErrorDetails {
290    error_info: Option<ErrorInfo>,
291    bad_request: Option<BadRequest>,
292    retry_info: Option<RetryInfo>,
293    execution_error: Option<ExecutionError>,
294}
295
296impl ErrorDetails {
297    pub fn new() -> Self {
298        Self::default()
299    }
300
301    pub fn error_info(&self) -> Option<&ErrorInfo> {
302        self.error_info.as_ref()
303    }
304
305    pub fn bad_request(&self) -> Option<&BadRequest> {
306        self.bad_request.as_ref()
307    }
308
309    pub fn retry_info(&self) -> Option<&RetryInfo> {
310        self.retry_info.as_ref()
311    }
312
313    pub fn execution_error(&self) -> Option<&ExecutionError> {
314        self.execution_error.as_ref()
315    }
316
317    pub fn details(&self) -> &[prost_types::Any] {
318        &[]
319    }
320
321    pub fn with_error_info(mut self, error_info: ErrorInfo) -> Self {
322        self.error_info = Some(error_info);
323        self
324    }
325
326    pub fn with_bad_request(mut self, bad_request: BadRequest) -> Self {
327        self.bad_request = Some(bad_request);
328        self
329    }
330
331    pub fn with_execution_error(mut self, execution_error: ExecutionError) -> Self {
332        self.execution_error = Some(execution_error);
333        self
334    }
335
336    #[allow(clippy::boxed_local)]
337    fn into_status_details(self: Box<Self>) -> Vec<prost_types::Any> {
338        let mut details = Vec::new();
339
340        if let Some(error_info) = &self.error_info {
341            details.push(
342                prost_types::Any::from_msg(error_info).expect("Message encoding cannot fail"),
343            );
344        }
345
346        if let Some(bad_request) = &self.bad_request {
347            details.push(
348                prost_types::Any::from_msg(bad_request).expect("Message encoding cannot fail"),
349            );
350        }
351
352        if let Some(retry_info) = &self.retry_info {
353            details.push(
354                prost_types::Any::from_msg(retry_info).expect("Message encoding cannot fail"),
355            );
356        }
357
358        if let Some(execution_error) = &self.execution_error {
359            details.push(
360                prost_types::Any::from_msg(execution_error).expect("Message encoding cannot fail"),
361            );
362        }
363        details
364    }
365}
366
367#[derive(Debug)]
368pub struct ObjectNotFoundError {
369    object_id: sui_sdk_types::Address,
370    version: Option<sui_sdk_types::Version>,
371    max_version: Option<sui_sdk_types::Version>,
372    checkpoint: Option<sui_sdk_types::CheckpointSequenceNumber>,
373    removal: Option<ObjectRemoval>,
374}
375
376/// The deletion or wrap a read resolved to: the object is not found because the version the read
377/// selected removed it from the live set. Servers describe a removal only when they find it (see
378/// [`ObjectNotFoundError::removed`]). The removing transaction is not part of it:
379/// `ListObjectVersions` lists it when the request's `removal_read_mask` names `transaction`.
380#[derive(Clone, Copy, Debug, PartialEq, Eq)]
381pub struct ObjectRemoval {
382    /// The version at which the object was deleted or wrapped.
383    pub version: sui_sdk_types::Version,
384    pub kind: ObjectRemovalKind,
385}
386
387impl ObjectNotFoundError {
388    pub fn new(object_id: sui_sdk_types::Address) -> Self {
389        Self {
390            object_id,
391            version: None,
392            max_version: None,
393            checkpoint: None,
394            removal: None,
395        }
396    }
397
398    pub fn new_with_version(
399        object_id: sui_sdk_types::Address,
400        version: sui_sdk_types::Version,
401    ) -> Self {
402        Self {
403            version: Some(version),
404            ..Self::new(object_id)
405        }
406    }
407
408    /// The object had no version at or below `max_version`, or was deleted or wrapped at the
409    /// newest one.
410    pub fn new_with_max_version(
411        object_id: sui_sdk_types::Address,
412        max_version: sui_sdk_types::Version,
413    ) -> Self {
414        Self {
415            max_version: Some(max_version),
416            ..Self::new(object_id)
417        }
418    }
419
420    /// Bound the read by `checkpoint`: the object had no live state at the end of `checkpoint`,
421    /// or the exact version was not found or was written after `checkpoint`, or the newest
422    /// version at or below `max_version` was written after `checkpoint`, deleted or wrapped the
423    /// object, or does not exist.
424    pub fn at_checkpoint(self, checkpoint: sui_sdk_types::CheckpointSequenceNumber) -> Self {
425        Self {
426            checkpoint: Some(checkpoint),
427            ..self
428        }
429    }
430
431    /// The read resolved to `removal`. The error keeps code `NotFound` and carries an
432    /// `OBJECT_REMOVED` [`ErrorInfo`] describing the removal.
433    ///
434    /// The detail is best effort: a server attaches it only when it finds the removal, so a
435    /// `NotFound` without it does not prove that the object never existed. A fullnode that has
436    /// pruned the removal's tombstone, or whose tombstone lookup refuses it as possibly below the
437    /// object lower bound, or a store that keeps no tombstones, answers a read that resolves to a
438    /// removal without it: with a plain `NotFound`, or, for an exact `version` or `max_version`
439    /// read on a fullnode that has pruned object versions, with `OUT_OF_RANGE` /
440    /// `BELOW_EARLIEST_AVAILABLE`, since the version may have been pruned. A fullnode that fails
441    /// to read the tombstone also answers without it, except for a `max_version` read without
442    /// `at_checkpoint`: that read selects its version with tombstones, so the failure fails the
443    /// read.
444    pub fn removed(self, removal: ObjectRemoval) -> Self {
445        Self {
446            removal: Some(removal),
447            ..self
448        }
449    }
450}
451
452impl std::fmt::Display for ObjectNotFoundError {
453    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454        write!(f, "Object {}", self.object_id)?;
455
456        if let Some(version) = self.version {
457            write!(f, " with version {version}")?;
458        }
459
460        if let Some(max_version) = self.max_version {
461            write!(f, " with version at most {max_version}")?;
462        }
463
464        if let Some(checkpoint) = self.checkpoint {
465            write!(f, " at checkpoint {checkpoint}")?;
466        }
467
468        write!(f, " not found")
469    }
470}
471
472impl std::error::Error for ObjectNotFoundError {}
473
474impl From<ObjectNotFoundError> for crate::RpcError {
475    fn from(value: ObjectNotFoundError) -> Self {
476        let message = value.to_string();
477        let Some(removal) = value.removal else {
478            return Self::new(tonic::Code::NotFound, message);
479        };
480        let kind = object_removal::Kind::from(removal.kind).as_str_name();
481        let metadata = [
482            ("removedVersion", removal.version.to_string()),
483            ("removalKind", kind.to_owned()),
484        ]
485        .into_iter()
486        .map(|(key, value)| (key.to_owned(), value))
487        .collect();
488        let error_info = ErrorInfo::default()
489            .with_reason(ErrorReason::ObjectRemoved.as_str_name())
490            .with_domain(ErrorReason::DOMAIN)
491            .with_metadata(metadata);
492        Self {
493            code: Code::NotFound,
494            message: Some(message),
495            details: Some(Box::new(ErrorDetails::new().with_error_info(error_info))),
496        }
497    }
498}
499
500#[derive(Debug)]
501pub struct CheckpointNotFoundError {
502    sequence_number: Option<u64>,
503    digest: Option<sui_sdk_types::Digest>,
504}
505
506impl CheckpointNotFoundError {
507    pub fn sequence_number(sequence_number: u64) -> Self {
508        Self {
509            sequence_number: Some(sequence_number),
510            digest: None,
511        }
512    }
513
514    pub fn digest(digest: sui_sdk_types::Digest) -> Self {
515        Self {
516            sequence_number: None,
517            digest: Some(digest),
518        }
519    }
520}
521
522impl std::fmt::Display for CheckpointNotFoundError {
523    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
524        write!(f, "Checkpoint ")?;
525
526        if let Some(s) = self.sequence_number {
527            write!(f, "{s} ")?;
528        }
529
530        if let Some(d) = &self.digest {
531            write!(f, "{d} ")?;
532        }
533
534        write!(f, "not found")
535    }
536}
537
538impl std::error::Error for CheckpointNotFoundError {}
539
540impl From<CheckpointNotFoundError> for crate::RpcError {
541    fn from(value: CheckpointNotFoundError) -> Self {
542        Self::new(tonic::Code::NotFound, value.to_string())
543    }
544}
545
546#[derive(Debug)]
547pub struct EpochNotFoundError {
548    epoch: sui_sdk_types::EpochId,
549}
550
551impl EpochNotFoundError {
552    pub fn new(epoch: sui_sdk_types::EpochId) -> Self {
553        Self { epoch }
554    }
555}
556
557impl std::fmt::Display for EpochNotFoundError {
558    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559        write!(f, "Epoch {} not found", self.epoch)
560    }
561}
562
563impl std::error::Error for EpochNotFoundError {}
564
565impl From<EpochNotFoundError> for crate::RpcError {
566    fn from(value: EpochNotFoundError) -> Self {
567        Self::new(tonic::Code::NotFound, value.to_string())
568    }
569}
570
571/// Gas selection could not find enough SUI to cover the transaction's gas budget.
572#[derive(Debug)]
573pub struct InsufficientGasBalanceError {
574    owner: sui_types::base_types::SuiAddress,
575    required_budget: u64,
576    coin_balance: u64,
577    address_balance: u64,
578}
579
580impl InsufficientGasBalanceError {
581    pub fn new(
582        owner: sui_types::base_types::SuiAddress,
583        required_budget: u64,
584        coin_balance: u64,
585        address_balance: u64,
586    ) -> Self {
587        Self {
588            owner,
589            required_budget,
590            coin_balance,
591            address_balance,
592        }
593    }
594}
595
596impl std::fmt::Display for InsufficientGasBalanceError {
597    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
598        write!(
599            f,
600            "Unable to perform gas selection due to insufficient SUI \
601            balance (in address balance or coins) for account {} \
602            to satisfy required budget {}.",
603            self.owner, self.required_budget,
604        )
605    }
606}
607
608impl std::error::Error for InsufficientGasBalanceError {}
609
610impl From<InsufficientGasBalanceError> for crate::RpcError {
611    fn from(value: InsufficientGasBalanceError) -> Self {
612        let metadata = [
613            ("owner", value.owner.to_string()),
614            ("requiredBudget", value.required_budget.to_string()),
615            ("coinBalance", value.coin_balance.to_string()),
616            ("addressBalance", value.address_balance.to_string()),
617        ]
618        .into_iter()
619        .map(|(key, metadata_value)| (key.to_owned(), metadata_value))
620        .collect();
621        let error_info = ErrorInfo::default()
622            .with_reason(ErrorReason::InsufficientGasBalance.as_str_name())
623            .with_domain(ErrorReason::DOMAIN)
624            .with_metadata(metadata);
625        let details = ErrorDetails::new().with_error_info(error_info);
626
627        Self {
628            code: Code::InvalidArgument,
629            message: Some(value.to_string()),
630            details: Some(Box::new(details)),
631        }
632    }
633}