sui_graphql_rpc/types/
balance_change.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use async_graphql::*;
5use sui_json_rpc_types::BalanceChange as StoredBalanceChange;
6use sui_types::object::Owner as NativeOwner;
7
8use super::{big_int::BigInt, move_type::MoveType, owner::Owner, sui_address::SuiAddress};
9use crate::error::Error;
10
11pub(crate) struct BalanceChange {
12    stored: StoredBalanceChange,
13    /// The checkpoint sequence number this was viewed at.
14    checkpoint_viewed_at: u64,
15}
16
17/// Effects to the balance (sum of coin values per coin type) owned by an address or object.
18#[Object]
19impl BalanceChange {
20    /// The address or object whose balance has changed.
21    async fn owner(&self) -> Option<Owner> {
22        use NativeOwner as O;
23
24        match self.stored.owner {
25            O::AddressOwner(addr)
26            | O::ObjectOwner(addr)
27            | O::ConsensusAddressOwner { owner: addr, .. } => Some(Owner {
28                address: SuiAddress::from(addr),
29                checkpoint_viewed_at: self.checkpoint_viewed_at,
30                root_version: None,
31            }),
32
33            O::Shared { .. } | O::Immutable => None,
34        }
35    }
36
37    /// The inner type of the coin whose balance has changed (e.g. `0x2::sui::SUI`).
38    async fn coin_type(&self) -> Option<MoveType> {
39        Some(self.stored.coin_type.clone().into())
40    }
41
42    /// The signed balance change.
43    async fn amount(&self) -> Option<BigInt> {
44        Some(BigInt::from(self.stored.amount))
45    }
46}
47
48impl BalanceChange {
49    /// `checkpoint_viewed_at` represents the checkpoint sequence number at which this
50    /// `BalanceChange` was queried for. This is stored on `BalanceChange` so that when viewing that
51    /// entity's state, it will be as if it was read at the same checkpoint.
52    pub(crate) fn read(bytes: &[u8], checkpoint_viewed_at: u64) -> Result<Self, Error> {
53        let stored = bcs::from_bytes(bytes)
54            .map_err(|e| Error::Internal(format!("Error deserializing BalanceChange: {e}")))?;
55
56        Ok(Self {
57            stored,
58            checkpoint_viewed_at,
59        })
60    }
61}