Skip to main content

iota_types/
error.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// Modifications Copyright (c) 2024 IOTA Stiftung
4// SPDX-License-Identifier: Apache-2.0
5
6use std::{collections::BTreeMap, convert::AsRef, fmt::Debug};
7
8use iota_sdk_types::{
9    Address, CheckpointContentsDigest, CommandArgumentError, ObjectDigest, ObjectId,
10    ObjectReference, Owner, TransactionDigest, TransactionEffectsDigest, Version,
11};
12use serde::{Deserialize, Serialize};
13use strum::{AsRefStr, IntoStaticStr};
14use thiserror::Error;
15#[cfg(not(target_arch = "wasm32"))]
16use tonic::Status;
17use typed_store_error::TypedStoreError;
18
19use crate::{
20    attestation::{AuthorityIndex, SharedInputIndex},
21    base_types::*,
22    committee::{Committee, EpochId, StakeUnit},
23    messages_checkpoint::CheckpointSequenceNumber,
24};
25
26#[cfg(test)]
27#[path = "unit_tests/error_codec_tests.rs"]
28mod error_codec_tests;
29
30pub const TRANSACTION_NOT_FOUND_MSG_PREFIX: &str = "Could not find the referenced transaction";
31pub const TRANSACTIONS_NOT_FOUND_MSG_PREFIX: &str = "Could not find the referenced transactions";
32
33#[macro_export]
34macro_rules! fp_bail {
35    ($e:expr) => {
36        return Err($e)
37    };
38}
39
40#[macro_export(local_inner_macros)]
41macro_rules! fp_ensure {
42    ($cond:expr, $e:expr) => {
43        if !($cond) {
44            fp_bail!($e);
45        }
46    };
47}
48
49use iota_sdk_types::ExecutionError as ExecutionFailureStatus;
50
51#[macro_export]
52macro_rules! exit_main {
53    ($result:expr) => {
54        match $result {
55            Ok(_) => (),
56            Err(err) => {
57                let err = format!("{:?}", err);
58                println!("{}", err.bold().red());
59                std::process::exit(1);
60            }
61        }
62    };
63}
64
65#[macro_export]
66macro_rules! make_invariant_violation {
67    ($($args:expr),* $(,)?) => {{
68        if cfg!(debug_assertions) {
69            panic!($($args),*)
70        }
71        ExecutionError::invariant_violation(format!($($args),*))
72    }}
73}
74
75#[macro_export]
76macro_rules! invariant_violation {
77    ($($args:expr),* $(,)?) => {
78        return Err(make_invariant_violation!($($args),*).into())
79    };
80}
81
82#[macro_export]
83macro_rules! assert_invariant {
84    ($cond:expr, $($args:expr),* $(,)?) => {{
85        if !$cond {
86            invariant_violation!($($args),*)
87        }
88    }};
89}
90
91/// Errors in the user-provided transaction input.
92///
93/// Embedded in [`IotaError::UserInput`], so it is also sent between nodes:
94/// add new variants only at the very end of the enum (see the WARNING on
95/// [`IotaError`]).
96#[cfg_attr(test, derive(iota_macros::EnumVariantOrder))]
97#[derive(
98    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
99)]
100pub enum UserInputError {
101    #[error("Mutable object {object_id} cannot appear more than once in one transaction")]
102    MutableObjectUsedMoreThanOnce { object_id: ObjectId },
103    #[error("Wrong number of parameters for the transaction")]
104    ObjectInputArityViolation,
105    #[error("Could not find the referenced object {object_id} at version {version:?}")]
106    ObjectNotFound {
107        object_id: ObjectId,
108        version: Option<Version>,
109    },
110    #[error(
111        "Object ID {} Version {} Digest {} is not available for consumption, current version: {current_version}",
112        .provided_obj_ref.object_id, .provided_obj_ref.version, .provided_obj_ref.digest
113    )]
114    ObjectVersionUnavailableForConsumption {
115        provided_obj_ref: ObjectReference,
116        current_version: Version,
117    },
118    #[error("Package verification failed: {err}")]
119    PackageVerificationTimedout { err: String },
120    #[error("Dependent package not found on-chain: {package_id}")]
121    DependentPackageNotFound { package_id: ObjectId },
122    #[error("Mutable parameter provided, immutable parameter expected")]
123    ImmutableParameterExpected { object_id: ObjectId },
124    #[error("Size limit exceeded: {limit} is {value}")]
125    SizeLimitExceeded { limit: String, value: String },
126    #[error(
127        "Object {child_id} is owned by object {parent_id}. \
128        Objects owned by other objects cannot be used as input arguments"
129    )]
130    InvalidChildObjectArgument {
131        child_id: ObjectId,
132        parent_id: ObjectId,
133    },
134    #[error("Invalid Object digest for object {object_id}. Expected digest : {expected_digest}")]
135    InvalidObjectDigest {
136        object_id: ObjectId,
137        expected_digest: ObjectDigest,
138    },
139    #[error("Sequence numbers above the maximal value are not usable for transfers")]
140    InvalidSequenceNumber,
141    #[error("A move object is expected, instead a move package is passed: {object_id}")]
142    MovePackageAsObject { object_id: ObjectId },
143    #[error("A move package is expected, instead a move object is passed: {object_id}")]
144    MoveObjectAsPackage { object_id: ObjectId },
145    #[error("Transaction was not signed by the correct sender: {}", error)]
146    IncorrectUserSignature { error: String },
147
148    #[error("Object used as shared is not shared")]
149    NotSharedObject,
150    #[error("The transaction inputs contain duplicated ObjectReference's")]
151    DuplicateObjectRefInput,
152    #[error("A transaction input {object_id} is inconsistent")]
153    InconsistentInput { object_id: ObjectId },
154
155    // Gas related errors
156    #[error("Transaction gas payment missing")]
157    MissingGasPayment,
158    #[error("Gas object is not an owned object with owner: {}", owner)]
159    GasObjectNotOwnedObject { owner: Owner },
160    #[error("Gas budget: {} is higher than max: {}", gas_budget, max_budget)]
161    GasBudgetTooHigh { gas_budget: u64, max_budget: u64 },
162    #[error("Gas budget: {} is lower than min: {}", gas_budget, min_budget)]
163    GasBudgetTooLow { gas_budget: u64, min_budget: u64 },
164    #[error(
165        "Balance of gas object {} is lower than the needed amount: {}",
166        gas_balance,
167        needed_gas_amount
168    )]
169    GasBalanceTooLow {
170        gas_balance: u128,
171        needed_gas_amount: u128,
172    },
173    #[error("Transaction kind does not support Sponsored Transaction")]
174    UnsupportedSponsoredTransactionKind,
175    #[error(
176        "Gas price {} under reference gas price (RGP) {}",
177        gas_price,
178        reference_gas_price
179    )]
180    GasPriceUnderRGP {
181        gas_price: u64,
182        reference_gas_price: u64,
183    },
184    #[error("Gas price cannot exceed {} nanos", max_gas_price)]
185    GasPriceTooHigh { max_gas_price: u64 },
186    #[error("Object {object_id} is not a gas object")]
187    InvalidGasObject { object_id: ObjectId },
188    #[error("Gas object does not have enough balance to cover minimal gas spend")]
189    InsufficientBalanceToCoverMinimalGas,
190
191    #[error(
192        "Could not find the referenced object {} as the asked version {} is higher than the latest {}",
193        object_id,
194        asked_version,
195        latest_version
196    )]
197    ObjectSequenceNumberTooHigh {
198        object_id: ObjectId,
199        asked_version: Version,
200        latest_version: Version,
201    },
202    #[error("Object deleted at reference {:?}", object_ref)]
203    ObjectDeleted { object_ref: ObjectReference },
204    #[error("Invalid Batch Transaction: {}", error)]
205    InvalidBatchTransaction { error: String },
206    #[error("This Move function is currently disabled and not available for call")]
207    BlockedMoveFunction,
208    #[error("Empty input coins for Pay related transaction")]
209    EmptyInputCoins,
210    #[error("Invalid Move View Function call: {error}")]
211    InvalidMoveViewFunction { error: String },
212
213    #[error(
214        "IOTA payment transactions use first input coin for gas payment, but found a different gas object"
215    )]
216    UnexpectedGasPaymentObject,
217
218    #[error("Wrong initial version given for shared object")]
219    SharedObjectStartingVersionMismatch,
220
221    #[error("Wrong id given for shared object")]
222    SharedObjectIdMismatch,
223
224    #[error(
225        "Attempt to transfer object {object_id} that does not have public transfer. Object transfer must be done instead using a distinct Move function call"
226    )]
227    TransferObjectWithoutPublicTransfer { object_id: ObjectId },
228
229    #[error(
230        "TransferObjects, MergeCoin, and Publish cannot have empty arguments. \
231        If MakeMoveVec has empty arguments, it must have a type specified"
232    )]
233    EmptyCommandInput,
234
235    #[error("Transaction is denied: {error}")]
236    TransactionDenied { error: String },
237
238    #[error("Feature is not supported: {0}")]
239    Unsupported(String),
240
241    #[error("Query transactions with move function input error: {0}")]
242    MoveFunctionInput(String),
243
244    #[error("Verified checkpoint not found for sequence number: {0}")]
245    VerifiedCheckpointNotFound(CheckpointSequenceNumber),
246
247    #[error("Verified checkpoint not found for digest: {0}")]
248    VerifiedCheckpointDigestNotFound(String),
249
250    #[error("Latest checkpoint sequence number not found")]
251    LatestCheckpointSequenceNumberNotFound,
252
253    #[error("Checkpoint contents not found for digest: {0}")]
254    CheckpointContentsNotFound(CheckpointContentsDigest),
255
256    #[error("Genesis transaction not found")]
257    GenesisTransactionNotFound,
258
259    #[error("Transaction {0} not found")]
260    TransactionCursorNotFound(u64),
261
262    #[error("Object {object_id} is a system object and cannot be accessed by user transactions")]
263    InaccessibleSystemObject { object_id: ObjectId },
264    #[error(
265        "{max_publish_commands} max publish/upgrade commands allowed, {publish_count} provided"
266    )]
267    MaxPublishCountExceeded {
268        max_publish_commands: u64,
269        publish_count: u64,
270    },
271
272    #[error("Immutable parameter provided, mutable parameter expected for {object_id}")]
273    MutableParameterExpected { object_id: ObjectId },
274
275    #[error("Address {address} is denied for coin {coin_type}")]
276    AddressDeniedForCoin { address: Address, coin_type: String },
277
278    #[error("Commands following a command with Random can only be TransferObjects or MergeCoins")]
279    PostRandomCommandRestrictions,
280
281    // Soft Bundle related errors
282    #[error("Number of transactions exceeds the maximum allowed ({limit}) in a Soft Bundle")]
283    TooManyTransactionsInSoftBundle { limit: u64 },
284    #[error(
285        "Total transactions size ({size}) bytes exceeds the maximum allowed ({limit}) bytes in a Soft Bundle"
286    )]
287    SoftBundleTooLarge { size: u64, limit: u64 },
288    #[error("Transaction {} in Soft Bundle contains no shared objects", digest)]
289    NoSharedObject { digest: TransactionDigest },
290    #[error("Transaction {} in Soft Bundle has already been executed", digest)]
291    AlreadyExecuted { digest: TransactionDigest },
292    #[error("At least one certificate in Soft Bundle has already been processed")]
293    CertificateAlreadyProcessed,
294    #[error(
295        "Gas price for transaction {digest} in Soft Bundle mismatch: want {expected}, have {actual}"
296    )]
297    GasPriceMismatch {
298        digest: TransactionDigest,
299        expected: u64,
300        actual: u64,
301    },
302
303    #[error("Coin type is globally paused for use: {coin_type}")]
304    CoinTypeGlobalPause { coin_type: String },
305
306    #[error("Invalid identifier found in the transaction: {error}")]
307    InvalidIdentifier { error: String },
308
309    // `MoveAuthenticator` related errors
310    #[error(
311        "Account object {account_id} with version {account_version} was deleted in transaction {transaction_digest}"
312    )]
313    AccountObjectDeleted {
314        account_id: ObjectId,
315        account_version: Version,
316        transaction_digest: TransactionDigest,
317    },
318    #[error(
319        "Account object {account_id} with version {account_version} is used in a canceled transaction"
320    )]
321    AccountObjectInCanceledTransaction {
322        account_id: ObjectId,
323        account_version: Version,
324    },
325    #[error("Account object {object_id} is not a shared or immutable object that is unsupported")]
326    AccountObjectNotSupported { object_id: ObjectId },
327    #[error(
328        "The fetched account object version {actual_version} does not match the expected version {expected_version}, object id: {object_id}"
329    )]
330    AccountObjectVersionMismatch {
331        object_id: ObjectId,
332        expected_version: Version,
333        actual_version: Version,
334    },
335    #[error(
336        "The fetched account object digest {actual_digest} does not match the expected digest {expected_digest}, object id: {object_id}"
337    )]
338    InvalidAccountObjectDigest {
339        object_id: ObjectId,
340        expected_digest: ObjectDigest,
341        actual_digest: ObjectDigest,
342    },
343
344    #[error(
345        "AuthenticatorFunctionRef {authenticator_function_ref_id} not found for account {account_object_id} with version {account_object_version}"
346    )]
347    MoveAuthenticatorNotFound {
348        authenticator_function_ref_id: ObjectId,
349        account_object_id: ObjectId,
350        account_object_version: Version,
351    },
352    #[error("Unable to get a `MoveAuthenticator` object ID for account {account_object_id}")]
353    UnableToGetMoveAuthenticatorId { account_object_id: ObjectId },
354    #[error(
355        "Invalid authenticator function ref field value found for the account {account_object_id}"
356    )]
357    InvalidAuthenticatorFunctionRefField { account_object_id: ObjectId },
358
359    #[error("Package {package_id} is in the `MoveAuthenticator` input that is unsupported")]
360    PackageIsInMoveAuthenticatorInput { package_id: ObjectId },
361    #[error(
362        "Address-owned object {object_id} is in the `MoveAuthenticator` input that is unsupported"
363    )]
364    AddressOwnedIsInMoveAuthenticatorInput { object_id: ObjectId },
365    #[error(
366        "Object-owned object {object_id} is in the `MoveAuthenticator` input that is unsupported"
367    )]
368    ObjectOwnedIsInMoveAuthenticatorInput { object_id: ObjectId },
369    #[error(
370        "Mutable shared object {object_id} is in the `MoveAuthenticator` input that is unsupported"
371    )]
372    MutableSharedIsInMoveAuthenticatorInput { object_id: ObjectId },
373    #[error(
374        "Immutable account object {object_id} cannot authenticate a transaction, only a shared account object is supported"
375    )]
376    ImmutableAccountObjectNotSupported { object_id: ObjectId },
377    #[error(
378        "Randomness state object {object_id} is in the `MoveAuthenticator` input that is unsupported"
379    )]
380    RandomnessStateIsInMoveAuthenticatorInput { object_id: ObjectId },
381    #[error(
382        "Invalid argument at command {command_idx}, argument {argument_idx}: index {index} is out of bounds"
383    )]
384    InvalidArgumentIndex {
385        command_idx: usize,
386        argument_idx: usize,
387        index: u16,
388    },
389    #[error(
390        "Input object {object_id}{} can't be used: at the consensus commit that sequenced the transaction, it was already consumed, deleted, or didn't match what the transaction declared",
391        at_version(.version)
392    )]
393    InputObjectNotAvailableAtCommit {
394        object_id: ObjectId,
395        version: Option<Version>,
396    },
397    #[error(
398        "Transaction {digest} that this transaction depends on is not among the executed transactions"
399    )]
400    TransactionDependencyNotFound { digest: TransactionDigest },
401    #[error(
402        "Transaction {digest} that this transaction depends on failed, was cancelled, or was rejected"
403    )]
404    TransactionDependencyFailed { digest: TransactionDigest },
405    #[error(
406        "Transaction {digest} that this transaction depends on executed in epoch {executed_epoch}; a dependency must be a transaction of the current epoch"
407    )]
408    TransactionDependencyNotInCurrentEpoch {
409        digest: TransactionDigest,
410        executed_epoch: EpochId,
411    },
412    #[error(
413        "Invalid argument at command {command_idx}, argument {argument_idx}: a transaction dependency input cannot be used by a command"
414    )]
415    TransactionDependencyInputUsed {
416        command_idx: usize,
417        argument_idx: usize,
418    },
419    #[error(
420        "A transaction with a transaction dependency input must set an epoch expiration equal to the current epoch"
421    )]
422    TransactionDependencyRequiresExpiration,
423}
424
425/// Formats `version` as " at version {version}", or as nothing when it is
426/// absent.
427fn at_version(version: &Option<Version>) -> String {
428    version
429        .map(|version| format!(" at version {version}"))
430        .unwrap_or_default()
431}
432
433/// Custom error type for Iota.
434///
435/// WARNING: This enum is sent between nodes, and the code of a variant is its
436/// declaration index. Add new variants only at the very end of the enum, then
437/// re-run the unit tests and commit the updated variant-order snapshot from
438/// `tests/staged/` together with the change.
439///
440/// The same rules apply to enums embedded in variant fields, such as
441/// [`UserInputError`].
442#[cfg_attr(test, derive(iota_macros::EnumVariantOrder))]
443#[derive(
444    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
445)]
446pub enum IotaError {
447    #[error("Error checking transaction input objects: {error}")]
448    UserInput { error: UserInputError },
449
450    #[error("There are already {queue_len} transactions pending, above threshold of {threshold}")]
451    TooManyTransactionsPendingExecution { queue_len: usize, threshold: usize },
452
453    #[error("There are too many transactions pending in consensus")]
454    TooManyTransactionsPendingConsensus,
455
456    #[error(
457        "Input {object_id} already has {queue_len} transactions pending, above threshold of {threshold}"
458    )]
459    TooManyTransactionsPendingOnObject {
460        object_id: ObjectId,
461        queue_len: usize,
462        threshold: usize,
463    },
464
465    #[error(
466        "Input {object_id} has a transaction {txn_age_sec} seconds old pending, above threshold of {threshold} seconds"
467    )]
468    TooOldTransactionPendingOnObject {
469        object_id: ObjectId,
470        txn_age_sec: u64,
471        threshold: u64,
472    },
473
474    #[error("Soft bundle must only contain transactions of UserTransaction kind")]
475    InvalidTxKindInSoftBundle,
476
477    // Signature verification
478    #[error("Signature is not valid: {}", error)]
479    InvalidSignature { error: String },
480    #[error("Required Signature from {expected} is absent {actual:?}")]
481    SignerSignatureAbsent {
482        expected: String,
483        actual: Vec<String>,
484    },
485    #[error("Expect {expected} signer signatures but got {actual}")]
486    SignerSignatureNumberMismatch { expected: usize, actual: usize },
487    #[error("Value was not signed by the correct sender: {}", error)]
488    IncorrectSigner { error: String },
489    #[error(
490        "Value was not signed by a known authority. signer: {:?}, index: {:?}, committee: {committee}",
491        signer,
492        index
493    )]
494    UnknownSigner {
495        signer: Option<String>,
496        index: Option<u32>,
497        committee: Box<Committee>,
498    },
499    #[error(
500        "Validator {signer:?} responded multiple signatures for the same message, conflicting: {conflicting_sig}"
501    )]
502    StakeAggregatorRepeatedSigner {
503        signer: AuthorityName,
504        conflicting_sig: bool,
505    },
506    // TODO: Used for distinguishing between different occurrences of invalid signatures, to allow
507    // retries in some cases.
508    #[error("Signature is not valid, but a retry may result in a valid one: {error}")]
509    PotentiallyTemporarilyInvalidSignature { error: String },
510
511    // Certificate verification and execution
512    #[error(
513        "Signature or certificate from wrong epoch, expected {expected_epoch}, got {actual_epoch}"
514    )]
515    WrongEpoch {
516        expected_epoch: EpochId,
517        actual_epoch: EpochId,
518    },
519    #[error("Signatures in a certificate must form a quorum")]
520    CertificateRequiresQuorum,
521    #[error("Transaction certificate processing failed: {err}")]
522    // DEPRECATED: "local execution" was removed from fullnodes
523    ErrorWhileProcessingCertificate { err: String },
524    #[error(
525        "Failed to get a quorum of signed effects when processing transaction: {effects_map:?}"
526    )]
527    QuorumFailedToGetEffectsQuorumWhenProcessingTransaction {
528        effects_map: BTreeMap<TransactionEffectsDigest, (Vec<AuthorityName>, StakeUnit)>,
529    },
530    #[error(
531        "Failed to verify Tx certificate with executed effects, error: {error}, validator: {validator_name:?}"
532    )]
533    FailedToVerifyTxCertWithExecutedEffects {
534        validator_name: AuthorityName,
535        error: String,
536    },
537    #[error("Transaction is already finalized but with different user signatures")]
538    TxAlreadyFinalizedWithDifferentUserSigs,
539
540    // Account access
541    #[error("Invalid authenticator")]
542    InvalidAuthenticator,
543    #[error("Invalid address")]
544    InvalidAddress,
545    #[error("Invalid transaction digest")]
546    InvalidTransactionDigest,
547    #[error("Invalid move authentication digest")]
548    InvalidMoveAuthenticatorDigest,
549
550    #[error("Invalid digest length. Expected {expected}, got {actual}")]
551    InvalidDigestLength { expected: usize, actual: usize },
552    #[error("Invalid DKG message size")]
553    InvalidDkgMessageSize,
554
555    #[error("Unexpected message")]
556    UnexpectedMessage,
557
558    #[error("Failed to execute the Move authenticator, reason: {error}")]
559    MoveAuthenticatorExecutionFailure { error: String },
560
561    // Move module publishing related errors
562    #[error("Failed to verify the Move module, reason: {error}")]
563    ModuleVerificationFailure { error: String },
564    #[error("Failed to deserialize the Move module, reason: {error}")]
565    ModuleDeserializationFailure { error: String },
566    #[error("Failed to publish the Move module(s), reason: {error}")]
567    ModulePublishFailure { error: String },
568    #[error("Failed to build Move modules: {error}")]
569    ModuleBuildFailure { error: String },
570
571    // Move call related errors
572    #[error("Function resolution failure: {error}")]
573    FunctionNotFound { error: String },
574    #[error("Module not found in package: {module_name:?}")]
575    ModuleNotFound { module_name: String },
576    #[error("Type error while binding function arguments: {error}")]
577    Type { error: String },
578    #[error("Circular object ownership detected")]
579    CircularObjectOwnership,
580
581    // Internal state errors
582    #[error("Attempt to re-initialize a transaction lock for objects {refs:?}")]
583    ObjectLockAlreadyInitialized { refs: Vec<ObjectReference> },
584    #[error("Object {obj_ref:?} already locked by a different transaction: {pending_transaction}")]
585    ObjectLockConflict {
586        obj_ref: ObjectReference,
587        pending_transaction: TransactionDigest,
588    },
589    #[error(
590        "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:?}"
591    )]
592    ObjectLockedAtFutureEpoch {
593        obj_refs: Vec<ObjectReference>,
594        locked_epoch: EpochId,
595        new_epoch: EpochId,
596        locked_by_tx: TransactionDigest,
597    },
598    #[error("Transaction {digest:?} was recently submitted; duplicate resubmission suppressed")]
599    RecentlyResubmitted { digest: TransactionDigest },
600    #[error("{TRANSACTION_NOT_FOUND_MSG_PREFIX} [{digest}]")]
601    TransactionNotFound { digest: TransactionDigest },
602    #[error("{TRANSACTIONS_NOT_FOUND_MSG_PREFIX} [{digests:?}]")]
603    TransactionsNotFound { digests: Vec<TransactionDigest> },
604    #[error("Could not find the referenced transaction events [{digest}]")]
605    TransactionEventsNotFound { digest: TransactionDigest },
606    #[error(
607        "Attempt to move to `Executed` state an transaction that has already been executed: {digest}"
608    )]
609    TransactionAlreadyExecuted { digest: TransactionDigest },
610    #[error("Object ID did not have the expected type")]
611    BadObjectType { error: String },
612    #[error("Fail to retrieve Object layout for {st}")]
613    FailObjectLayout { st: String },
614
615    #[error("Execution invariant violated")]
616    ExecutionInvariantViolation,
617    #[error("Validator {authority:?} is faulty in a Byzantine manner: {reason}")]
618    ByzantineAuthoritySuspicion {
619        authority: AuthorityName,
620        reason: String,
621    },
622    #[error(
623        "Attempted to access {object} through parent {given_parent}, \
624        but it's actual parent is {actual_owner}"
625    )]
626    InvalidChildObjectAccess {
627        object: ObjectId,
628        given_parent: ObjectId,
629        actual_owner: Owner,
630    },
631
632    #[error("Authority Error: {error}")]
633    GenericAuthority { error: String },
634
635    #[error("Failed to dispatch subscription: {error}")]
636    FailedToDispatchSubscription { error: String },
637
638    #[error("Failed to serialize Owner: {error}")]
639    OwnerFailedToSerialize { error: String },
640
641    #[error("Failed to deserialize fields into JSON: {error}")]
642    ExtraFieldFailedToDeserialize { error: String },
643
644    #[error("Failed to execute transaction locally by Orchestrator: {error}")]
645    TransactionOrchestratorLocalExecution { error: String },
646
647    // Errors returned by authority and client read API's
648    #[error("Failure serializing transaction in the requested format: {error}")]
649    TransactionSerialization { error: String },
650    #[error("Failure serializing object in the requested format: {error}")]
651    ObjectSerialization { error: String },
652    #[error("Failure deserializing object in the requested format: {error}")]
653    ObjectDeserialization { error: String },
654    #[error("Failure deserializing runtime module metadata in the requested format: {error}")]
655    RuntimeModuleMetadataDeserialization { error: String },
656    #[error("Event store component is not active on this node")]
657    NoEventStore,
658
659    // Client side error
660    #[error("Too many authority errors were detected for {action}: {errors:?}")]
661    TooManyIncorrectAuthorities {
662        errors: Vec<(AuthorityName, IotaError)>,
663        action: String,
664    },
665    #[error("Invalid transaction range query to the fullnode: {error}")]
666    FullNodeInvalidTxRangeQuery { error: String },
667
668    // Errors related to the authority-consensus interface.
669    #[error("Failed to submit transaction to consensus: {0}")]
670    FailedToSubmitToConsensus(String),
671    #[error("Failed to connect with consensus node: {0}")]
672    ConsensusConnectionBroken(String),
673    #[error("Failed to execute handle_consensus_transaction on Iota: {0}")]
674    HandleConsensusTransactionFailure(String),
675
676    // Cryptography errors.
677    #[error("Signature key generation error: {0}")]
678    SignatureKeyGen(String),
679    #[error("Key Conversion Error: {0}")]
680    KeyConversion(String),
681    #[error("Invalid Private Key provided")]
682    InvalidPrivateKey,
683
684    // Unsupported Operations on Fullnode
685    #[error("Fullnode does not support handle_certificate")]
686    FullNodeCantHandleCertificate,
687    #[error("Fullnode does not support ValidatorV2 endpoints")]
688    FullNodeCantHandleValidatorV2,
689    #[error("Fullnode does not support handle_authority_capabilities")]
690    FullNodeCantHandleAuthorityCapabilities,
691
692    // Epoch related errors.
693    #[error("Validator temporarily stopped processing transactions due to epoch change")]
694    ValidatorHaltedAtEpochEnd,
695    #[error("Operations for epoch {0} have ended")]
696    EpochEnded(EpochId),
697    #[error("Error when advancing epoch: {error}")]
698    AdvanceEpoch { error: String },
699
700    #[error("Transaction Expired")]
701    TransactionExpired,
702
703    // These are errors that occur when an RPC fails and is simply the utf8 message sent in a
704    // Tonic::Status
705    #[error("{1} - {0}")]
706    Rpc(String, String),
707
708    #[error("Method not allowed")]
709    InvalidRpcMethod,
710
711    // TODO: We should fold this into UserInputError::Unsupported.
712    #[error("Use of disabled feature: {error}")]
713    UnsupportedFeature { error: String },
714
715    #[error("Unable to communicate with the Quorum Driver channel: {error}")]
716    QuorumDriverCommunication { error: String },
717
718    #[error("Operation timed out")]
719    Timeout,
720
721    #[error("Error executing {0}")]
722    Execution(String),
723
724    #[error("Invalid committee composition")]
725    InvalidCommittee(String),
726
727    #[error("Missing committee information for epoch {0}")]
728    MissingCommitteeAtEpoch(EpochId),
729
730    #[error("Index store not available on this Fullnode")]
731    IndexStoreNotAvailable,
732
733    #[error("Failed to read dynamic field from table in the object store: {0}")]
734    DynamicFieldRead(String),
735
736    #[error("Failed to read or deserialize system state related data structures on-chain: {0}")]
737    IotaSystemStateRead(String),
738
739    #[error("Unexpected version error: {0}")]
740    UnexpectedVersion(String),
741
742    #[error("Message version is not supported at the current protocol version: {error}")]
743    WrongMessageVersion { error: String },
744
745    #[error("unknown error: {0}")]
746    Unknown(String),
747
748    #[error("Failed to perform file operation: {0}")]
749    FileIO(String),
750
751    #[error("Failed to get JWK")]
752    JWKRetrieval,
753
754    #[error("Storage error: {0}")]
755    Storage(String),
756
757    #[error(
758        "Validator cannot handle the request at the moment. Please retry after at least {retry_after_secs} seconds"
759    )]
760    ValidatorOverloadedRetryAfter { retry_after_secs: u64 },
761
762    #[error("Too many requests")]
763    TooManyRequests,
764
765    #[error("The request did not contain a certificate")]
766    NoCertificateProvided,
767
768    #[error("Invalid admin request: {0}")]
769    InvalidAdminRequest(String),
770
771    #[error("Could not find the referenced transaction effects [{digest}]")]
772    TransactionEffectsNotFound { digest: TransactionDigest },
773
774    #[error("Dynamic field with key={key} and ID={id} does not exist on parent {parent_id}")]
775    DynamicFieldNotExists {
776        parent_id: ObjectId,
777        id: ObjectId,
778        key: String,
779    },
780
781    #[error(
782        "Attestation author mismatch: attestation claims attestor {expected:?} \
783         but the block was authored by {actual:?}"
784    )]
785    AttestationAuthorMismatch {
786        expected: AuthorityIndex,
787        actual: AuthorityIndex,
788    },
789
790    #[error(
791        "Attestation reports computation_units = {actual} gas units, \
792         below the protocol minimum of {minimum} \
793         (`min(base_tx_cost_fixed, gas_rounding_step)`); \
794         no honest dry-run can meter below this minimum"
795    )]
796    AttestationUnitsBelowMinimum { actual: u64, minimum: u64 },
797
798    #[error(
799        "Attestation reports computation_units = {actual} gas units, \
800         above the user's budget maximum of {maximum} (`gas_budget / gas_price`); \
801         an honest dry-run cannot exceed what the tx can pay for"
802    )]
803    AttestationUnitsAboveBudget { actual: u64, maximum: u64 },
804
805    #[error(
806        "Attestor {attestor:?} is cut off for the rest of the epoch: the squared \
807         units of its refuted attestations reached \
808         `attestation_max_refuted_units_squared`"
809    )]
810    AttestorCutOff { attestor: AuthorityIndex },
811
812    #[error(
813        "Attestation records a version at {index:?}, where the transaction names \
814         no shared object"
815    )]
816    AttestationIndexNamesNoSharedObject { index: SharedInputIndex },
817
818    #[error("Attestation records a version at {index:?} more than once")]
819    AttestationIndexRepeated { index: SharedInputIndex },
820
821    #[error(
822        "Attestation records versions {first} and {second} of object {object_id}, \
823         which the transaction names at two indexes"
824    )]
825    AttestationObjectVersionsDiffer {
826        object_id: ObjectId,
827        first: Version,
828        second: Version,
829    },
830
831    #[error(
832        "Attestation records no version at {index:?}, where a Move authenticator \
833         names a shared object"
834    )]
835    AttestationAuthenticatorInputMissing { index: SharedInputIndex },
836}
837
838#[repr(u64)]
839#[expect(non_camel_case_types)]
840#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
841/// Sub-status codes for the `UNKNOWN_VERIFICATION_ERROR` VM Status Code which
842/// provides more context TODO: add more Vm Status errors. We use
843/// `UNKNOWN_VERIFICATION_ERROR` as a catchall for now.
844pub enum VMMVerifierErrorSubStatusCode {
845    MULTIPLE_RETURN_VALUES_NOT_ALLOWED = 0,
846    INVALID_OBJECT_CREATION = 1,
847}
848
849#[repr(u64)]
850#[expect(non_camel_case_types)]
851#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
852/// Sub-status codes for the `MEMORY_LIMIT_EXCEEDED` VM Status Code which
853/// provides more context
854pub enum VMMemoryLimitExceededSubStatusCode {
855    EVENT_COUNT_LIMIT_EXCEEDED = 0,
856    EVENT_SIZE_LIMIT_EXCEEDED = 1,
857    NEW_ID_COUNT_LIMIT_EXCEEDED = 2,
858    DELETED_ID_COUNT_LIMIT_EXCEEDED = 3,
859    TRANSFER_ID_COUNT_LIMIT_EXCEEDED = 4,
860    OBJECT_RUNTIME_CACHE_LIMIT_EXCEEDED = 5,
861    OBJECT_RUNTIME_STORE_LIMIT_EXCEEDED = 6,
862    TOTAL_EVENT_SIZE_LIMIT_EXCEEDED = 7,
863}
864
865pub type IotaResult<T = ()> = Result<T, IotaError>;
866pub type UserInputResult<T = ()> = Result<T, UserInputError>;
867
868impl From<iota_protocol_config::Error> for IotaError {
869    fn from(error: iota_protocol_config::Error) -> Self {
870        IotaError::WrongMessageVersion { error: error.0 }
871    }
872}
873
874impl From<ExecutionError> for IotaError {
875    fn from(error: ExecutionError) -> Self {
876        IotaError::Execution(error.to_string())
877    }
878}
879
880impl From<iota_sdk_types::hash::MissingSignatureError> for IotaError {
881    fn from(error: iota_sdk_types::hash::MissingSignatureError) -> Self {
882        IotaError::InvalidSignature {
883            error: error.to_string(),
884        }
885    }
886}
887
888#[cfg(not(target_arch = "wasm32"))]
889impl From<Status> for IotaError {
890    fn from(status: Status) -> Self {
891        if status.message() == "Too many requests" {
892            return Self::TooManyRequests;
893        }
894        let result = bcs::from_bytes::<IotaError>(status.details());
895        if let Ok(iota_error) = result {
896            iota_error
897        } else {
898            Self::Rpc(
899                status.message().to_owned(),
900                status.code().description().to_owned(),
901            )
902        }
903    }
904}
905
906impl From<TypedStoreError> for IotaError {
907    fn from(e: TypedStoreError) -> Self {
908        Self::Storage(e.to_string())
909    }
910}
911
912impl From<crate::storage::error::Error> for IotaError {
913    fn from(e: crate::storage::error::Error) -> Self {
914        Self::Storage(e.to_string())
915    }
916}
917
918#[cfg(not(target_arch = "wasm32"))]
919impl From<IotaError> for Status {
920    fn from(error: IotaError) -> Self {
921        let bytes = bcs::to_bytes(&error).unwrap();
922        Status::with_details(tonic::Code::Internal, error.to_string(), bytes.into())
923    }
924}
925
926impl From<ExecutionErrorKind> for IotaError {
927    fn from(kind: ExecutionErrorKind) -> Self {
928        ExecutionError::from_kind(kind).into()
929    }
930}
931
932impl From<&str> for IotaError {
933    fn from(error: &str) -> Self {
934        IotaError::GenericAuthority {
935            error: error.to_string(),
936        }
937    }
938}
939
940impl From<String> for IotaError {
941    fn from(error: String) -> Self {
942        IotaError::GenericAuthority { error }
943    }
944}
945
946impl TryFrom<IotaError> for UserInputError {
947    type Error = anyhow::Error;
948
949    fn try_from(err: IotaError) -> Result<Self, Self::Error> {
950        match err {
951            IotaError::UserInput { error } => Ok(error),
952            other => anyhow::bail!("error `{other}` is not UserInput"),
953        }
954    }
955}
956
957impl From<UserInputError> for IotaError {
958    fn from(error: UserInputError) -> Self {
959        IotaError::UserInput { error }
960    }
961}
962
963impl IotaError {
964    pub fn individual_error_indicates_epoch_change(&self) -> bool {
965        matches!(
966            self,
967            IotaError::ValidatorHaltedAtEpochEnd | IotaError::MissingCommitteeAtEpoch(_)
968        )
969    }
970
971    /// Returns if the error is retryable and if the error's retryability is
972    /// explicitly categorized.
973    /// There should be only a handful of retryable errors. For now we list
974    /// common non-retryable error below to help us find more retryable
975    /// errors in logs.
976    pub fn is_retryable(&self) -> (bool, bool) {
977        let retryable = match self {
978            IotaError::Rpc { .. } => true,
979
980            // Reconfig error
981            IotaError::ValidatorHaltedAtEpochEnd => true,
982            IotaError::MissingCommitteeAtEpoch(..) => true,
983            IotaError::WrongEpoch { .. } => true,
984            IotaError::EpochEnded { .. } => true,
985
986            IotaError::UserInput { error } => {
987                match error {
988                    // Only ObjectNotFound and DependentPackageNotFound is potentially retryable
989                    UserInputError::ObjectNotFound { .. } => true,
990                    UserInputError::DependentPackageNotFound { .. } => true,
991                    // Every validator drops the transaction at the commit for
992                    // good, so a resubmission of it gets the same answer.
993                    UserInputError::InputObjectNotAvailableAtCommit { .. } => false,
994                    // The dependency may still be submitted or executed.
995                    UserInputError::TransactionDependencyNotFound { .. } => true,
996                    _ => false,
997                }
998            }
999
1000            IotaError::PotentiallyTemporarilyInvalidSignature { .. } => true,
1001
1002            // Overload errors
1003            IotaError::TooManyTransactionsPendingExecution { .. } => true,
1004            IotaError::TooManyTransactionsPendingOnObject { .. } => true,
1005            IotaError::TooOldTransactionPendingOnObject { .. } => true,
1006            IotaError::TooManyTransactionsPendingConsensus => true,
1007            IotaError::ValidatorOverloadedRetryAfter { .. } => true,
1008
1009            // Transient consensus failure — other validators likely unaffected
1010            IotaError::FailedToSubmitToConsensus(..) => true,
1011
1012            // Same digest already in flight — client should wait for the
1013            // original to land or retry once the soft locks are released.
1014            IotaError::RecentlyResubmitted { .. } => true,
1015
1016            // Non retryable error
1017            IotaError::Execution(..) => false,
1018            IotaError::ByzantineAuthoritySuspicion { .. } => false,
1019            IotaError::QuorumFailedToGetEffectsQuorumWhenProcessingTransaction { .. } => false,
1020            IotaError::TxAlreadyFinalizedWithDifferentUserSigs => false,
1021            IotaError::FailedToVerifyTxCertWithExecutedEffects { .. } => false,
1022            IotaError::ObjectLockConflict { .. } => false,
1023
1024            // NB: This is not an internal overload, but instead an imposed rate
1025            // limit / blocking of a client. It must be non-retryable otherwise
1026            // we will make the threat worse through automatic retries.
1027            IotaError::TooManyRequests => false,
1028
1029            // Signature errors — non-retryable, invalid input
1030            IotaError::InvalidSignature { .. } => false,
1031            IotaError::SignerSignatureAbsent { .. } => false,
1032            IotaError::SignerSignatureNumberMismatch { .. } => false,
1033            IotaError::IncorrectSigner { .. } => false,
1034            IotaError::UnknownSigner { .. } => false,
1035            IotaError::InvalidAuthenticator => false,
1036
1037            // Transaction lifecycle — non-retryable
1038            IotaError::TransactionExpired => false,
1039
1040            // Fullnode-internal aggregation errors — non-retryable
1041            IotaError::StakeAggregatorRepeatedSigner { .. } => false,
1042            IotaError::CertificateRequiresQuorum => false,
1043
1044            // For all un-categorized errors, return here with categorized = false.
1045            _ => return (false, false),
1046        };
1047
1048        (retryable, true)
1049    }
1050
1051    pub fn is_object_or_package_not_found(&self) -> bool {
1052        match self {
1053            IotaError::UserInput { error } => {
1054                matches!(
1055                    error,
1056                    UserInputError::ObjectNotFound { .. }
1057                        | UserInputError::DependentPackageNotFound { .. }
1058                )
1059            }
1060            _ => false,
1061        }
1062    }
1063
1064    pub fn is_overload(&self) -> bool {
1065        matches!(
1066            self,
1067            IotaError::TooManyTransactionsPendingExecution { .. }
1068                | IotaError::TooManyTransactionsPendingOnObject { .. }
1069                | IotaError::TooOldTransactionPendingOnObject { .. }
1070                | IotaError::TooManyTransactionsPendingConsensus
1071        )
1072    }
1073
1074    pub fn is_retryable_overload(&self) -> bool {
1075        matches!(self, IotaError::ValidatorOverloadedRetryAfter { .. })
1076    }
1077
1078    /// Returns `true` for errors caused by storage or epoch-lifecycle
1079    /// failures (RocksDB, epoch store closed) rather than semantic transaction
1080    /// problems. Used by post-consensus validation to distinguish fatal errors
1081    /// (halt the commit) from per-transaction drops.
1082    pub fn is_storage_or_epoch_error(&self) -> bool {
1083        matches!(
1084            self,
1085            IotaError::Storage(..)
1086                | IotaError::EpochEnded(..)
1087                | IotaError::ValidatorHaltedAtEpochEnd
1088        )
1089    }
1090
1091    pub fn retry_after_secs(&self) -> u64 {
1092        match self {
1093            IotaError::ValidatorOverloadedRetryAfter { retry_after_secs } => *retry_after_secs,
1094            _ => 0,
1095        }
1096    }
1097}
1098
1099/// Categorizes IotaError into ErrorCategory.
1100pub fn categorize(error: &IotaError) -> ErrorCategory {
1101    match error {
1102        IotaError::UserInput { error } => match error {
1103            UserInputError::ObjectNotFound { .. } => ErrorCategory::Aborted,
1104            UserInputError::DependentPackageNotFound { .. } => ErrorCategory::Aborted,
1105            UserInputError::InputObjectNotAvailableAtCommit { .. } => {
1106                ErrorCategory::InvalidTransaction
1107            }
1108            UserInputError::TransactionDependencyNotFound { .. } => ErrorCategory::Aborted,
1109            _ => ErrorCategory::InvalidTransaction,
1110        },
1111        IotaError::InvalidSignature { .. }
1112        | IotaError::SignerSignatureAbsent { .. }
1113        | IotaError::SignerSignatureNumberMismatch { .. }
1114        | IotaError::IncorrectSigner { .. }
1115        | IotaError::UnknownSigner { .. }
1116        | IotaError::TransactionExpired => ErrorCategory::InvalidTransaction,
1117
1118        IotaError::ObjectLockConflict { .. } => ErrorCategory::LockConflict,
1119
1120        IotaError::TooManyTransactionsPendingExecution { .. }
1121        | IotaError::TooManyTransactionsPendingOnObject { .. }
1122        | IotaError::TooOldTransactionPendingOnObject { .. }
1123        | IotaError::TooManyTransactionsPendingConsensus
1124        | IotaError::ValidatorOverloadedRetryAfter { .. } => ErrorCategory::ValidatorOverloaded,
1125
1126        _ => ErrorCategory::Aborted,
1127    }
1128}
1129
1130/// Types of IotaError categories for retry decisions.
1131#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, IntoStaticStr)]
1132pub enum ErrorCategory {
1133    /// A generic error that is retriable with new transaction resubmissions.
1134    Aborted,
1135    /// Any validator or full node can check if a transaction is valid.
1136    InvalidTransaction,
1137    /// Lock conflict on the transaction input.
1138    LockConflict,
1139    /// Unexpected client error, for example generating invalid request or
1140    /// entering into invalid state. And unexpected error from the remote
1141    /// peer.
1142    Internal,
1143    /// Validator is overloaded.
1144    ValidatorOverloaded,
1145    /// Target validator is down or there are network issues.
1146    Unavailable,
1147}
1148
1149impl ErrorCategory {
1150    /// Whether the failure is retriable with new transaction submission.
1151    pub fn is_submission_retriable(&self) -> bool {
1152        matches!(
1153            self,
1154            ErrorCategory::Aborted
1155                | ErrorCategory::ValidatorOverloaded
1156                | ErrorCategory::Unavailable
1157        )
1158    }
1159}
1160
1161impl IotaError {
1162    /// Categorizes this error into an ErrorCategory.
1163    pub fn categorize(&self) -> ErrorCategory {
1164        categorize(self)
1165    }
1166}
1167
1168impl Ord for IotaError {
1169    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1170        Ord::cmp(self.as_ref(), other.as_ref())
1171    }
1172}
1173
1174impl PartialOrd for IotaError {
1175    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1176        Some(self.cmp(other))
1177    }
1178}
1179
1180type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
1181
1182pub type ExecutionErrorKind = ExecutionFailureStatus;
1183
1184#[derive(Debug)]
1185pub struct ExecutionError {
1186    inner: Box<ExecutionErrorInner>,
1187}
1188
1189#[derive(Debug)]
1190struct ExecutionErrorInner {
1191    kind: ExecutionErrorKind,
1192    source: Option<BoxError>,
1193    command: Option<u64>,
1194}
1195
1196impl ExecutionError {
1197    pub fn new(kind: ExecutionErrorKind, source: Option<BoxError>) -> Self {
1198        Self {
1199            inner: Box::new(ExecutionErrorInner {
1200                kind,
1201                source,
1202                command: None,
1203            }),
1204        }
1205    }
1206
1207    pub fn new_with_source<E: Into<BoxError>>(kind: ExecutionErrorKind, source: E) -> Self {
1208        Self::new(kind, Some(source.into()))
1209    }
1210
1211    pub fn invariant_violation<E: Into<BoxError>>(source: E) -> Self {
1212        Self::new_with_source(ExecutionFailureStatus::InvariantViolation, source)
1213    }
1214
1215    pub fn with_command_index(mut self, command: u64) -> Self {
1216        self.inner.command = Some(command);
1217        self
1218    }
1219
1220    /// Rewrap this error, produced while executing a Move authenticator, as a
1221    /// [`ExecutionFailureStatus::MoveAuthentication`]. The command index
1222    /// is dropped: it referred to a command of the authenticator's own
1223    /// programmable transaction and is meaningless in the transaction's
1224    /// effects, where it would otherwise collide with the first command of the
1225    /// programmable transaction.
1226    pub fn into_move_authentication_error(self) -> Self {
1227        let ExecutionErrorInner { kind, source, .. } = *self.inner;
1228        Self::new(
1229            ExecutionFailureStatus::MoveAuthentication {
1230                error: Box::new(kind),
1231            },
1232            source,
1233        )
1234    }
1235
1236    pub fn from_kind(kind: ExecutionErrorKind) -> Self {
1237        Self::new(kind, None)
1238    }
1239
1240    pub fn kind(&self) -> &ExecutionErrorKind {
1241        &self.inner.kind
1242    }
1243
1244    pub fn command(&self) -> Option<u64> {
1245        self.inner.command
1246    }
1247
1248    pub fn source(&self) -> &Option<BoxError> {
1249        &self.inner.source
1250    }
1251
1252    pub fn to_execution_status(&self) -> (ExecutionFailureStatus, Option<u64>) {
1253        (self.kind().clone(), self.command())
1254    }
1255}
1256
1257impl std::fmt::Display for ExecutionError {
1258    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1259        write!(f, "{}: {}", self.inner.kind.as_ref(), self.inner.kind)?;
1260        if let Some(source) = self.inner.source.as_ref() {
1261            write!(f, "; caused by: {source}")?;
1262        }
1263        if let Some(command) = self.inner.command {
1264            write!(f, "; at command index: {command}")?;
1265        }
1266        Ok(())
1267    }
1268}
1269
1270impl std::error::Error for ExecutionError {
1271    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1272        self.inner.source.as_ref().map(|e| &**e as _)
1273    }
1274}
1275
1276impl From<ExecutionErrorKind> for ExecutionError {
1277    fn from(kind: ExecutionErrorKind) -> Self {
1278        Self::from_kind(kind)
1279    }
1280}
1281
1282pub fn command_argument_error(e: CommandArgumentError, arg_idx: usize) -> ExecutionError {
1283    ExecutionError::from_kind(ExecutionErrorKind::command_argument_error(
1284        e,
1285        arg_idx as u16,
1286    ))
1287}