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(Debug, Clone)]
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                    .type_
34                    .coin_type_opt()
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 id = ObjectId::new((&contents[..ObjectId::LENGTH]).try_into().unwrap());
43                let balance =
44                    u64::from_le_bytes((&contents[ObjectId::LENGTH..]).try_into().unwrap());
45
46                Ok(Self {
47                    coin_type: coin_type.clone(),
48                    id,
49                    balance,
50                })
51            }
52            _ => Err(CoinFromObjectError::NotACoin), // package
53        }
54    }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum CoinFromObjectError {
59    NotACoin,
60    InvalidContentLength,
61}
62
63impl CoinFromObjectError {
64    crate::def_is!(NotACoin, InvalidContentLength);
65}
66
67impl std::fmt::Display for CoinFromObjectError {
68    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
69        match self {
70            CoinFromObjectError::NotACoin => write!(f, "not a coin"),
71            CoinFromObjectError::InvalidContentLength => write!(f, "invalid content length"),
72        }
73    }
74}
75
76impl std::error::Error for CoinFromObjectError {}