Skip to main content

sui_core/accumulators/
balances.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use sui_types::{
5    TypeTag, accumulator_root::AccumulatorValue, balance::Balance, base_types::SuiAddress,
6    error::SuiResult, storage::RuntimeObjectResolver,
7};
8
9/// Get the balance for a given owner address (which can be a wallet or an object)
10/// and currency type (e.g. 0x2::sui::SUI)
11pub fn get_balance(
12    owner: SuiAddress,
13    runtime_object_resolver: &dyn RuntimeObjectResolver,
14    currency_type: TypeTag,
15) -> SuiResult<u64> {
16    let balance_type = Balance::type_tag(currency_type);
17    let address_balance =
18        AccumulatorValue::load(runtime_object_resolver, None, owner, &balance_type)?
19            .and_then(|b| b.as_u128())
20            .unwrap_or(0);
21
22    let u64_balance = if address_balance > u64::MAX as u128 {
23        // This will not happen with normal currency types which have a max supply of u64::MAX
24        // But you can create "fake" supplies (with no metadata or treasury cap) and overlow
25        // the u64 limit.
26        tracing::warn!(
27            "address balance for {} {} is greater than u64::MAX",
28            owner,
29            balance_type.to_canonical_string(true)
30        );
31        u64::MAX
32    } else {
33        address_balance as u64
34    };
35
36    Ok(u64_balance)
37}