Skip to main content

iota_sdk_types/
framework.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2025 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5//! Rust definitions of move/iota framework types.
6
7use super::{Object, ObjectId, TypeTag};
8
9#[derive(Clone, Debug)]
10pub struct Coin {
11    coin_type: TypeTag,
12    id: ObjectId,
13    balance: u64,
14}
15
16impl Coin {
17    pub fn coin_type(&self) -> &TypeTag {
18        &self.coin_type
19    }
20
21    pub fn id(&self) -> &ObjectId {
22        &self.id
23    }
24
25    pub fn balance(&self) -> u64 {
26        self.balance
27    }
28
29    pub fn try_from_object(object: &Object) -> Result<Self, CoinFromObjectError> {
30        match &object.data {
31            super::ObjectData::Struct(move_struct) => {
32                let coin_type = move_struct
33                    .object_type()
34                    .opt_coin_type()
35                    .ok_or(CoinFromObjectError::NotACoin)?;
36
37                let contents = move_struct.contents();
38                if contents.len() != ObjectId::LENGTH + std::mem::size_of::<u64>() {
39                    return Err(CoinFromObjectError::InvalidContentLength);
40                }
41
42                let balance =
43                    u64::from_le_bytes((&contents[ObjectId::LENGTH..]).try_into().unwrap());
44
45                Ok(Self {
46                    coin_type: coin_type.clone(),
47                    id: move_struct.id(),
48                    balance,
49                })
50            }
51            _ => Err(CoinFromObjectError::NotACoin), // package
52        }
53    }
54}
55
56impl crate::TreeDisplay for Coin {
57    fn fmt_tree(&self, w: &mut crate::TreeWriter<'_, '_>) -> std::fmt::Result {
58        w.header("Coin")?;
59        w.leaf("Coin Type", &self.coin_type, false)?;
60        w.leaf("ID", &self.id, false)?;
61        w.leaf("Balance", &self.balance, true)
62    }
63}
64
65crate::impl_tree_display!(Coin);
66
67#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
68#[non_exhaustive]
69pub enum CoinFromObjectError {
70    #[error("not a coin")]
71    NotACoin,
72    #[error("invalid content length")]
73    InvalidContentLength,
74}
75
76impl CoinFromObjectError {
77    crate::def_is!(NotACoin, InvalidContentLength);
78}