Skip to main content

sui_types/
error.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5use crate::{
6    base_types::*,
7    committee::{Committee, EpochId, StakeUnit},
8    digests::CheckpointContentsDigest,
9    execution_status::{CommandArgumentError, CommandIndex, ExecutionErrorKind, ExecutionFailure},
10    messages_checkpoint::CheckpointSequenceNumber,
11    object::Owner,
12};
13
14use schemars::JsonSchema;
15use serde::{Deserialize, Serialize};
16use std::{collections::BTreeMap, fmt::Debug, slice::SliceIndex};
17use strum_macros::{AsRefStr, IntoStaticStr};
18use thiserror::Error;
19use tonic::Status;
20use typed_store_error::TypedStoreError;
21
22pub const TRANSACTION_NOT_FOUND_MSG_PREFIX: &str = "Could not find the referenced transaction";
23pub const TRANSACTIONS_NOT_FOUND_MSG_PREFIX: &str = "Could not find the referenced transactions";
24
25#[macro_export]
26macro_rules! fp_bail {
27    ($e:expr) => {
28        return Err($e)
29    };
30}
31
32#[macro_export(local_inner_macros)]
33macro_rules! fp_ensure {
34    ($cond:expr, $e:expr) => {
35        if !($cond) {
36            fp_bail!($e);
37        }
38    };
39}
40
41#[macro_export]
42macro_rules! exit_main {
43    ($result:expr) => {
44        match $result {
45            Ok(_) => (),
46            Err(err) => {
47                let err = format!("{:?}", err);
48                println!("{}", err.bold().red());
49                std::process::exit(1);
50            }
51        }
52    };
53}
54
55#[macro_export]
56macro_rules! make_invariant_violation {
57    ($($args:expr),* $(,)?) => {{
58        if cfg!(debug_assertions) {
59            panic!($($args),*)
60        }
61        $crate::error::ExecutionError::invariant_violation(format!($($args),*))
62    }}
63}
64
65#[macro_export]
66macro_rules! invariant_violation {
67    ($($args:expr),* $(,)?) => {
68        return Err(make_invariant_violation!($($args),*).into())
69    };
70}
71
72#[macro_export]
73macro_rules! assert_invariant {
74    ($cond:expr, $($args:expr),* $(,)?) => {{
75        if !$cond {
76            invariant_violation!($($args),*)
77        }
78    }};
79}
80
81/// A helper macro for performing a checked cast from one type to another, returning a
82/// ExecutionError invariant violation if the cast fails.
83#[macro_export]
84macro_rules! checked_as {
85    ($value:expr, $target_type:ty) => {{
86        let v = $value;
87        <$target_type>::try_from(v).map_err(|e| {
88            $crate::make_invariant_violation!(
89                "Value {} cannot be safely cast to {}: {:?}",
90                v,
91                stringify!($target_type),
92                e
93            )
94        })
95    }};
96}
97
98/// A trait for safe indexing into collections that returns a ExecutionError as long as the
99/// collection implements `AsRef<[T]>`.
100/// This is useful for avoiding panics on out-of-bounds access, and instead returning a proper
101/// error.
102pub trait SafeIndex<T> {
103    /// Get a reference to the element at the given `index`, or return invariant violation error
104    /// if the index is out of bounds.
105    fn safe_get<'a, I>(&'a self, index: I) -> Result<&'a I::Output, ExecutionError>
106    where
107        I: SliceIndex<[T]>,
108        T: 'a;
109
110    /// Get a mutable reference to the element at the given `index`, or return invariant violation
111    /// error if the index is out of bounds.
112    fn safe_get_mut<'a, I>(&'a mut self, index: I) -> Result<&'a mut I::Output, ExecutionError>
113    where
114        I: SliceIndex<[T]>,
115        T: 'a;
116}
117
118impl<T, C> SafeIndex<T> for C
119where
120    C: AsRef<[T]> + AsMut<[T]>,
121{
122    fn safe_get<'a, I>(&'a self, index: I) -> Result<&'a I::Output, ExecutionError>
123    where
124        I: SliceIndex<[T]>,
125        T: 'a,
126    {
127        let slice = self.as_ref();
128        let len = slice.len();
129        slice.get(index).ok_or_else(|| {
130            crate::make_invariant_violation!("Index out of bounds for collection of length {}", len)
131        })
132    }
133
134    fn safe_get_mut<'a, I>(&'a mut self, index: I) -> Result<&'a mut I::Output, ExecutionError>
135    where
136        I: SliceIndex<[T]>,
137        T: 'a,
138    {
139        let slice = self.as_mut();
140        let len = slice.len();
141        slice.get_mut(index).ok_or_else(|| {
142            crate::make_invariant_violation!("Index out of bounds for collection of length {}", len)
143        })
144    }
145}
146
147#[derive(
148    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
149)]
150pub enum UserInputError {
151    #[error("Mutable object {object_id} cannot appear more than one in one transaction")]
152    MutableObjectUsedMoreThanOnce { object_id: ObjectID },
153    #[error("Wrong number of parameters for the transaction")]
154    ObjectInputArityViolation,
155    #[error(
156        "Could not find the referenced object {} at version {:?}",
157        object_id,
158        version
159    )]
160    ObjectNotFound {
161        object_id: ObjectID,
162        version: Option<SequenceNumber>,
163    },
164    #[error(
165        "Transaction needs to be rebuilt because object {} version {} ({}) is unavailable for consumption, current version: {current_version}",
166        .provided_obj_ref.0, .provided_obj_ref.1, .provided_obj_ref.2
167    )]
168    ObjectVersionUnavailableForConsumption {
169        provided_obj_ref: ObjectRef,
170        current_version: SequenceNumber,
171    },
172    #[error("Package verification failed: {err}")]
173    PackageVerificationTimeout { err: String },
174    #[error("Dependent package not found on-chain: {package_id}")]
175    DependentPackageNotFound { package_id: ObjectID },
176    #[error("Mutable parameter provided, immutable parameter expected")]
177    ImmutableParameterExpectedError { object_id: ObjectID },
178    #[error("Size limit exceeded: {limit} is {value}")]
179    SizeLimitExceeded { limit: String, value: String },
180    #[error(
181        "Object {child_id} is owned by object {parent_id}. \
182        Objects owned by other objects cannot be used as input arguments"
183    )]
184    InvalidChildObjectArgument {
185        child_id: ObjectID,
186        parent_id: ObjectID,
187    },
188    #[error("Invalid Object digest for object {object_id}. Expected digest : {expected_digest}")]
189    InvalidObjectDigest {
190        object_id: ObjectID,
191        expected_digest: ObjectDigest,
192    },
193    #[error("Sequence numbers above the maximal value are not usable for transfers")]
194    InvalidSequenceNumber,
195    #[error("A move object is expected, instead a move package is passed: {object_id}")]
196    MovePackageAsObject { object_id: ObjectID },
197    #[error("A move package is expected, instead a move object is passed: {object_id}")]
198    MoveObjectAsPackage { object_id: ObjectID },
199    #[error("Transaction was not signed by the correct sender: {}", error)]
200    IncorrectUserSignature { error: String },
201
202    #[error("Object used as shared is not shared")]
203    NotSharedObjectError,
204    #[error("The transaction inputs contain duplicated ObjectRef's")]
205    DuplicateObjectRefInput,
206
207    // Gas related errors
208    #[error("Transaction gas payment missing")]
209    MissingGasPayment,
210    #[error("Gas object is not an owned object with owner: {:?}", owner)]
211    GasObjectNotOwnedObject { owner: Owner },
212    #[error("Gas budget: {gas_budget} is higher than max: {max_budget}")]
213    GasBudgetTooHigh { gas_budget: u64, max_budget: u64 },
214    #[error("Gas budget: {gas_budget} is lower than min: {min_budget}")]
215    GasBudgetTooLow { gas_budget: u64, min_budget: u64 },
216    #[error(
217        "Balance of gas object {gas_balance} is lower than the needed amount: {needed_gas_amount}"
218    )]
219    GasBalanceTooLow {
220        gas_balance: u128,
221        needed_gas_amount: u128,
222    },
223    #[error("Transaction kind does not support Sponsored Transaction")]
224    UnsupportedSponsoredTransactionKind,
225    #[error("Gas price {gas_price} under reference gas price (RGP) {reference_gas_price}")]
226    GasPriceUnderRGP {
227        gas_price: u64,
228        reference_gas_price: u64,
229    },
230    #[error("Gas price cannot exceed {max_gas_price} mist")]
231    GasPriceTooHigh { max_gas_price: u64 },
232    #[error("Object {object_id} is not a gas object")]
233    InvalidGasObject { object_id: ObjectID },
234    #[error("Gas object does not have enough balance to cover minimal gas spend")]
235    InsufficientBalanceToCoverMinimalGas,
236
237    #[error(
238        "Could not find the referenced object {object_id} as the asked version {asked_version:?} is higher than the latest {latest_version:?}"
239    )]
240    ObjectSequenceNumberTooHigh {
241        object_id: ObjectID,
242        asked_version: SequenceNumber,
243        latest_version: SequenceNumber,
244    },
245    #[error("Object deleted at reference ({}, {:?}, {})", object_ref.0, object_ref.1, object_ref.2)]
246    ObjectDeleted { object_ref: ObjectRef },
247    #[error("Invalid Batch Transaction: {error}")]
248    InvalidBatchTransaction { error: String },
249    #[error("This Move function is currently disabled and not available for call")]
250    BlockedMoveFunction,
251    #[error("Empty input coins for Pay related transaction")]
252    EmptyInputCoins,
253
254    #[error(
255        "SUI payment transactions use first input coin for gas payment, but found a different gas object"
256    )]
257    UnexpectedGasPaymentObject,
258
259    #[error("Wrong initial version given for shared object")]
260    SharedObjectStartingVersionMismatch,
261
262    #[error(
263        "Attempt to transfer object {object_id} that does not have public transfer. Object transfer must be done instead using a distinct Move function call"
264    )]
265    TransferObjectWithoutPublicTransferError { object_id: ObjectID },
266
267    #[error(
268        "TransferObjects, MergeCoin, and Publish cannot have empty arguments. \
269        If MakeMoveVec has empty arguments, it must have a type specified"
270    )]
271    EmptyCommandInput,
272
273    #[error("Transaction is denied: {error}")]
274    TransactionDenied { error: String },
275
276    #[error("Feature is not supported: {0}")]
277    Unsupported(String),
278
279    #[error("Query transactions with move function input error: {0}")]
280    MoveFunctionInputError(String),
281
282    #[error("Verified checkpoint not found for sequence number: {0}")]
283    VerifiedCheckpointNotFound(CheckpointSequenceNumber),
284
285    #[error("Verified checkpoint not found for digest: {0}")]
286    VerifiedCheckpointDigestNotFound(String),
287
288    #[error("Latest checkpoint sequence number not found")]
289    LatestCheckpointSequenceNumberNotFound,
290
291    #[error("Checkpoint contents not found for digest: {0}")]
292    CheckpointContentsNotFound(CheckpointContentsDigest),
293
294    #[error("Genesis transaction not found")]
295    GenesisTransactionNotFound,
296
297    #[error("Transaction {0} not found")]
298    TransactionCursorNotFound(u64),
299
300    #[error(
301        "Object {} is a system object and cannot be accessed by user transactions",
302        object_id
303    )]
304    InaccessibleSystemObject { object_id: ObjectID },
305    #[error(
306        "{max_publish_commands} max publish/upgrade commands allowed, {publish_count} provided"
307    )]
308    MaxPublishCountExceeded {
309        max_publish_commands: u64,
310        publish_count: u64,
311    },
312
313    #[error("Immutable parameter provided, mutable parameter expected")]
314    MutableParameterExpected { object_id: ObjectID },
315
316    #[error("Address {address} is denied for coin {coin_type}")]
317    AddressDeniedForCoin {
318        address: SuiAddress,
319        coin_type: String,
320    },
321
322    #[error("Commands following a command with Random can only be TransferObjects or MergeCoins")]
323    PostRandomCommandRestrictions,
324
325    // Soft Bundle related errors
326    #[error("Number of transactions ({size}) exceeds the maximum allowed ({limit}) in a batch")]
327    TooManyTransactionsInBatch { size: usize, limit: u64 },
328    #[error(
329        "Total transactions size ({size}) bytes exceeds the maximum allowed ({limit}) bytes in a Soft Bundle"
330    )]
331    TotalTransactionSizeTooLargeInBatch { size: usize, limit: u64 },
332    #[error("Transaction {digest} in Soft Bundle contains no shared objects")]
333    NoSharedObjectError { digest: TransactionDigest },
334    #[error("Transaction {digest} in Soft Bundle has already been executed")]
335    AlreadyExecutedInSoftBundleError { digest: TransactionDigest },
336    #[error("At least one certificate in Soft Bundle has already been processed")]
337    CertificateAlreadyProcessed,
338    #[error("Transaction {digest} was already executed")]
339    TransactionAlreadyExecuted { digest: TransactionDigest },
340    #[error(
341        "Gas price for transaction {digest} in Soft Bundle mismatch: want {expected}, have {actual}"
342    )]
343    GasPriceMismatchError {
344        digest: TransactionDigest,
345        expected: u64,
346        actual: u64,
347    },
348
349    #[error("Coin type is globally paused for use: {coin_type}")]
350    CoinTypeGlobalPause { coin_type: String },
351
352    #[error("Invalid identifier found in the transaction: {error}")]
353    InvalidIdentifier { error: String },
354
355    #[error("Object used as owned is not owned")]
356    NotOwnedObjectError,
357
358    #[error("Invalid withdraw reservation: {error}")]
359    InvalidWithdrawReservation { error: String },
360
361    #[error("Transaction with empty gas payment must specify an expiration.")]
362    MissingTransactionExpiration,
363
364    #[error("Invalid transaction expiration: {error}")]
365    InvalidExpiration { error: String },
366
367    #[error("Transaction chain ID {provided} does not match network chain ID {expected}.")]
368    InvalidChainId { provided: String, expected: String },
369
370    #[error("Transaction {digest} appears more than once in the request")]
371    RepeatedTransactions { digest: TransactionDigest },
372}
373
374#[derive(
375    Eq,
376    PartialEq,
377    Clone,
378    Debug,
379    Serialize,
380    Deserialize,
381    Hash,
382    AsRefStr,
383    IntoStaticStr,
384    JsonSchema,
385    Error,
386)]
387#[serde(tag = "code", rename = "ObjectResponseError", rename_all = "camelCase")]
388pub enum SuiObjectResponseError {
389    #[error("Object {object_id} does not exist")]
390    NotExists { object_id: ObjectID },
391    #[error("Cannot find dynamic field for parent object {parent_object_id}")]
392    DynamicFieldNotFound { parent_object_id: ObjectID },
393    #[error(
394        "Object has been deleted object_id: {object_id} at version: {version:?} in digest {digest}"
395    )]
396    Deleted {
397        object_id: ObjectID,
398        /// Object version.
399        version: SequenceNumber,
400        /// Base64 string representing the object digest
401        digest: ObjectDigest,
402    },
403    #[error("Unknown Error")]
404    Unknown,
405    #[error("Display Error: {error}")]
406    DisplayError { error: String },
407    // TODO: also integrate SuiPastObjectResponse (VersionNotFound,  VersionTooHigh)
408}
409
410/// Custom error type for Sui.
411#[derive(Eq, PartialEq, Clone, Serialize, Deserialize, Error, Hash)]
412#[error(transparent)]
413pub struct SuiError(#[from] pub Box<SuiErrorKind>);
414
415/// Custom error type for Sui.
416#[derive(
417    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
418)]
419pub enum SuiErrorKind {
420    #[error("Error checking transaction input objects: {error}")]
421    UserInputError { error: UserInputError },
422
423    #[error("Error checking transaction object: {error}")]
424    SuiObjectResponseError { error: SuiObjectResponseError },
425
426    #[error("Expecting a single owner, shared ownership found")]
427    UnexpectedOwnerType,
428
429    #[error("There are already {queue_len} transactions pending, above threshold of {threshold}")]
430    TooManyTransactionsPendingExecution { queue_len: usize, threshold: usize },
431
432    #[error("There are too many transactions pending in consensus")]
433    TooManyTransactionsPendingConsensus,
434
435    #[error(
436        "Input {object_id} already has {queue_len} transactions pending, above threshold of {threshold}"
437    )]
438    TooManyTransactionsPendingOnObject {
439        object_id: ObjectID,
440        queue_len: usize,
441        threshold: usize,
442    },
443
444    #[error(
445        "Input {object_id} has a transaction {txn_age_sec} seconds old pending, above threshold of {threshold} seconds"
446    )]
447    TooOldTransactionPendingOnObject {
448        object_id: ObjectID,
449        txn_age_sec: u64,
450        threshold: u64,
451    },
452
453    #[error("Soft bundle must only contain transactions of UserTransaction kind")]
454    InvalidTxKindInSoftBundle,
455
456    // Signature verification
457    #[error("Signature is not valid: {}", error)]
458    InvalidSignature { error: String },
459    #[error("Required Signature from {expected} is absent {:?}", actual)]
460    SignerSignatureAbsent {
461        expected: String,
462        actual: Vec<String>,
463    },
464    #[error("Expect {expected} signer signatures but got {actual}")]
465    SignerSignatureNumberMismatch { expected: usize, actual: usize },
466    #[error("Value was not signed by the correct sender: {}", error)]
467    IncorrectSigner { error: String },
468    #[error(
469        "Value was not signed by a known authority. signer: {:?}, index: {:?}, committee: {committee}",
470        signer,
471        index
472    )]
473    UnknownSigner {
474        signer: Option<String>,
475        index: Option<u32>,
476        committee: Box<Committee>,
477    },
478    #[error(
479        "Validator {:?} responded multiple signatures for the same message, conflicting: {:?}",
480        signer,
481        conflicting_sig
482    )]
483    StakeAggregatorRepeatedSigner {
484        signer: AuthorityName,
485        conflicting_sig: bool,
486    },
487    // TODO: Used for distinguishing between different occurrences of invalid signatures, to allow retries in some cases.
488    #[error(
489        "Signature is not valid, but a retry may result in a valid one: {}",
490        error
491    )]
492    PotentiallyTemporarilyInvalidSignature { error: String },
493
494    // Certificate verification and execution
495    #[error(
496        "Signature or certificate from wrong epoch, expected {expected_epoch}, got {actual_epoch}"
497    )]
498    WrongEpoch {
499        expected_epoch: EpochId,
500        actual_epoch: EpochId,
501    },
502    #[error("Signatures in a certificate must form a quorum")]
503    CertificateRequiresQuorum,
504    #[allow(non_camel_case_types)]
505    #[error("DEPRECATED")]
506    DEPRECATED_ErrorWhileProcessingCertificate,
507    #[error(
508        "Failed to get a quorum of signed effects when processing transaction: {effects_map:?}"
509    )]
510    QuorumFailedToGetEffectsQuorumWhenProcessingTransaction {
511        effects_map: BTreeMap<TransactionEffectsDigest, (Vec<AuthorityName>, StakeUnit)>,
512    },
513    #[error(
514        "Failed to verify Tx certificate with executed effects, error: {error:?}, validator: {validator_name:?}"
515    )]
516    FailedToVerifyTxCertWithExecutedEffects {
517        validator_name: AuthorityName,
518        error: String,
519    },
520    #[error("Transaction is already finalized but with different user signatures")]
521    TxAlreadyFinalizedWithDifferentUserSigs,
522
523    // Account access
524    #[error("Invalid authenticator")]
525    InvalidAuthenticator,
526    #[error("Invalid address")]
527    InvalidAddress,
528    #[error("Invalid transaction digest.")]
529    InvalidTransactionDigest,
530
531    #[error("Invalid digest length. Expected {expected}, got {actual}")]
532    InvalidDigestLength { expected: usize, actual: usize },
533    #[error("Invalid DKG message size")]
534    InvalidDkgMessageSize,
535
536    #[error("Unexpected message: {0}")]
537    UnexpectedMessage(String),
538
539    // Move module publishing related errors
540    #[error("Failed to verify the Move module, reason: {error}.")]
541    ModuleVerificationFailure { error: String },
542    #[error("Failed to deserialize the Move module, reason: {error}.")]
543    ModuleDeserializationFailure { error: String },
544    #[error("Failed to publish the Move module(s), reason: {error}")]
545    ModulePublishFailure { error: String },
546    #[error("Failed to build Move modules: {error}.")]
547    ModuleBuildFailure { error: String },
548
549    // Move call related errors
550    #[error("Function resolution failure: {error}.")]
551    FunctionNotFound { error: String },
552    #[error("Module not found in package: {module_name}.")]
553    ModuleNotFound { module_name: String },
554    #[error("Type error while binding function arguments: {error}.")]
555    TypeError { error: String },
556    #[error("Circular object ownership detected")]
557    CircularObjectOwnership,
558
559    // Internal state errors
560    #[error("Attempt to re-initialize a transaction lock for objects {:?}.", refs)]
561    ObjectLockAlreadyInitialized { refs: Vec<ObjectRef> },
562    #[error(
563        "Object {obj_ref:?} already locked by a different transaction: {pending_transaction:?}"
564    )]
565    ObjectLockConflict {
566        obj_ref: ObjectRef,
567        pending_transaction: TransactionDigest,
568    },
569    #[error(
570        "Objects {obj_refs:?} are already locked by a transaction from a future epoch {locked_epoch:?}), attempt to override with a transaction from epoch {new_epoch:?}"
571    )]
572    ObjectLockedAtFutureEpoch {
573        obj_refs: Vec<ObjectRef>,
574        locked_epoch: EpochId,
575        new_epoch: EpochId,
576        locked_by_tx: TransactionDigest,
577    },
578    #[error("{TRANSACTION_NOT_FOUND_MSG_PREFIX} [{:?}].", digest)]
579    TransactionNotFound { digest: TransactionDigest },
580    #[error("{TRANSACTIONS_NOT_FOUND_MSG_PREFIX} [{:?}].", digests)]
581    TransactionsNotFound { digests: Vec<TransactionDigest> },
582    #[error("Could not find the referenced transaction events [{digest:?}].")]
583    TransactionEventsNotFound { digest: TransactionDigest },
584    #[error("Could not find the referenced transaction effects [{digest:?}].")]
585    TransactionEffectsNotFound { digest: TransactionDigest },
586    #[error(
587        "Attempt to move to `Executed` state an transaction that has already been executed: {:?}.",
588        digest
589    )]
590    TransactionAlreadyExecuted { digest: TransactionDigest },
591    #[error("Transaction reject reason not found for transaction {digest:?}")]
592    TransactionRejectReasonNotFound { digest: TransactionDigest },
593    #[error("Object ID did not have the expected type")]
594    BadObjectType { error: String },
595    #[error("Fail to retrieve Object layout for {st}")]
596    FailObjectLayout { st: String },
597
598    #[error("Execution invariant violated")]
599    ExecutionInvariantViolation,
600    #[error("Validator {authority:?} is faulty in a Byzantine manner: {reason:?}")]
601    ByzantineAuthoritySuspicion {
602        authority: AuthorityName,
603        reason: String,
604    },
605    #[allow(non_camel_case_types)]
606    #[serde(rename = "StorageError")]
607    #[error("DEPRECATED")]
608    DEPRECATED_StorageError,
609    #[allow(non_camel_case_types)]
610    #[serde(rename = "GenericStorageError")]
611    #[error("DEPRECATED")]
612    DEPRECATED_GenericStorageError,
613    #[error(
614        "Attempted to access {object} through parent {given_parent}, \
615        but it's actual parent is {actual_owner}"
616    )]
617    InvalidChildObjectAccess {
618        object: ObjectID,
619        given_parent: ObjectID,
620        actual_owner: Owner,
621    },
622
623    #[allow(non_camel_case_types)]
624    #[serde(rename = "StorageMissingFieldError")]
625    #[error("DEPRECATED")]
626    DEPRECATED_StorageMissingFieldError,
627    #[allow(non_camel_case_types)]
628    #[serde(rename = "StorageCorruptedFieldError")]
629    #[error("DEPRECATED")]
630    DEPRECATED_StorageCorruptedFieldError,
631
632    #[error("Authority Error: {error}")]
633    GenericAuthorityError { error: String },
634
635    #[error("Generic Bridge Error: {error}")]
636    GenericBridgeError { error: String },
637
638    #[error("Failed to dispatch subscription: {error}")]
639    FailedToDispatchSubscription { error: String },
640
641    #[error("Failed to serialize Owner: {error}")]
642    OwnerFailedToSerialize { error: String },
643
644    #[error("Failed to deserialize fields into JSON: {error}")]
645    ExtraFieldFailedToDeserialize { error: String },
646
647    #[error("Failed to execute transaction locally by Orchestrator: {error}")]
648    TransactionOrchestratorLocalExecutionError { error: String },
649
650    // Errors returned by authority and client read API's
651    #[error("Failure serializing transaction in the requested format: {error}")]
652    TransactionSerializationError { error: String },
653    #[error("Failure deserializing transaction from the provided format: {error}")]
654    TransactionDeserializationError { error: String },
655    #[error("Failure serializing transaction effects from the provided format: {error}")]
656    TransactionEffectsSerializationError { error: String },
657    #[error("Failure deserializing transaction effects from the provided format: {error}")]
658    TransactionEffectsDeserializationError { error: String },
659    #[error("Failure serializing transaction events from the provided format: {error}")]
660    TransactionEventsSerializationError { error: String },
661    #[error("Failure deserializing transaction events from the provided format: {error}")]
662    TransactionEventsDeserializationError { error: String },
663    #[error("Failure serializing object in the requested format: {error}")]
664    ObjectSerializationError { error: String },
665    #[error("Failure deserializing object in the requested format: {error}")]
666    ObjectDeserializationError { error: String },
667    #[error("Event store component is not active on this node")]
668    NoEventStore,
669
670    // Client side error
671    #[error("Too many authority errors were detected for {}: {:?}", action, errors)]
672    TooManyIncorrectAuthorities {
673        errors: Vec<(AuthorityName, SuiError)>,
674        action: String,
675    },
676    #[error("Invalid transaction range query to the fullnode: {error}")]
677    FullNodeInvalidTxRangeQuery { error: String },
678
679    // Errors related to the authority-consensus interface.
680    #[error("Failed to submit transaction to consensus: {0}")]
681    FailedToSubmitToConsensus(String),
682    #[error("Failed to connect with consensus node: {0}")]
683    ConsensusConnectionBroken(String),
684    #[error("Failed to execute handle_consensus_transaction on Sui: {0}")]
685    HandleConsensusTransactionFailure(String),
686
687    // Cryptography errors.
688    #[error("Signature key generation error: {0}")]
689    SignatureKeyGenError(String),
690    #[error("Key Conversion Error: {0}")]
691    KeyConversionError(String),
692    #[error("Invalid Private Key provided")]
693    InvalidPrivateKey,
694
695    // Unsupported Operations on Fullnode
696    #[error("Fullnode does not support handle_certificate")]
697    FullNodeCantHandleCertificate,
698
699    // Epoch related errors.
700    #[error("Validator temporarily stopped processing transactions due to epoch change")]
701    ValidatorHaltedAtEpochEnd,
702    #[error("Operations for epoch {0} have ended")]
703    EpochEnded(EpochId),
704    #[error("Error when advancing epoch: {error}")]
705    AdvanceEpochError { error: String },
706
707    #[error("Transaction Expired")]
708    TransactionExpired,
709
710    // These are errors that occur when an RPC fails and is simply the utf8 message sent in a
711    // Tonic::Status
712    #[error("{1} - {0}")]
713    RpcError(String, String),
714
715    #[error("Method not allowed")]
716    InvalidRpcMethodError,
717
718    #[error("Use of disabled feature: {error}")]
719    UnsupportedFeatureError { error: String },
720
721    #[error("Unable to communicate with the Quorum Driver channel: {error}")]
722    QuorumDriverCommunicationError { error: String },
723
724    #[error("Operation timed out")]
725    TimeoutError,
726
727    #[error("Error executing {0}")]
728    ExecutionError(String),
729
730    #[error("Invalid committee composition")]
731    InvalidCommittee(String),
732
733    #[error("Missing committee information for epoch {0}")]
734    MissingCommitteeAtEpoch(EpochId),
735
736    #[error("Index store not available on this Fullnode.")]
737    IndexStoreNotAvailable,
738
739    #[error("Failed to read dynamic field from table in the object store: {0}")]
740    DynamicFieldReadError(String),
741
742    #[error("Failed to read or deserialize system state related data structures on-chain: {0}")]
743    SuiSystemStateReadError(String),
744
745    #[error("Failed to read or deserialize bridge related data structures on-chain: {0}")]
746    SuiBridgeReadError(String),
747
748    #[error("Unexpected version error: {0}")]
749    UnexpectedVersion(String),
750
751    #[error("Message version is not supported at the current protocol version: {error}")]
752    WrongMessageVersion { error: String },
753
754    #[error("unknown error: {0}")]
755    Unknown(String),
756
757    #[error("Failed to perform file operation: {0}")]
758    FileIOError(String),
759
760    #[error("Failed to get JWK")]
761    JWKRetrievalError,
762
763    #[error("Storage error: {0}")]
764    Storage(String),
765
766    #[error(
767        "Validator cannot handle the request at the moment. Please retry after at least {retry_after_secs} seconds."
768    )]
769    ValidatorOverloadedRetryAfter { retry_after_secs: u64 },
770
771    #[error("Too many requests")]
772    TooManyRequests,
773
774    #[error("The request did not contain a certificate")]
775    NoCertificateProvidedError,
776
777    #[error("Nitro attestation verify failed: {0}")]
778    NitroAttestationFailedToVerify(String),
779
780    #[error("Failed to serialize {type_info}, error: {error}")]
781    GrpcMessageSerializeError { type_info: String, error: String },
782
783    #[error("Failed to deserialize {type_info}, error: {error}")]
784    GrpcMessageDeserializeError { type_info: String, error: String },
785
786    #[error(
787        "Validator consensus rounds are lagging behind. last committed leader round: {last_committed_round}, requested round: {round}"
788    )]
789    ValidatorConsensusLagging {
790        round: u32,
791        last_committed_round: u32,
792    },
793
794    #[error("Invalid admin request: {0}")]
795    InvalidAdminRequest(String),
796
797    #[error("Invalid request: {0}")]
798    InvalidRequest(String),
799
800    #[error(
801        "The current set of aliases for a required signer changed after the transaction was submitted"
802    )]
803    AliasesChanged,
804
805    // Retriable by client because another validator can create the correct claim.
806    #[error("Object {object_id} not found among input objects.")]
807    ImmutableObjectClaimNotFoundInInput { object_id: ObjectID },
808
809    // Retriable by client because another validator can create the correct claim.
810    #[error("Immutable object {object_id} was not included in immutable claims.")]
811    ImmutableObjectNotClaimed { object_id: ObjectID },
812
813    // Retriable by client because the object can be frozen in the future.
814    #[error(
815        "Claimed object {claimed_object_id} is not immutable. Found object ref: {found_object_ref:?}"
816    )]
817    InvalidImmutableObjectClaim {
818        claimed_object_id: ObjectID,
819        found_object_ref: ObjectRef,
820    },
821
822    #[error(
823        "Transaction was outbid by higher-gas-price transactions in the admission queue (current minimum gas price required: {min_gas_price})"
824    )]
825    TransactionRejectedDueToOutbiddingDuringCongestion { min_gas_price: u64 },
826
827    #[error("Transaction {digest} is being processed post-consensus: {status}")]
828    TransactionProcessing {
829        digest: TransactionDigest,
830        status: String,
831    },
832
833    #[error("Transaction {digest} has been recently submitted to this validator.")]
834    TransactionSubmitted { digest: TransactionDigest },
835}
836
837#[repr(u64)]
838#[allow(non_camel_case_types)]
839#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
840/// Sub-status codes for the `UNKNOWN_VERIFICATION_ERROR` VM Status Code which provides more context
841/// TODO: add more Vm Status errors. We use `UNKNOWN_VERIFICATION_ERROR` as a catchall for now.
842pub enum VMMVerifierErrorSubStatusCode {
843    MULTIPLE_RETURN_VALUES_NOT_ALLOWED = 0,
844    INVALID_OBJECT_CREATION = 1,
845}
846
847#[repr(u64)]
848#[allow(non_camel_case_types)]
849#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
850/// Sub-status codes for the `MEMORY_LIMIT_EXCEEDED` VM Status Code which provides more context
851pub enum VMMemoryLimitExceededSubStatusCode {
852    EVENT_COUNT_LIMIT_EXCEEDED = 0,
853    EVENT_SIZE_LIMIT_EXCEEDED = 1,
854    NEW_ID_COUNT_LIMIT_EXCEEDED = 2,
855    DELETED_ID_COUNT_LIMIT_EXCEEDED = 3,
856    TRANSFER_ID_COUNT_LIMIT_EXCEEDED = 4,
857    OBJECT_RUNTIME_CACHE_LIMIT_EXCEEDED = 5,
858    OBJECT_RUNTIME_STORE_LIMIT_EXCEEDED = 6,
859    TOTAL_EVENT_SIZE_LIMIT_EXCEEDED = 7,
860    SCRATCH_SIZE_LIMIT_EXCEEDED = 8,
861}
862
863pub type SuiResult<T = ()> = Result<T, SuiError>;
864pub type UserInputResult<T = ()> = Result<T, UserInputError>;
865
866impl From<SuiErrorKind> for SuiError {
867    fn from(error: SuiErrorKind) -> Self {
868        SuiError(Box::new(error))
869    }
870}
871
872impl std::ops::Deref for SuiError {
873    type Target = SuiErrorKind;
874
875    fn deref(&self) -> &Self::Target {
876        &self.0
877    }
878}
879
880impl From<sui_protocol_config::Error> for SuiError {
881    fn from(error: sui_protocol_config::Error) -> Self {
882        SuiErrorKind::WrongMessageVersion { error: error.0 }.into()
883    }
884}
885
886impl From<ExecutionError> for SuiError {
887    fn from(error: ExecutionError) -> Self {
888        SuiErrorKind::ExecutionError(error.to_string()).into()
889    }
890}
891
892impl From<Status> for SuiError {
893    fn from(status: Status) -> Self {
894        if status.message() == "Too many requests" {
895            return SuiErrorKind::TooManyRequests.into();
896        }
897
898        let result = bcs::from_bytes::<SuiError>(status.details());
899        if let Ok(sui_error) = result {
900            sui_error
901        } else {
902            SuiErrorKind::RpcError(
903                status.message().to_owned(),
904                status.code().description().to_owned(),
905            )
906            .into()
907        }
908    }
909}
910
911impl From<TypedStoreError> for SuiError {
912    fn from(e: TypedStoreError) -> Self {
913        SuiErrorKind::Storage(e.to_string()).into()
914    }
915}
916
917impl From<crate::storage::error::Error> for SuiError {
918    fn from(e: crate::storage::error::Error) -> Self {
919        SuiErrorKind::Storage(e.to_string()).into()
920    }
921}
922
923impl From<SuiErrorKind> for Status {
924    fn from(error: SuiErrorKind) -> Self {
925        let bytes = bcs::to_bytes(&error).unwrap();
926        Status::with_details(tonic::Code::Internal, error.to_string(), bytes.into())
927    }
928}
929
930impl From<SuiError> for Status {
931    fn from(error: SuiError) -> Self {
932        Status::from(error.into_inner())
933    }
934}
935
936impl From<ExecutionErrorKind> for SuiError {
937    fn from(kind: ExecutionErrorKind) -> Self {
938        ExecutionError::from_kind(kind).into()
939    }
940}
941
942impl From<&str> for SuiError {
943    fn from(error: &str) -> Self {
944        SuiErrorKind::GenericAuthorityError {
945            error: error.to_string(),
946        }
947        .into()
948    }
949}
950
951impl From<String> for SuiError {
952    fn from(error: String) -> Self {
953        SuiErrorKind::GenericAuthorityError { error }.into()
954    }
955}
956
957impl TryFrom<SuiErrorKind> for UserInputError {
958    type Error = anyhow::Error;
959
960    fn try_from(err: SuiErrorKind) -> Result<Self, Self::Error> {
961        match err {
962            SuiErrorKind::UserInputError { error } => Ok(error),
963            other => anyhow::bail!("error {:?} is not UserInputError", other),
964        }
965    }
966}
967
968impl TryFrom<SuiError> for UserInputError {
969    type Error = anyhow::Error;
970
971    fn try_from(err: SuiError) -> Result<Self, Self::Error> {
972        err.into_inner().try_into()
973    }
974}
975
976impl From<UserInputError> for SuiError {
977    fn from(error: UserInputError) -> Self {
978        SuiErrorKind::UserInputError { error }.into()
979    }
980}
981
982impl From<SuiObjectResponseError> for SuiError {
983    fn from(error: SuiObjectResponseError) -> Self {
984        SuiErrorKind::SuiObjectResponseError { error }.into()
985    }
986}
987
988impl PartialEq<SuiErrorKind> for SuiError {
989    fn eq(&self, other: &SuiErrorKind) -> bool {
990        &*self.0 == other
991    }
992}
993
994impl PartialEq<SuiError> for SuiErrorKind {
995    fn eq(&self, other: &SuiError) -> bool {
996        self == &*other.0
997    }
998}
999
1000impl SuiError {
1001    pub fn as_inner(&self) -> &SuiErrorKind {
1002        &self.0
1003    }
1004
1005    pub fn into_inner(self) -> SuiErrorKind {
1006        *self.0
1007    }
1008}
1009
1010impl SuiErrorKind {
1011    /// Returns the variant name of the error. Sub-variants within UserInputError are unpacked too.
1012    pub fn to_variant_name(&self) -> &'static str {
1013        match &self {
1014            SuiErrorKind::UserInputError { error } => error.into(),
1015            _ => self.into(),
1016        }
1017    }
1018
1019    pub fn individual_error_indicates_epoch_change(&self) -> bool {
1020        matches!(
1021            self,
1022            SuiErrorKind::ValidatorHaltedAtEpochEnd | SuiErrorKind::MissingCommitteeAtEpoch(_)
1023        )
1024    }
1025
1026    /// Returns if the error is retryable and if the error's retryability is
1027    /// explicitly categorized.
1028    /// There should be only a handful of retryable errors. For now we list common
1029    /// non-retryable error below to help us find more retryable errors in logs.
1030    pub fn is_retryable(&self) -> (bool, bool) {
1031        let retryable = match self {
1032            // Network error
1033            SuiErrorKind::RpcError { .. } => true,
1034
1035            // Reconfig error
1036            SuiErrorKind::ValidatorHaltedAtEpochEnd => true,
1037            SuiErrorKind::MissingCommitteeAtEpoch(..) => true,
1038            SuiErrorKind::WrongEpoch { .. } => true,
1039            SuiErrorKind::EpochEnded(..) => true,
1040
1041            SuiErrorKind::UserInputError { error } => {
1042                match error {
1043                    // Only ObjectNotFound and DependentPackageNotFound is potentially retryable
1044                    UserInputError::ObjectNotFound { .. } => true,
1045                    UserInputError::DependentPackageNotFound { .. } => true,
1046                    _ => false,
1047                }
1048            }
1049
1050            SuiErrorKind::PotentiallyTemporarilyInvalidSignature { .. } => true,
1051
1052            // Overload errors
1053            SuiErrorKind::TooManyTransactionsPendingExecution { .. } => true,
1054            SuiErrorKind::TooManyTransactionsPendingOnObject { .. } => true,
1055            SuiErrorKind::TooOldTransactionPendingOnObject { .. } => true,
1056            SuiErrorKind::TooManyTransactionsPendingConsensus => true,
1057            SuiErrorKind::TransactionRejectedDueToOutbiddingDuringCongestion { .. } => true,
1058            SuiErrorKind::ValidatorOverloadedRetryAfter { .. } => true,
1059
1060            // The transaction is already being processed by consensus, so a fresh
1061            // submission is pointless. The client should retry by waiting for effects
1062            // rather than resubmitting.
1063            SuiErrorKind::TransactionProcessing { .. } => true,
1064            SuiErrorKind::TransactionSubmitted { .. } => true,
1065
1066            // Non retryable error
1067            SuiErrorKind::ExecutionError(..) => false,
1068            SuiErrorKind::ByzantineAuthoritySuspicion { .. } => false,
1069            SuiErrorKind::QuorumFailedToGetEffectsQuorumWhenProcessingTransaction { .. } => false,
1070            SuiErrorKind::TxAlreadyFinalizedWithDifferentUserSigs => false,
1071            SuiErrorKind::FailedToVerifyTxCertWithExecutedEffects { .. } => false,
1072            SuiErrorKind::ObjectLockConflict { .. } => false,
1073
1074            // NB: This is not an internal overload, but instead an imposed rate
1075            // limit / blocking of a client. It must be non-retryable otherwise
1076            // we will make the threat worse through automatic retries.
1077            SuiErrorKind::TooManyRequests => false,
1078
1079            // For all un-categorized errors, return here with categorized = false.
1080            _ => return (false, false),
1081        };
1082
1083        (retryable, true)
1084    }
1085
1086    pub fn is_object_or_package_not_found(&self) -> bool {
1087        match self {
1088            SuiErrorKind::UserInputError { error } => {
1089                matches!(
1090                    error,
1091                    UserInputError::ObjectNotFound { .. }
1092                        | UserInputError::DependentPackageNotFound { .. }
1093                )
1094            }
1095            _ => false,
1096        }
1097    }
1098
1099    pub fn is_overload(&self) -> bool {
1100        matches!(
1101            self,
1102            SuiErrorKind::TooManyTransactionsPendingExecution { .. }
1103                | SuiErrorKind::TooManyTransactionsPendingOnObject { .. }
1104                | SuiErrorKind::TooOldTransactionPendingOnObject { .. }
1105                | SuiErrorKind::TooManyTransactionsPendingConsensus
1106                | SuiErrorKind::TransactionRejectedDueToOutbiddingDuringCongestion { .. }
1107        )
1108    }
1109
1110    pub fn is_retryable_overload(&self) -> bool {
1111        matches!(self, SuiErrorKind::ValidatorOverloadedRetryAfter { .. })
1112    }
1113
1114    pub fn retry_after_secs(&self) -> u64 {
1115        match self {
1116            SuiErrorKind::ValidatorOverloadedRetryAfter { retry_after_secs } => *retry_after_secs,
1117            _ => 0,
1118        }
1119    }
1120
1121    /// Categorizes SuiError into ErrorCategory.
1122    pub fn categorize(&self) -> ErrorCategory {
1123        match self {
1124            SuiErrorKind::UserInputError { error } => {
1125                match error {
1126                    // ObjectNotFound and DependentPackageNotFound are potentially valid because the missing
1127                    // input can be created by other transactions.
1128                    UserInputError::ObjectNotFound { .. } => ErrorCategory::Aborted,
1129                    UserInputError::DependentPackageNotFound { .. } => ErrorCategory::Aborted,
1130                    // Other UserInputError variants indeed indicate invalid transaction.
1131                    _ => ErrorCategory::InvalidTransaction,
1132                }
1133            }
1134
1135            SuiErrorKind::InvalidSignature { .. }
1136            | SuiErrorKind::SignerSignatureAbsent { .. }
1137            | SuiErrorKind::SignerSignatureNumberMismatch { .. }
1138            | SuiErrorKind::IncorrectSigner { .. }
1139            | SuiErrorKind::UnknownSigner { .. }
1140            | SuiErrorKind::TransactionExpired => ErrorCategory::InvalidTransaction,
1141
1142            SuiErrorKind::ObjectLockConflict { .. } => ErrorCategory::LockConflict,
1143
1144            SuiErrorKind::Unknown { .. }
1145            | SuiErrorKind::GrpcMessageSerializeError { .. }
1146            | SuiErrorKind::GrpcMessageDeserializeError { .. }
1147            | SuiErrorKind::ByzantineAuthoritySuspicion { .. }
1148            | SuiErrorKind::InvalidTxKindInSoftBundle
1149            | SuiErrorKind::UnsupportedFeatureError { .. }
1150            | SuiErrorKind::InvalidRequest { .. } => ErrorCategory::Internal,
1151
1152            SuiErrorKind::TooManyTransactionsPendingExecution { .. }
1153            | SuiErrorKind::TooManyTransactionsPendingOnObject { .. }
1154            | SuiErrorKind::TooOldTransactionPendingOnObject { .. }
1155            | SuiErrorKind::TooManyTransactionsPendingConsensus
1156            | SuiErrorKind::TransactionRejectedDueToOutbiddingDuringCongestion { .. }
1157            | SuiErrorKind::ValidatorOverloadedRetryAfter { .. } => {
1158                ErrorCategory::ValidatorOverloaded
1159            }
1160
1161            SuiErrorKind::TimeoutError => ErrorCategory::Unavailable,
1162
1163            // Other variants are assumed to be retriable with new transaction submissions.
1164            _ => ErrorCategory::Aborted,
1165        }
1166    }
1167}
1168
1169impl Ord for SuiError {
1170    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1171        Ord::cmp(self.as_ref(), other.as_ref())
1172    }
1173}
1174
1175impl PartialOrd for SuiError {
1176    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1177        Some(self.cmp(other))
1178    }
1179}
1180
1181impl std::fmt::Debug for SuiError {
1182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1183        self.as_inner().fmt(f)
1184    }
1185}
1186
1187pub(crate) type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
1188pub type ExecutionErrorMetadata = BTreeMap<String, String>;
1189
1190/// A trait for execution errors that provides common methods for accessing error information and creating new errors.
1191pub trait ExecutionErrorTrait:
1192    From<ExecutionError> + Debug + std::error::Error + Send + Sync + Sized + 'static
1193{
1194    fn new(
1195        failure: ExecutionFailure,
1196        source: Option<BoxError>,
1197        metadata: ExecutionErrorMetadata,
1198    ) -> Self;
1199
1200    fn from_execution_failure(failure: ExecutionFailure) -> Self {
1201        Self::new(failure, None, ExecutionErrorMetadata::default())
1202    }
1203
1204    fn from_kind(kind: ExecutionErrorKind) -> Self {
1205        Self::from_execution_failure(ExecutionFailure::new(kind, None))
1206    }
1207
1208    fn new_with_source<E>(kind: ExecutionErrorKind, source: E) -> Self
1209    where
1210        E: Into<BoxError>,
1211    {
1212        Self::new(
1213            ExecutionFailure::new(kind, None),
1214            Some(source.into()),
1215            ExecutionErrorMetadata::default(),
1216        )
1217    }
1218
1219    fn with_command_index(self, command: CommandIndex) -> Self;
1220    fn kind(&self) -> &ExecutionErrorKind;
1221    fn command(&self) -> Option<CommandIndex>;
1222
1223    fn to_execution_failure(&self) -> ExecutionFailure {
1224        ExecutionFailure::new(self.kind().clone(), self.command())
1225    }
1226}
1227
1228#[derive(Debug)]
1229pub struct ExecutionError {
1230    inner: Box<ExecutionErrorInner>,
1231}
1232
1233#[derive(Debug)]
1234struct ExecutionErrorInner {
1235    kind: ExecutionErrorKind,
1236    source: Option<BoxError>,
1237    command: Option<CommandIndex>,
1238}
1239
1240impl ExecutionError {
1241    pub fn new(kind: ExecutionErrorKind, source: Option<BoxError>) -> Self {
1242        Self {
1243            inner: Box::new(ExecutionErrorInner {
1244                kind,
1245                source,
1246                command: None,
1247            }),
1248        }
1249    }
1250
1251    pub fn new_with_source<E: Into<BoxError>>(kind: ExecutionErrorKind, source: E) -> Self {
1252        Self::new(kind, Some(source.into()))
1253    }
1254
1255    pub fn invariant_violation<E: Into<BoxError>>(source: E) -> Self {
1256        Self::new_with_source(ExecutionErrorKind::InvariantViolation, source)
1257    }
1258
1259    pub fn with_command_index(mut self, command: CommandIndex) -> Self {
1260        self.inner.command = Some(command);
1261        self
1262    }
1263
1264    pub fn from_kind(kind: ExecutionErrorKind) -> Self {
1265        Self::new(kind, None)
1266    }
1267
1268    pub fn kind(&self) -> &ExecutionErrorKind {
1269        &self.inner.kind
1270    }
1271
1272    pub fn command(&self) -> Option<CommandIndex> {
1273        self.inner.command
1274    }
1275
1276    pub fn source(&self) -> &Option<BoxError> {
1277        &self.inner.source
1278    }
1279
1280    pub fn to_execution_status(&self) -> (ExecutionErrorKind, Option<CommandIndex>) {
1281        (self.kind().clone(), self.command())
1282    }
1283}
1284
1285impl ExecutionErrorTrait for ExecutionError {
1286    fn new(
1287        failure: ExecutionFailure,
1288        source: Option<BoxError>,
1289        _metadata: ExecutionErrorMetadata,
1290    ) -> Self {
1291        let ExecutionFailure { error, command } = failure;
1292        let err = ExecutionError::new(error, source);
1293        if let Some(command) = command {
1294            err.with_command_index(command)
1295        } else {
1296            err
1297        }
1298    }
1299
1300    fn with_command_index(self, command: CommandIndex) -> Self {
1301        self.with_command_index(command)
1302    }
1303
1304    fn kind(&self) -> &ExecutionErrorKind {
1305        self.kind()
1306    }
1307
1308    fn command(&self) -> Option<CommandIndex> {
1309        self.command()
1310    }
1311}
1312
1313#[derive(Debug)]
1314pub struct ExecutionErrorContext {
1315    kind: ExecutionErrorKind,
1316    metadata: ExecutionErrorMetadata,
1317    source: Option<BoxError>,
1318    command: Option<CommandIndex>,
1319}
1320
1321impl ExecutionErrorContext {
1322    pub fn kind(&self) -> &ExecutionErrorKind {
1323        &self.kind
1324    }
1325
1326    pub fn command(&self) -> Option<CommandIndex> {
1327        self.command
1328    }
1329
1330    pub fn metadata_with_source(&self) -> Option<ExecutionErrorMetadata> {
1331        let mut metadata = self.metadata.clone();
1332        if let Some(source) = self.source.as_ref() {
1333            metadata.insert("source".to_string(), source.to_string());
1334        }
1335
1336        (!metadata.is_empty()).then_some(metadata)
1337    }
1338
1339    pub fn to_execution_status(&self) -> (ExecutionErrorKind, Option<CommandIndex>) {
1340        (self.kind().clone(), self.command())
1341    }
1342}
1343
1344impl ExecutionErrorTrait for ExecutionErrorContext {
1345    fn new(
1346        failure: ExecutionFailure,
1347        source: Option<BoxError>,
1348        metadata: ExecutionErrorMetadata,
1349    ) -> Self {
1350        let ExecutionFailure { error, command } = failure;
1351        Self {
1352            kind: error,
1353            metadata,
1354            source,
1355            command,
1356        }
1357    }
1358
1359    fn with_command_index(self, command: CommandIndex) -> Self {
1360        Self {
1361            command: Some(command),
1362            ..self
1363        }
1364    }
1365
1366    fn kind(&self) -> &ExecutionErrorKind {
1367        self.kind()
1368    }
1369
1370    fn command(&self) -> Option<CommandIndex> {
1371        self.command()
1372    }
1373}
1374
1375impl std::fmt::Display for ExecutionErrorContext {
1376    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1377        write!(f, "ExecutionErrorContext: {:?}", self)
1378    }
1379}
1380
1381impl std::error::Error for ExecutionErrorContext {
1382    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1383        self.source.as_deref().map(|e| e as _)
1384    }
1385}
1386
1387impl From<ExecutionErrorKind> for ExecutionErrorContext {
1388    fn from(kind: ExecutionErrorKind) -> Self {
1389        <Self as ExecutionErrorTrait>::from_kind(kind)
1390    }
1391}
1392
1393impl From<ExecutionFailure> for ExecutionErrorContext {
1394    fn from(value: ExecutionFailure) -> Self {
1395        <Self as ExecutionErrorTrait>::from_execution_failure(value)
1396    }
1397}
1398
1399impl From<ExecutionError> for ExecutionErrorContext {
1400    fn from(value: ExecutionError) -> Self {
1401        let ExecutionError { inner } = value;
1402        let ExecutionErrorInner {
1403            kind,
1404            source,
1405            command,
1406        } = *inner;
1407        Self {
1408            kind,
1409            metadata: BTreeMap::new(),
1410            source,
1411            command,
1412        }
1413    }
1414}
1415
1416impl From<ExecutionErrorContext> for ExecutionError {
1417    fn from(value: ExecutionErrorContext) -> Self {
1418        let ExecutionErrorContext {
1419            kind,
1420            metadata: _,
1421            source,
1422            command,
1423        } = value;
1424        let err = ExecutionError::new(kind, source);
1425        if let Some(command) = command {
1426            err.with_command_index(command)
1427        } else {
1428            err
1429        }
1430    }
1431}
1432
1433impl std::fmt::Display for ExecutionError {
1434    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1435        write!(f, "ExecutionError: {:?}", self)
1436    }
1437}
1438
1439impl std::error::Error for ExecutionError {
1440    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1441        self.inner.source.as_ref().map(|e| &**e as _)
1442    }
1443}
1444
1445impl From<ExecutionErrorKind> for ExecutionError {
1446    fn from(kind: ExecutionErrorKind) -> Self {
1447        Self::from_kind(kind)
1448    }
1449}
1450
1451impl From<ExecutionFailure> for ExecutionError {
1452    fn from(value: ExecutionFailure) -> Self {
1453        <Self as ExecutionErrorTrait>::from_execution_failure(value)
1454    }
1455}
1456
1457pub fn command_argument_error(e: CommandArgumentError, arg_idx: usize) -> ExecutionError {
1458    ExecutionError::from_kind(ExecutionErrorKind::command_argument_error(
1459        e,
1460        arg_idx as u16,
1461    ))
1462}
1463
1464/// Types of SuiError.
1465#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, IntoStaticStr)]
1466pub enum ErrorCategory {
1467    // A generic error that is retriable with new transaction resubmissions.
1468    Aborted,
1469    // Any validator or full node can check if a transaction is valid.
1470    InvalidTransaction,
1471    // Lock conflict on the transaction input.
1472    LockConflict,
1473    // Unexpected client error, for example generating invalid request or entering into invalid state.
1474    // And unexpected error from the remote peer. The validator may be malicious or there is a software bug.
1475    Internal,
1476    // Validator is overloaded.
1477    ValidatorOverloaded,
1478    // Target validator is down or there are network issues.
1479    Unavailable,
1480}
1481
1482impl ErrorCategory {
1483    // Whether the failure is retriable with new transaction submission.
1484    pub fn is_submission_retriable(&self) -> bool {
1485        matches!(
1486            self,
1487            ErrorCategory::Aborted
1488                | ErrorCategory::ValidatorOverloaded
1489                | ErrorCategory::Unavailable
1490        )
1491    }
1492}