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

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

use crate::{
    IOTA_FRAMEWORK_ADDRESS,
    balance::{Balance, Supply},
    base_types::ObjectID,
    error::{ExecutionError, ExecutionErrorKind, IotaError},
    id::UID,
    object::{Data, Object},
};

pub const COIN_MODULE_NAME: &IdentStr = ident_str!("coin");
pub const COIN_STRUCT_NAME: &IdentStr = ident_str!("Coin");
pub const COIN_METADATA_STRUCT_NAME: &IdentStr = ident_str!("CoinMetadata");
pub const COIN_TREASURE_CAP_NAME: &IdentStr = ident_str!("TreasuryCap");
pub const COIN_JOIN_FUNC_NAME: &IdentStr = ident_str!("join");

pub const PAY_MODULE_NAME: &IdentStr = ident_str!("pay");
pub const PAY_SPLIT_N_FUNC_NAME: &IdentStr = ident_str!("divide_and_keep");
pub const PAY_SPLIT_VEC_FUNC_NAME: &IdentStr = ident_str!("split_vec");

// Rust version of the Move iota::coin::Coin type
#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema, Eq, PartialEq)]
pub struct Coin {
    pub id: UID,
    pub balance: Balance,
}

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

    pub fn type_(type_param: TypeTag) -> StructTag {
        StructTag {
            address: IOTA_FRAMEWORK_ADDRESS,
            name: COIN_STRUCT_NAME.to_owned(),
            module: COIN_MODULE_NAME.to_owned(),
            type_params: vec![type_param],
        }
    }

    /// Is this other StructTag representing a Coin?
    pub fn is_coin(other: &StructTag) -> bool {
        other.address == IOTA_FRAMEWORK_ADDRESS
            && other.module.as_ident_str() == COIN_MODULE_NAME
            && other.name.as_ident_str() == COIN_STRUCT_NAME
    }

    /// Create a coin from BCS bytes
    pub fn from_bcs_bytes(content: &[u8]) -> Result<Self, bcs::Error> {
        bcs::from_bytes(content)
    }

    /// If the given object is a Coin, deserialize its contents and extract the
    /// balance Ok(Some(u64)). If it's not a Coin, return Ok(None).
    /// The cost is 2 comparisons if not a coin, and deserialization if its a
    /// Coin.
    pub fn extract_balance_if_coin(object: &Object) -> Result<Option<u64>, bcs::Error> {
        match &object.data {
            Data::Move(move_obj) => {
                if !move_obj.is_coin() {
                    return Ok(None);
                }

                let coin = Self::from_bcs_bytes(move_obj.contents())?;
                Ok(Some(coin.value()))
            }
            _ => Ok(None), // package
        }
    }

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

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

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

    pub fn layout(type_param: TypeTag) -> MoveStructLayout {
        MoveStructLayout {
            type_: Self::type_(type_param.clone()),
            fields: vec![
                MoveFieldLayout::new(
                    ident_str!("id").to_owned(),
                    MoveTypeLayout::Struct(UID::layout()),
                ),
                MoveFieldLayout::new(
                    ident_str!("balance").to_owned(),
                    MoveTypeLayout::Struct(Balance::layout(type_param)),
                ),
            ],
        }
    }

    /// Add balance to this coin, erroring if the new total balance exceeds the
    /// maximum
    pub fn add(&mut self, balance: Balance) -> Result<(), ExecutionError> {
        let Some(new_value) = self.value().checked_add(balance.value()) else {
            return Err(ExecutionError::from_kind(
                ExecutionErrorKind::CoinBalanceOverflow,
            ));
        };
        self.balance = Balance::new(new_value);
        Ok(())
    }

    // Split amount out of this coin to a new coin.
    // Related coin objects need to be updated in temporary_store to persist the
    // changes, including creating the coin object related to the newly created
    // coin.
    pub fn split(&mut self, amount: u64, new_coin_id: UID) -> Result<Coin, ExecutionError> {
        self.balance.withdraw(amount)?;
        Ok(Coin::new(new_coin_id, amount))
    }
}

// Rust version of the Move iota::coin::TreasuryCap type
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, JsonSchema)]
pub struct TreasuryCap {
    pub id: UID,
    pub total_supply: Supply,
}

impl TreasuryCap {
    pub fn is_treasury_type(other: &StructTag) -> bool {
        other.address == IOTA_FRAMEWORK_ADDRESS
            && other.module.as_ident_str() == COIN_MODULE_NAME
            && other.name.as_ident_str() == COIN_TREASURE_CAP_NAME
    }

    /// Create a TreasuryCap from BCS bytes
    pub fn from_bcs_bytes(content: &[u8]) -> Result<Self, IotaError> {
        bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization {
            error: format!("Unable to deserialize TreasuryCap object: {}", err),
        })
    }

    pub fn type_(type_param: StructTag) -> StructTag {
        StructTag {
            address: IOTA_FRAMEWORK_ADDRESS,
            name: COIN_TREASURE_CAP_NAME.to_owned(),
            module: COIN_MODULE_NAME.to_owned(),
            type_params: vec![TypeTag::Struct(Box::new(type_param))],
        }
    }

    /// Checks if the provided type is `TreasuryCap<T>`, returning the type T if
    /// so.
    pub fn is_treasury_with_coin_type(other: &StructTag) -> Option<&StructTag> {
        if Self::is_treasury_type(other) && other.type_params.len() == 1 {
            match other.type_params.first() {
                Some(TypeTag::Struct(coin_type)) => Some(coin_type),
                _ => None,
            }
        } else {
            None
        }
    }
}

impl TryFrom<Object> for TreasuryCap {
    type Error = IotaError;
    fn try_from(object: Object) -> Result<Self, Self::Error> {
        match &object.data {
            Data::Move(o) => {
                if o.type_().is_treasury_cap() {
                    return TreasuryCap::from_bcs_bytes(o.contents());
                }
            }
            Data::Package(_) => {}
        }

        Err(IotaError::Type {
            error: format!("Object type is not a TreasuryCap: {:?}", object),
        })
    }
}

// Rust version of the Move iota::coin::CoinMetadata type
#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema, Eq, PartialEq)]
pub struct CoinMetadata {
    pub id: UID,
    /// Number of decimal places the coin uses.
    pub decimals: u8,
    /// Name for the token
    pub name: String,
    /// Symbol for the token
    pub symbol: String,
    /// Description of the token
    pub description: String,
    /// URL for the token logo
    pub icon_url: Option<String>,
}

impl CoinMetadata {
    /// Is this other StructTag representing a CoinMetadata?
    pub fn is_coin_metadata(other: &StructTag) -> bool {
        other.address == IOTA_FRAMEWORK_ADDRESS
            && other.module.as_ident_str() == COIN_MODULE_NAME
            && other.name.as_ident_str() == COIN_METADATA_STRUCT_NAME
    }

    /// Create a coin from BCS bytes
    pub fn from_bcs_bytes(content: &[u8]) -> Result<Self, IotaError> {
        bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization {
            error: format!("Unable to deserialize CoinMetadata object: {}", err),
        })
    }

    pub fn type_(type_param: StructTag) -> StructTag {
        StructTag {
            address: IOTA_FRAMEWORK_ADDRESS,
            name: COIN_METADATA_STRUCT_NAME.to_owned(),
            module: COIN_MODULE_NAME.to_owned(),
            type_params: vec![TypeTag::Struct(Box::new(type_param))],
        }
    }

    /// Checks if the provided type is `CoinMetadata<T>`, returning the type T
    /// if so.
    pub fn is_coin_metadata_with_coin_type(other: &StructTag) -> Option<&StructTag> {
        if Self::is_coin_metadata(other) && other.type_params.len() == 1 {
            match other.type_params.first() {
                Some(TypeTag::Struct(coin_type)) => Some(coin_type),
                _ => None,
            }
        } else {
            None
        }
    }
}

impl TryFrom<Object> for CoinMetadata {
    type Error = IotaError;
    fn try_from(object: Object) -> Result<Self, Self::Error> {
        TryFrom::try_from(&object)
    }
}

impl TryFrom<&Object> for CoinMetadata {
    type Error = IotaError;
    fn try_from(object: &Object) -> Result<Self, Self::Error> {
        match &object.data {
            Data::Move(o) => {
                if o.type_().is_coin_metadata() {
                    return CoinMetadata::from_bcs_bytes(o.contents());
                }
            }
            Data::Package(_) => {}
        }

        Err(IotaError::Type {
            error: format!("Object type is not a CoinMetadata: {:?}", object),
        })
    }
}