iota_graphql_rpc/types/
balance_change.rs

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