sui_sdk_types/
framework.rs

1//! Rust definitions of move/sui framework types.
2
3use super::Object;
4use super::ObjectId;
5use super::TypeTag;
6use std::borrow::Cow;
7
8#[derive(Debug, Clone)]
9pub struct Coin<'a> {
10    coin_type: Cow<'a, TypeTag>,
11    id: ObjectId,
12    balance: u64,
13}
14
15impl<'a> Coin<'a> {
16    pub fn coin_type(&self) -> &TypeTag {
17        &self.coin_type
18    }
19
20    pub fn id(&self) -> &ObjectId {
21        &self.id
22    }
23
24    pub fn balance(&self) -> u64 {
25        self.balance
26    }
27
28    pub fn try_from_object(object: &'a Object) -> Option<Self> {
29        match &object.data {
30            super::ObjectData::Struct(move_struct) => {
31                let coin_type = move_struct.type_.is_coin()?;
32
33                let contents = &move_struct.contents;
34                if contents.len() != ObjectId::LENGTH + std::mem::size_of::<u64>() {
35                    return None;
36                }
37
38                let id = ObjectId::new((&contents[..ObjectId::LENGTH]).try_into().unwrap());
39                let balance =
40                    u64::from_le_bytes((&contents[ObjectId::LENGTH..]).try_into().unwrap());
41
42                Some(Self {
43                    coin_type: Cow::Borrowed(coin_type),
44                    id,
45                    balance,
46                })
47            }
48            _ => None, // package
49        }
50    }
51
52    pub fn into_owned(self) -> Coin<'static> {
53        Coin {
54            coin_type: Cow::Owned(self.coin_type.into_owned()),
55            id: self.id,
56            balance: self.balance,
57        }
58    }
59}