sui_json_rpc/
error.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::authority_state::StateReadError;
5use fastcrypto::error::FastCryptoError;
6use hyper::header::InvalidHeaderValue;
7use itertools::Itertools;
8use jsonrpsee::core::ClientError as RpcError;
9use jsonrpsee::types::error::INTERNAL_ERROR_CODE;
10use jsonrpsee::types::{ErrorObject, ErrorObjectOwned};
11use std::collections::BTreeMap;
12use sui_json_rpc_api::{TRANSACTION_EXECUTION_CLIENT_ERROR_CODE, TRANSIENT_ERROR_CODE};
13use sui_name_service::NameServiceError;
14use sui_types::committee::{QUORUM_THRESHOLD, TOTAL_VOTING_POWER};
15use sui_types::error::{
16    ErrorCategory, SuiError, SuiErrorKind, SuiObjectResponseError, UserInputError,
17};
18use sui_types::transaction_driver_types::TransactionSubmissionError;
19use thiserror::Error;
20use tokio::task::JoinError;
21
22pub type RpcInterimResult<T = ()> = Result<T, Error>;
23
24#[derive(Debug, Error)]
25pub enum Error {
26    #[error(transparent)]
27    SuiError(SuiError),
28
29    #[error(transparent)]
30    InternalError(#[from] anyhow::Error),
31
32    #[error("Deserialization error: {0}")]
33    BcsError(#[from] bcs::Error),
34    #[error("Unexpected error: {0}")]
35    UnexpectedError(String),
36
37    #[error(transparent)]
38    RPCServerError(#[from] jsonrpsee::core::ClientError),
39
40    #[error(transparent)]
41    RPCError(#[from] jsonrpsee::types::ErrorObjectOwned),
42
43    #[error(transparent)]
44    RegisterMethodError(#[from] jsonrpsee::server::RegisterMethodError),
45
46    #[error(transparent)]
47    InvalidHeaderValue(#[from] InvalidHeaderValue),
48
49    #[error(transparent)]
50    UserInputError(#[from] UserInputError),
51
52    #[error(transparent)]
53    EncodingError(#[from] eyre::Report),
54
55    #[error(transparent)]
56    TokioJoinError(#[from] JoinError),
57
58    #[error(transparent)]
59    TransactionSubmissionError(#[from] TransactionSubmissionError),
60
61    #[error(transparent)]
62    FastCryptoError(#[from] FastCryptoError),
63
64    #[error(transparent)]
65    SuiObjectResponseError(#[from] SuiObjectResponseError),
66
67    #[error(transparent)]
68    SuiRpcInputError(#[from] SuiRpcInputError),
69
70    // TODO(wlmyng): convert StateReadError::Internal message to generic internal error message.
71    #[error(transparent)]
72    StateReadError(#[from] StateReadError),
73
74    #[error("Unsupported Feature: {0}")]
75    UnsupportedFeature(String),
76
77    #[error("transparent")]
78    NameServiceError(#[from] NameServiceError),
79}
80
81impl From<SuiErrorKind> for Error {
82    fn from(e: SuiErrorKind) -> Self {
83        match e {
84            SuiErrorKind::UserInputError { error } => Self::UserInputError(error),
85            SuiErrorKind::SuiObjectResponseError { error } => Self::SuiObjectResponseError(error),
86            SuiErrorKind::UnsupportedFeatureError { error } => Self::UnsupportedFeature(error),
87            SuiErrorKind::IndexStoreNotAvailable => Self::UnsupportedFeature(
88                "Required indexes are not available on this node".to_string(),
89            ),
90            other => Self::SuiError(SuiError(Box::new(other))),
91        }
92    }
93}
94
95impl From<SuiError> for Error {
96    fn from(e: SuiError) -> Self {
97        e.into_inner().into()
98    }
99}
100
101fn invalid_params<E: std::fmt::Display>(e: E) -> ErrorObjectOwned {
102    ErrorObject::owned(
103        jsonrpsee::types::error::ErrorCode::InvalidParams.code(),
104        e.to_string(),
105        None::<()>,
106    )
107}
108
109fn failed<E: std::fmt::Display>(e: E) -> ErrorObjectOwned {
110    ErrorObject::owned(
111        jsonrpsee::types::error::CALL_EXECUTION_FAILED_CODE,
112        e.to_string(),
113        None::<()>,
114    )
115}
116
117impl From<Error> for ErrorObjectOwned {
118    /// `InvalidParams`/`INVALID_PARAMS_CODE` for client errors.
119    fn from(e: Error) -> ErrorObjectOwned {
120        match e {
121            Error::UserInputError(_) => invalid_params(e),
122            Error::UnsupportedFeature(_) => invalid_params(e),
123            Error::SuiObjectResponseError(err) => match err {
124                SuiObjectResponseError::NotExists { .. }
125                | SuiObjectResponseError::DynamicFieldNotFound { .. }
126                | SuiObjectResponseError::Deleted { .. }
127                | SuiObjectResponseError::DisplayError { .. } => invalid_params(err),
128                _ => failed(err),
129            },
130            Error::NameServiceError(err) => match err {
131                NameServiceError::ExceedsMaxLength { .. }
132                | NameServiceError::InvalidHyphens
133                | NameServiceError::InvalidLength { .. }
134                | NameServiceError::InvalidUnderscore
135                | NameServiceError::LabelsEmpty
136                | NameServiceError::InvalidSeparator => invalid_params(err),
137                _ => failed(err),
138            },
139            Error::SuiRpcInputError(err) => invalid_params(err),
140            Error::SuiError(sui_error) => match sui_error.as_inner() {
141                SuiErrorKind::TransactionNotFound { .. }
142                | SuiErrorKind::TransactionsNotFound { .. }
143                | SuiErrorKind::TransactionEventsNotFound { .. } => invalid_params(sui_error),
144                _ => failed(sui_error),
145            },
146            Error::StateReadError(err) => match err {
147                StateReadError::Client(_) => invalid_params(err),
148                _ => ErrorObject::owned(
149                    jsonrpsee::types::error::INTERNAL_ERROR_CODE,
150                    err.to_string(),
151                    None::<()>,
152                ),
153            },
154            Error::TransactionSubmissionError(err) => {
155                match err {
156                    TransactionSubmissionError::InvalidUserSignature(err) => ErrorObject::owned(
157                        TRANSACTION_EXECUTION_CLIENT_ERROR_CODE,
158                        format!("Invalid user signature: {err}"),
159                        None::<()>,
160                    ),
161                    TransactionSubmissionError::TxAlreadyFinalizedWithDifferentUserSignatures => {
162                        ErrorObject::owned(
163                            TRANSACTION_EXECUTION_CLIENT_ERROR_CODE,
164                            "The transaction is already finalized but with different user signatures",
165                            None::<()>,
166                        )
167                    }
168                    TransactionSubmissionError::TimeoutBeforeFinality
169                    | TransactionSubmissionError::TimeoutBeforeFinalityWithErrors { .. }
170                    | TransactionSubmissionError::FailedWithTransientErrorAfterMaximumAttempts {
171                        ..
172                    } => ErrorObject::owned(TRANSIENT_ERROR_CODE, err.to_string(), None::<()>),
173                    TransactionSubmissionError::ObjectsDoubleUsed { conflicting_txes } => {
174                        let weights: Vec<u64> =
175                            conflicting_txes.values().map(|(_, stake)| *stake).collect();
176                        let remaining: u64 = TOTAL_VOTING_POWER - weights.iter().sum::<u64>();
177
178                        // better version of above
179                        let reason = if weights.iter().all(|w| remaining + w < QUORUM_THRESHOLD) {
180                            "equivocated until the next epoch"
181                        } else {
182                            "reserved for another transaction"
183                        };
184
185                        let error_message = format!(
186                            "Failed to sign transaction by a quorum of validators because one or more of its objects is {reason}. Other transactions locking these objects:\n{}",
187                            conflicting_txes
188                                .iter()
189                                .sorted_by(|(_, (_, a)), (_, (_, b))| b.cmp(a))
190                                .map(|(digest, (o, stake))| {
191                                    let objects = o
192                                        .iter()
193                                        .map(|(_, obj_ref)| format!("    - {}", obj_ref.0))
194                                        .join("\n");
195
196                                    format!(
197                                        "- {} (stake {}.{})\n{}",
198                                        digest,
199                                        stake / 100,
200                                        stake % 100,
201                                        objects,
202                                    )
203                                })
204                                .join("\n"),
205                        );
206
207                        let new_map = conflicting_txes
208                            .into_iter()
209                            .map(|(digest, (pairs, _))| {
210                                (
211                                    digest,
212                                    pairs.into_iter().map(|(_, obj_ref)| obj_ref).collect(),
213                                )
214                            })
215                            .collect::<BTreeMap<_, Vec<_>>>();
216
217                        ErrorObject::owned(
218                            TRANSACTION_EXECUTION_CLIENT_ERROR_CODE,
219                            error_message,
220                            Some(new_map),
221                        )
222                    }
223                    TransactionSubmissionError::NonRecoverableTransactionError { errors } => {
224                        let new_errors: Vec<String> = errors
225                            .into_iter()
226                            // sort by total stake, descending, so users see the most prominent one first
227                            .sorted_by(|(_, a, _), (_, b, _)| b.cmp(a))
228                            .filter_map(|(err, _, _)| {
229                                match err.as_inner() {
230                                    // Special handling of UserInputError:
231                                    // ObjectNotFound and DependentPackageNotFound are considered
232                                    // retryable errors but they have different treatment
233                                    // in AuthorityAggregator.
234                                    // The optimal fix would be to examine if the total stake
235                                    // of ObjectNotFound/DependentPackageNotFound exceeds the
236                                    // quorum threshold, but it takes a Committee here.
237                                    // So, we take an easier route and consider them non-retryable
238                                    // at all. Combining this with the sorting above, clients will
239                                    // see the dominant error first.
240                                    SuiErrorKind::UserInputError { error } => {
241                                        Some(error.to_string())
242                                    }
243                                    _ => {
244                                        if err.is_retryable().0 {
245                                            None
246                                        } else {
247                                            Some(err.to_string())
248                                        }
249                                    }
250                                }
251                            })
252                            .collect();
253
254                        assert!(
255                            !new_errors.is_empty(),
256                            "NonRecoverableTransactionError should have at least one non-retryable error"
257                        );
258
259                        let mut error_list = vec![];
260
261                        for err in new_errors.iter() {
262                            error_list.push(format!("- {}", err));
263                        }
264
265                        let error_msg = format!(
266                            "Transaction validator signing failed due to issues with transaction inputs, please review the errors and try again:\n{}",
267                            error_list.join("\n")
268                        );
269
270                        ErrorObject::owned(
271                            TRANSACTION_EXECUTION_CLIENT_ERROR_CODE,
272                            error_msg,
273                            None::<()>,
274                        )
275                    }
276                    TransactionSubmissionError::TransactionDriverInternalError(_) => {
277                        ErrorObject::owned(
278                            INTERNAL_ERROR_CODE,
279                            "Internal error occurred while executing transaction.",
280                            None::<()>,
281                        )
282                    }
283                    TransactionSubmissionError::SystemOverload { .. }
284                    | TransactionSubmissionError::SystemOverloadRetryAfter { .. } => {
285                        ErrorObject::owned(TRANSIENT_ERROR_CODE, err.to_string(), None::<()>)
286                    }
287                    TransactionSubmissionError::TransactionFailed { category, details } => {
288                        let code = match category {
289                            ErrorCategory::Internal => INTERNAL_ERROR_CODE,
290                            ErrorCategory::Aborted => TRANSIENT_ERROR_CODE,
291                            ErrorCategory::InvalidTransaction => {
292                                TRANSACTION_EXECUTION_CLIENT_ERROR_CODE
293                            }
294                            ErrorCategory::LockConflict => TRANSACTION_EXECUTION_CLIENT_ERROR_CODE,
295                            ErrorCategory::ValidatorOverloaded => TRANSIENT_ERROR_CODE,
296                            ErrorCategory::Unavailable => INTERNAL_ERROR_CODE,
297                        };
298                        ErrorObject::owned(code, details, None::<()>)
299                    }
300                }
301            }
302            _ => failed(e),
303        }
304    }
305}
306
307#[derive(Debug, Error)]
308pub enum SuiRpcInputError {
309    #[error("Input contains duplicates")]
310    ContainsDuplicates,
311
312    #[error("Input exceeds limit of {0}")]
313    SizeLimitExceeded(String),
314
315    #[error("{0}")]
316    GenericNotFound(String),
317
318    #[error("{0}")]
319    GenericInvalid(String),
320
321    #[error(
322        "request_type` must set to `None` or `WaitForLocalExecution` if effects is required in the response"
323    )]
324    InvalidExecuteTransactionRequestType,
325
326    #[error("Unsupported protocol version requested. Min supported: {0}, max supported: {1}")]
327    ProtocolVersionUnsupported(u64, u64),
328
329    #[error("{0}")]
330    CannotParseSuiStructTag(String),
331
332    #[error(transparent)]
333    Base64(#[from] eyre::Report),
334
335    #[error("Deserialization error: {0}")]
336    Bcs(#[from] bcs::Error),
337
338    #[error(transparent)]
339    FastCryptoError(#[from] FastCryptoError),
340
341    #[error(transparent)]
342    Anyhow(#[from] anyhow::Error),
343
344    #[error(transparent)]
345    UserInputError(#[from] UserInputError),
346}
347
348impl From<SuiRpcInputError> for RpcError {
349    fn from(e: SuiRpcInputError) -> Self {
350        RpcError::Call(invalid_params(e))
351    }
352}
353
354impl From<SuiRpcInputError> for ErrorObjectOwned {
355    fn from(e: SuiRpcInputError) -> Self {
356        invalid_params(e)
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use expect_test::expect;
364    use jsonrpsee::types::ErrorObjectOwned;
365    use sui_types::base_types::AuthorityName;
366    use sui_types::base_types::ObjectID;
367    use sui_types::base_types::ObjectRef;
368    use sui_types::base_types::SequenceNumber;
369    use sui_types::committee::StakeUnit;
370    use sui_types::crypto::AuthorityPublicKey;
371    use sui_types::crypto::AuthorityPublicKeyBytes;
372    use sui_types::digests::ObjectDigest;
373    use sui_types::digests::TransactionDigest;
374
375    fn test_object_ref(id: u8) -> ObjectRef {
376        (
377            ObjectID::from_single_byte(id),
378            SequenceNumber::from_u64(0),
379            ObjectDigest::new([id; 32]),
380        )
381    }
382
383    mod match_transaction_submission_error_tests {
384        use sui_types::error::SuiErrorKind;
385
386        use super::*;
387
388        #[test]
389        fn test_invalid_user_signature() {
390            let transaction_driver_error = TransactionSubmissionError::InvalidUserSignature(
391                SuiErrorKind::InvalidSignature {
392                    error: "Test inner invalid signature".to_string(),
393                }
394                .into(),
395            );
396
397            let error_object: ErrorObjectOwned =
398                Error::TransactionSubmissionError(transaction_driver_error).into();
399            let expected_code = expect!["-32002"];
400            expected_code.assert_eq(&error_object.code().to_string());
401            let expected_message = expect![
402                "Invalid user signature: Signature is not valid: Test inner invalid signature"
403            ];
404            expected_message.assert_eq(error_object.message());
405        }
406
407        #[test]
408        fn test_timeout_before_finality() {
409            let transaction_driver_error = TransactionSubmissionError::TimeoutBeforeFinality;
410
411            let error_object: ErrorObjectOwned =
412                Error::TransactionSubmissionError(transaction_driver_error).into();
413            let expected_code = expect!["-32050"];
414            expected_code.assert_eq(&error_object.code().to_string());
415            let expected_message = expect!["Transaction timed out before reaching finality"];
416            expected_message.assert_eq(error_object.message());
417        }
418
419        #[test]
420        fn test_failed_with_transient_error_after_maximum_attempts() {
421            let transaction_driver_error =
422                TransactionSubmissionError::FailedWithTransientErrorAfterMaximumAttempts {
423                    total_attempts: 10,
424                };
425
426            let error_object: ErrorObjectOwned =
427                Error::TransactionSubmissionError(transaction_driver_error).into();
428            let expected_code = expect!["-32050"];
429            expected_code.assert_eq(&error_object.code().to_string());
430            let expected_message = expect![
431                "Transaction failed to reach finality with transient error after 10 attempts."
432            ];
433            expected_message.assert_eq(error_object.message());
434        }
435
436        #[test]
437        fn test_objects_double_used() {
438            use sui_types::crypto::VerifyingKey;
439            let mut conflicting_txes: BTreeMap<
440                TransactionDigest,
441                (Vec<(AuthorityName, ObjectRef)>, StakeUnit),
442            > = BTreeMap::new();
443            let tx_digest = TransactionDigest::from([1; 32]);
444            let object_ref = test_object_ref(0);
445
446            // 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi has enough stake to escape equivocation
447            let stake_unit: StakeUnit = 8000;
448            let authority_name = AuthorityPublicKeyBytes([0; AuthorityPublicKey::LENGTH]);
449            conflicting_txes.insert(tx_digest, (vec![(authority_name, object_ref)], stake_unit));
450
451            // 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR stake below quorum threshold
452            let tx_digest = TransactionDigest::from([2; 32]);
453            let stake_unit: StakeUnit = 500;
454            let authority_name = AuthorityPublicKeyBytes([1; AuthorityPublicKey::LENGTH]);
455            conflicting_txes.insert(tx_digest, (vec![(authority_name, object_ref)], stake_unit));
456
457            let quorum_driver_error =
458                TransactionSubmissionError::ObjectsDoubleUsed { conflicting_txes };
459
460            let error_object: ErrorObjectOwned =
461                Error::TransactionSubmissionError(quorum_driver_error).into();
462            let expected_code = expect!["-32002"];
463            expected_code.assert_eq(&error_object.code().to_string());
464            println!("error_object.message() {}", error_object.message());
465            let expected_message = expect![[r#"
466                Failed to sign transaction by a quorum of validators because one or more of its objects is reserved for another transaction. Other transactions locking these objects:
467                - 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi (stake 80.0)
468                    - 0x0000000000000000000000000000000000000000000000000000000000000000
469                - 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR (stake 5.0)
470                    - 0x0000000000000000000000000000000000000000000000000000000000000000"#]];
471            expected_message.assert_eq(error_object.message());
472            let expected_data = expect![[
473                r#"{"4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi":[["0x0000000000000000000000000000000000000000000000000000000000000000",0,"11111111111111111111111111111111"]],"8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR":[["0x0000000000000000000000000000000000000000000000000000000000000000",0,"11111111111111111111111111111111"]]}"#
474            ]];
475            let actual_data = error_object.data().unwrap().to_string();
476            expected_data.assert_eq(&actual_data);
477        }
478
479        #[test]
480        fn test_objects_double_used_equivocated() {
481            use sui_types::crypto::VerifyingKey;
482            let mut conflicting_txes: BTreeMap<
483                TransactionDigest,
484                (Vec<(AuthorityName, ObjectRef)>, StakeUnit),
485            > = BTreeMap::new();
486            let tx_digest = TransactionDigest::from([1; 32]);
487            let object_ref_1 = test_object_ref(0);
488            let object_ref_2 = test_object_ref(1);
489
490            // 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi has lower stake at 10
491            let stake_unit: StakeUnit = 4000;
492            let authority_name = AuthorityPublicKeyBytes([0; AuthorityPublicKey::LENGTH]);
493            conflicting_txes.insert(
494                tx_digest,
495                (
496                    vec![
497                        (authority_name, object_ref_1),
498                        (authority_name, object_ref_2),
499                    ],
500                    stake_unit,
501                ),
502            );
503
504            // 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR is a higher stake and should be first in the list
505            let tx_digest = TransactionDigest::from([2; 32]);
506            let stake_unit: StakeUnit = 5000;
507            let authority_name = AuthorityPublicKeyBytes([1; AuthorityPublicKey::LENGTH]);
508            conflicting_txes.insert(
509                tx_digest,
510                (
511                    vec![
512                        (authority_name, object_ref_1),
513                        (authority_name, object_ref_2),
514                    ],
515                    stake_unit,
516                ),
517            );
518
519            let quorum_driver_error =
520                TransactionSubmissionError::ObjectsDoubleUsed { conflicting_txes };
521
522            let error_object: ErrorObjectOwned =
523                Error::TransactionSubmissionError(quorum_driver_error).into();
524            let expected_code = expect!["-32002"];
525            expected_code.assert_eq(&error_object.code().to_string());
526            let expected_message = expect![[r#"
527                Failed to sign transaction by a quorum of validators because one or more of its objects is equivocated until the next epoch. Other transactions locking these objects:
528                - 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR (stake 50.0)
529                    - 0x0000000000000000000000000000000000000000000000000000000000000000
530                    - 0x0000000000000000000000000000000000000000000000000000000000000001
531                - 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi (stake 40.0)
532                    - 0x0000000000000000000000000000000000000000000000000000000000000000
533                    - 0x0000000000000000000000000000000000000000000000000000000000000001"#]];
534            expected_message.assert_eq(error_object.message());
535            let expected_data = expect![[
536                r#"{"4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi":[["0x0000000000000000000000000000000000000000000000000000000000000000",0,"11111111111111111111111111111111"],["0x0000000000000000000000000000000000000000000000000000000000000001",0,"4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi"]],"8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR":[["0x0000000000000000000000000000000000000000000000000000000000000000",0,"11111111111111111111111111111111"],["0x0000000000000000000000000000000000000000000000000000000000000001",0,"4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi"]]}"#
537            ]];
538            let actual_data = error_object.data().unwrap().to_string();
539            expected_data.assert_eq(&actual_data);
540        }
541
542        #[test]
543        fn test_non_recoverable_transaction_error() {
544            let quorum_driver_error = TransactionSubmissionError::NonRecoverableTransactionError {
545                errors: vec![
546                    (
547                        SuiErrorKind::UserInputError {
548                            error: UserInputError::GasBalanceTooLow {
549                                gas_balance: 10,
550                                needed_gas_amount: 100,
551                            },
552                        }
553                        .into(),
554                        0,
555                        vec![],
556                    ),
557                    (
558                        SuiErrorKind::UserInputError {
559                            error: UserInputError::ObjectVersionUnavailableForConsumption {
560                                provided_obj_ref: test_object_ref(0),
561                                current_version: 10.into(),
562                            },
563                        }
564                        .into(),
565                        0,
566                        vec![],
567                    ),
568                ],
569            };
570
571            let error_object: ErrorObjectOwned =
572                Error::TransactionSubmissionError(quorum_driver_error).into();
573            let expected_code = expect!["-32002"];
574            expected_code.assert_eq(&error_object.code().to_string());
575            let expected_message = expect![
576                "Transaction validator signing failed due to issues with transaction inputs, please review the errors and try again:\n- Balance of gas object 10 is lower than the needed amount: 100\n- Object ID 0x0000000000000000000000000000000000000000000000000000000000000000 Version 0x0 Digest 11111111111111111111111111111111 is not available for consumption, current version: 0xa"
577            ];
578            expected_message.assert_eq(error_object.message());
579        }
580
581        #[test]
582        fn test_non_recoverable_transaction_error_with_transient_errors() {
583            let quorum_driver_error = TransactionSubmissionError::NonRecoverableTransactionError {
584                errors: vec![
585                    (
586                        SuiErrorKind::UserInputError {
587                            error: UserInputError::ObjectNotFound {
588                                object_id: test_object_ref(0).0,
589                                version: None,
590                            },
591                        }
592                        .into(),
593                        0,
594                        vec![],
595                    ),
596                    (
597                        SuiErrorKind::RpcError("Hello".to_string(), "Testing".to_string()).into(),
598                        0,
599                        vec![],
600                    ),
601                ],
602            };
603
604            let error_object: ErrorObjectOwned =
605                Error::TransactionSubmissionError(quorum_driver_error).into();
606            let expected_code = expect!["-32002"];
607            expected_code.assert_eq(&error_object.code().to_string());
608            let expected_message = expect![
609                "Transaction validator signing failed due to issues with transaction inputs, please review the errors and try again:\n- Could not find the referenced object 0x0000000000000000000000000000000000000000000000000000000000000000 at version None"
610            ];
611            expected_message.assert_eq(error_object.message());
612        }
613
614        #[test]
615        fn test_transaction_driver_internal_error() {
616            let quorum_driver_error = TransactionSubmissionError::TransactionDriverInternalError(
617                SuiErrorKind::UnexpectedMessage("test".to_string()).into(),
618            );
619
620            let error_object: ErrorObjectOwned =
621                Error::TransactionSubmissionError(quorum_driver_error).into();
622            let expected_code = expect!["-32603"];
623            expected_code.assert_eq(&error_object.code().to_string());
624            let expected_message = expect!["Internal error occurred while executing transaction."];
625            expected_message.assert_eq(error_object.message());
626        }
627
628        #[test]
629        fn test_system_overload() {
630            let quorum_driver_error = TransactionSubmissionError::SystemOverload {
631                overloaded_stake: 10,
632                errors: vec![(
633                    SuiErrorKind::UnexpectedMessage("test".to_string()).into(),
634                    0,
635                    vec![],
636                )],
637            };
638
639            let error_object: ErrorObjectOwned =
640                Error::TransactionSubmissionError(quorum_driver_error).into();
641            let expected_code = expect!["-32050"];
642            expected_code.assert_eq(&error_object.code().to_string());
643            let expected_message = expect![
644                "Transaction is not processed because 10 of validators by stake are overloaded with certificates pending execution."
645            ];
646            expected_message.assert_eq(error_object.message());
647        }
648    }
649}