forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.rs
More file actions
633 lines (594 loc) Β· 27.1 KB
/
Copy pathhandlers.rs
File metadata and controls
633 lines (594 loc) Β· 27.1 KB
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use crate::chains::factory::ChainFactory;
use crate::chains::traits::ChainAdapter;
use crate::cli::parser::{ChainCommand, Cli, Commands, ConfigAction, DbAction};
use crate::utils;
use anyhow::{Result, anyhow};
use colored::*;
use futures::stream::StreamExt;
use mongodb::bson::doc;
use mongodb::bson::Document;
use mongodb::bson::oid::ObjectId;
use mongodb::options::FindOptions;
use serde_json::Value;
use std::sync::Arc;
use txio_api::dtos::request::LoginRequest;
use txio_api::dtos::response::AuthResponse;
use txio_api::infra::db::{describe_connection_error, establish_connection};
use txio_api::model::rpc::RpcLog;
use txio_api::repositories::rpc_repository::RpcRepository;
use txio_api::repositories::user_repository::UserRepository;
use txio_api::utils::auth_jwt::JwtHelper;
use txio_api::utils::config::Config;
use dialoguer::{Confirm, Input, Password};
use std::str::FromStr;
pub struct CommandHandler;
impl CommandHandler {
pub async fn handle(cli: Cli) -> Result<()> {
match cli.command {
Commands::Chains => {
println!("{}", "Supported Blockchains:".bold().cyan());
for chain in ChainFactory::list_chains() {
println!(" - {}", chain.green());
}
}
Commands::Switch { chain } => {
if ChainFactory::list_chains().contains(&chain.to_lowercase().as_str()) {
utils::save_current_chain(&chain.to_lowercase())?;
println!(
"{} Switched default chain to {}",
"β".green(),
chain.bold().cyan()
);
} else {
let msg = format!("Unknown chain '{}'", chain);
let suggestion = ChainFactory::suggest_chain(&chain);
if let Some(s) = suggestion {
println!("{} {} \n\nDid you mean:\n {}", "β".red(), msg, s.green());
} else {
println!("{} {}", "β".red(), msg);
}
}
}
Commands::Login => {
Self::handle_login().await?;
}
Commands::Logout => {
utils::remove_token()?;
println!("{} Logged out successfully.", "β".green());
}
Commands::Status => {
let chain = utils::get_current_chain().unwrap_or_else(|| "sui".to_string());
let logged_in = utils::get_token().is_some();
println!("{}", "βββ txio Status βββ".bold().cyan());
println!(" {} Default chain: {}", "Β»".dimmed(), chain.green().bold());
println!(" {} Network: {}", "Β»".dimmed(), format!("{:?}", cli.network).yellow());
println!(" {} Authenticated: {}", "Β»".dimmed(),
if logged_in { "Yes".green().bold() } else { "No".red().bold() }
);
if let Ok(adapter) = ChainFactory::get_adapter(&chain, cli.rpc_url.clone(), cli.network.clone()) {
let rpc = cli.rpc_url.as_deref().unwrap_or(adapter.default_rpc());
let healthy = adapter.get_gas_price().await.is_ok();
println!(" {} RPC endpoint: {}", "Β»".dimmed(), rpc.dimmed());
println!(" {} RPC health: {}", "Β»".dimmed(),
if healthy { "β OK".green().bold() } else { "β Unreachable".red().bold() }
);
}
}
Commands::Config { action } => {
match action {
ConfigAction::List => {
let entries = utils::list_config()?;
if entries.is_empty() {
println!("{}", "No configuration entries set.".dimmed());
} else {
println!("{}", "CLI Configuration:".bold().cyan());
for (k, v) in entries {
println!(" {} = {}", k.yellow(), v.green());
}
}
}
ConfigAction::Get { key } => {
match utils::get_config(&key)? {
Some(v) => println!("{} = {}", key.yellow(), v.green()),
None => println!("{} Key '{}' not found.", "β".red(), key),
}
}
ConfigAction::Set { key, value } => {
utils::save_config(&key, &value)?;
println!("{} Set {} = {}", "β".green(), key.yellow(), value.green());
}
ConfigAction::Unset { key } => {
utils::remove_config(&key)?;
println!("{} Removed key '{}'.", "β".green(), key.yellow());
}
}
}
Commands::Sui { command } => {
let adapter =
ChainFactory::get_adapter("sui", cli.rpc_url.clone(), cli.network.clone())?;
Self::handle_chain_command(adapter, command, cli.pretty, cli.email).await?;
}
Commands::Ethereum { command } => {
let adapter = ChainFactory::get_adapter(
"ethereum",
cli.rpc_url.clone(),
cli.network.clone(),
)?;
Self::handle_chain_command(adapter, command, cli.pretty, cli.email).await?;
}
Commands::Solana { command } => {
let adapter =
ChainFactory::get_adapter("solana", cli.rpc_url.clone(), cli.network.clone())?;
Self::handle_chain_command(adapter, command, cli.pretty, cli.email).await?;
}
Commands::Aptos { command } => {
let adapter =
ChainFactory::get_adapter("aptos", cli.rpc_url.clone(), cli.network.clone())?;
Self::handle_chain_command(adapter, command, cli.pretty, cli.email).await?;
}
Commands::Soroban { command } => {
let adapter =
ChainFactory::get_adapter("soroban", cli.rpc_url.clone(), cli.network.clone())?;
Self::handle_chain_command(adapter, command, cli.pretty, cli.email).await?;
}
Commands::Db { action } => {
Self::handle_db_command(action).await?;
}
Commands::Completion { shell } => {
use clap::CommandFactory;
let mut cmd = Cli::command();
clap_complete::generate(shell, &mut cmd, "txio", &mut std::io::stdout());
}
_ => {
println!("{}", "Feature coming soon!".yellow());
}
}
Ok(())
}
async fn handle_db_command(action: DbAction) -> Result<()> {
let config = Config::from_env().map_err(|e| anyhow!("Failed to load config: {}", e))?;
let client = establish_connection(&config.mongo_uri)
.await
.map_err(|e| anyhow!("{}", describe_connection_error(&config.mongo_uri, &e)))?;
let db = client.database("txio_db");
match action {
DbAction::ListUsers => {
let collection = db.collection::<Document>("users");
println!("{}", "Registered Users:".bold().cyan());
let mut cursor = collection
.find(None, None)
.await
.map_err(|e| anyhow!("Failed to query users: {}", e))?;
let mut count = 0;
while let Some(result) = cursor.next().await {
let doc: Document = result.map_err(|e| anyhow!("Cursor error: {}", e))?;
count += 1;
if let Ok(email) = doc.get_str("email") {
println!(" - {}", email.green());
} else {
println!(" - {}", "[User without email]".dimmed());
}
}
if count == 0 {
println!(" {}", "No users found.".yellow());
}
}
DbAction::DeleteUser { email } => {
let confirmed = Confirm::new()
.with_prompt(format!("Delete user '{}'? This cannot be undone", email.red()))
.default(false)
.interact()?;
if !confirmed {
println!("{} Aborted.", "β".red());
return Ok(());
}
let user_repo = UserRepository::new(&client);
match user_repo.find_by_email(&email).await {
Ok(user) => {
if let Some(id) = user.id {
match user_repo.delete_by_id(&id.to_hex()).await {
Ok(_) => println!("{} User '{}' deleted.", "β".green(), email.bold()),
Err(e) => println!("{} Delete failed: {}", "β".red(), e),
}
} else {
println!("{} User record has no ID.", "β".red());
}
}
Err(_) => println!("{} User '{}' not found.", "β".red(), email),
}
}
DbAction::Stats => {
let user_count = db
.collection::<Document>("users")
.count_documents(None, None)
.await
.unwrap_or(0);
let log_count = db
.collection::<Document>("rpc_logs")
.count_documents(None, None)
.await
.unwrap_or(0);
println!("{}", "βββ Database Stats βββ".bold().cyan());
println!(" {} Registered users: {}", "Β»".dimmed(), user_count.to_string().green().bold());
println!(" {} Total RPC logs: {}", "Β»".dimmed(), log_count.to_string().yellow().bold());
}
DbAction::ListLogs { limit } => {
let opts = FindOptions::builder()
.sort(doc! { "_id": -1 })
.limit(Some(limit as i64))
.build();
let mut cursor = db
.collection::<Document>("rpc_logs")
.find(None, Some(opts))
.await
.map_err(|e| anyhow!("Failed to query logs: {}", e))?;
println!("{}", "Recent RPC Logs:".bold().cyan());
let mut count = 0u64;
while let Some(result) = cursor.next().await {
let doc = result.map_err(|e| anyhow!("Cursor error: {}", e))?;
count += 1;
let method = doc.get_str("method").unwrap_or("unknown");
let success = doc.get_bool("success").unwrap_or(false);
let status = if success { "OK".green() } else { "ERR".red() };
let err = doc.get_str("error_message").unwrap_or("").dimmed();
println!(
" [{}] {} {}",
status,
method.cyan(),
if !err.is_empty() { format!("β {}", err) } else { String::new() }
);
}
if count == 0 {
println!(" {}", "No logs found.".yellow());
}
}
}
Ok(())
}
async fn handle_login() -> Result<()> {
println!("{}", "--- txio Account Login ---".bold().cyan());
let email: String = Input::new().with_prompt("Email").interact_text()?;
let password = Password::new().with_prompt("Password").interact()?;
println!("\n{} Logging in...", "β³".yellow());
let login_request = LoginRequest {
email: email.clone(),
password,
};
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| reqwest::Client::new());
let api_url =
std::env::var("API_URL").unwrap_or_else(|_| "http://localhost:8000".to_string());
let response = client
.post(format!("{}/api/v1/auth/login", api_url))
.json(&login_request)
.send()
.await?;
if response.status().is_success() {
let auth_response: AuthResponse = response.json().await?;
utils::save_token(&auth_response.token)?;
println!(
"{} Login successful! Welcome, {}.",
"β".green(),
auth_response.user.email.bold().cyan()
);
} else {
let status = response.status();
let error_body = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
println!(
"{} Login failed ({}): {}",
"β".red(),
status,
error_body.red()
);
}
Ok(())
}
async fn handle_chain_command(
adapter: Arc<dyn ChainAdapter>,
command: ChainCommand,
pretty: bool,
email: Option<String>,
) -> Result<()> {
match command {
ChainCommand::Call { method, params } => {
let params_val: Value = if let Some(p) = params {
serde_json::from_str(&p).map_err(|e| anyhow!("Invalid JSON params: {}", e))?
} else {
Value::Array(vec![])
};
println!(
"{} Calling {} on {}...",
"π".bold(),
method.cyan(),
adapter.name().green()
);
let result = adapter.call_rpc(&method, params_val.clone()).await;
let mut user_id_to_log: Option<ObjectId> = None;
if let Ok(config) = Config::from_env() {
if let Ok(client) = establish_connection(&config.mongo_uri).await {
if let Some(user_email) = email {
let user_repo = UserRepository::new(&client);
if let Ok(user) = user_repo.find_by_email(&user_email).await {
user_id_to_log = user.id;
}
} else if let Some(token) = utils::get_token() {
let jwt_helper = JwtHelper::new(config.jwt_secret);
if let Ok(claims) = jwt_helper.verify_token(&token) {
if let Ok(oid) = ObjectId::from_str(&claims.sub) {
user_id_to_log = Some(oid);
}
}
}
if let Some(user_id) = user_id_to_log {
let rpc_repo = RpcRepository::new(&client);
let log = RpcLog::new(
user_id,
method.clone(),
params_val,
result.is_ok(),
result.as_ref().err().map(|e| e.to_string()),
);
let _ = rpc_repo.save(&log).await;
}
}
}
let response = result?;
Self::print_value(&response, pretty)?;
}
ChainCommand::Balance { address } => {
println!(
"{} Fetching balance for {} on {}...\n",
"π°".bold(),
address.dimmed(),
adapter.name().green()
);
let resolved_address = if let Some(addr) = adapter.resolve_name(&address).await? {
println!(
"{} Resolved {} to {}\n",
"π".blue(),
address.yellow(),
addr.cyan()
);
addr
} else {
if address.ends_with(".sui") || address.ends_with(".eth") {
println!(
"{} {} could not be resolved! Proceeding with raw input...\n",
"β οΈ".yellow(),
address.yellow()
);
}
address
};
let result = adapter.get_balance(&resolved_address).await?;
let chain_name = adapter.name();
if chain_name == "Sui" {
if let Some(arr) = result.as_array() {
if arr.is_empty() {
println!(" {} No coins found.", "0".dimmed());
} else {
println!(
"{0: <15} | {1: <10} | {2}",
"Balance".bold(),
"Objects".bold(),
"Coin Type".bold()
);
println!("{0:-<15}-+-{0:-<10}-+-{0:-<40}", "");
for item in arr {
let balance = item
.get("totalBalance")
.and_then(|v| v.as_str())
.unwrap_or("0");
let count = item
.get("coinObjectCount")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let coin_type = item
.get("coinType")
.and_then(|v| v.as_str())
.unwrap_or("Unknown");
let display_balance = if coin_type == "0x2::sui::SUI" {
if let Ok(b) = balance.parse::<f64>() {
format!("{:.4} SUI", b / 1_000_000_000.0)
} else {
balance.to_string()
}
} else {
balance.to_string()
};
let short_coin = if coin_type.len() > 30 {
let parts: Vec<&str> = coin_type.split("::").collect();
if parts.len() >= 3 {
format!("{}::{}", parts[1].blue(), parts[2].cyan())
} else {
format!(
"{}...{}",
&coin_type[..10],
&coin_type[coin_type.len() - 10..]
)
.cyan()
.to_string()
}
} else {
coin_type.cyan().to_string()
};
println!(
"{0: <15} | {1: <10} | {2}",
display_balance.green().bold(),
count.to_string().yellow(),
short_coin
);
}
println!();
}
} else {
Self::print_value(&result, pretty)?;
}
} else if chain_name == "Ethereum" {
if let Some(hex_str) = result.as_str() {
let clean_hex = hex_str.trim_start_matches("0x");
if let Ok(wei) = u128::from_str_radix(clean_hex, 16) {
let eth = wei as f64 / 1_000_000_000_000_000_000.0;
println!(
"{} {:.4} ETH",
"Balance:".bold().cyan(),
eth.to_string().green().bold()
);
} else {
println!("{} {}", "Balance (Wei Hex):".bold().cyan(), hex_str.green());
}
} else {
Self::print_value(&result, pretty)?;
}
} else if chain_name == "Solana" {
if let Some(val) = result.get("value").and_then(|v| v.as_u64()) {
let sol = val as f64 / 1_000_000_000.0;
println!(
"{} {:.4} SOL",
"Balance:".bold().cyan(),
sol.to_string().green().bold()
);
} else {
Self::print_value(&result, pretty)?;
}
} else if chain_name == "Aptos" {
let mut found = false;
if let Some(arr) = result.as_array() {
for resource in arr {
if let Some(res_type) = resource.get("type").and_then(|t| t.as_str()) {
if res_type == "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>" {
if let Some(coin) =
resource.get("data").and_then(|d| d.get("coin"))
{
if let Some(val_str) =
coin.get("value").and_then(|v| v.as_str())
{
if let Ok(val) = val_str.parse::<f64>() {
let apt = val / 100_000_000.0;
println!(
"{} {:.4} APT",
"Balance:".bold().cyan(),
apt.to_string().green().bold()
);
found = true;
break;
}
}
}
}
}
}
}
if !found {
Self::print_value(&result, pretty)?;
}
} else {
Self::print_value(&result, pretty)?;
}
}
ChainCommand::Tx { hash } => {
println!(
"{} Fetching transaction {} on {}...\n",
"π".bold(),
hash.dimmed(),
adapter.name().green()
);
let result = adapter.get_transaction(&hash).await?;
Self::print_value(&result, pretty)?;
}
ChainCommand::Object { id } => {
println!(
"{} Inspecting {} on {}...\n",
"π".bold(),
id.dimmed(),
adapter.name().green()
);
let result = adapter.get_account(&id).await?;
Self::print_value(&result, pretty)?;
}
ChainCommand::History { address, limit } => {
println!(
"{} Fetching {} recent transactions for {} on {}...\n",
"π".bold(),
limit,
address.dimmed(),
adapter.name().green()
);
let result = adapter.get_history(&address, limit).await?;
Self::print_value(&result, pretty)?;
}
ChainCommand::Gas => {
println!(
"{} Fetching gas price on {}...\n",
"β½".bold(),
adapter.name().green()
);
let result = adapter.get_gas_price().await?;
let chain = adapter.name();
if chain == "Sui" {
let mist = result
.as_str()
.and_then(|s| s.parse::<u64>().ok())
.or_else(|| result.as_u64())
.unwrap_or(0);
println!(
"{} {} MIST ({:.9} SUI per gas unit)",
"Reference Gas Price:".bold().cyan(),
mist.to_string().green().bold(),
mist as f64 / 1_000_000_000.0
);
} else if chain == "Ethereum" {
if let Some(hex) = result.as_str() {
let clean = hex.trim_start_matches("0x");
if let Ok(wei) = u128::from_str_radix(clean, 16) {
let gwei = wei as f64 / 1_000_000_000.0;
println!(
"{} {:.4} Gwei ({} wei)",
"Gas Price:".bold().cyan(),
gwei.to_string().green().bold(),
wei.to_string().yellow()
);
} else {
Self::print_value(&result, pretty)?;
}
} else {
Self::print_value(&result, pretty)?;
}
} else {
Self::print_value(&result, pretty)?;
}
}
ChainCommand::Block { number } => {
match number {
Some(n) => println!(
"{} Fetching block #{} on {}...\n",
"π¦".bold(),
n,
adapter.name().green()
),
None => println!(
"{} Fetching latest block on {}...\n",
"π¦".bold(),
adapter.name().green()
),
}
let result = adapter.get_block(number).await?;
Self::print_value(&result, pretty)?;
}
}
Ok(())
}
fn print_value(value: &Value, pretty: bool) -> Result<()> {
if pretty {
println!("{}", serde_json::to_string_pretty(value)?);
} else {
println!("{}", serde_json::to_string(value)?);
}
Ok(())
}
}