sui_types/
balance.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::SUI_FRAMEWORK_ADDRESS;
5use crate::error::{ExecutionError, ExecutionErrorKind};
6use crate::sui_serde::BigInt;
7use crate::sui_serde::Readable;
8use move_core_types::account_address::AccountAddress;
9use move_core_types::annotated_value::{MoveFieldLayout, MoveStructLayout, MoveTypeLayout};
10use move_core_types::ident_str;
11use move_core_types::identifier::IdentStr;
12use move_core_types::language_storage::{StructTag, TypeTag};
13use schemars::JsonSchema;
14use serde::Deserialize;
15use serde::Serialize;
16use serde_with::serde_as;
17
18pub const SUI_MODULE_NAME: &IdentStr = ident_str!("sui");
19pub const BALANCE_MODULE_NAME: &IdentStr = ident_str!("balance");
20pub const BALANCE_STRUCT_NAME: &IdentStr = ident_str!("Balance");
21pub const RESOLVED_BALANCE_STRUCT: (&AccountAddress, &IdentStr, &IdentStr) = (
22    &SUI_FRAMEWORK_ADDRESS,
23    BALANCE_MODULE_NAME,
24    BALANCE_STRUCT_NAME,
25);
26pub const BALANCE_CREATE_REWARDS_FUNCTION_NAME: &IdentStr = ident_str!("create_staking_rewards");
27pub const BALANCE_DESTROY_REBATES_FUNCTION_NAME: &IdentStr = ident_str!("destroy_storage_rebates");
28
29pub const BALANCE_REDEEM_FUNDS_FUNCTION_NAME: &IdentStr = ident_str!("redeem_funds");
30pub const BALANCE_SEND_FUNDS_FUNCTION_NAME: &IdentStr = ident_str!("send_funds");
31#[serde_as]
32#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, JsonSchema)]
33pub struct Supply {
34    #[schemars(with = "BigInt<u64>")]
35    #[serde_as(as = "Readable<BigInt<u64>, _>")]
36    pub value: u64,
37}
38
39#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema, Eq, PartialEq)]
40pub struct Balance {
41    value: u64,
42}
43
44impl Balance {
45    pub fn new(value: u64) -> Self {
46        Self { value }
47    }
48
49    pub fn type_(type_param: TypeTag) -> StructTag {
50        StructTag {
51            address: SUI_FRAMEWORK_ADDRESS,
52            module: BALANCE_MODULE_NAME.to_owned(),
53            name: BALANCE_STRUCT_NAME.to_owned(),
54            type_params: vec![type_param],
55        }
56    }
57
58    pub fn type_tag(type_param: TypeTag) -> TypeTag {
59        TypeTag::Struct(Box::new(Self::type_(type_param)))
60    }
61
62    pub fn is_balance(s: &StructTag) -> bool {
63        s.address == SUI_FRAMEWORK_ADDRESS
64            && s.module.as_ident_str() == BALANCE_MODULE_NAME
65            && s.name.as_ident_str() == BALANCE_STRUCT_NAME
66    }
67
68    pub fn is_balance_type(type_param: &TypeTag) -> bool {
69        if let TypeTag::Struct(struct_tag) = type_param {
70            Self::is_balance(struct_tag)
71        } else {
72            false
73        }
74    }
75
76    /// If the given type is `Balance<T>`, return `Some(T)`.
77    pub fn maybe_get_balance_type_param(ty: &TypeTag) -> Option<TypeTag> {
78        if let TypeTag::Struct(struct_tag) = ty
79            && Self::is_balance(struct_tag)
80        {
81            assert_eq!(struct_tag.type_params.len(), 1);
82            return Some(struct_tag.type_params[0].clone());
83        }
84        None
85    }
86
87    pub fn withdraw(&mut self, amount: u64) -> Result<(), ExecutionError> {
88        fp_ensure!(
89            self.value >= amount,
90            ExecutionError::new_with_source(
91                ExecutionErrorKind::InsufficientCoinBalance,
92                format!("balance: {} required: {}", self.value, amount)
93            )
94        );
95        self.value -= amount;
96        Ok(())
97    }
98
99    pub fn deposit_for_safe_mode(&mut self, amount: u64) {
100        self.value += amount;
101    }
102
103    pub fn value(&self) -> u64 {
104        self.value
105    }
106
107    pub fn to_bcs_bytes(&self) -> Vec<u8> {
108        bcs::to_bytes(&self).unwrap()
109    }
110
111    pub fn layout(type_param: TypeTag) -> MoveStructLayout {
112        MoveStructLayout {
113            type_: Self::type_(type_param),
114            fields: vec![MoveFieldLayout::new(
115                ident_str!("value").to_owned(),
116                MoveTypeLayout::U64,
117            )],
118        }
119    }
120
121    /// Check if a struct layout represents a `Balance<T>` type with the expected field structure.
122    pub fn is_balance_layout(struct_layout: &MoveStructLayout) -> bool {
123        let ty = &struct_layout.type_;
124
125        if !Self::is_balance(ty) {
126            return false;
127        }
128
129        if ty.type_params.len() != 1 {
130            return false;
131        }
132
133        if struct_layout.fields.len() != 1 {
134            return false;
135        }
136
137        let Some(field) = struct_layout.fields.first() else {
138            return false;
139        };
140
141        if field.name.as_str() != "value" {
142            return false;
143        }
144
145        if !matches!(field.layout, MoveTypeLayout::U64) {
146            return false;
147        }
148
149        true
150    }
151}