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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::borrow::Cow;
use colored::{ColoredString, Colorize};
use num_format::{Locale, ToFormattedString};
use prettytable::{format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR, row, Table};
use solana_client::{
nonblocking::rpc_client::RpcClient as Client, rpc_config::RpcTransactionConfig,
};
use solana_sdk::{
address_lookup_table::state::AddressLookupTable,
hash::Hash,
instruction::AccountMeta,
message::VersionedMessage,
transaction::{TransactionVersion, VersionedTransaction},
};
use solana_transaction_status::{
EncodedConfirmedTransactionWithStatusMeta, EncodedTransactionWithStatusMeta,
UiTransactionEncoding, UiTransactionStatusMeta,
};
use crate::{utils::get_network, Transaction};
pub async fn handler(rpc_url: String, transaction: Transaction) {
// Build RPC Client
let client = Client::new(get_network(&rpc_url));
// Fetch transaction
let fetched_transaction = client
.get_transaction_with_config(
&transaction.signature,
RpcTransactionConfig {
encoding: Some(UiTransactionEncoding::Base58),
max_supported_transaction_version: Some(0),
..Default::default()
},
)
.await
.unwrap();
// Parse transaction
let parsed_transaction = parse_transaction(fetched_transaction, &client)
.await
.unwrap();
parsed_transaction.view();
// let EncodedTransactionWithStatusMeta {
// transaction:
// EncodedTransaction::Json(UiTransaction {
// signatures,
// message:
// UiMessage::Raw(UiRawMessage {
// header: _,
// account_keys,
// recent_blockhash: _,
// instructions,
// address_table_lookups: _,
// }),
// }),
// meta:
// Some(UiTransactionStatusMeta {
// err,
// status,
// fee,
// pre_balances,
// post_balances,
// inner_instructions,
// log_messages,
// pre_token_balances,
// post_token_balances,
// rewards,
// loaded_addresses,
// return_data,
// }),
// version: _,
// } = transaction.transaction
// else {
// println!("failed to parse transaction");
// return;
// };
// let mut output = String::new();
// // Print accounts
// let header = "|-------------------- Accounts --------------------|---- Pre-Balances ----|---- Post-Balances ----|";
// output.push_str(header);
// output.push_str("\n");
// for (i, (account, (pre, post))) in account_keys
// .into_iter()
// .zip(pre_balances.into_iter().zip(post_balances))
// .enumerate()
// {
// let (pre_string, post_string) = if pre == post {
// (format!("{pre}").white(), format!("{post}").white())
// } else if pre > post {
// (format!("{pre}").red(), format!("{post}").red())
// } else {
// (format!("{pre}").green(), format!("{post}").green())
// };
// output.push_str(&format!(
// "| {i:>3}: {account:>44}| {pre_string:>20} | {post_string:>21} |\n"
// ))
// }
// output.push_str("|----------------------------------------------- Logs --------------------------------------------|\n");
// output.push_str("| |\n");
// for ref mut message in log_messages.unwrap() {
// if message.len() + 4 > header.len() {
// message.truncate(header.len() - 3);
// message.push_str("...");
// } else {
// while message.len() + 4 < header.len() {
// message.push_str(" ")
// }
// message.push_str(" |");
// }
// output.push_str("| ");
// output.push_str(&message);
// output.push_str("\n");
// }
// output.push_str("|-------------------------------------------------------------------------------------------------|\n");
// // Print accounts
// output.push_str("-------------------- Balances --------------------\n");
// for (i, account) in account_keys.into_iter().enumerate() {
// output.push_str(&format!(" {i:>3}: {account}\n"))
// }
// // Print accounts
// output.push_str("------------------ Instructions ------------------\n");
// for (i, instruction) in instruction.into_iter().enumerate() {
// output.push_str(&format!(" {i:>3}: {account}\n"))
// }
// println!("{output}");
}
async fn parse_transaction(
transaction: EncodedConfirmedTransactionWithStatusMeta,
client: &Client,
) -> Option<ParsedTransaction> {
let EncodedConfirmedTransactionWithStatusMeta {
slot,
transaction:
EncodedTransactionWithStatusMeta {
transaction: encoded_transaction,
meta,
version,
},
block_time,
} = transaction;
let Some(meta) = meta else {
// TODO
return None;
};
let Some(time) = block_time else {
// TODO
return None;
};
let Some(version) = version else {
// TODO
return None;
};
// Decode transaction
let VersionedTransaction {
signatures: _,
message,
} = encoded_transaction
.decode()
.expect("TODO: failed to decode error");
// Get accounts
let accounts = match &message {
VersionedMessage::Legacy(legacy) => {
// Legacy only has static accounts
let accounts = legacy
.account_keys
.iter()
.enumerate()
.map(|(idx, &account)| {
if legacy.is_writable(idx) {
AccountMeta::new(account, legacy.is_signer(idx))
} else {
AccountMeta::new_readonly(account, legacy.is_signer(idx))
}
})
.collect();
// Legacy only has static accounts
accounts
}
VersionedMessage::V0(v0) => {
// Start with static accounts
let mut accounts: Vec<AccountMeta> = v0
.account_keys
.iter()
.enumerate()
.map(|(idx, &account)| {
if v0.is_maybe_writable(idx) {
AccountMeta::new(account, message.is_signer(idx))
} else {
AccountMeta::new_readonly(account, message.is_signer(idx))
}
})
.collect();
// Then, try account lookups
// (this may fail if lookup table is deactivated and closed)
if let Some(lookups) = message.address_table_lookups() {
for lookup in lookups {
// Fetch and try deserialize
match client
.get_account_data(&lookup.account_key)
.await
.as_deref()
.map(AddressLookupTable::deserialize)
{
// If fetch + deserialize succeeded, perform lookups.
// Lookups cannot be signers.
Ok(Ok(alt)) => {
// Write accounts
for &idx in &lookup.writable_indexes {
accounts.push(AccountMeta::new(alt.addresses[idx as usize], false))
}
// Read accounts
for &idx in &lookup.readonly_indexes {
accounts.push(AccountMeta::new_readonly(
alt.addresses[idx as usize],
false,
))
}
}
e => {
println!(
"failed to perform lookup for table {}: {e:#?}",
lookup.account_key
);
}
}
}
}
accounts
}
};
// First, static accounts
Some(ParsedTransaction {
meta,
time,
accounts,
slot,
version,
blockhash: *message.recent_blockhash(),
})
}
pub struct ParsedTransaction {
meta: UiTransactionStatusMeta,
accounts: Vec<AccountMeta>,
blockhash: Hash,
slot: u64,
version: TransactionVersion,
time: i64,
}
impl ParsedTransaction {
fn view(self) {
// Create status table
let mut status_table = Table::new();
status_table.set_titles(row![
c-> "Transaction Overview",
]);
let result = if self.meta.status.is_ok() {
"SUCCESS".green()
} else {
"FAILURE".red()
};
let cus: u64 = Option::unwrap(self.meta.compute_units_consumed.into());
status_table.add_row(row!["Result", result]);
status_table.add_row(row!["Slot", self.slot]);
status_table.add_row(row!["Timestamp", self.time]);
status_table.add_row(row!["Fee", format_fee(self.meta.fee)]);
status_table.add_row(row!["Version", format_version(&self.version)]);
status_table.add_row(row!["Recent Blockhash", self.blockhash.to_string()]);
status_table.add_row(row![
"Compute Units Consumed",
cus.to_formatted_string(&Locale::en)
]);
// Create accounts table
let mut accounts_table = Table::new();
let accounts_iter = self.accounts.iter();
let pre_balances_iter = self.meta.pre_balances.iter();
let post_balances_iter = self.meta.post_balances.iter();
accounts_table.set_titles(row![
c->"Accounts",
c->"Signer",
c->"Writable",
c->"Pre-Balances",
c->"Post-balances"
]);
let sgn = |account: &AccountMeta| {
if account.is_signer {
"TRUE".green()
} else {
"FALSE".red()
}
};
let wrt = |account: &AccountMeta| {
if account.is_writable {
"TRUE".green()
} else {
"FALSE".red()
}
};
for (account, (pre, post)) in accounts_iter.zip(pre_balances_iter.zip(post_balances_iter)) {
accounts_table.add_row(row![
account.pubkey.to_string(),
sgn(account),
wrt(account),
format_pre_post(pre, pre, post),
format_pre_post(post, pre, post),
]);
}
// TODO: Token Accounts pre/post
let mut _token_accounts = Table::new();
// TODO: Instructions table
let mut _instructions_table = Table::new();
// Get terminal size for newlines
use terminal_size::{terminal_size, Width};
let size = terminal_size();
let width = size
.map(|(Width(w), _height)| w as usize)
.unwrap_or(32)
.saturating_sub(6);
// Create logs table
let mut logs_table = Table::new();
logs_table.set_titles(row![c->"Program Logs"]);
let opt_log_messages: Option<Vec<String>> = self.meta.log_messages.into();
if let Some(log_msgs) = opt_log_messages {
for log in log_msgs {
// let mut rem: &str = &log;
// let mut curr = rem;
// while rem.len() > LOG_MAX_WIDTH {
// (curr, rem) = rem.split_at(LOG_MAX_WIDTH);
// // logs_table.add_row(row)
// }
// curr = rem;
// logs_table.add_row(row![log]);
logs_table.add_row(row![insert_newlines(&log, width)]);
}
}
// Print the table to stdout
let mut table_of_tables = Table::new();
table_of_tables.add_row(row![c->status_table]);
table_of_tables.add_row(row![c->accounts_table]);
table_of_tables.add_row(row![c->logs_table]);
table_of_tables.set_format(*FORMAT_NO_BORDER_LINE_SEPARATOR);
table_of_tables.printstd();
}
}
#[inline(always)]
fn insert_newlines(s: &str, n: usize) -> String {
let mut result = String::new();
let mut counter = 0;
for c in s.chars() {
if counter == n {
result.push('\n');
counter = 0;
}
result.push(c);
counter += 1;
}
result
}
#[inline(always)]
fn format_fee(fee_lamports: u64) -> String {
let floating = fee_lamports as f64 / 1e9;
format!("◎{floating}")
}
#[inline(always)]
fn format_version(version: &TransactionVersion) -> Cow<'static, str> {
match version {
TransactionVersion::Legacy(_) => Cow::Borrowed("Legacy"),
TransactionVersion::Number(n) => Cow::Owned(n.to_string()),
}
}
#[inline(always)]
fn format_pre_post(current: &u64, pre: &u64, post: &u64) -> ColoredString {
if pre > post {
current.to_formatted_string(&Locale::en).red()
} else if pre < post {
current.to_formatted_string(&Locale::en).green()
} else {
current.to_formatted_string(&Locale::en).into()
}
}