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
// Copyright (c) Mysten Labs, Inc.
// Modifications Copyright (c) 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::{
    convert::{TryFrom, TryInto},
    fmt::{Display, Formatter},
};

use move_core_types::{
    annotated_value::MoveStructLayout,
    ident_str,
    identifier::IdentStr,
    language_storage::{StructTag, TypeTag},
};
use serde::{Deserialize, Serialize};

use crate::{
    IOTA_FRAMEWORK_ADDRESS,
    balance::{Balance, Supply},
    base_types::{ObjectID, SequenceNumber},
    coin::{Coin, TreasuryCap},
    error::{ExecutionError, ExecutionErrorKind},
    id::UID,
    object::{Data, MoveObject, Object},
};

/// The number of Nanos per Iota token
pub const NANOS_PER_IOTA: u64 = 1_000_000_000;

/// Total supply in IOTA at genesis, after the migration from a Stardust ledger,
/// before any inflation mechanism
pub const STARDUST_TOTAL_SUPPLY_IOTA: u64 = 4_600_000_000;

// Note: cannot use checked arithmetic here since `const unwrap` is still
// unstable.
/// Total supply at genesis denominated in Nanos, after the migration from a
/// Stardust ledger, before any inflation mechanism
pub const STARDUST_TOTAL_SUPPLY_NANOS: u64 = STARDUST_TOTAL_SUPPLY_IOTA * NANOS_PER_IOTA;

pub const GAS_MODULE_NAME: &IdentStr = ident_str!("iota");
pub const GAS_STRUCT_NAME: &IdentStr = ident_str!("IOTA");
pub const GAS_TREASURY_CAP_STRUCT_NAME: &IdentStr = ident_str!("IotaTreasuryCap");

pub use checked::*;

#[iota_macros::with_checked_arithmetic]
mod checked {
    use super::*;

    pub struct GAS {}
    impl GAS {
        pub fn type_() -> StructTag {
            StructTag {
                address: IOTA_FRAMEWORK_ADDRESS,
                name: GAS_STRUCT_NAME.to_owned(),
                module: GAS_MODULE_NAME.to_owned(),
                type_params: Vec::new(),
            }
        }

        pub fn type_tag() -> TypeTag {
            TypeTag::Struct(Box::new(Self::type_()))
        }

        pub fn is_gas(other: &StructTag) -> bool {
            &Self::type_() == other
        }

        pub fn is_gas_type(other: &TypeTag) -> bool {
            match other {
                TypeTag::Struct(s) => Self::is_gas(s),
                _ => false,
            }
        }
    }

    /// Rust version of the Move iota::coin::Coin<Iota::iota::IOTA> type
    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct GasCoin(pub Coin);

    impl GasCoin {
        pub fn new(id: ObjectID, value: u64) -> Self {
            Self(Coin::new(UID::new(id), value))
        }

        pub fn value(&self) -> u64 {
            self.0.value()
        }

        pub fn type_() -> StructTag {
            Coin::type_(TypeTag::Struct(Box::new(GAS::type_())))
        }

        /// Return `true` if `s` is the type of a gas coin (i.e.,
        /// 0x2::coin::Coin<0x2::iota::IOTA>)
        pub fn is_gas_coin(s: &StructTag) -> bool {
            Coin::is_coin(s) && s.type_params.len() == 1 && GAS::is_gas_type(&s.type_params[0])
        }

        /// Return `true` if `s` is the type of a gas balance (i.e.,
        /// 0x2::balance::Balance<0x2::iota::IOTA>)
        pub fn is_gas_balance(s: &StructTag) -> bool {
            Balance::is_balance(s)
                && s.type_params.len() == 1
                && GAS::is_gas_type(&s.type_params[0])
        }

        pub fn id(&self) -> &ObjectID {
            self.0.id()
        }

        pub fn to_bcs_bytes(&self) -> Vec<u8> {
            bcs::to_bytes(&self).unwrap()
        }

        pub fn to_object(&self, version: SequenceNumber) -> MoveObject {
            MoveObject::new_gas_coin(version, *self.id(), self.value())
        }

        pub fn layout() -> MoveStructLayout {
            Coin::layout(TypeTag::Struct(Box::new(GAS::type_())))
        }

        #[cfg(any(feature = "test-utils", test))]
        pub fn new_for_testing(value: u64) -> Self {
            Self::new(ObjectID::random(), value)
        }

        #[cfg(any(feature = "test-utils", test))]
        pub fn new_for_testing_with_id(id: ObjectID, value: u64) -> Self {
            Self::new(id, value)
        }
    }

    impl TryFrom<&MoveObject> for GasCoin {
        type Error = ExecutionError;

        fn try_from(value: &MoveObject) -> Result<GasCoin, ExecutionError> {
            if !value.type_().is_gas_coin() {
                return Err(ExecutionError::new_with_source(
                    ExecutionErrorKind::InvalidGasObject,
                    format!("Gas object type is not a gas coin: {}", value.type_()),
                ));
            }
            let gas_coin: GasCoin = bcs::from_bytes(value.contents()).map_err(|err| {
                ExecutionError::new_with_source(
                    ExecutionErrorKind::InvalidGasObject,
                    format!("Unable to deserialize gas object: {:?}", err),
                )
            })?;
            Ok(gas_coin)
        }
    }

    impl TryFrom<&Object> for GasCoin {
        type Error = ExecutionError;

        fn try_from(value: &Object) -> Result<GasCoin, ExecutionError> {
            match &value.data {
                Data::Move(obj) => obj.try_into(),
                Data::Package(_) => Err(ExecutionError::new_with_source(
                    ExecutionErrorKind::InvalidGasObject,
                    format!("Gas object type is not a gas coin: {:?}", value),
                )),
            }
        }
    }

    impl Display for GasCoin {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(f, "Coin {{ id: {}, value: {} }}", self.id(), self.value())
        }
    }

    // Rust version of the IotaTreasuryCap type
    #[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
    pub struct IotaTreasuryCap {
        pub inner: TreasuryCap,
    }

    impl IotaTreasuryCap {
        pub fn type_() -> StructTag {
            StructTag {
                address: IOTA_FRAMEWORK_ADDRESS,
                module: GAS_MODULE_NAME.to_owned(),
                name: GAS_TREASURY_CAP_STRUCT_NAME.to_owned(),
                type_params: Vec::new(),
            }
        }

        /// Returns the `TreasuryCap<IOTA>` object ID.
        pub fn id(&self) -> &ObjectID {
            self.inner.id.object_id()
        }

        /// Returns the total `Supply` of `Coin<IOTA>`.
        pub fn total_supply(&self) -> &Supply {
            &self.inner.total_supply
        }
    }
}