Skip to main content

kaspa_cli_lib/extensions/
transaction.rs

1use crate::imports::*;
2use kaspa_consensus_core::tx::{TransactionInput, TransactionOutpoint};
3use kaspa_wallet_core::storage::Binding;
4use kaspa_wallet_core::storage::{TransactionData, TransactionKind, TransactionRecord};
5use kaspa_wallet_core::wallet::WalletGuard;
6use workflow_log::style;
7
8pub trait TransactionTypeExtension {
9    fn style(&self, s: &str) -> String;
10    fn style_with_sign(&self, s: &str, history: bool) -> String;
11}
12
13impl TransactionTypeExtension for TransactionKind {
14    fn style(&self, s: &str) -> String {
15        match self {
16            TransactionKind::Incoming => style(s).green().to_string(),
17            TransactionKind::Outgoing => style(s).red().to_string(),
18            TransactionKind::External => style(s).red().to_string(),
19            TransactionKind::Batch => style(s).dim().to_string(),
20            TransactionKind::Reorg => style(s).dim().to_string(),
21            TransactionKind::Stasis => style(s).dim().to_string(),
22            TransactionKind::TransferIncoming => style(s).green().to_string(),
23            TransactionKind::TransferOutgoing => style(s).red().to_string(),
24            TransactionKind::Change => style(s).dim().to_string(),
25        }
26    }
27
28    fn style_with_sign(&self, s: &str, history: bool) -> String {
29        match self {
30            TransactionKind::Incoming => style("+".to_string() + s).green().to_string(),
31            TransactionKind::TransferIncoming => style("+".to_string() + s).green().to_string(),
32            TransactionKind::Outgoing => style("-".to_string() + s).red().to_string(),
33            TransactionKind::TransferOutgoing => style("-".to_string() + s).red().to_string(),
34            TransactionKind::External => style("-".to_string() + s).red().to_string(),
35            TransactionKind::Batch => style("".to_string() + s).dim().to_string(),
36            TransactionKind::Reorg => {
37                { if history { style("".to_string() + s).dim() } else { style("-".to_string() + s).red() } }.to_string()
38            }
39            TransactionKind::Stasis => style("".to_string() + s).dim().to_string(),
40            _ => style(s).dim().to_string(),
41        }
42    }
43}
44
45#[async_trait]
46pub trait TransactionExtension {
47    async fn format_transaction(&self, wallet: &Arc<Wallet>, include_utxos: bool, guard: &WalletGuard) -> Vec<String>;
48    async fn format_transaction_with_state(
49        &self,
50        wallet: &Arc<Wallet>,
51        state: Option<&str>,
52        include_utxos: bool,
53        guard: &WalletGuard,
54    ) -> Vec<String>;
55    async fn format_transaction_with_args(
56        &self,
57        wallet: &Arc<Wallet>,
58        state: Option<&str>,
59        current_daa_score: Option<u64>,
60        include_utxos: bool,
61        history: bool,
62        account: Option<Arc<dyn Account>>,
63        guard: &WalletGuard,
64    ) -> Vec<String>;
65}
66
67#[async_trait]
68impl TransactionExtension for TransactionRecord {
69    async fn format_transaction(&self, wallet: &Arc<Wallet>, include_utxos: bool, guard: &WalletGuard) -> Vec<String> {
70        self.format_transaction_with_args(wallet, None, None, include_utxos, false, None, guard).await
71    }
72
73    async fn format_transaction_with_state(
74        &self,
75        wallet: &Arc<Wallet>,
76        state: Option<&str>,
77        include_utxos: bool,
78        guard: &WalletGuard,
79    ) -> Vec<String> {
80        self.format_transaction_with_args(wallet, state, None, include_utxos, false, None, guard).await
81    }
82
83    async fn format_transaction_with_args(
84        &self,
85        wallet: &Arc<Wallet>,
86        state: Option<&str>,
87        current_daa_score: Option<u64>,
88        include_utxos: bool,
89        history: bool,
90        account: Option<Arc<dyn Account>>,
91        guard: &WalletGuard,
92    ) -> Vec<String> {
93        let TransactionRecord { id, binding, block_daa_score, transaction_data, .. } = self;
94
95        let name = match binding {
96            Binding::Custom(id) => style(id.short()).cyan(),
97            Binding::Account(account_id) => {
98                let account = if let Some(account) = account {
99                    Some(account)
100                } else {
101                    wallet.get_account_by_id(account_id, guard).await.ok().flatten()
102                };
103
104                if let Some(account) = account {
105                    style(account.name_with_id()).cyan()
106                } else {
107                    style(account_id.short() + " ??").magenta()
108                }
109            }
110        };
111
112        let transaction_type = transaction_data.kind();
113        let kind = transaction_type.style(&transaction_type.to_string());
114
115        let maturity = current_daa_score.map(|score| self.maturity(score).to_string()).unwrap_or_default();
116
117        let block_daa_score = block_daa_score.separated_string();
118        let state = state.unwrap_or(&maturity);
119        let mut lines = vec![format!("{name} {id} @{block_daa_score} DAA - {kind} {state}")];
120
121        let suffix = kaspa_suffix(&self.network_id.network_type);
122
123        match transaction_data {
124            TransactionData::Reorg { utxo_entries, aggregate_input_value }
125            | TransactionData::Stasis { utxo_entries, aggregate_input_value }
126            | TransactionData::Incoming { utxo_entries, aggregate_input_value }
127            | TransactionData::External { utxo_entries, aggregate_input_value }
128            | TransactionData::Change { utxo_entries, aggregate_input_value, .. } => {
129                let aggregate_input_value =
130                    transaction_type.style_with_sign(sompi_to_kaspa_string(*aggregate_input_value).as_str(), history);
131                lines.push(format!("{:>4}UTXOs: {}  Total: {}", "", utxo_entries.len(), aggregate_input_value));
132                if include_utxos {
133                    for utxo_entry in utxo_entries {
134                        let address =
135                            style(utxo_entry.address.as_ref().map(|addr| addr.to_string()).unwrap_or_else(|| "n/a".to_string()))
136                                .blue();
137                        let index = utxo_entry.index;
138                        let is_coinbase = if utxo_entry.is_coinbase {
139                            style(format!("coinbase utxo [{index}]")).dim()
140                        } else {
141                            style(format!("standard utxo [{index}]")).dim()
142                        };
143                        let amount = transaction_type.style_with_sign(sompi_to_kaspa_string(utxo_entry.amount).as_str(), history);
144
145                        lines.push(format!("{:>4}{address}", ""));
146                        lines.push(format!("{:>4}{amount} {suffix} {is_coinbase}", ""));
147                    }
148                }
149            }
150            TransactionData::Outgoing { fees, aggregate_input_value, transaction, payment_value, change_value, .. }
151            | TransactionData::Batch { fees, aggregate_input_value, transaction, payment_value, change_value, .. }
152            | TransactionData::TransferIncoming { fees, aggregate_input_value, transaction, payment_value, change_value, .. }
153            | TransactionData::TransferOutgoing { fees, aggregate_input_value, transaction, payment_value, change_value, .. } => {
154                if let Some(payment_value) = payment_value {
155                    lines.push(format!(
156                        "{:>4}Payment: {}  Used: {}  Fees: {}  Change: {}  UTXOs: [{}↠{}]",
157                        "",
158                        style(sompi_to_kaspa_string(*payment_value)).red(),
159                        style(sompi_to_kaspa_string(*aggregate_input_value)).blue(),
160                        style(sompi_to_kaspa_string(*fees)).red(),
161                        style(sompi_to_kaspa_string(*change_value)).green(),
162                        transaction.inputs.len(),
163                        transaction.outputs.len(),
164                    ));
165                } else {
166                    lines.push(format!(
167                        "{:>4}Sweep: {}  Fees: {}  Change: {}  UTXOs: [{}↠{}]",
168                        "",
169                        style(sompi_to_kaspa_string(*aggregate_input_value)).blue(),
170                        style(sompi_to_kaspa_string(*fees)).red(),
171                        style(sompi_to_kaspa_string(*change_value)).green(),
172                        transaction.inputs.len(),
173                        transaction.outputs.len(),
174                    ));
175                }
176
177                if include_utxos {
178                    for input in transaction.inputs.iter() {
179                        let TransactionInput { previous_outpoint, signature_script: _, sequence, .. } = input;
180                        let TransactionOutpoint { transaction_id, index } = previous_outpoint;
181                        let sig_op_count = input.compute_commit.sig_op_count().unwrap_or(0);
182
183                        lines.push(format!("{:>4}{sequence:>2}: {transaction_id}:{index} SigOps: {sig_op_count}", ""));
184                    }
185                }
186            }
187        }
188
189        lines
190    }
191}