sui_indexer_alt_jsonrpc/data/
tx_balance_changes.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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::{BTreeSet, HashMap},
    sync::Arc,
};

use async_graphql::dataloader::Loader;
use diesel::{ExpressionMethods, JoinOnDsl, QueryDsl, SelectableHelper};
use sui_indexer_alt_schema::{
    schema::{tx_balance_changes, tx_digests},
    transactions::StoredTxBalanceChange,
};
use sui_types::digests::TransactionDigest;

use crate::data::error::Error;

use super::pg_reader::PgReader;

/// Key for fetching a transaction's balance changes by digest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct TxBalanceChangeKey(pub TransactionDigest);

#[async_trait::async_trait]
impl Loader<TxBalanceChangeKey> for PgReader {
    type Value = StoredTxBalanceChange;
    type Error = Arc<Error>;

    async fn load(
        &self,
        keys: &[TxBalanceChangeKey],
    ) -> Result<HashMap<TxBalanceChangeKey, Self::Value>, Self::Error> {
        use tx_balance_changes::dsl as b;
        use tx_digests::dsl as t;

        if keys.is_empty() {
            return Ok(HashMap::new());
        }

        let mut conn = self.connect().await.map_err(Arc::new)?;

        let digests: BTreeSet<_> = keys.iter().map(|d| d.0.into_inner()).collect();
        let balance_changes: Vec<(Vec<u8>, StoredTxBalanceChange)> = conn
            .results(
                b::tx_balance_changes
                    .inner_join(t::tx_digests.on(b::tx_sequence_number.eq(t::tx_sequence_number)))
                    .select((t::tx_digest, StoredTxBalanceChange::as_select()))
                    .filter(t::tx_digest.eq_any(digests)),
            )
            .await
            .map_err(Arc::new)?;

        let digest_to_balance_changes: HashMap<_, _> = balance_changes.into_iter().collect();

        Ok(keys
            .iter()
            .filter_map(|key| {
                let slice: &[u8] = key.0.as_ref();
                Some((*key, digest_to_balance_changes.get(slice).cloned()?))
            })
            .collect())
    }
}