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::ChildObjectResolver,
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    child_object_resolver: &dyn ChildObjectResolver,
14    currency_type: TypeTag,
15) -> SuiResult<u64> {
16    let balance_type = Balance::type_tag(currency_type);
17    let address_balance =
18        AccumulatorValue::load(child_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}
38
39/// Get all balances and corresponding currency types for a given owner address
40/// (which can be a wallet or an object)
41pub fn get_all_balances_for_owner(
42    owner: SuiAddress,
43    child_object_resolver: &dyn ChildObjectResolver,
44    index_store: &crate::jsonrpc_index::IndexStore,
45) -> SuiResult<Vec<(TypeTag, u64)>> {
46    let currency_types = index_store.get_address_balance_coin_types_iter(owner);
47    let mut balances = Vec::new();
48    for currency_type in currency_types {
49        let balance = get_balance(owner, child_object_resolver, currency_type.clone())?;
50        balances.push((currency_type, balance));
51    }
52    Ok(balances)
53}