1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::ObjectID;
use move_binary_format::file_format::{CodeOffset, TypeParameterIndex};
use move_core_types::language_storage::ModuleId;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use sui_macros::EnumVariantOrder;
use thiserror::Error;

#[cfg(test)]
#[path = "unit_tests/execution_status_tests.rs"]
mod execution_status_tests;

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum ExecutionStatus {
    Success,
    /// Gas used in the failed case, and the error.
    Failure {
        /// The error
        error: ExecutionFailureStatus,
        /// Which command the error occurred
        command: Option<CommandIndex>,
    },
}

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, EnumVariantOrder)]
pub enum ExecutionFailureStatus {
    //
    // General transaction errors
    //
    #[error("Insufficient Gas.")]
    InsufficientGas,
    #[error("Invalid Gas Object. Possibly not address-owned or possibly not a SUI coin.")]
    InvalidGasObject,
    #[error("INVARIANT VIOLATION.")]
    InvariantViolation,
    #[error("Attempted to used feature that is not supported yet")]
    FeatureNotYetSupported,
    #[error(
        "Move object with size {object_size} is larger \
        than the maximum object size {max_object_size}"
    )]
    MoveObjectTooBig {
        object_size: u64,
        max_object_size: u64,
    },
    #[error(
        "Move package with size {object_size} is larger than the \
        maximum object size {max_object_size}"
    )]
    MovePackageTooBig {
        object_size: u64,
        max_object_size: u64,
    },
    #[error("Circular Object Ownership, including object {object}.")]
    CircularObjectOwnership { object: ObjectID },

    //
    // Coin errors
    //
    #[error("Insufficient coin balance for operation.")]
    InsufficientCoinBalance,
    #[error("The coin balance overflows u64")]
    CoinBalanceOverflow,

    //
    // Publish/Upgrade errors
    //
    #[error(
        "Publish Error, Non-zero Address. \
        The modules in the package must have their self-addresses set to zero."
    )]
    PublishErrorNonZeroAddress,

    #[error(
        "Sui Move Bytecode Verification Error. \
        Please run the Sui Move Verifier for more information."
    )]
    SuiMoveVerificationError,

    //
    // Errors from the Move VM
    //
    // Indicates an error from a non-abort instruction
    #[error(
        "Move Primitive Runtime Error. Location: {0}. \
        Arithmetic error, stack overflow, max value depth, etc."
    )]
    MovePrimitiveRuntimeError(MoveLocationOpt),
    #[error("Move Runtime Abort. Location: {0}, Abort Code: {1}")]
    MoveAbort(MoveLocation, u64),
    #[error(
        "Move Bytecode Verification Error. \
        Please run the Bytecode Verifier for more information."
    )]
    VMVerificationOrDeserializationError,
    #[error("MOVE VM INVARIANT VIOLATION.")]
    VMInvariantViolation,

    //
    // Programmable Transaction Errors
    //
    #[error("Function Not Found.")]
    FunctionNotFound,
    #[error(
        "Arity mismatch for Move function. \
        The number of arguments does not match the number of parameters"
    )]
    ArityMismatch,
    #[error(
        "Type arity mismatch for Move function. \
        Mismatch between the number of actual versus expected type arguments."
    )]
    TypeArityMismatch,
    #[error("Non Entry Function Invoked. Move Call must start with an entry function")]
    NonEntryFunctionInvoked,
    #[error("Invalid command argument at {arg_idx}. {kind}")]
    CommandArgumentError {
        arg_idx: u16,
        kind: CommandArgumentError,
    },
    #[error("Error for type argument at index {argument_idx}: {kind}")]
    TypeArgumentError {
        argument_idx: TypeParameterIndex,
        kind: TypeArgumentError,
    },
    #[error(
        "Unused result without the drop ability. \
        Command result {result_idx}, return value {secondary_idx}"
    )]
    UnusedValueWithoutDrop { result_idx: u16, secondary_idx: u16 },
    #[error(
        "Invalid public Move function signature. \
        Unsupported return type for return value {idx}"
    )]
    InvalidPublicFunctionReturnType { idx: u16 },
    #[error("Invalid Transfer Object, object does not have public transfer.")]
    InvalidTransferObject,

    //
    // Post-execution errors
    //
    // Indicates the effects from the transaction are too large
    #[error(
        "Effects of size {current_size} bytes too large. \
    Limit is {max_size} bytes"
    )]
    EffectsTooLarge { current_size: u64, max_size: u64 },

    #[error(
        "Publish/Upgrade Error, Missing dependency. \
         A dependency of a published or upgraded package has not been assigned an on-chain \
         address."
    )]
    PublishUpgradeMissingDependency,

    #[error(
        "Publish/Upgrade Error, Dependency downgrade. \
         Indirect (transitive) dependency of published or upgraded package has been assigned an \
         on-chain version that is less than the version required by one of the package's \
         transitive dependencies."
    )]
    PublishUpgradeDependencyDowngrade,

    #[error("Invalid package upgrade. {upgrade_error}")]
    PackageUpgradeError { upgrade_error: PackageUpgradeError },

    // Indicates the transaction tried to write objects too large to storage
    #[error(
        "Written objects of {current_size} bytes too large. \
    Limit is {max_size} bytes"
    )]
    WrittenObjectsTooLarge { current_size: u64, max_size: u64 },

    #[error("Certificate is on the deny list")]
    CertificateDenied,

    #[error(
        "Sui Move Bytecode Verification Timeout. \
        Please run the Sui Move Verifier for more information."
    )]
    SuiMoveVerificationTimedout,

    #[error("The shared object operation is not allowed.")]
    SharedObjectOperationNotAllowed,

    #[error("Certificate cannot be executed due to a dependency on a deleted shared object")]
    InputObjectDeleted,
    // NOTE: if you want to add a new enum,
    // please add it at the end for Rust SDK backward compatibility.
}

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash)]
pub struct MoveLocation {
    pub module: ModuleId,
    pub function: u16,
    pub instruction: CodeOffset,
    pub function_name: Option<String>,
}

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash)]
pub struct MoveLocationOpt(pub Option<MoveLocation>);

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash, Error)]
pub enum CommandArgumentError {
    #[error("The type of the value does not match the expected type")]
    TypeMismatch,
    #[error("The argument cannot be deserialized into a value of the specified type")]
    InvalidBCSBytes,
    #[error("The argument cannot be instantiated from raw bytes")]
    InvalidUsageOfPureArg,
    #[error(
        "Invalid argument to private entry function. \
        These functions cannot take arguments from other Move functions"
    )]
    InvalidArgumentToPrivateEntryFunction,
    #[error("Out of bounds access to input or result vector {idx}")]
    IndexOutOfBounds { idx: u16 },
    #[error(
        "Out of bounds secondary access to result vector \
        {result_idx} at secondary index {secondary_idx}"
    )]
    SecondaryIndexOutOfBounds { result_idx: u16, secondary_idx: u16 },
    #[error(
        "Invalid usage of result {result_idx}, \
        expected a single result but found either no return values or multiple."
    )]
    InvalidResultArity { result_idx: u16 },
    #[error(
        "Invalid taking of the Gas coin. \
        It can only be used by-value with TransferObjects"
    )]
    InvalidGasCoinUsage,
    #[error(
        "Invalid usage of value. \
        Mutably borrowed values require unique usage. \
        Immutably borrowed values cannot be taken or borrowed mutably. \
        Taken values cannot be used again."
    )]
    InvalidValueUsage,
    #[error("Immutable objects cannot be passed by-value.")]
    InvalidObjectByValue,
    #[error("Immutable objects cannot be passed by mutable reference, &mut.")]
    InvalidObjectByMutRef,
    #[error(
        "Shared object operations such a wrapping, freezing, or converting to owned are not \
        allowed."
    )]
    SharedObjectOperationNotAllowed,
}

#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash, Error)]
pub enum PackageUpgradeError {
    #[error("Unable to fetch package at {package_id}")]
    UnableToFetchPackage { package_id: ObjectID },
    #[error("Object {object_id} is not a package")]
    NotAPackage { object_id: ObjectID },
    #[error("New package is incompatible with previous version")]
    IncompatibleUpgrade,
    #[error("Digest in upgrade ticket and computed digest disagree")]
    DigestDoesNotMatch { digest: Vec<u8> },
    #[error("Upgrade policy {policy} is not a valid upgrade policy")]
    UnknownUpgradePolicy { policy: u8 },
    #[error("Package ID {package_id} does not match package ID in upgrade ticket {ticket_id}")]
    PackageIDDoesNotMatch {
        package_id: ObjectID,
        ticket_id: ObjectID,
    },
}

#[derive(Eq, PartialEq, Clone, Copy, Debug, Serialize, Deserialize, Hash, Error)]
pub enum TypeArgumentError {
    #[error("A type was not found in the module specified.")]
    TypeNotFound,
    #[error("A type provided did not match the specified constraints.")]
    ConstraintNotSatisfied,
}

impl ExecutionFailureStatus {
    pub fn command_argument_error(kind: CommandArgumentError, arg_idx: u16) -> Self {
        Self::CommandArgumentError { arg_idx, kind }
    }
}

impl Display for MoveLocationOpt {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            None => write!(f, "UNKNOWN"),
            Some(l) => write!(f, "{l}"),
        }
    }
}

impl Display for MoveLocation {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let Self {
            module,
            function,
            instruction,
            function_name,
        } = self;
        if let Some(fname) = function_name {
            write!(
                f,
                "{module}::{fname} (function index {function}) at offset {instruction}"
            )
        } else {
            write!(
                f,
                "{module} in function definition {function} at offset {instruction}"
            )
        }
    }
}

impl ExecutionStatus {
    pub fn new_failure(
        error: ExecutionFailureStatus,
        command: Option<CommandIndex>,
    ) -> ExecutionStatus {
        ExecutionStatus::Failure { error, command }
    }

    pub fn is_ok(&self) -> bool {
        matches!(self, ExecutionStatus::Success { .. })
    }

    pub fn is_err(&self) -> bool {
        matches!(self, ExecutionStatus::Failure { .. })
    }

    pub fn unwrap(&self) {
        match self {
            ExecutionStatus::Success => {}
            ExecutionStatus::Failure { .. } => {
                panic!("Unable to unwrap() on {:?}", self);
            }
        }
    }

    pub fn unwrap_err(self) -> (ExecutionFailureStatus, Option<CommandIndex>) {
        match self {
            ExecutionStatus::Success { .. } => {
                panic!("Unable to unwrap() on {:?}", self);
            }
            ExecutionStatus::Failure { error, command } => (error, command),
        }
    }
}

pub type CommandIndex = usize;