sui_types/
balance_change.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use crate::base_types::SuiAddress;
use crate::coin::Coin;
use crate::effects::TransactionEffects;
use crate::effects::TransactionEffectsAPI;
use crate::full_checkpoint_content::ObjectSet;
use crate::object::Object;
use crate::object::Owner;
use crate::storage::ObjectKey;
use move_core_types::language_storage::TypeTag;

#[derive(Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct BalanceChange {
    /// Owner of the balance change
    pub address: SuiAddress,

    /// Type of the Coin
    pub coin_type: TypeTag,

    /// The amount indicate the balance value changes.
    ///
    /// A negative amount means spending coin value and positive means receiving coin value.
    pub amount: i128,
}

impl std::fmt::Debug for BalanceChange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BalanceChange")
            .field("address", &self.address)
            .field("coin_type", &self.coin_type.to_canonical_string(true))
            .field("amount", &self.amount)
            .finish()
    }
}

fn coins(objects: &[Object]) -> impl Iterator<Item = (&SuiAddress, TypeTag, u64)> + '_ {
    objects.iter().filter_map(|object| {
        let address = match object.owner() {
            Owner::AddressOwner(sui_address)
            | Owner::ObjectOwner(sui_address)
            | Owner::ConsensusAddressOwner {
                owner: sui_address, ..
            } => sui_address,
            Owner::Shared { .. } | Owner::Immutable => return None,
        };
        let (coin_type, balance) = Coin::extract_balance_if_coin(object).ok().flatten()?;
        Some((address, coin_type, balance))
    })
}

pub fn derive_balance_changes(
    _effects: &TransactionEffects,
    input_objects: &[Object],
    output_objects: &[Object],
) -> Vec<BalanceChange> {
    // 1. subtract all input coins
    let balances = coins(input_objects).fold(
        std::collections::BTreeMap::<_, i128>::new(),
        |mut acc, (address, coin_type, balance)| {
            *acc.entry((address, coin_type)).or_default() -= balance as i128;
            acc
        },
    );

    // 2. add all mutated/output coins
    let balances =
        coins(output_objects).fold(balances, |mut acc, (address, coin_type, balance)| {
            *acc.entry((address, coin_type)).or_default() += balance as i128;
            acc
        });

    balances
        .into_iter()
        .filter_map(|((address, coin_type), amount)| {
            if amount == 0 {
                return None;
            }

            Some(BalanceChange {
                address: *address,
                coin_type,
                amount,
            })
        })
        .collect()
}

pub fn derive_balance_changes_2(
    effects: &TransactionEffects,
    objects: &ObjectSet,
) -> Vec<BalanceChange> {
    let input_objects = effects
        .modified_at_versions()
        .into_iter()
        .filter_map(|(object_id, version)| objects.get(&ObjectKey(object_id, version)).cloned())
        .collect::<Vec<_>>();
    let output_objects = effects
        .all_changed_objects()
        .into_iter()
        .filter_map(|(object_ref, _owner, _kind)| objects.get(&object_ref.into()).cloned())
        .collect::<Vec<_>>();

    // 1. subtract all input coins
    let balances = coins(&input_objects).fold(
        std::collections::BTreeMap::<_, i128>::new(),
        |mut acc, (address, coin_type, balance)| {
            *acc.entry((address, coin_type)).or_default() -= balance as i128;
            acc
        },
    );

    // 2. add all mutated/output coins
    let balances =
        coins(&output_objects).fold(balances, |mut acc, (address, coin_type, balance)| {
            *acc.entry((address, coin_type)).or_default() += balance as i128;
            acc
        });

    balances
        .into_iter()
        .filter_map(|((address, coin_type), amount)| {
            if amount == 0 {
                return None;
            }

            Some(BalanceChange {
                address: *address,
                coin_type,
                amount,
            })
        })
        .collect()
}